Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion client/grpc_worker_tracing_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -638,7 +638,8 @@ func TestWorkerTracingEntityHandlerSpanContext(t *testing.T) {
registry := task.NewTaskRegistry()
require.NoError(t, registry.AddEntityN("counter", func(ctx *task.EntityContext) (any, error) {
handlerContext = trace.SpanContextFromContext(ctx.Context())
_, span := h.provider.Tracer("app").Start(ctx.Context(), "app")
// Discover the provider from the context, as otelhttp does.
_, span := trace.SpanFromContext(ctx.Context()).TracerProvider().Tracer("app").Start(ctx.Context(), "app")
appContext = span.SpanContext()
span.End()
if err := ctx.SignalEntity(api.NewEntityID("other", "key"), "ping", nil); err != nil {
Expand Down
17 changes: 10 additions & 7 deletions durabletaskscheduler/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,10 @@ type Client struct {
// it with a deadline-bound Hello call.
// A nil logger uses [api.DefaultLogger]. clientOptions configure client
// behavior that Options does not cover, such as client.WithTracerProvider to
// enable client spans. Configure data conversion, large payloads, and the
// default version through Options rather than the equivalent client options;
// for example, ScheduledTasks always encodes with Options.DataConverter.
// enable client spans. Data conversion always comes from Options, overriding
// client.WithDataConverter, so direct operations and ScheduledTasks encode
// payloads the same way. Large payloads and the default version set in Options
// likewise override the equivalent client options.
func NewClient(
ctx context.Context,
options *Options,
Expand Down Expand Up @@ -68,14 +69,16 @@ func NewClient(
prepared.ChannelRecreateMinInterval,
logger,
)
configuredOptions := []durabletaskclient.TaskHubGrpcClientOption{
durabletaskclient.WithLargePayloads(prepared.LargePayloads),
durabletaskclient.WithDataConverter(prepared.DataConverter),
// Caller options come first so the DTS-owned settings below take
// precedence; ScheduledTasks must encode with the same converter.
configuredOptions := append([]durabletaskclient.TaskHubGrpcClientOption{}, clientOptions...)
configuredOptions = append(configuredOptions, durabletaskclient.WithDataConverter(prepared.DataConverter))
if prepared.LargePayloads != nil {
configuredOptions = append(configuredOptions, durabletaskclient.WithLargePayloads(prepared.LargePayloads))
}
if prepared.Versioning != nil && prepared.Versioning.DefaultVersion != "" {
configuredOptions = append(configuredOptions, durabletaskclient.WithDefaultVersion(prepared.Versioning.DefaultVersion))
}
configuredOptions = append(configuredOptions, clientOptions...)
return &Client{
TaskHubGrpcClient: durabletaskclient.NewTaskHubGrpcClient(connection, logger, configuredOptions...),
connection: connection,
Expand Down
24 changes: 24 additions & 0 deletions durabletaskscheduler/client_tracing_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,27 @@ func TestNewClientAppliesTrailingClientOptions(t *testing.T) {
propagated := helpers.SpanContextFromTraceContext(server.start.ParentTraceContext)
require.Equal(t, spans[0].SpanContext().SpanID(), propagated.SpanID())
}

func TestNewClientOptionsOverrideConflictingClientOptions(t *testing.T) {
server := new(startRecordingServer)
listener, stop := startBufconnServer(t, server)
defer stop()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
options := insecureBufconnOptions(t, listener)
options.DataConverter = prefixedConverter{}
options.Versioning = &task.VersioningOptions{DefaultVersion: "1.0"}

client, err := NewClient(ctx, options, api.DefaultLogger(),
durabletaskclient.WithDataConverter(api.JSONDataConverter{}),
durabletaskclient.WithDefaultVersion("2.0"))
require.NoError(t, err)
defer func() { require.NoError(t, client.Close()) }()
_, err = client.ScheduleNewOrchestration(ctx, "Orch", api.WithInput("hello"))
require.NoError(t, err)

server.mu.Lock()
defer server.mu.Unlock()
require.Equal(t, `converter:"hello"`, server.start.GetInput().GetValue())
require.Equal(t, "1.0", server.start.GetVersion().GetValue())
}
62 changes: 41 additions & 21 deletions internal/dttrace/dttrace.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,8 @@ var ErrUnsupportedTracerProvider = errors.New(

// Tracer emits Durable Task spans through a validated tracer provider.
type Tracer struct {
tracer trace.Tracer
provider trace.TracerProvider
tracer trace.Tracer
}

// NewTracer validates that provider honors persisted span IDs and answers
Expand All @@ -68,7 +69,7 @@ func NewTracer(provider trace.TracerProvider) (*Tracer, error) {
if err := checkReconstruction(tracer); err != nil {
return nil, err
}
return &Tracer{tracer: tracer}, nil
return &Tracer{provider: provider, tracer: tracer}, nil
}

// checkReconstruction starts a probe span under an unsampled parent. The
Expand Down Expand Up @@ -310,13 +311,17 @@ type Orchestration struct {
failedChildren map[int32]struct{}
timers map[int32]createdTimer
newSends map[int32]pendingSpan
acceptedSends map[int32]struct{}
entityCalls map[string]entityCall
entitySignals map[int32]entitySignal
entityAcks map[entitySignalKey]struct{}
pending []pendingSpan
responseTime time.Time
emitted bool
// history is this dispatch's past and new events. The acknowledgement
// sets are built from it only when a replayed send or signal needs them.
history [][]*protos.HistoryEvent
acksLoaded bool
acceptedSends map[int32]struct{}
entityAcks map[entitySignalKey]struct{}
pending []pendingSpan
responseTime time.Time
emitted bool

logicalOnce sync.Once
logical trace.SpanContext
Expand All @@ -338,23 +343,10 @@ func (t *Tracer) StartOrchestration(
instanceID: instanceID,
scheduled: make(map[int32]scheduledTask),
timers: make(map[int32]createdTimer),
history: eventLists,
}
for _, events := range eventLists {
for _, event := range events {
// An acknowledgement proves acceptance even when the turn budget
// prevents the replay engine from consuming it in this dispatch.
if event.GetEventSent() != nil {
if o.acceptedSends == nil {
o.acceptedSends = make(map[int32]struct{})
}
o.acceptedSends[event.EventId] = struct{}{}
}
if signaled := event.GetEntityOperationSignaled(); signaled != nil {
if o.entityAcks == nil {
o.entityAcks = make(map[entitySignalKey]struct{})
}
o.entityAcks[entitySignalKey{eventID: event.EventId, requestID: signaled.RequestId}] = struct{}{}
}
if started := event.GetExecutionStarted(); started != nil {
o.started = true
o.name = started.GetName()
Expand Down Expand Up @@ -692,12 +684,40 @@ func (o *Orchestration) ConfirmSendEvent(eventID int32, replaying bool) {
delete(o.newSends, eventID)
}

// loadAcks indexes the send and entity-signal acknowledgements anywhere in
// this dispatch's history. An acknowledgement proves acceptance even when the
// turn budget or a suspension prevents the replay engine from consuming it in
// this dispatch.
func (o *Orchestration) loadAcks() {
if o.acksLoaded {
return
}
o.acksLoaded = true
for _, events := range o.history {
for _, event := range events {
if event.GetEventSent() != nil {
if o.acceptedSends == nil {
o.acceptedSends = make(map[int32]struct{})
}
o.acceptedSends[event.EventId] = struct{}{}
}
if signaled := event.GetEntityOperationSignaled(); signaled != nil {
if o.entityAcks == nil {
o.entityAcks = make(map[entitySignalKey]struct{})
}
o.entityAcks[entitySignalKey{eventID: event.EventId, requestID: signaled.RequestId}] = struct{}{}
}
}
}
}

// sendSpan returns the span for a SendEvent action left in an accepted
// response, or false when an earlier response already exported it.
func (o *Orchestration) sendSpan(action *protos.OrchestratorAction) (pendingSpan, bool) {
if span, ok := o.newSends[action.Id]; ok {
return span, true
}
o.loadAcks()
if _, ok := o.acceptedSends[action.Id]; ok {
return pendingSpan{}, false
}
Expand Down
42 changes: 31 additions & 11 deletions internal/dttrace/entity.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,18 +102,34 @@ func WithEntityBatch(ctx context.Context, batch *EntityBatch) context.Context {
return context.WithValue(ctx, entityBatchKey{}, batch)
}

// EntityOperationSpanContext returns the reserved, non-recording span context
// of the operation at index in the batch attached to ctx. It returns an invalid
// span context when tracing is disabled or requestID does not match.
func EntityOperationSpanContext(ctx context.Context, index int, requestID string) trace.SpanContext {
// EntityOperationSpan returns the reserved, non-recording span of the
// operation at index in the batch attached to ctx. Its TracerProvider is the
// worker's provider, so instrumentation that discovers its tracer from the
// span in a context records children of the operation span. It returns nil
// when tracing is disabled or requestID does not match.
func EntityOperationSpan(ctx context.Context, index int, requestID string) trace.Span {
batch, _ := ctx.Value(entityBatchKey{}).(*EntityBatch)
if batch == nil || index < 0 || index >= len(batch.operations) ||
batch.operations[index].requestID != requestID {
return trace.SpanContext{}
batch.operations[index].requestID != requestID ||
!batch.operations[index].spanContext.IsValid() {
return nil
}
return batch.operations[index].spanContext
spanContext := batch.operations[index].spanContext
return reservedSpan{
Span: trace.SpanFromContext(trace.ContextWithSpanContext(context.Background(), spanContext)),
provider: batch.tracer.provider,
}
}

// reservedSpan is a non-recording span that reports the worker's provider
// instead of the no-op provider of [trace.ContextWithSpanContext].
type reservedSpan struct {
trace.Span
provider trace.TracerProvider
}

func (s reservedSpan) TracerProvider() trace.TracerProvider { return s.provider }

// Emit exports the reserved operation spans. Call it only after the backend
// accepts result, so rejected or abandoned batches export nothing. start and
// end bound operations whose result has no timestamps. Dropped operations
Expand Down Expand Up @@ -257,6 +273,7 @@ func (o *Orchestration) completeEntity(
type entitySignal struct {
id api.EntityID
signal *protos.EntityOperationSignaledEvent
key entitySignalKey
at time.Time
replaying bool
}
Expand Down Expand Up @@ -288,13 +305,10 @@ func (o *Orchestration) RecordEntitySignal(action *protos.OrchestratorAction, id
}
signal := action.GetSendEntityMessage().GetEntityOperationSignaled()
key := entitySignalKey{eventID: action.Id, requestID: signal.GetRequestId()}
if _, acknowledged := o.entityAcks[key]; acknowledged && replaying {
return
}
if o.entitySignals == nil {
o.entitySignals = make(map[int32]entitySignal)
}
recorded := entitySignal{id: id, signal: signal, replaying: replaying}
recorded := entitySignal{id: id, signal: signal, key: key, replaying: replaying}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This now stores a full record for every replayed entity signal until replay consumes its ack. Previously, signals with an ack already in the request skipped this record. In an isolated tracing benchmark with 10,000 fully acknowledged signals, replay rose from 2.6 to 4.2 ms and from 1.31 to 3.67 MB per dispatch. Can we keep the cheaper event-send path without paying for a full record per replayed entity signal, for example by tracking only the minimal replay state until an action survives into the response?

if !replaying {
recorded.at = time.Now()
}
Expand All @@ -320,6 +334,12 @@ func (o *Orchestration) signalSpan(action *protos.OrchestratorAction) (pendingSp
if !ok {
return pendingSpan{}, false
}
if recorded.replaying {
o.loadAcks()
if _, acknowledged := o.entityAcks[recorded.key]; acknowledged {
return pendingSpan{}, false
}
}
return o.signalSpanFor(action.Id, recorded), true
}

Expand Down
12 changes: 7 additions & 5 deletions task/executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -426,9 +426,9 @@ func (te *taskExecutor) ExecuteEntity(
}
startedAt := time.Now().UTC()
isSignal := req.Properties[helpers.EntitySignalProperty(operation.RequestId)].GetBoolValue()
spanContext := dttrace.EntityOperationSpanContext(ctx, i, operation.RequestId)
span := dttrace.EntityOperationSpan(ctx, i, operation.RequestId)
operationCtx := te.newEntityContext(
ctx, entityID, operation, state, nextActionID, startedAt, isSignal, spanContext)
ctx, entityID, operation, state, nextActionID, startedAt, isSignal, span)
output, operationErr := invokeEntity(batch.Entity, operationCtx)
endedAt := time.Now().UTC()

Expand Down Expand Up @@ -480,13 +480,15 @@ func (te *taskExecutor) newEntityContext(
nextActionID int32,
currentTime time.Time,
isSignal bool,
spanContext trace.SpanContext,
span trace.Span,
) *EntityContext {
ctx = api.ContextWithFields(ctx, te.contextFields)
if spanContext.IsValid() {
var spanContext trace.SpanContext
if span != nil {
// The operation span is reconstructed after the batch is accepted;
// handlers see its reserved, non-recording identity.
ctx = trace.ContextWithSpanContext(ctx, spanContext)
spanContext = span.SpanContext()
ctx = trace.ContextWithSpan(ctx, span)
}
ctx = api.WithEntityContextInfo(ctx, api.EntityContextInfo{
EntityID: entityID,
Expand Down
18 changes: 11 additions & 7 deletions tracing/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ As a result:
- A running, suspended, or never-completing orchestration has no exported
orchestration span yet. Its exported children can appear under a parent that
your backend doesn't show until the orchestration completes. If the
orchestration is purged or abandoned first, the parent never appears.
orchestration is purged before it completes, the parent never appears.
- If tracing is enabled while an orchestration is already running, its span
starts at the first traced dispatch.
- The JavaScript SDK works differently. It emits one SERVER span per dispatch.
Expand All @@ -100,7 +100,7 @@ omitted when the task is unversioned. Entity names are lowercase, as in
| Operation | Span name | Kind and parent |
| --- | --- | --- |
| Client schedules orchestration | `create_orchestration:<name>` | PRODUCER under caller |
| Orchestration execution | `orchestration:<name>` | SERVER under create span, or under the propagated caller context when client tracing is off; trace root without caller context |
| Orchestration execution | `orchestration:<name>` | SERVER under create span, or under the propagated caller context when client tracing is off; trace root without a propagated parent trace context |
| Activity scheduling | `activity:<name>` | CLIENT under orchestration |
| Activity execution | `activity:<name>` | SERVER under scheduling span; active in `ActivityContext.Context()` |
| Sub-orchestration scheduling | `orchestration:<child>` | CLIENT under parent orchestration |
Expand Down Expand Up @@ -133,7 +133,9 @@ When each kind of span is exported:
They use the operation result's timestamps.
`EntityContext.Context()` carries the operation's span context as a
non-recording span, so application spans that you start from it nest under
the operation span.
the operation span. That span reports the worker's tracer provider, so
instrumentation such as `otelhttp` that finds its provider from the context
also records children.

Replayed history emits no new spans. Orchestration spans aren't live inside the
orchestrator. An application span that you start from orchestrator code isn't
Expand All @@ -155,9 +157,11 @@ names and kinds:

Failures get an error status. Successful spans leave the status unset.

Without caller context, an orchestration becomes the root of a new trace. Its
trace ID is derived from the orchestration's persisted identity, not from the
base ID generator. With the default parent-based sampler, sampling follows the
Without a propagated parent trace context, an orchestration becomes the root of
a new trace. Its trace ID is derived from the orchestration's persisted
identity, not from the base ID generator. With client tracing enabled, the
`create_orchestration` span is always propagated as the parent, even when the

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we replace always with when the provider returns a valid span context? The client accepts a no-op provider; with no active caller span, that provider returns no valid context and the request has no trace parent.

caller has no active span. With the default parent-based sampler, sampling follows the
propagated trace flags and keeps tracestate, so unsampled orchestration trees
stay unsampled. Custom base samplers also control child-span decisions; use
`sdktrace.ParentBased(sdktrace.TraceIDRatioBased(ratio))` for ratio sampling that
Expand All @@ -182,7 +186,7 @@ and [durabletask-js](https://github.com/microsoft/durabletask-js)
| Instrumentation scope | `Microsoft.DurableTask` | `Microsoft.DurableTask` | `durabletask` | `Microsoft.DurableTask` |
| Client create orchestration and raise event | PRODUCER | PRODUCER | PRODUCER | PRODUCER |
| Orchestration span | One logical SERVER span per execution, with persisted ID and start time | One logical SERVER span per execution, with persisted ID and start time | One logical SERVER span per execution, with persisted ID and start time | One SERVER span per dispatch that starts at the dispatch, with `durabletask.task.replay_span_id` and `replay_start_time` attributes |
| Orchestration without caller context | New root trace | No orchestration span | New root trace | Uses the active context, or a new root trace if there isn't one |
| Orchestration without a propagated parent trace context | New root trace | No orchestration span | New root trace | Uses the active context, or a new root trace if there isn't one |
| Export timing | After the backend accepts the completion | Before the completion is accepted | Before the completion is accepted | Before the completion is accepted |
| Activity and sub-orchestration scheduling and execution | CLIENT and SERVER | CLIENT and SERVER | CLIENT and SERVER | CLIENT and SERVER. The CLIENT span doesn't reuse the propagated span ID, so the SERVER span's parent is never exported |
| Durable timers | `orchestration:<name>:timer` INTERNAL | `orchestration:<name>:timer` INTERNAL | `orchestration:<name>:timer` INTERNAL | `orchestration:<name>:timer` INTERNAL |
Expand Down