diff --git a/client/grpc_worker_tracing_test.go b/client/grpc_worker_tracing_test.go index 875304ee..5cd3501a 100644 --- a/client/grpc_worker_tracing_test.go +++ b/client/grpc_worker_tracing_test.go @@ -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 { diff --git a/durabletaskscheduler/client.go b/durabletaskscheduler/client.go index e6421c3a..4d20a8f5 100644 --- a/durabletaskscheduler/client.go +++ b/durabletaskscheduler/client.go @@ -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, @@ -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, diff --git a/durabletaskscheduler/client_tracing_test.go b/durabletaskscheduler/client_tracing_test.go index 0041528f..361e2641 100644 --- a/durabletaskscheduler/client_tracing_test.go +++ b/durabletaskscheduler/client_tracing_test.go @@ -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()) +} diff --git a/internal/dttrace/dttrace.go b/internal/dttrace/dttrace.go index a9632cf5..dd2cf35c 100644 --- a/internal/dttrace/dttrace.go +++ b/internal/dttrace/dttrace.go @@ -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 @@ -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 @@ -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 @@ -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() @@ -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 } diff --git a/internal/dttrace/entity.go b/internal/dttrace/entity.go index 95b04428..78bcaf1e 100644 --- a/internal/dttrace/entity.go +++ b/internal/dttrace/entity.go @@ -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 @@ -257,6 +273,7 @@ func (o *Orchestration) completeEntity( type entitySignal struct { id api.EntityID signal *protos.EntityOperationSignaledEvent + key entitySignalKey at time.Time replaying bool } @@ -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} if !replaying { recorded.at = time.Now() } @@ -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 } diff --git a/task/executor.go b/task/executor.go index 60bdcf53..7748e16b 100644 --- a/task/executor.go +++ b/task/executor.go @@ -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() @@ -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, diff --git a/tracing/README.md b/tracing/README.md index 6de1523e..3e39a64a 100644 --- a/tracing/README.md +++ b/tracing/README.md @@ -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. @@ -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:` | PRODUCER under caller | -| Orchestration execution | `orchestration:` | SERVER under create span, or under the propagated caller context when client tracing is off; trace root without caller context | +| Orchestration execution | `orchestration:` | 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:` | CLIENT under orchestration | | Activity execution | `activity:` | SERVER under scheduling span; active in `ActivityContext.Context()` | | Sub-orchestration scheduling | `orchestration:` | CLIENT under parent orchestration | @@ -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 @@ -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 +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 @@ -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::timer` INTERNAL | `orchestration::timer` INTERNAL | `orchestration::timer` INTERNAL | `orchestration::timer` INTERNAL |