From dbc7bcbd3744c2549925b94339268d3cdd3a6ec9 Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Fri, 20 Nov 2026 12:23:15 -0700 Subject: [PATCH 1/2] Document and exercise enabled replay-aware tracing Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- README.md | 72 ++++-- samples/distributedtracing/README.md | 33 ++- .../distributedtracing/distributedtracing.go | 60 +++-- .../dts_tracing_enabled_test.go | 218 ++++++++++++++++++ tests/tracingtree/tracingtree.go | 3 +- tracing/README.md | 141 +++++++++++ tracing/tracing.go | 3 + 7 files changed, 487 insertions(+), 43 deletions(-) create mode 100644 tests/durabletaskscheduler/dts_tracing_enabled_test.go create mode 100644 tracing/README.md diff --git a/README.md b/README.md index 6abc0d89..fc04507c 100644 --- a/README.md +++ b/README.md @@ -50,7 +50,7 @@ Use these features for large systems or for special conditions. | Data converters | Replace the default JSON serialization of your payloads. | | Large payloads | Keep large payloads in Azure Blob Storage and send a reference token. | | Tags and trace context | Attach user tags to actions. Send the caller trace context to DTS. | -| Distributed tracing | Emit OpenTelemetry spans from your process. DTS emits the durable spans. | +| [Distributed tracing](./tracing/README.md) | Opt in to replay-aware client and worker OpenTelemetry spans through your application's provider. | | Replay-hazard analysis | Find nondeterministic orchestrator code with `cmd/orchestratorvet`. | | History export (preview) | Copy terminal orchestration histories to Azure Blob Storage. | @@ -530,7 +530,7 @@ Activity contexts expose the activity's own name, version, and task ID in from native history fields, including after sub-orchestration starts and ContinueAsNew version changes. -The client sends the sampled caller trace context when it schedules an orchestration or signals an entity. The worker adds separate action trace contexts for the service-owned activity and sub-orchestration spans. The worker does not emit duplicate local Durable Task spans. V2 entity requests do not carry per-operation trace context, so entity-emitted actions cannot inherit it. +The client sends the sampled caller trace context when it schedules an orchestration or signals an entity. By default, the worker propagates action trace contexts without emitting local Durable Task spans. Opt-in tracing adds replay-aware client and worker spans through your application's provider. V2 entity requests do not carry per-operation trace context, so entity execution spans are independent roots. Use `task.OrchestrationOptions.MaxEventsPerTurn` to limit the new events in one turn. If the worker uses only part of a batch, it sets `numEventsProcessed`. DTS then keeps the remaining events for the next replay. This count obeys the DTS work-item rules. The orchestration control markers do not count against the limit. @@ -555,17 +555,12 @@ accounts. See [large payload configuration](./durabletaskscheduler/README.md#lar ## Distributed tracing -The SDK sends the W3C trace context of a sampled caller when it schedules an orchestration. DTS owns the spans for the orchestrations, activities, timers, and sub-orchestrations. Your application code can use standard [OpenTelemetry](https://opentelemetry.io/) instrumentation. Use it for caller spans, custom activity spans, and outbound dependencies. - -When DTS supplies an activity trace parent, the SDK restores it on -`ActivityContext.Context()` without creating another durable-operation span. -Application instrumentation can therefore attach outbound requests to the -service-owned trace. - -This example sends the traces of your process to an [OpenTelemetry Collector](https://opentelemetry.io/docs/collector/) over OTLP/HTTP. Configure the DTS telemetry separately for the service-owned spans. +Tracing is opt-in. Without tracing options, the SDK propagates W3C context but +emits no local durable-operation spans. Enable client PRODUCER spans and +replay-aware worker spans using an application-owned OpenTelemetry provider: ```go -func ConfigureOTLPTracing(ctx context.Context) (*trace.TracerProvider, error) { +func ConfigureOTLPTracing(ctx context.Context) (*sdktrace.TracerProvider, error) { exp, err := otlptracehttp.New( ctx, otlptracehttp.WithEndpoint("localhost:4318"), @@ -575,15 +570,11 @@ func ConfigureOTLPTracing(ctx context.Context) (*trace.TracerProvider, error) { return nil, err } - // NOTE: Do not use the simple span processor in production. - // Use the batch span processor in production. - processor := trace.NewSimpleSpanProcessor(exp) - // processor := trace.NewBatchSpanProcessor(exp) - - tp := trace.NewTracerProvider( - trace.WithSpanProcessor(processor), - trace.WithSampler(trace.AlwaysSample()), - trace.WithResource(resource.NewWithAttributes( + tp := sdktrace.NewTracerProvider( + sdktrace.WithBatcher(exp), + tracing.WithIDGenerator(nil), + tracing.WithSampler(sdktrace.ParentBased(sdktrace.AlwaysSample())), + sdktrace.WithResource(resource.NewWithAttributes( "durabletask.io", attribute.KeyValue{Key: "service.name", Value: attribute.StringValue("sample-app")}, )), @@ -593,7 +584,46 @@ func ConfigureOTLPTracing(ctx context.Context) (*trace.TracerProvider, error) { } ``` -The [distributed tracing sample](./samples/distributedtracing) starts a caller span before `ScheduleNewOrchestration`. DTS then joins its service-side spans to the same trace. The sample also instruments an HTTP request from an activity. +Use the configured provider for each surface you want to enable: + +```go +tp, err := ConfigureOTLPTracing(ctx) +if err != nil { + return err +} +worker, err := durabletaskscheduler.NewWorker(options, registry, logger, + durabletaskclient.WithWorkerTracerProvider(tp)) +if err != nil { + return err +} +managementClient, err := durabletaskscheduler.NewClient(ctx, options, logger, + durabletaskclient.WithTracerProvider(tp)) +if err != nil { + return err +} +``` + +Check constructor errors and configure **both** tracing wrappers on the worker +provider. They reconstruct completed spans with persisted identities and +consistent sampling decisions across replay; providers missing either are +rejected. The application owns the provider and should stop workers before +flushing/shutting it down. + +The tree includes caller -> create orchestration PRODUCER -> orchestration +SERVER -> activity/sub-orchestration CLIENT -> execution SERVER, plus timer +INTERNAL and event-send PRODUCER spans. Activity spans are active in +`ActivityContext.Context()`, so application HTTP/database spans nest under them. +Replayed history emits no new spans, but telemetry is not exactly-once. + +Entity spans follow DurableTask.Core semantics. V2 entity execution spans are +independent roots because operations carry no parent context. Events have no +receipt CONSUMER span or sender-to-receiver trace join. Service telemetry is +configured separately from these application-process spans. + +The [tracing guide](./tracing/README.md) includes the full span catalog and +Python/.NET gRPC parity table. The +[distributed tracing sample](./samples/distributedtracing) exports durable and +application HTTP spans to a real OTLP collector and verifies their receipt. ## History export (preview) diff --git a/samples/distributedtracing/README.md b/samples/distributedtracing/README.md index b1761cb4..20c9999c 100644 --- a/samples/distributedtracing/README.md +++ b/samples/distributedtracing/README.md @@ -1,20 +1,37 @@ # Distributed tracing sample -Demonstrates application trace propagation into Durable Task Scheduler using -OTLP/HTTP and a real OpenTelemetry collector. +Demonstrates opt-in, replay-aware Durable Task Scheduler tracing using the +application's OpenTelemetry provider, OTLP/HTTP, and a real collector. ## Features - Starts a caller span and schedules an orchestration under that trace. - Uses a local loopback HTTP target instead of an external dependency. -- Exports application spans over OTLP/HTTP to a collector. -- Verifies the collector file exporter received the caller and local HTTP spans - under the same trace ID. +- Enables worker spans with `client.WithWorkerTracerProvider` and client + PRODUCER spans with `client.WithTracerProvider`. +- Exports orchestration, activity scheduling/execution, timer, and application + spans over OTLP/HTTP to a collector. +- Verifies the collector file exporter received these spans under the caller's + trace ID. - Reads DTS history and verifies persisted trace context shares the caller trace. -DTS orchestration/activity/timer spans are service-owned. This sample validates -the trace context recorded in history and does not claim that the local worker -duplicates service spans. +Tracing remains disabled unless explicitly enabled. The sample configures its +provider with **both** `tracing.WithIDGenerator(nil)` and +`tracing.WithSampler(sdktrace.ParentBased(sdktrace.AlwaysSample()))`. These wrappers +let the worker reconstruct completed spans with persisted identities and make +consistent sampling decisions across replay; do not replace them with the raw +SDK options. The same provider is also installed globally for HTTP instrumentation. + +The exported tree is caller -> create-orchestration PRODUCER -> orchestration +SERVER -> activity CLIENT -> activity SERVER -> application HTTP spans, with a +timer INTERNAL span under the orchestration. The worker exports the orchestration +when it finishes and durable scheduling/timer spans after accepted completions, +not on every replay. The application flushes the provider after worker shutdown +and owns its final shutdown. + +These are application-process spans, separate from any scheduler-service +telemetry. See the [tracing guide](../../tracing/README.md) for span semantics, +SDK parity, and delivery/propagation limitations. ## Prerequisites diff --git a/samples/distributedtracing/distributedtracing.go b/samples/distributedtracing/distributedtracing.go index b8598036..08b2424b 100644 --- a/samples/distributedtracing/distributedtracing.go +++ b/samples/distributedtracing/distributedtracing.go @@ -1,5 +1,5 @@ -// Command distributedtracing propagates an application caller span into DTS and -// verifies that a real OTLP/HTTP collector received application spans. +// Command distributedtracing exports replay-aware DTS worker and client spans +// alongside application spans to a real OTLP/HTTP collector. package main import ( @@ -25,8 +25,11 @@ import ( oteltrace "go.opentelemetry.io/otel/trace" "github.com/microsoft/durabletask-go/api" + durabletaskclient "github.com/microsoft/durabletask-go/client" + "github.com/microsoft/durabletask-go/durabletaskscheduler" "github.com/microsoft/durabletask-go/samples/internal/dtssample" "github.com/microsoft/durabletask-go/task" + "github.com/microsoft/durabletask-go/tracing" ) const callerSpanName = "schedule_distributed_trace_sample" @@ -69,15 +72,35 @@ func run() (err error) { return fmt.Errorf("register activity: %w", err) } - app, err := dtssample.Start(ctx, registry) + options, err := dtssample.Options() if err != nil { return err } + managementClient, err := durabletaskscheduler.NewClient(ctx, options, api.DefaultLogger(), + durabletaskclient.WithTracerProvider(tp)) + if err != nil { + return fmt.Errorf("create client: %w", err) + } + defer func() { err = errors.Join(err, managementClient.Close()) }() + worker, err := durabletaskscheduler.NewWorker(options, registry, api.DefaultLogger(), + durabletaskclient.WithAutoWorkItemFilters(), + durabletaskclient.WithWorkerTracerProvider(tp)) + if err != nil { + return fmt.Errorf("create worker: %w", err) + } + if err := worker.Start(ctx); err != nil { + return fmt.Errorf("start worker: %w", err) + } + shutdownWorker := func() error { + shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 30*time.Second) + defer shutdownCancel() + return worker.Shutdown(shutdownCtx) + } var ownedIDs []api.InstanceID cleanupDone := false defer func() { if !cleanupDone { - err = errors.Join(err, dtssample.Cleanup(app.Client, ownedIDs...), app.Shutdown()) + err = errors.Join(err, dtssample.Cleanup(managementClient, ownedIDs...), shutdownWorker()) } }() @@ -89,7 +112,7 @@ func run() (err error) { traceID := callerSpan.SpanContext().TraceID().String() instanceID := dtssample.NewInstanceID("distributedtracing") ownedIDs = append(ownedIDs, instanceID) - if _, err := app.Client.ScheduleNewOrchestration(callerCtx, "DistributedTraceSampleOrchestrator", + if _, err := managementClient.ScheduleNewOrchestration(callerCtx, "DistributedTraceSampleOrchestrator", api.WithInstanceID(instanceID), api.WithInput(tracedTarget.URL), api.WithTags(map[string]string{"sample": "distributedtracing"})); err != nil { @@ -98,14 +121,14 @@ func run() (err error) { } callerSpan.End() - metadata, err := app.Client.WaitForOrchestrationCompletion(ctx, instanceID, api.WithFetchPayloads(true)) + metadata, err := managementClient.WaitForOrchestrationCompletion(ctx, instanceID, api.WithFetchPayloads(true)) if err != nil { return fmt.Errorf("wait for orchestration: %w", err) } if err := dtssample.RequireCompleted(metadata); err != nil { return err } - history, err := app.Client.GetOrchestrationHistory(ctx, instanceID, api.HistoryQuery{ExecutionID: metadata.ExecutionID}) + history, err := managementClient.GetOrchestrationHistory(ctx, instanceID, api.HistoryQuery{ExecutionID: metadata.ExecutionID}) if err != nil { return fmt.Errorf("read orchestration history: %w", err) } @@ -118,14 +141,24 @@ func run() (err error) { } log.Printf("Orchestration completed: %s", metadataEnc) - cleanupErr := dtssample.Cleanup(app.Client, ownedIDs...) - appErr := app.Shutdown() - traceErr := shutdownTracer(tp) + cleanupErr := dtssample.Cleanup(managementClient, ownedIDs...) + workerErr := shutdownWorker() + flushCtx, flushCancel := context.WithTimeout(context.Background(), 20*time.Second) + defer flushCancel() + traceErr := tp.ForceFlush(flushCtx) cleanupDone = true receiptCtx, receiptCancel := context.WithTimeout(context.Background(), 30*time.Second) defer receiptCancel() - receiptErr := waitForCollectorReceipt(receiptCtx, traceFile, traceID, []string{callerSpanName, "local_trace_target"}) - return errors.Join(cleanupErr, appErr, traceErr, receiptErr) + receiptErr := waitForCollectorReceipt(receiptCtx, traceFile, traceID, []string{ + callerSpanName, + "create_orchestration:DistributedTraceSampleOrchestrator", + "orchestration:DistributedTraceSampleOrchestrator", + "activity:DoWorkActivity", + "orchestration:DistributedTraceSampleOrchestrator:timer", + "activity:CallHttpEndpointActivity", + "local_trace_target", + }) + return errors.Join(cleanupErr, workerErr, traceErr, receiptErr) } func ConfigureOTLPTracing(ctx context.Context) (*sdktrace.TracerProvider, error) { @@ -139,7 +172,8 @@ func ConfigureOTLPTracing(ctx context.Context) (*sdktrace.TracerProvider, error) } tp := sdktrace.NewTracerProvider( sdktrace.WithSpanProcessor(sdktrace.NewBatchSpanProcessor(exp)), - sdktrace.WithSampler(sdktrace.AlwaysSample()), + tracing.WithIDGenerator(nil), + tracing.WithSampler(sdktrace.ParentBased(sdktrace.AlwaysSample())), sdktrace.WithResource(resource.NewWithAttributes( "durabletask.io", attribute.String("service.name", "distributedtracing-sample"), diff --git a/tests/durabletaskscheduler/dts_tracing_enabled_test.go b/tests/durabletaskscheduler/dts_tracing_enabled_test.go new file mode 100644 index 00000000..4d0a32b0 --- /dev/null +++ b/tests/durabletaskscheduler/dts_tracing_enabled_test.go @@ -0,0 +1,218 @@ +package durabletaskscheduler_test + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/google/uuid" + "github.com/microsoft/durabletask-go/api" + durabletaskclient "github.com/microsoft/durabletask-go/client" + "github.com/microsoft/durabletask-go/durabletaskscheduler" + "github.com/microsoft/durabletask-go/task" + "github.com/microsoft/durabletask-go/tests/tracingtree" + "github.com/microsoft/durabletask-go/tracing" + "github.com/stretchr/testify/require" + "go.opentelemetry.io/otel/codes" + sdktrace "go.opentelemetry.io/otel/sdk/trace" + "go.opentelemetry.io/otel/sdk/trace/tracetest" + "go.opentelemetry.io/otel/trace" +) + +// This uses an explicit provider without changing the global provider used by +// the disabled-mode tests in dts_tracing_tree_test.go. +func TestDTSEmulatorTracingEnabledTreeAndEntityRoots(t *testing.T) { + options := emulatorOptions(t) + exporter := tracetest.NewInMemoryExporter() + provider := sdktrace.NewTracerProvider( + tracing.WithIDGenerator(nil), + tracing.WithSampler(nil), + sdktrace.WithSyncer(exporter), + ) + t.Cleanup(func() { require.NoError(t, provider.Shutdown(context.Background())) }) + + entityID := api.NewEntityID("DTSEnabledEntity", uuid.NewString()) + registry := task.NewTaskRegistry() + require.NoError(t, registry.AddEntityN(entityID.Name, func(ctx *task.EntityContext) (any, error) { + if ctx.Operation == "fail" { + return nil, errors.New("traced entity failure") + } + return "entity", nil + })) + require.NoError(t, registry.AddActivityN("DTSEnabledEcho", func(task.ActivityContext) (any, error) { + return "echo", nil + })) + require.NoError(t, registry.AddOrchestratorN("DTSEnabledChild", func(ctx *task.OrchestrationContext) (any, error) { + var result string + err := ctx.CallActivity("DTSEnabledEcho").Await(&result) + return result, err + })) + require.NoError(t, registry.AddOrchestratorN("DTSEnabledReceiver", func(ctx *task.OrchestrationContext) (any, error) { + var result string + err := ctx.WaitForSingleEvent("ping", time.Minute).Await(&result) + return result, err + })) + require.NoError(t, registry.AddOrchestratorN("DTSEnabledParent", func(ctx *task.OrchestrationContext) (any, error) { + var receiver api.InstanceID + if err := ctx.GetInput(&receiver); err != nil { + return nil, err + } + var child string + if err := ctx.CallSubOrchestrator("DTSEnabledChild", + task.WithSubOrchestrationInstanceID(string(ctx.ID)+"_child")).Await(&child); err != nil { + return nil, err + } + if err := ctx.CreateTimer(10 * time.Millisecond).Await(nil); err != nil { + return nil, err + } + var proceed string + if err := ctx.WaitForSingleEvent("proceed", time.Minute).Await(&proceed); err != nil { + return nil, err + } + if err := ctx.SendEvent(receiver, "ping", "pong"); err != nil { + return nil, err + } + if err := ctx.SignalEntity(entityID, "signal"); err != nil { + return nil, err + } + var entity string + if err := ctx.CallEntity(entityID, "get").Await(&entity); err != nil { + return nil, err + } + if err := ctx.CallEntity(entityID, "fail").Await(nil); err == nil { + return nil, errors.New("expected entity call failure") + } + return child + "+" + proceed + "+" + entity, nil + })) + + ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second) + defer cancel() + managementClient, err := durabletaskscheduler.NewClient(ctx, options, api.DefaultLogger(), + durabletaskclient.WithTracerProvider(provider)) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, managementClient.Close()) }) + worker, err := durabletaskscheduler.NewWorker(options, registry, api.DefaultLogger(), + durabletaskclient.WithAutoWorkItemFilters(), + durabletaskclient.WithWorkerTracerProvider(provider)) + require.NoError(t, err) + require.NoError(t, worker.Start(ctx)) + t.Cleanup(func() { + shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 10*time.Second) + defer shutdownCancel() + require.NoError(t, worker.Shutdown(shutdownCtx)) + }) + + receiverID, err := managementClient.ScheduleNewOrchestration(ctx, "DTSEnabledReceiver", + api.WithInstanceID(uniqueInstanceID("go-enabled-receiver"))) + require.NoError(t, err) + callerCtx, caller := provider.Tracer("dts-enabled-test").Start(ctx, "caller/enabled") + parentID, err := managementClient.ScheduleNewOrchestration(callerCtx, "DTSEnabledParent", + api.WithInstanceID(uniqueInstanceID("go-enabled-parent")), api.WithInput(receiverID)) + require.NoError(t, err) + require.NoError(t, managementClient.SignalEntity(callerCtx, entityID, "clientSignal")) + caller.End() + _, err = managementClient.WaitForOrchestrationStart(ctx, parentID) + require.NoError(t, err) + require.NoError(t, managementClient.RaiseEvent(callerCtx, parentID, "proceed", api.WithEventPayload("go"))) + + parent, err := managementClient.WaitForOrchestrationCompletion(ctx, parentID, api.WithFetchPayloads(true)) + require.NoError(t, err) + require.Equal(t, api.RUNTIME_STATUS_COMPLETED, parent.RuntimeStatus) + require.Equal(t, `"echo+go+entity"`, parent.SerializedOutput) + receiver, err := managementClient.WaitForOrchestrationCompletion(ctx, receiverID, api.WithFetchPayloads(true)) + require.NoError(t, err) + require.Equal(t, api.RUNTIME_STATUS_COMPLETED, receiver.RuntimeStatus) + require.Equal(t, `"pong"`, receiver.SerializedOutput) + + // Completion can become visible to the client just before the worker exports + // its accepted response. Multiple dispatches must not duplicate replay spans. + require.Eventually(t, func() bool { return len(exporter.GetSpans()) == 19 }, + 10*time.Second, 20*time.Millisecond, "exported spans: %s", + tracingtree.Describe(exporter.GetSpans().Snapshots())) + spans := exporter.GetSpans().Snapshots() + find := func(name string, kind trace.SpanKind) sdktrace.ReadOnlySpan { + t.Helper() + var matches []sdktrace.ReadOnlySpan + for _, span := range spans { + if span.Name() == name && span.SpanKind() == kind { + matches = append(matches, span) + } + } + require.Len(t, matches, 1, "expected one %s %s; spans: %s", kind, name, tracingtree.Describe(spans)) + span := matches[0] + require.True(t, span.SpanContext().IsSampled()) + require.False(t, span.StartTime().IsZero()) + require.False(t, span.EndTime().Before(span.StartTime())) + if name != "caller/enabled" { + require.Equal(t, "durabletask", span.InstrumentationScope().Name) + } + return span + } + childOf := func(child, parent sdktrace.ReadOnlySpan) { + t.Helper() + require.Equal(t, parent.SpanContext().TraceID(), child.SpanContext().TraceID(), child.Name()) + require.Equal(t, parent.SpanContext().SpanID(), child.Parent().SpanID(), child.Name()) + } + callerSpan := find("caller/enabled", trace.SpanKindInternal) + create := find("create_orchestration:DTSEnabledParent", trace.SpanKindProducer) + childOf(create, callerSpan) + orchestration := find("orchestration:DTSEnabledParent", trace.SpanKindServer) + childOf(orchestration, create) + childClient := find("orchestration:DTSEnabledChild", trace.SpanKindClient) + childOf(childClient, orchestration) + childServer := find("orchestration:DTSEnabledChild", trace.SpanKindServer) + childOf(childServer, childClient) + activityClient := find("activity:DTSEnabledEcho", trace.SpanKindClient) + childOf(activityClient, childServer) + childOf(find("activity:DTSEnabledEcho", trace.SpanKindServer), activityClient) + childOf(find("orchestration:DTSEnabledParent:timer", trace.SpanKindInternal), orchestration) + childOf(find("orchestration_event:proceed", trace.SpanKindProducer), callerSpan) + childOf(find("orchestration_event:ping", trace.SpanKindProducer), orchestration) + receiverCreate := find("create_orchestration:DTSEnabledReceiver", trace.SpanKindProducer) + require.False(t, receiverCreate.Parent().IsValid()) + childOf(find("orchestration:DTSEnabledReceiver", trace.SpanKindServer), receiverCreate) + + clientSignal := "entity:" + entityID.Name + ":clientSignal" + for _, span := range spans { + require.False(t, span.Name() == clientSignal && span.SpanKind() == trace.SpanKindProducer, + "client SignalEntity propagates caller context without emitting a span") + } + clientSignalExecution := find(clientSignal, trace.SpanKindConsumer) + require.False(t, clientSignalExecution.Parent().IsValid(), "V2 entity executions must be independent roots") + require.NotEqual(t, caller.SpanContext().TraceID(), clientSignalExecution.SpanContext().TraceID()) + + for _, operation := range []struct { + name string + send, execute trace.SpanKind + attribute string + status codes.Code + }{ + {"signal", trace.SpanKindProducer, trace.SpanKindConsumer, "signal_entity", codes.Ok}, + {"get", trace.SpanKindClient, trace.SpanKindServer, "call_entity", codes.Ok}, + {"fail", trace.SpanKindClient, trace.SpanKindServer, "call_entity", codes.Error}, + } { + name := "entity:" + entityID.Name + ":" + operation.name + send := find(name, operation.send) + childOf(send, orchestration) + execute := find(name, operation.execute) + require.False(t, execute.Parent().IsValid(), "V2 entity executions must be independent roots") + require.NotEqual(t, caller.SpanContext().TraceID(), execute.SpanContext().TraceID()) + require.Empty(t, execute.Links(), "V2 has no propagated parent or synthetic request-ID link") + require.Equal(t, operation.status, execute.Status().Code) + for _, span := range []sdktrace.ReadOnlySpan{send, execute} { + attrs := make(map[string]string) + for _, attr := range span.Attributes() { + attrs[string(attr.Key)] = attr.Value.AsString() + } + require.Equal(t, operation.attribute, attrs["durabletask.task.operation"]) + } + if operation.status == codes.Error { + require.Equal(t, codes.Error, send.Status().Code) + require.Contains(t, execute.Status().Description, "traced entity failure") + } + } + // Every exported span was accounted for above; event receipt emits no + // CONSUMER span and does not reparent the receiving orchestration. + require.Len(t, spans, 19) +} diff --git a/tests/tracingtree/tracingtree.go b/tests/tracingtree/tracingtree.go index 4e112ed9..66698884 100644 --- a/tests/tracingtree/tracingtree.go +++ b/tests/tracingtree/tracingtree.go @@ -1,7 +1,8 @@ // Package tracingtree provides the application-process OpenTelemetry plumbing // used by the Durable Task Scheduler tracing tests: a process-wide in-memory // exporter and the caller span whose W3C context the SDK propagates to DTS. -// Durable operation spans are emitted by DTS service-side, not by the Go worker. +// Without explicit tracing options, durable operation spans are emitted by DTS +// service-side, not by the Go worker. package tracingtree import ( diff --git a/tracing/README.md b/tracing/README.md new file mode 100644 index 00000000..7b792194 --- /dev/null +++ b/tracing/README.md @@ -0,0 +1,141 @@ +# Replay-aware OpenTelemetry tracing + +Durable Task clients and workers **only propagate W3C context by default**. +Opt-in tracing exports durable operation spans through the application's +OpenTelemetry provider, alongside its ordinary application spans. It does not +require a scheduler-specific telemetry exporter. + +## Enable tracing + +Configure the worker's OpenTelemetry SDK provider with **both** wrappers: + +```go +provider := sdktrace.NewTracerProvider( + tracing.WithIDGenerator(nil), + tracing.WithSampler(sdktrace.ParentBased(sdktrace.AlwaysSample())), + sdktrace.WithBatcher(exporter), + sdktrace.WithResource(applicationResource), +) +worker, err := durabletaskscheduler.NewWorker(options, registry, logger, + client.WithWorkerTracerProvider(provider)) +managementClient, err := durabletaskscheduler.NewClient(ctx, options, logger, + client.WithTracerProvider(provider)) +``` + +Check both constructor errors. `client.WithTracerProvider` can use any tracer +provider, but `client.WithWorkerTracerProvider` rejects a provider missing either +wrapper with `tracing.ErrUnsupportedTracerProvider`. The ID generator honors +persisted span identities during reconstruction; ordinary application spans +still use its base generator. The sampler supports sampling queries without +creating live spans. Pass a custom generator or sampler into these wrappers +instead of replacing them with `sdktrace.WithIDGenerator` or +`sdktrace.WithSampler`. + +The application owns resources, processors, exporter, flushing, and provider +shutdown. Stop the worker before flushing/shutting down the provider. +`otel.SetTracerProvider(provider)` is optional for Durable Task, but useful for +application instrumentation that uses the global provider. See the +[distributed tracing sample](../samples/distributedtracing) for a complete +OTLP/HTTP collector setup and collector-receipt verification. + +## Spans and lifecycle + +All SDK spans use the `durabletask` instrumentation scope. Task names use +`:@()`, omitting the version suffix when unversioned. +Entity names use the lowercase form from `EntityID.String`. + +| Operation | Span name | Kind and parent | +| --- | --- | --- | +| Client schedules orchestration | `create_orchestration:` | PRODUCER under caller | +| Orchestration execution | `orchestration:` | SERVER under create span, or propagated caller when client tracing is disabled | +| 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 | +| Sub-orchestration execution | `orchestration:` | SERVER under scheduling span | +| Durable timer | `orchestration::timer` | INTERNAL under orchestration | +| Client raises event | `orchestration_event:` | PRODUCER under caller | +| Orchestrator sends event | `orchestration_event:` | PRODUCER under sending orchestration | +| Orchestrator signals entity | `entity::` | PRODUCER under orchestration | +| Orchestrator calls entity | `entity::` | CLIENT under orchestration | +| Entity signal execution | `entity::` | CONSUMER, independent root | +| Entity call execution | `entity::` | SERVER, independent root | + +Orchestration spans are reconstructed with persisted identity and start time +when an execution completes, fails, terminates, or continues as new. Activities +are live spans, so HTTP/database/application spans can nest under them. +Scheduling and timer spans are reconstructed from history when a dispatch +consuming the completion is accepted. Orchestrator event/entity signals export +after their sending dispatch is accepted. Entity executions export after an +accepted batch with operation-result timestamps and error status. + +Replayed history emits no new spans. Orchestration and entity execution spans +are not live inside their handlers; starting an application span from an +orchestrator does not automatically make it replay-safe. + +Attributes include `durabletask.type`, task name/version, instance ID, and +operation-specific status, execution/task IDs, or timer fire time. Entity spans +follow **DurableTask.Core** names and kinds, including +`durabletask.task.operation=signal_entity` or `call_entity`, rather than +introducing a new Go-only convention. Failures are marked with error status. + +Without caller context, an orchestration starts a trace derived from its +persisted identity. Sampling follows propagated trace flags, preserves +tracestate, and keeps unsampled orchestration trees unsampled. Root sampling is +queried again on each dispatch: use a sampler with a stable decision based on +the trace ID, such as the built-in parent-based/trace-ID-ratio samplers. +Continue-as-new and rewind start a new orchestration span identity. + +## SDK parity + +This comparison concerns application-process tracing in +[durabletask-python](https://github.com/microsoft/durabletask-python/blob/main/durabletask/internal/tracing.py) +and the +[durabletask-dotnet gRPC SDK](https://github.com/microsoft/durabletask-dotnet/blob/main/src/Shared/Grpc/Tracing/TraceHelper.cs), +not Azure Functions host or scheduler-service telemetry. + +| Feature | Go (enabled) | Python | .NET gRPC | +| --- | --- | --- | --- | +| Application provider/exporter integration | OpenTelemetry SDK provider; OTLP or another exporter | OpenTelemetry provider | `ActivitySource` via application OpenTelemetry | +| Client create orchestration / raise event | PRODUCER | PRODUCER | PRODUCER | +| Replay-aware orchestration execution | Reconstructed SERVER | Deferred SERVER | Reconstructed SERVER | +| Activity and sub-orchestration scheduling/execution | CLIENT / SERVER | CLIENT / SERVER | CLIENT / SERVER | +| Durable timers | INTERNAL | INTERNAL | INTERNAL | +| Orchestrator event send | PRODUCER | PRODUCER | PRODUCER | +| Event receipt consumer / sender-to-receiver trace join | Not available | Not available | Not available | +| Entity signal/call and operation execution | DurableTask.Core PRODUCER/CLIENT and CONSUMER/SERVER | Not implemented | Not implemented | +| Client entity signal | No span; sampled caller context propagated | None | No span; caller context propagated | +| Entity lock acquisition/release | No spans | No spans | No spans | +| Persisted span reconstruction integration | Public SDK ID-generator/sampler wrappers | Deferred spans via OTel SDK internals | `Activity` reconstruction helpers | + +Entity tracing matches the +[DurableTask.Core reference](https://github.com/Azure/durabletask/tree/main/src/DurableTask.Core/Tracing); +it is beyond the current Python and .NET gRPC tracing surfaces, not a claim that +those SDKs emit entity spans. + +## Limitations + +- Event messages have no trace context. Receipt emits no CONSUMER span, and + sending an event does not reparent or link the receiving orchestration. +- V2 entity operations have no propagated parent trace context. Execution spans + are independent roots sampled by the provider's root policy, not a joined + orchestration/entity tree. There are no synthetic request-ID links. +- Telemetry is **not exactly-once**. Abandoned dispatches emit no reconstructed + orchestration telemetry, but a successfully accepted completion retried by the + backend can export again. Live activity spans describe attempts, even when a + result is not accepted. +- Reconstruction requires the backend to return persisted orchestration trace + identity on subsequent dispatches. Service-side telemetry remains separate + and may overlap in operation names with enabled application-process spans. + +## End-to-end coverage + +`tests/durabletaskscheduler/dts_tracing_enabled_test.go` uses an explicit provider +and an in-memory exporter to assert client/orchestration/activity/sub-orchestration/ +timer/event parentage and independent entity roots, including entity failures +and a client signal that emits no client-side span. +The existing disabled-mode tests continue to assert propagation without SDK span +emission. + +Run these against a DTS emulator with `DTS_EMULATOR_ENDPOINT` or a configured +`DTS_CONNECTION_STRING`. They skip when neither is set. PR validation supplies +the pinned DTS emulator endpoint. diff --git a/tracing/tracing.go b/tracing/tracing.go index 1a66811a..4f613e79 100644 --- a/tracing/tracing.go +++ b/tracing/tracing.go @@ -1,6 +1,9 @@ // Package tracing configures opt-in OpenTelemetry spans for Durable Task // clients and workers. // +// The tracing README contains the span catalog, OTLP sample, and a parity +// comparison with durabletask-python and durabletask-dotnet's gRPC SDK. +// // By default clients and workers only propagate W3C trace context and emit no // spans. Enable worker spans with client.WithWorkerTracerProvider and a // provider built with [WithIDGenerator] and [WithSampler]: From d76c179a5c6f82a78642cd2337a65d0a427ef3ba Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Mon, 23 Nov 2026 13:08:13 -0700 Subject: [PATCH 2/2] Clarify tracing docs, parity, and enabled E2E coverage Document that DTS doesn't emit durable spans, logical versus execution-turn spans, and duplicate-source guidance. Add a durabletask-js column and the enablement, scope, root, export-timing, and status rows to the parity table, and correct the Python and JavaScript entity rows. Reconcile the changelog. Extend the enabled DTS E2E test with the Microsoft.DurableTask scope, unset success status, entity operation and integer task ID attributes, an activity failure, a continue-as-new generation pair, an application span under an entity operation, and a late-duplicate guard. The sample now uses a default resource, checks span kinds on receipt, and points readers at OTLP backends. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 9 +- README.md | 124 +++++--- samples/README.md | 2 +- samples/distributedtracing/README.md | 19 +- .../distributedtracing/distributedtracing.go | 112 +++++-- .../distributedtracing_test.go | 28 +- samples/observability/README.md | 4 +- .../dts_tracing_enabled_test.go | 167 ++++++++-- .../dts_tracing_tree_test.go | 2 +- tests/tracingtree/tracingtree.go | 9 +- tracing/README.md | 288 +++++++++++------- tracing/tracing.go | 22 +- 12 files changed, 543 insertions(+), 243 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f409bf62..262725a1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,10 +43,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Added benchmarks for analyzer scaling and allocations across orchestrator count and call-graph depth, for `task.TaskRegistry` orchestrator, activity, versioned, snapshot, and concurrent lookups, and for client work-item filter construction, wire conversion, validation, and per-work-item matching. - Added the preview top-level `exporthistory` package, which exports terminal orchestration histories to Azure Blob Storage as gzip-compressed JSONL. It provides a public client for creating, getting, listing, and per-job create/describe/delete operations; batch and continuous jobs; the `ExportJob` durable entity with `Pending`/`Active`/`Failed`/`Completed` lifecycle transitions; durable checkpoints; terminal-status filters; a per-batch instance limit; per-instance failure collection with implicit job failure when a checkpoint batch fails; delete-and-recreate rules; and typed validation, not-found, invalid-transition, and operation errors carrying stable cross-language error types. Each `Create` mints a nonempty run-generation token and reserves a generation-specific orchestration ID before signaling Run. Only the current generation can mutate job state, though older work may briefly remain in flight. Recreation performs no destructive cleanup and retains previous generations' histories. `Delete` atomically captures the removed generation's ID, and client cleanup targets only that typed result, preserving concurrent recreations even with custom data converters. Read `ExportJobDescription.OrchestratorInstanceID` instead of the removed job-name-only `GetOrchestratorInstanceID` helper. Legacy export-job state and mixed .NET/older Go export workers are not supported. Exported objects are stored as opaque gzip files, named `.jsonl.gz` with content type `application/gzip` and no `Content-Encoding`, so a reader always receives exactly the bytes the object name promises. The system entity, orchestrators, and activities are registered unversioned, and `exporthistory.WithExportHistory()` keeps them routable under strict worker versioning. Destination writes go through a narrow `exporthistory.Store` interface with a production `AzureBlobHistoryStore` implementation that validates containers and prefixes, rejects account URLs carrying userinfo, a query string, or a fragment, and creates each container once. The package is preview: its API, the serialized `ExportJob` state, and its system task names may change without a major version bump, and extended sessions remain unsupported. - Added `client.WithUnversionedActivityNames` and `task.WithUnversionedActivityNames`, the activity counterparts of the existing unversioned-orchestrator allow-lists. An activity inherits its caller's version, so a system component whose orchestration runs unversioned schedules unversioned activities that a strict-version worker would otherwise refuse to accept and would advertise under its own version. -- Added opt-in, replay-aware OpenTelemetry spans for orchestrations, activities, sub-orchestrations, and timers via `client.WithWorkerTracerProvider`, using the `Microsoft.DurableTask` instrumentation scope. The provider must use `tracing.WithIDGenerator` and `tracing.WithSampler`; otherwise the option fails with `tracing.ErrUnsupportedTracerProvider`. Span export is best effort, not exactly once. Default behavior is unchanged: the worker only propagates W3C trace context. +- Added opt-in, replay-aware OpenTelemetry spans for orchestrations, activities, sub-orchestrations, and timers via `client.WithWorkerTracerProvider`, using the `Microsoft.DurableTask` instrumentation scope. The provider must use `tracing.WithIDGenerator` and `tracing.WithSampler`; otherwise the option fails with an error that wraps `tracing.ErrUnsupportedTracerProvider` and names the failed check. Each orchestration execution exports one logical `orchestration:` SERVER span, reconstructed with its persisted identity after the backend accepts the execution's completion; replays and individual dispatches emit no spans. Durable Task Scheduler persists and forwards trace context but doesn't emit durable spans, so SDK tracing is the supported way to get them into an application's backend. Telemetry is best effort in both directions: retried or redelivered work can export duplicate spans, and spans can be lost when the backend accepts a completion but its reply is lost. Without the option, the worker only propagates W3C trace context. - Added opt-in client PRODUCER spans via `client.WithTracerProvider`, which accepts any provider: `create_orchestration:[@()]` for `ScheduleNewOrchestration`, parenting the new orchestration, and `orchestration_event:` for `RaiseEvent`. `durabletaskscheduler.NewClient` accepts trailing `client.TaskHubGrpcClientOption` values. -- With worker tracing enabled, `OrchestrationContext.SendEvent` emits an `orchestration_event:` PRODUCER span under the sending orchestration's span when the dispatch is accepted; replayed sends emit nothing. Event receipt emits no span because the event protocol carries no trace context. -- With worker tracing enabled, entities emit `entity::` spans with `durabletask.task.operation` (`call_entity` or `signal_entity`) and `durabletask.entity.operation` attributes. Entity operation executions emit SERVER (call) or CONSUMER (signal) spans that are exported only after the backend accepts the batch completion; each operation's span context is available to its handler through `EntityContext.Context()` and is stamped on the signals and orchestrations it starts. Orchestrations emit CLIENT spans for entity calls and PRODUCER spans for entity signals. Lock operations emit no spans. Entity execution spans are independent trace roots because V2 entity messages carry no trace context. +- With worker tracing enabled, `OrchestrationContext.SendEvent` emits an `orchestration_event:` PRODUCER span under the sending orchestration's span when the dispatch is accepted; replayed sends emit nothing. A new send whose acknowledgement arrives in the same dispatch is exported with that dispatch. Event receipt emits no span because the event protocol carries no trace context. +- With worker tracing enabled, entities emit `entity::` spans with `durabletask.task.operation` (`call_entity` or `signal_entity`) and `durabletask.entity.operation` attributes. Entity operation executions emit SERVER (call) or CONSUMER (signal) spans that are exported only after the backend accepts the batch completion; each operation's span context is available to its handler through `EntityContext.Context()`, so application spans started from it nest under the operation span. The signals and orchestrations an operation starts carry that context, but Durable Task Scheduler doesn't currently forward it. Successful entity operations leave the span status unset. Orchestrations emit CLIENT spans for entity calls and PRODUCER spans for entity signals. Lock operations emit no spans. Entity execution spans are independent trace roots because V2 entity messages carry no trace context. +- Added the [tracing guide](tracing/README.md), with the span catalog, logical orchestration spans, service-side telemetry and duplicate guidance, limitations, and a tracing parity table for the .NET, Python, and JavaScript SDKs. Added an enabled-tracing DTS emulator test, and the `distributedtracing` sample now exports SDK durable spans and application spans to an OTLP collector. ### Removed @@ -118,7 +119,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `durabletaskscheduler` identity fields are now trimmed for every authentication mode, and blank `AdditionallyAllowedTenants` entries are dropped. Previously only `ManagedIdentity` trimmed `ClientID`, so padded values reached Azure Identity verbatim. - `durabletaskscheduler` token scopes now trim whitespace and all trailing slashes from `Options.ResourceID`. Previously only one trailing slash was removed and untrimmed values produced a malformed scope. - The owned DTS management client now observes both unary and streaming RPC outcomes for channel recreation. Caller cancellation, caller deadlines, and expected instance-wait deadlines are neutral and no longer reset or poison an existing transport-failure streak. -- `TaskHubGrpcClient.ScheduleNewOrchestration` now sends the caller's W3C trace context on `CreateInstanceRequest`, so the service can parent the `create_orchestration` span to it. Previously every orchestration scheduled over gRPC or the Durable Task Scheduler began a disconnected root trace instead of joining the caller's trace. +- `TaskHubGrpcClient.ScheduleNewOrchestration` now sends the caller's W3C trace context on `CreateInstanceRequest`, so the orchestration and its durable work join the caller's trace. Previously every orchestration scheduled over gRPC or the Durable Task Scheduler began a disconnected root trace instead of joining the caller's trace. - `ContinueAsNew` with `task.WithKeepUnprocessedEvents` no longer drops an external event that arrives in the same work item after the orchestrator returns while a `WaitForSingleEvent` for that name is still pending, such as the loser of a `WhenAny` with a timer. Previously the event completed the unreachable wait and was missing from the next execution. Applications that re-sent such events to work around the loss can now see both copies. A failed or terminated completion no longer carries events forward when `ContinueAsNew` was called earlier in the turn. - Rejected rewind histories now identify the Go SDK's history-rewrite limitation instead of implying that DTS does not support rewind. The shared unsupported-feature error message is neutral about the source of the limitation; `errors.Is(err, api.ErrFeatureNotSupported)` and rewind safety checks are unchanged. diff --git a/README.md b/README.md index fc04507c..9885d786 100644 --- a/README.md +++ b/README.md @@ -50,7 +50,7 @@ Use these features for large systems or for special conditions. | Data converters | Replace the default JSON serialization of your payloads. | | Large payloads | Keep large payloads in Azure Blob Storage and send a reference token. | | Tags and trace context | Attach user tags to actions. Send the caller trace context to DTS. | -| [Distributed tracing](./tracing/README.md) | Opt in to replay-aware client and worker OpenTelemetry spans through your application's provider. | +| [Distributed tracing](./tracing/README.md) | Opt in to replay-aware client and worker OpenTelemetry spans through your application's provider. DTS doesn't emit durable spans itself. | | Replay-hazard analysis | Find nondeterministic orchestrator code with `cmd/orchestratorvet`. | | History export (preview) | Copy terminal orchestration histories to Azure Blob Storage. | @@ -530,7 +530,7 @@ Activity contexts expose the activity's own name, version, and task ID in from native history fields, including after sub-orchestration starts and ContinueAsNew version changes. -The client sends the sampled caller trace context when it schedules an orchestration or signals an entity. By default, the worker propagates action trace contexts without emitting local Durable Task spans. Opt-in tracing adds replay-aware client and worker spans through your application's provider. V2 entity requests do not carry per-operation trace context, so entity execution spans are independent roots. +The client sends the sampled caller trace context when it schedules an orchestration or signals an entity. By default, the worker propagates action trace contexts without emitting Durable Task spans. DTS persists and forwards trace context but doesn't emit durable spans either. Opt-in tracing adds replay-aware client and worker spans through your application's provider. V2 entity requests do not carry per-operation trace context, so entity execution spans are independent roots. Use `task.OrchestrationOptions.MaxEventsPerTurn` to limit the new events in one turn. If the worker uses only part of a batch, it sets `numEventsProcessed`. DTS then keeps the remaining events for the next replay. This count obeys the DTS work-item rules. The orchestration control markers do not count against the limit. @@ -555,75 +555,109 @@ accounts. See [large payload configuration](./durabletaskscheduler/README.md#lar ## Distributed tracing -Tracing is opt-in. Without tracing options, the SDK propagates W3C context but -emits no local durable-operation spans. Enable client PRODUCER spans and -replay-aware worker spans using an application-owned OpenTelemetry provider: +Tracing is opt-in. Without tracing options, the SDK propagates W3C trace context +but emits no spans. DTS persists and forwards that context, but it doesn't emit +durable orchestration, activity, or timer spans or export spans to your +backend. To see durable spans next to your application telemetry, enable SDK +tracing with an OpenTelemetry provider that your application owns: ```go func ConfigureOTLPTracing(ctx context.Context) (*sdktrace.TracerProvider, error) { - exp, err := otlptracehttp.New( - ctx, + exp, err := otlptracehttp.New(ctx, otlptracehttp.WithEndpoint("localhost:4318"), otlptracehttp.WithInsecure(), ) if err != nil { return nil, err } + res, err := resource.New(ctx, + resource.WithAttributes(semconv.ServiceName("sample-app")), + resource.WithFromEnv(), + resource.WithTelemetrySDK(), + ) + if err != nil { + return nil, err + } tp := sdktrace.NewTracerProvider( sdktrace.WithBatcher(exp), tracing.WithIDGenerator(nil), tracing.WithSampler(sdktrace.ParentBased(sdktrace.AlwaysSample())), - sdktrace.WithResource(resource.NewWithAttributes( - "durabletask.io", - attribute.KeyValue{Key: "service.name", Value: attribute.StringValue("sample-app")}, - )), + sdktrace.WithResource(res), ) otel.SetTracerProvider(tp) return tp, nil } ``` -Use the configured provider for each surface you want to enable: +Pass the provider to each surface you want to trace, and shut down in order: +the worker, then the client, then the provider. ```go -tp, err := ConfigureOTLPTracing(ctx) -if err != nil { - return err -} -worker, err := durabletaskscheduler.NewWorker(options, registry, logger, - durabletaskclient.WithWorkerTracerProvider(tp)) -if err != nil { - return err -} -managementClient, err := durabletaskscheduler.NewClient(ctx, options, logger, - durabletaskclient.WithTracerProvider(tp)) -if err != nil { - return err +func run(ctx context.Context) (err error) { + tp, err := ConfigureOTLPTracing(ctx) + if err != nil { + return err + } + defer func() { + shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + err = errors.Join(err, tp.Shutdown(shutdownCtx)) + }() + + worker, err := durabletaskscheduler.NewWorker(options, registry, logger, + durabletaskclient.WithWorkerTracerProvider(tp)) + if err != nil { + return err + } + managementClient, err := durabletaskscheduler.NewClient(ctx, options, logger, + durabletaskclient.WithTracerProvider(tp)) + if err != nil { + return err + } + defer func() { err = errors.Join(err, managementClient.Close()) }() + if err := worker.Start(ctx); err != nil { + return err + } + defer func() { + shutdownCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + err = errors.Join(err, worker.Shutdown(shutdownCtx)) + }() + + // Schedule and wait for orchestrations. + return nil } ``` -Check constructor errors and configure **both** tracing wrappers on the worker -provider. They reconstruct completed spans with persisted identities and -consistent sampling decisions across replay; providers missing either are -rejected. The application owns the provider and should stop workers before -flushing/shutting it down. - -The tree includes caller -> create orchestration PRODUCER -> orchestration -SERVER -> activity/sub-orchestration CLIENT -> execution SERVER, plus timer -INTERNAL and event-send PRODUCER spans. Activity spans are active in -`ActivityContext.Context()`, so application HTTP/database spans nest under them. -Replayed history emits no new spans, but telemetry is not exactly-once. - -Entity spans follow DurableTask.Core semantics. V2 entity execution spans are -independent roots because operations carry no parent context. Events have no -receipt CONSUMER span or sender-to-receiver trace join. Service telemetry is -configured separately from these application-process spans. - -The [tracing guide](./tracing/README.md) includes the full span catalog and -Python/.NET gRPC parity table. The +Deferred calls run in reverse order, so the worker shuts down first, the client +closes next, and the provider flushes last. The worker provider must use +**both** tracing wrappers. They let the worker reconstruct completed spans with +persisted identities and consistent sampling decisions across replay. The worker +rejects a provider that is missing either wrapper with an error that wraps +`tracing.ErrUnsupportedTracerProvider`. + +The trace tree is caller -> create orchestration PRODUCER -> orchestration +SERVER -> activity or sub-orchestration CLIENT -> execution SERVER, plus timer +INTERNAL and event-send PRODUCER spans. Each orchestration execution has one +logical span that's exported when the execution finishes, not one span per +replay. Activity spans are active in `ActivityContext.Context()`, so your HTTP +and database spans nest under them. Telemetry is best effort in both +directions: retried or redelivered work can export duplicate spans, and spans +can be lost if a completion is accepted but its reply is lost. + +Entity spans follow DurableTask.Core names and kinds. V2 entity execution spans +are independent roots because entity operations carry no parent context. Event +receipt emits no CONSUMER span and doesn't join the sender's trace. If another +component also emits durable spans for the same work into your backend, enable +only one source. + +The [tracing guide](./tracing/README.md) has the full span catalog, the +difference between logical and execution-turn spans, the limitations, and a +parity table for the .NET, Python, and JavaScript SDKs. The [distributed tracing sample](./samples/distributedtracing) exports durable and -application HTTP spans to a real OTLP collector and verifies their receipt. +application HTTP spans to a real OTLP collector and verifies that the collector +received them. ## History export (preview) diff --git a/samples/README.md b/samples/README.md index fe796ea6..93eb41ed 100644 --- a/samples/README.md +++ b/samples/README.md @@ -29,7 +29,7 @@ operation is not evidence that a feature works end to end. | [observability](observability) | Tags/context, replay-safe logs and metric hooks | None | | [worker](worker) | Concurrency, graceful drain, restart/recovery and connection ownership | None | | [authentication](authentication) | Azure connection-string and programmatic identity authentication | Azure DTS and an authorized identity | -| [distributedtracing](distributedtracing) | Application spans, caller propagation and actual OTLP receipt | OTLP collector and readable trace capture | +| [distributedtracing](distributedtracing) | Opt-in SDK durable spans, application spans, caller propagation and actual OTLP receipt | OTLP collector and readable trace capture | | [exporthistory](exporthistory) | Export jobs and downloaded JSON/JSONL objects | Blob storage and an explicitly isolated Go-only hub | | [replayanalysis](replayanalysis) | Analyzer diagnostics and safe runnable counterparts | Local `cmd/orchestratorvet` sources | | [serviceoperations](serviceoperations) | Hub-wide filtered purge and empty-entity maintenance | Deletes data; read the sample's warning | diff --git a/samples/distributedtracing/README.md b/samples/distributedtracing/README.md index 20c9999c..12127fd1 100644 --- a/samples/distributedtracing/README.md +++ b/samples/distributedtracing/README.md @@ -11,8 +11,8 @@ application's OpenTelemetry provider, OTLP/HTTP, and a real collector. PRODUCER spans with `client.WithTracerProvider`. - Exports orchestration, activity scheduling/execution, timer, and application spans over OTLP/HTTP to a collector. -- Verifies the collector file exporter received these spans under the caller's - trace ID. +- Verifies that the collector file exporter received these spans, with their + expected span kinds, under the caller's trace ID. - Reads DTS history and verifies persisted trace context shares the caller trace. Tracing remains disabled unless explicitly enabled. The sample configures its @@ -29,9 +29,18 @@ when it finishes and durable scheduling/timer spans after accepted completions, not on every replay. The application flushes the provider after worker shutdown and owns its final shutdown. -These are application-process spans, separate from any scheduler-service -telemetry. See the [tracing guide](../../tracing/README.md) for span semantics, -SDK parity, and delivery/propagation limitations. +DTS persists and forwards trace context but doesn't emit durable spans, so these +SDK spans are how durable work reaches your telemetry backend. They use the +`Microsoft.DurableTask` instrumentation scope and the provider's resource. See +the [tracing guide](../../tracing/README.md) for span semantics, SDK parity, +and delivery and propagation limitations. + +The collector in this sample writes spans to a file so the sample can verify +them. To view the spans, add an exporter to the collector's `traces` pipeline +for Jaeger, Azure Monitor, or any other OTLP-compatible backend. You can also +point `OTEL_EXPORTER_OTLP_ENDPOINT` straight at a backend that accepts +OTLP/HTTP, but then the sample's receipt check fails because it reads the +collector's file. ## Prerequisites diff --git a/samples/distributedtracing/distributedtracing.go b/samples/distributedtracing/distributedtracing.go index 08b2424b..85663aae 100644 --- a/samples/distributedtracing/distributedtracing.go +++ b/samples/distributedtracing/distributedtracing.go @@ -17,11 +17,11 @@ import ( "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" "go.opentelemetry.io/otel" - "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp" "go.opentelemetry.io/otel/propagation" "go.opentelemetry.io/otel/sdk/resource" sdktrace "go.opentelemetry.io/otel/sdk/trace" + semconv "go.opentelemetry.io/otel/semconv/v1.43.0" oteltrace "go.opentelemetry.io/otel/trace" "github.com/microsoft/durabletask-go/api" @@ -149,14 +149,16 @@ func run() (err error) { cleanupDone = true receiptCtx, receiptCancel := context.WithTimeout(context.Background(), 30*time.Second) defer receiptCancel() - receiptErr := waitForCollectorReceipt(receiptCtx, traceFile, traceID, []string{ - callerSpanName, - "create_orchestration:DistributedTraceSampleOrchestrator", - "orchestration:DistributedTraceSampleOrchestrator", - "activity:DoWorkActivity", - "orchestration:DistributedTraceSampleOrchestrator:timer", - "activity:CallHttpEndpointActivity", - "local_trace_target", + receiptErr := waitForCollectorReceipt(receiptCtx, traceFile, traceID, []expectedSpan{ + {name: callerSpanName, kind: oteltrace.SpanKindClient}, + {name: "create_orchestration:DistributedTraceSampleOrchestrator", kind: oteltrace.SpanKindProducer}, + {name: "orchestration:DistributedTraceSampleOrchestrator", kind: oteltrace.SpanKindServer}, + {name: "activity:DoWorkActivity", kind: oteltrace.SpanKindClient}, + {name: "activity:DoWorkActivity", kind: oteltrace.SpanKindServer}, + {name: "orchestration:DistributedTraceSampleOrchestrator:timer", kind: oteltrace.SpanKindInternal}, + {name: "activity:CallHttpEndpointActivity", kind: oteltrace.SpanKindClient}, + {name: "activity:CallHttpEndpointActivity", kind: oteltrace.SpanKindServer}, + {name: "local_trace_target", kind: oteltrace.SpanKindServer}, }) return errors.Join(cleanupErr, workerErr, traceErr, receiptErr) } @@ -170,14 +172,20 @@ func ConfigureOTLPTracing(ctx context.Context) (*sdktrace.TracerProvider, error) if err != nil { return nil, err } + // OTEL_SERVICE_NAME and OTEL_RESOURCE_ATTRIBUTES override the service name. + res, err := resource.New(ctx, + resource.WithAttributes(semconv.ServiceName("distributedtracing-sample")), + resource.WithFromEnv(), + resource.WithTelemetrySDK(), + ) + if err != nil { + return nil, errors.Join(err, exp.Shutdown(ctx)) + } tp := sdktrace.NewTracerProvider( sdktrace.WithSpanProcessor(sdktrace.NewBatchSpanProcessor(exp)), tracing.WithIDGenerator(nil), tracing.WithSampler(sdktrace.ParentBased(sdktrace.AlwaysSample())), - sdktrace.WithResource(resource.NewWithAttributes( - "durabletask.io", - attribute.String("service.name", "distributedtracing-sample"), - )), + sdktrace.WithResource(res), ) otel.SetTracerProvider(tp) otel.SetTextMapPropagator(propagation.TraceContext{}) @@ -281,13 +289,27 @@ func requireHistoryTraceContext(events []*api.HistoryEvent, traceID string) erro return nil } -func waitForCollectorReceipt(ctx context.Context, path string, traceID string, spanNames []string) error { +// expectedSpan is a span the collector must receive. An unspecified kind +// matches any kind. +type expectedSpan struct { + name string + kind oteltrace.SpanKind +} + +func (s expectedSpan) String() string { + if s.kind == oteltrace.SpanKindUnspecified { + return s.name + } + return s.name + " (" + s.kind.String() + ")" +} + +func waitForCollectorReceipt(ctx context.Context, path string, traceID string, expected []expectedSpan) error { var lastErr error var missing []string for { body, err := os.ReadFile(path) if err == nil { - missing, lastErr = missingSpansForTrace(string(body), traceID, spanNames) + missing, lastErr = missingSpansForTrace(string(body), traceID, expected) if lastErr == nil && len(missing) == 0 { return nil } @@ -300,40 +322,40 @@ func waitForCollectorReceipt(ctx context.Context, path string, traceID string, s return fmt.Errorf("collector trace file %s could not be verified: %w", path, lastErr) } return fmt.Errorf("collector trace file %s did not contain trace %s spans %v; missing %v: %w", - path, traceID, spanNames, missing, ctx.Err()) + path, traceID, expected, missing, ctx.Err()) case <-time.After(500 * time.Millisecond): } } } -func traceFileContains(body, traceID string, spanNames []string) bool { - missing, err := missingSpansForTrace(body, traceID, spanNames) +func traceFileContains(body, traceID string, expected []expectedSpan) bool { + missing, err := missingSpansForTrace(body, traceID, expected) return err == nil && len(missing) == 0 } -func missingSpansForTrace(body, traceID string, spanNames []string) ([]string, error) { +func missingSpansForTrace(body, traceID string, expected []expectedSpan) ([]string, error) { spans, err := traceSpansFromCollectorFile(body) - if err != nil { - return spanNames, err - } - found := map[string]struct{}{} - for _, span := range spans { - if strings.EqualFold(span.traceID, traceID) { - found[span.name] = struct{}{} - } - } var missing []string - for _, name := range spanNames { - if _, ok := found[name]; !ok { - missing = append(missing, name) + for _, want := range expected { + found := false + for _, span := range spans { + if strings.EqualFold(span.traceID, traceID) && span.name == want.name && + (want.kind == oteltrace.SpanKindUnspecified || span.kind == want.kind) { + found = true + break + } + } + if !found { + missing = append(missing, want.String()) } } - return missing, nil + return missing, err } type collectedSpan struct { traceID string name string + kind oteltrace.SpanKind } func traceSpansFromCollectorFile(body string) ([]collectedSpan, error) { @@ -359,7 +381,7 @@ func collectSpans(value any, spans *[]collectedSpan) { traceID := stringField(typed, "traceId", "traceID", "trace_id") name := stringField(typed, "name") if traceID != "" && name != "" { - *spans = append(*spans, collectedSpan{traceID: traceID, name: name}) + *spans = append(*spans, collectedSpan{traceID: traceID, name: name, kind: spanKind(typed["kind"])}) } for _, child := range typed { collectSpans(child, spans) @@ -371,6 +393,30 @@ func collectSpans(value any, spans *[]collectedSpan) { } } +// spanKind decodes an OTLP JSON span kind, which is an enum number such as 2 +// or, from some encoders, an enum name such as "SPAN_KIND_SERVER". OTLP and +// the OpenTelemetry Go API number span kinds the same way. +func spanKind(value any) oteltrace.SpanKind { + switch typed := value.(type) { + case float64: + return oteltrace.SpanKind(typed) + case string: + switch typed { + case "SPAN_KIND_INTERNAL": + return oteltrace.SpanKindInternal + case "SPAN_KIND_SERVER": + return oteltrace.SpanKindServer + case "SPAN_KIND_CLIENT": + return oteltrace.SpanKindClient + case "SPAN_KIND_PRODUCER": + return oteltrace.SpanKindProducer + case "SPAN_KIND_CONSUMER": + return oteltrace.SpanKindConsumer + } + } + return oteltrace.SpanKindUnspecified +} + func stringField(fields map[string]any, names ...string) string { for _, name := range names { value, ok := fields[name].(string) diff --git a/samples/distributedtracing/distributedtracing_test.go b/samples/distributedtracing/distributedtracing_test.go index 1af65dde..5ff0a037 100644 --- a/samples/distributedtracing/distributedtracing_test.go +++ b/samples/distributedtracing/distributedtracing_test.go @@ -1,26 +1,44 @@ package main -import "testing" +import ( + "testing" + + oteltrace "go.opentelemetry.io/otel/trace" +) func TestTraceFileContains(t *testing.T) { body := `{"resourceSpans":[{"scopeSpans":[{"spans":[{"traceId":"abc123","name":"schedule_distributed_trace_sample"},{"traceId":"abc123","name":"local_trace_target"}]}]}]}` - if !traceFileContains(body, "abc123", []string{callerSpanName, "local_trace_target"}) { + if !traceFileContains(body, "abc123", []expectedSpan{{name: callerSpanName}, {name: "local_trace_target"}}) { t.Fatal("expected trace file body to contain required trace and spans") } - if traceFileContains(body, "missing", []string{callerSpanName}) { + if traceFileContains(body, "missing", []expectedSpan{{name: callerSpanName}}) { t.Fatal("unexpected trace match") } - if traceFileContains(body, "abc123", []string{"missing"}) { + if traceFileContains(body, "abc123", []expectedSpan{{name: "missing"}}) { t.Fatal("unexpected span match") } } +func TestTraceFileContainsRequiresSpanKinds(t *testing.T) { + body := `{"resourceSpans":[{"scopeSpans":[{"spans":[{"traceId":"abc123","name":"activity:A","kind":3},{"traceId":"abc123","name":"activity:B","kind":"SPAN_KIND_SERVER"}]}]}]}` + if !traceFileContains(body, "abc123", []expectedSpan{ + {name: "activity:A", kind: oteltrace.SpanKindClient}, + {name: "activity:B", kind: oteltrace.SpanKindServer}, + }) { + t.Fatal("expected numeric and named span kinds to match") + } + missing, err := missingSpansForTrace(body, "abc123", []expectedSpan{{name: "activity:A", kind: oteltrace.SpanKindServer}}) + if err != nil || len(missing) != 1 || missing[0] != "activity:A (server)" { + t.Fatalf("missing=%v err=%v, want the SERVER span reported missing", missing, err) + } +} + func TestTraceFileContainsRejectsStaleSpansFromOtherTraces(t *testing.T) { body := ` {"resourceSpans":[{"scopeSpans":[{"spans":[{"traceId":"current-trace","name":"schedule_distributed_trace_sample"}]}]}]} {"resourceSpans":[{"scopeSpans":[{"spans":[{"traceId":"stale-trace","name":"local_trace_target"}]}]}]} ` - if traceFileContains(body, "current-trace", []string{callerSpanName, "local_trace_target"}) { + if traceFileContains(body, "current-trace", []expectedSpan{{name: callerSpanName}, {name: "local_trace_target"}}) { t.Fatal("expected spans split across traces to fail") } } diff --git a/samples/observability/README.md b/samples/observability/README.md index a80f5e9e..6242d996 100644 --- a/samples/observability/README.md +++ b/samples/observability/README.md @@ -2,8 +2,8 @@ This sample uses the SDK's standard-library observability surfaces: tags, immutable context fields, `slog` logging, and retry/history metric hooks. It -does not add a telemetry framework or an OpenTelemetry collector; DTS-owned -durable spans are covered elsewhere. +does not add a telemetry framework or an OpenTelemetry collector. For opt-in +durable spans, see the [distributedtracing](../distributedtracing) sample. ## Run diff --git a/tests/durabletaskscheduler/dts_tracing_enabled_test.go b/tests/durabletaskscheduler/dts_tracing_enabled_test.go index 4d0a32b0..a4a0974f 100644 --- a/tests/durabletaskscheduler/dts_tracing_enabled_test.go +++ b/tests/durabletaskscheduler/dts_tracing_enabled_test.go @@ -14,15 +14,31 @@ import ( "github.com/microsoft/durabletask-go/tests/tracingtree" "github.com/microsoft/durabletask-go/tracing" "github.com/stretchr/testify/require" + "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/codes" sdktrace "go.opentelemetry.io/otel/sdk/trace" "go.opentelemetry.io/otel/sdk/trace/tracetest" "go.opentelemetry.io/otel/trace" ) -// This uses an explicit provider without changing the global provider used by -// the disabled-mode tests in dts_tracing_tree_test.go. +// TestDTSEmulatorTracingEnabledTreeAndEntityRoots is the end-to-end check of +// opt-in tracing (see tracing/README.md). It asserts the exact exported span +// set: client/orchestration/activity/sub-orchestration/timer/event parentage, +// activity failure status, distinct span identities across continue-as-new, +// independent entity roots with application spans nested under them, and a +// client entity signal that emits no client-side span. The disabled-mode tests +// in dts_tracing_tree_test.go assert propagation without SDK spans. Both run +// against a DTS emulator through DTS_EMULATOR_ENDPOINT or DTS_CONNECTION_STRING +// and skip when neither is set. +// +// It uses an explicit provider without changing the global provider used by +// the disabled-mode tests. func TestDTSEmulatorTracingEnabledTreeAndEntityRoots(t *testing.T) { + const ( + durableScope = "Microsoft.DurableTask" + testScope = "dts-enabled-test" + spanCount = 25 + ) options := emulatorOptions(t) exporter := tracetest.NewInMemoryExporter() provider := sdktrace.NewTracerProvider( @@ -35,14 +51,21 @@ func TestDTSEmulatorTracingEnabledTreeAndEntityRoots(t *testing.T) { entityID := api.NewEntityID("DTSEnabledEntity", uuid.NewString()) registry := task.NewTaskRegistry() require.NoError(t, registry.AddEntityN(entityID.Name, func(ctx *task.EntityContext) (any, error) { - if ctx.Operation == "fail" { + switch ctx.Operation { + case "fail": return nil, errors.New("traced entity failure") + case "get": + _, span := provider.Tracer(testScope).Start(ctx.Context(), "app/entity-get") + span.End() } return "entity", nil })) require.NoError(t, registry.AddActivityN("DTSEnabledEcho", func(task.ActivityContext) (any, error) { return "echo", nil })) + require.NoError(t, registry.AddActivityN("DTSEnabledFail", func(task.ActivityContext) (any, error) { + return nil, errors.New("traced activity failure") + })) require.NoError(t, registry.AddOrchestratorN("DTSEnabledChild", func(ctx *task.OrchestrationContext) (any, error) { var result string err := ctx.CallActivity("DTSEnabledEcho").Await(&result) @@ -53,6 +76,17 @@ func TestDTSEmulatorTracingEnabledTreeAndEntityRoots(t *testing.T) { err := ctx.WaitForSingleEvent("ping", time.Minute).Await(&result) return result, err })) + require.NoError(t, registry.AddOrchestratorN("DTSEnabledLoop", func(ctx *task.OrchestrationContext) (any, error) { + var generation int + if err := ctx.GetInput(&generation); err != nil { + return nil, err + } + if generation == 0 { + ctx.ContinueAsNew(1) + return nil, nil + } + return generation, nil + })) require.NoError(t, registry.AddOrchestratorN("DTSEnabledParent", func(ctx *task.OrchestrationContext) (any, error) { var receiver api.InstanceID if err := ctx.GetInput(&receiver); err != nil { @@ -63,6 +97,9 @@ func TestDTSEmulatorTracingEnabledTreeAndEntityRoots(t *testing.T) { task.WithSubOrchestrationInstanceID(string(ctx.ID)+"_child")).Await(&child); err != nil { return nil, err } + if err := ctx.CallActivity("DTSEnabledFail").Await(nil); err == nil { + return nil, errors.New("expected activity failure") + } if err := ctx.CreateTimer(10 * time.Millisecond).Await(nil); err != nil { return nil, err } @@ -96,7 +133,7 @@ func TestDTSEmulatorTracingEnabledTreeAndEntityRoots(t *testing.T) { durabletaskclient.WithAutoWorkItemFilters(), durabletaskclient.WithWorkerTracerProvider(provider)) require.NoError(t, err) - require.NoError(t, worker.Start(ctx)) + require.NoError(t, worker.Start(context.Background())) t.Cleanup(func() { shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 10*time.Second) defer shutdownCancel() @@ -106,10 +143,13 @@ func TestDTSEmulatorTracingEnabledTreeAndEntityRoots(t *testing.T) { receiverID, err := managementClient.ScheduleNewOrchestration(ctx, "DTSEnabledReceiver", api.WithInstanceID(uniqueInstanceID("go-enabled-receiver"))) require.NoError(t, err) - callerCtx, caller := provider.Tracer("dts-enabled-test").Start(ctx, "caller/enabled") + callerCtx, caller := provider.Tracer(testScope).Start(ctx, "caller/enabled") parentID, err := managementClient.ScheduleNewOrchestration(callerCtx, "DTSEnabledParent", api.WithInstanceID(uniqueInstanceID("go-enabled-parent")), api.WithInput(receiverID)) require.NoError(t, err) + loopID, err := managementClient.ScheduleNewOrchestration(callerCtx, "DTSEnabledLoop", + api.WithInstanceID(uniqueInstanceID("go-enabled-loop")), api.WithInput(0)) + require.NoError(t, err) require.NoError(t, managementClient.SignalEntity(callerCtx, entityID, "clientSignal")) caller.End() _, err = managementClient.WaitForOrchestrationStart(ctx, parentID) @@ -124,48 +164,97 @@ func TestDTSEmulatorTracingEnabledTreeAndEntityRoots(t *testing.T) { require.NoError(t, err) require.Equal(t, api.RUNTIME_STATUS_COMPLETED, receiver.RuntimeStatus) require.Equal(t, `"pong"`, receiver.SerializedOutput) + loop, err := managementClient.WaitForOrchestrationCompletion(ctx, loopID, api.WithFetchPayloads(true)) + require.NoError(t, err) + require.Equal(t, api.RUNTIME_STATUS_COMPLETED, loop.RuntimeStatus) + require.Equal(t, "1", loop.SerializedOutput) // Completion can become visible to the client just before the worker exports - // its accepted response. Multiple dispatches must not duplicate replay spans. - require.Eventually(t, func() bool { return len(exporter.GetSpans()) == 19 }, + // its accepted response. Multiple dispatches must not duplicate replay spans, + // including spans exported late. + require.Eventually(t, func() bool { return len(exporter.GetSpans()) == spanCount }, 10*time.Second, 20*time.Millisecond, "exported spans: %s", tracingtree.Describe(exporter.GetSpans().Snapshots())) + require.Never(t, func() bool { return len(exporter.GetSpans()) > spanCount }, + time.Second, 50*time.Millisecond, "late duplicate spans") spans := exporter.GetSpans().Snapshots() - find := func(name string, kind trace.SpanKind) sdktrace.ReadOnlySpan { - t.Helper() + for _, span := range spans { + scope := durableScope + if span.Name() == "caller/enabled" || span.Name() == "app/entity-get" { + scope = testScope + } + require.Equal(t, scope, span.InstrumentationScope().Name, span.Name()) + require.True(t, span.SpanContext().IsSampled(), span.Name()) + require.False(t, span.StartTime().IsZero(), span.Name()) + require.False(t, span.EndTime().Before(span.StartTime()), span.Name()) + } + findAll := func(name string, kind trace.SpanKind) []sdktrace.ReadOnlySpan { var matches []sdktrace.ReadOnlySpan for _, span := range spans { if span.Name() == name && span.SpanKind() == kind { matches = append(matches, span) } } + return matches + } + find := func(name string, kind trace.SpanKind) sdktrace.ReadOnlySpan { + t.Helper() + matches := findAll(name, kind) require.Len(t, matches, 1, "expected one %s %s; spans: %s", kind, name, tracingtree.Describe(spans)) - span := matches[0] - require.True(t, span.SpanContext().IsSampled()) - require.False(t, span.StartTime().IsZero()) - require.False(t, span.EndTime().Before(span.StartTime())) - if name != "caller/enabled" { - require.Equal(t, "durabletask", span.InstrumentationScope().Name) - } - return span + return matches[0] } childOf := func(child, parent sdktrace.ReadOnlySpan) { t.Helper() require.Equal(t, parent.SpanContext().TraceID(), child.SpanContext().TraceID(), child.Name()) require.Equal(t, parent.SpanContext().SpanID(), child.Parent().SpanID(), child.Name()) } + attrs := func(span sdktrace.ReadOnlySpan) map[string]attribute.Value { + values := make(map[string]attribute.Value) + for _, attr := range span.Attributes() { + values[string(attr.Key)] = attr.Value + } + return values + } + requireTask := func(span sdktrace.ReadOnlySpan, instanceID api.InstanceID) { + t.Helper() + values := attrs(span) + require.Equal(t, string(instanceID), values["durabletask.task.instance_id"].AsString(), span.Name()) + require.Equal(t, attribute.INT64, values["durabletask.task.task_id"].Type(), span.Name()) + } + status := func(span sdktrace.ReadOnlySpan) string { + return attrs(span)["durabletask.task.status"].AsString() + } + callerSpan := find("caller/enabled", trace.SpanKindInternal) create := find("create_orchestration:DTSEnabledParent", trace.SpanKindProducer) childOf(create, callerSpan) orchestration := find("orchestration:DTSEnabledParent", trace.SpanKindServer) childOf(orchestration, create) + require.Equal(t, "Completed", status(orchestration)) + require.Equal(t, codes.Unset, orchestration.Status().Code) childClient := find("orchestration:DTSEnabledChild", trace.SpanKindClient) childOf(childClient, orchestration) + requireTask(childClient, parentID) childServer := find("orchestration:DTSEnabledChild", trace.SpanKindServer) childOf(childServer, childClient) activityClient := find("activity:DTSEnabledEcho", trace.SpanKindClient) childOf(activityClient, childServer) - childOf(find("activity:DTSEnabledEcho", trace.SpanKindServer), activityClient) + activityServer := find("activity:DTSEnabledEcho", trace.SpanKindServer) + childOf(activityServer, activityClient) + require.Equal(t, "Completed", status(activityServer)) + require.Equal(t, codes.Unset, activityServer.Status().Code) + + failClient := find("activity:DTSEnabledFail", trace.SpanKindClient) + childOf(failClient, orchestration) + requireTask(failClient, parentID) + require.Equal(t, codes.Error, failClient.Status().Code) + failServer := find("activity:DTSEnabledFail", trace.SpanKindServer) + childOf(failServer, failClient) + requireTask(failServer, parentID) + require.Equal(t, "Failed", status(failServer)) + require.Equal(t, codes.Error, failServer.Status().Code) + require.Contains(t, failServer.Status().Description, "traced activity failure") + childOf(find("orchestration:DTSEnabledParent:timer", trace.SpanKindInternal), orchestration) childOf(find("orchestration_event:proceed", trace.SpanKindProducer), callerSpan) childOf(find("orchestration_event:ping", trace.SpanKindProducer), orchestration) @@ -173,14 +262,25 @@ func TestDTSEmulatorTracingEnabledTreeAndEntityRoots(t *testing.T) { require.False(t, receiverCreate.Parent().IsValid()) childOf(find("orchestration:DTSEnabledReceiver", trace.SpanKindServer), receiverCreate) - clientSignal := "entity:" + entityID.Name + ":clientSignal" - for _, span := range spans { - require.False(t, span.Name() == clientSignal && span.SpanKind() == trace.SpanKindProducer, - "client SignalEntity propagates caller context without emitting a span") + // Each continue-as-new generation is its own logical orchestration span. + loopCreate := find("create_orchestration:DTSEnabledLoop", trace.SpanKindProducer) + childOf(loopCreate, callerSpan) + generations := findAll("orchestration:DTSEnabledLoop", trace.SpanKindServer) + require.Len(t, generations, 2, tracingtree.Describe(spans)) + for _, generation := range generations { + childOf(generation, loopCreate) } + require.NotEqual(t, generations[0].SpanContext().SpanID(), generations[1].SpanContext().SpanID()) + require.ElementsMatch(t, []string{"ContinuedAsNew", "Completed"}, + []string{status(generations[0]), status(generations[1])}) + + clientSignal := "entity:" + entityID.Name + ":clientSignal" + require.Empty(t, findAll(clientSignal, trace.SpanKindProducer), + "client SignalEntity propagates caller context without emitting a span") clientSignalExecution := find(clientSignal, trace.SpanKindConsumer) require.False(t, clientSignalExecution.Parent().IsValid(), "V2 entity executions must be independent roots") require.NotEqual(t, caller.SpanContext().TraceID(), clientSignalExecution.SpanContext().TraceID()) + require.Equal(t, "clientSignal", attrs(clientSignalExecution)["durabletask.entity.operation"].AsString()) for _, operation := range []struct { name string @@ -188,31 +288,34 @@ func TestDTSEmulatorTracingEnabledTreeAndEntityRoots(t *testing.T) { attribute string status codes.Code }{ - {"signal", trace.SpanKindProducer, trace.SpanKindConsumer, "signal_entity", codes.Ok}, - {"get", trace.SpanKindClient, trace.SpanKindServer, "call_entity", codes.Ok}, + {"signal", trace.SpanKindProducer, trace.SpanKindConsumer, "signal_entity", codes.Unset}, + {"get", trace.SpanKindClient, trace.SpanKindServer, "call_entity", codes.Unset}, {"fail", trace.SpanKindClient, trace.SpanKindServer, "call_entity", codes.Error}, } { name := "entity:" + entityID.Name + ":" + operation.name send := find(name, operation.send) childOf(send, orchestration) + requireTask(send, parentID) + require.Equal(t, operation.status, send.Status().Code, name) execute := find(name, operation.execute) require.False(t, execute.Parent().IsValid(), "V2 entity executions must be independent roots") require.NotEqual(t, caller.SpanContext().TraceID(), execute.SpanContext().TraceID()) require.Empty(t, execute.Links(), "V2 has no propagated parent or synthetic request-ID link") - require.Equal(t, operation.status, execute.Status().Code) + require.Equal(t, operation.status, execute.Status().Code, name) + require.Equal(t, entityID.String(), attrs(execute)["durabletask.task.instance_id"].AsString()) for _, span := range []sdktrace.ReadOnlySpan{send, execute} { - attrs := make(map[string]string) - for _, attr := range span.Attributes() { - attrs[string(attr.Key)] = attr.Value.AsString() - } - require.Equal(t, operation.attribute, attrs["durabletask.task.operation"]) + values := attrs(span) + require.Equal(t, operation.attribute, values["durabletask.task.operation"].AsString(), name) + require.Equal(t, operation.name, values["durabletask.entity.operation"].AsString(), name) } if operation.status == codes.Error { - require.Equal(t, codes.Error, send.Status().Code) require.Contains(t, execute.Status().Description, "traced entity failure") } + if operation.name == "get" { + childOf(find("app/entity-get", trace.SpanKindInternal), execute) + } } // Every exported span was accounted for above; event receipt emits no // CONSUMER span and does not reparent the receiving orchestration. - require.Len(t, spans, 19) + require.Len(t, spans, spanCount) } diff --git a/tests/durabletaskscheduler/dts_tracing_tree_test.go b/tests/durabletaskscheduler/dts_tracing_tree_test.go index 1a5cc254..e084fc82 100644 --- a/tests/durabletaskscheduler/dts_tracing_tree_test.go +++ b/tests/durabletaskscheduler/dts_tracing_tree_test.go @@ -230,7 +230,7 @@ func TestDTSEmulatorTracingTreeActivityFailureSubOrchestrationsAndEvents(t *test // The caller's trace context must be persisted verbatim on the orchestration that the // client scheduled. This is the hand-off point between the caller's trace and the - // scheduler-side span tree. + // durable work that joins it. parentEvents := fetchHistory(t, ctx, managementClient, parentID, parentMetadata.ExecutionID) started := executionStarted(t, parentEvents) require.NotNil(t, started.ParentTraceContext, "the scheduler did not persist the caller's trace context") diff --git a/tests/tracingtree/tracingtree.go b/tests/tracingtree/tracingtree.go index 66698884..1ba7396c 100644 --- a/tests/tracingtree/tracingtree.go +++ b/tests/tracingtree/tracingtree.go @@ -1,8 +1,9 @@ // Package tracingtree provides the application-process OpenTelemetry plumbing // used by the Durable Task Scheduler tracing tests: a process-wide in-memory // exporter and the caller span whose W3C context the SDK propagates to DTS. -// Without explicit tracing options, durable operation spans are emitted by DTS -// service-side, not by the Go worker. +// DTS persists and propagates trace context but does not emit durable operation +// spans, and without explicit tracing options the Go client and worker emit +// none either. package tracingtree import ( @@ -18,8 +19,8 @@ import ( "go.opentelemetry.io/otel/trace" ) -// attributeInstanceID is the instance-ID attribute DTS stamps on its -// service-side durable operation spans. It is used only in diagnostic output. +// attributeInstanceID is the instance-ID attribute on Durable Task spans. It is +// used only in diagnostic output. const attributeInstanceID = "durabletask.task.instance_id" var ( diff --git a/tracing/README.md b/tracing/README.md index 7b792194..57c59d8f 100644 --- a/tracing/README.md +++ b/tracing/README.md @@ -1,53 +1,106 @@ # Replay-aware OpenTelemetry tracing -Durable Task clients and workers **only propagate W3C context by default**. -Opt-in tracing exports durable operation spans through the application's -OpenTelemetry provider, alongside its ordinary application spans. It does not -require a scheduler-specific telemetry exporter. +By default, Durable Task clients and workers **only propagate W3C trace +context**. They emit no spans. When you opt in, the SDK exports durable +orchestration, activity, sub-orchestration, timer, event, and entity spans +through your application's OpenTelemetry provider, next to your own application +spans. Your provider sends them to any OpenTelemetry-compatible backend. You +don't need a scheduler-specific telemetry exporter. ## Enable tracing -Configure the worker's OpenTelemetry SDK provider with **both** wrappers: +Configure the worker's OpenTelemetry SDK provider with **both** Durable Task +wrappers. Then pass the provider to the worker and, optionally, to the client: ```go provider := sdktrace.NewTracerProvider( - tracing.WithIDGenerator(nil), - tracing.WithSampler(sdktrace.ParentBased(sdktrace.AlwaysSample())), - sdktrace.WithBatcher(exporter), - sdktrace.WithResource(applicationResource), + tracing.WithIDGenerator(nil), + tracing.WithSampler(sdktrace.ParentBased(sdktrace.AlwaysSample())), + sdktrace.WithBatcher(exporter), + sdktrace.WithResource(res), ) + worker, err := durabletaskscheduler.NewWorker(options, registry, logger, - client.WithWorkerTracerProvider(provider)) + client.WithWorkerTracerProvider(provider)) +if err != nil { + // errors.Is(err, tracing.ErrUnsupportedTracerProvider) reports a provider + // that is missing a wrapper. + return err +} managementClient, err := durabletaskscheduler.NewClient(ctx, options, logger, - client.WithTracerProvider(provider)) + client.WithTracerProvider(provider)) +if err != nil { + return err +} ``` -Check both constructor errors. `client.WithTracerProvider` can use any tracer -provider, but `client.WithWorkerTracerProvider` rejects a provider missing either -wrapper with `tracing.ErrUnsupportedTracerProvider`. The ID generator honors -persisted span identities during reconstruction; ordinary application spans -still use its base generator. The sampler supports sampling queries without -creating live spans. Pass a custom generator or sampler into these wrappers -instead of replacing them with `sdktrace.WithIDGenerator` or -`sdktrace.WithSampler`. - -The application owns resources, processors, exporter, flushing, and provider -shutdown. Stop the worker before flushing/shutting down the provider. -`otel.SetTracerProvider(provider)` is optional for Durable Task, but useful for -application instrumentation that uses the global provider. See the -[distributed tracing sample](../samples/distributedtracing) for a complete -OTLP/HTTP collector setup and collector-receipt verification. +`client.WithTracerProvider` accepts any tracer provider, including +`otel.GetTracerProvider()`. `client.WithWorkerTracerProvider` rejects a provider +that doesn't use both wrappers. The error wraps +`tracing.ErrUnsupportedTracerProvider` and names the failed check. The wrappers +must be the provider's top-level ID generator and sampler: + +- The ID generator applies persisted span identities when the worker + reconstructs spans. Your application spans still get IDs from its base + generator. +- The sampler answers sampling queries without starting live spans. + +To customize either one, pass your generator or sampler to the wrapper as its +base. Don't replace the wrapper with `sdktrace.WithIDGenerator` or +`sdktrace.WithSampler`, and don't nest the wrapper inside another sampler. + +Your application owns the provider's resource, processors, exporter, flushing, +and shutdown. Shut down the worker, close the client, and then shut down the +provider. `otel.SetTracerProvider(provider)` is optional for Durable Task, but +it helps instrumentation libraries that use the global provider. For a complete +setup, see the [distributed tracing sample](../samples/distributedtracing). It +exports to an OTLP/HTTP collector, which can forward the spans to Jaeger, Azure +Monitor, or another OTLP backend. + +## Service-side telemetry and duplicates + +Durable Task Scheduler (DTS) persists and forwards trace context, but it doesn't +emit durable orchestration, activity, timer, sub-orchestration, or entity spans. +It also doesn't export spans to your telemetry backend. To see durable spans in +your backend, enable SDK tracing. + +SDK spans use the `Microsoft.DurableTask` instrumentation scope and your +provider's resource. If another component, such as a host or a future +scheduler-side export, emits durable spans for the same work into the same +backend, enable only one source. To keep the SDK silent, omit +`client.WithWorkerTracerProvider` and `client.WithTracerProvider`. + +## Logical spans, not execution-turn spans + +An orchestrator replays from history on each dispatch. The SDK doesn't emit a +span for each dispatch or replay. Instead, it emits one logical +`orchestration:` SERVER span for each execution. Each continue-as-new +generation is a separate execution. The span starts at the execution's first +traced dispatch and ends when the execution completes, fails, terminates, or +continues as new. The worker persists the span's ID and start time with the +backend, and reconstructs the span with that identity when the execution +finishes. + +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. +- 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. ## Spans and lifecycle -All SDK spans use the `durabletask` instrumentation scope. Task names use -`:@()`, omitting the version suffix when unversioned. -Entity names use the lowercase form from `EntityID.String`. +Task span names use `:@()`. The `@()` suffix is +omitted when the task is unversioned. Entity names are lowercase, as in +`EntityID.String`. | Operation | Span name | Kind and parent | | --- | --- | --- | | Client schedules orchestration | `create_orchestration:` | PRODUCER under caller | -| Orchestration execution | `orchestration:` | SERVER under create span, or propagated caller when client tracing is disabled | +| Orchestration execution | `orchestration:` | SERVER under create span, or under the propagated caller context when client tracing is off; trace root without caller 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 | @@ -60,82 +113,111 @@ Entity names use the lowercase form from `EntityID.String`. | Entity signal execution | `entity::` | CONSUMER, independent root | | Entity call execution | `entity::` | SERVER, independent root | -Orchestration spans are reconstructed with persisted identity and start time -when an execution completes, fails, terminates, or continues as new. Activities -are live spans, so HTTP/database/application spans can nest under them. -Scheduling and timer spans are reconstructed from history when a dispatch -consuming the completion is accepted. Orchestrator event/entity signals export -after their sending dispatch is accepted. Entity executions export after an -accepted batch with operation-result timestamps and error status. - -Replayed history emits no new spans. Orchestration and entity execution spans -are not live inside their handlers; starting an application span from an -orchestrator does not automatically make it replay-safe. - -Attributes include `durabletask.type`, task name/version, instance ID, and -operation-specific status, execution/task IDs, or timer fire time. Entity spans -follow **DurableTask.Core** names and kinds, including -`durabletask.task.operation=signal_entity` or `call_entity`, rather than -introducing a new Go-only convention. Failures are marked with error status. - -Without caller context, an orchestration starts a trace derived from its -persisted identity. Sampling follows propagated trace flags, preserves -tracestate, and keeps unsampled orchestration trees unsampled. Root sampling is -queried again on each dispatch: use a sampler with a stable decision based on -the trace ID, such as the built-in parent-based/trace-ID-ratio samplers. -Continue-as-new and rewind start a new orchestration span identity. +When each kind of span is exported: + +- **Orchestration spans** are exported after the backend accepts the completion + of the execution. +- **Activity execution spans** are live. HTTP, database, and other application + spans that you start from `ActivityContext.Context()` nest under them. The + span starts after the worker's version check, so work that the worker rejects + for a version mismatch exports no span. The span ends right after the + activity runs and reports the activity's own outcome, even if that outcome + doesn't reach the backend. +- **Scheduling, entity-call, and timer spans** are reconstructed from history. + They're exported when the backend accepts the dispatch that consumes their + completion. +- **Event-send and entity-signal spans** are exported after the backend accepts + their sending dispatch. If a new send's acknowledgement arrives in the same + dispatch, the span is exported with that dispatch. +- **Entity execution spans** are exported after the backend accepts the batch. + 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. + +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 +replay-safe. + +Attributes include `durabletask.type`, `durabletask.task.name`, +`durabletask.task.version`, and `durabletask.task.instance_id`. Some spans also +carry `durabletask.task.execution_id`, the integer `durabletask.task.task_id`, +`durabletask.task.status`, or `durabletask.fire_at`. On activity, timer, +sub-orchestration scheduling, and entity caller spans, +`durabletask.task.instance_id` is the calling orchestration's instance ID. On +entity execution spans, it's the entity ID. Entity spans follow +[DurableTask.Core](https://github.com/Azure/durabletask/tree/main/src/DurableTask.Core/Tracing) +names and kinds: + +- `durabletask.task.operation` is `call_entity` or `signal_entity`. +- `durabletask.entity.operation` is the operation name, as in the Python and + JavaScript SDKs. + +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. Sampling follows the propagated trace flags and keeps +tracestate, so unsampled orchestration trees stay unsampled. The worker +evaluates root sampling again on each dispatch. Use a sampler whose decision +depends only on the trace ID, such as the SDK's built-in parent-based and +trace-ID-ratio samplers. Continue-as-new and rewind start a new orchestration +span identity. A rewind that carries a parent trace context reparents the +orchestration under that context. ## SDK parity -This comparison concerns application-process tracing in -[durabletask-python](https://github.com/microsoft/durabletask-python/blob/main/durabletask/internal/tracing.py) -and the -[durabletask-dotnet gRPC SDK](https://github.com/microsoft/durabletask-dotnet/blob/main/src/Shared/Grpc/Tracing/TraceHelper.cs), -not Azure Functions host or scheduler-service telemetry. - -| Feature | Go (enabled) | Python | .NET gRPC | -| --- | --- | --- | --- | -| Application provider/exporter integration | OpenTelemetry SDK provider; OTLP or another exporter | OpenTelemetry provider | `ActivitySource` via application OpenTelemetry | -| Client create orchestration / raise event | PRODUCER | PRODUCER | PRODUCER | -| Replay-aware orchestration execution | Reconstructed SERVER | Deferred SERVER | Reconstructed SERVER | -| Activity and sub-orchestration scheduling/execution | CLIENT / SERVER | CLIENT / SERVER | CLIENT / SERVER | -| Durable timers | INTERNAL | INTERNAL | INTERNAL | -| Orchestrator event send | PRODUCER | PRODUCER | PRODUCER | -| Event receipt consumer / sender-to-receiver trace join | Not available | Not available | Not available | -| Entity signal/call and operation execution | DurableTask.Core PRODUCER/CLIENT and CONSUMER/SERVER | Not implemented | Not implemented | -| Client entity signal | No span; sampled caller context propagated | None | No span; caller context propagated | -| Entity lock acquisition/release | No spans | No spans | No spans | -| Persisted span reconstruction integration | Public SDK ID-generator/sampler wrappers | Deferred spans via OTel SDK internals | `Activity` reconstruction helpers | - -Entity tracing matches the -[DurableTask.Core reference](https://github.com/Azure/durabletask/tree/main/src/DurableTask.Core/Tracing); -it is beyond the current Python and .NET gRPC tracing surfaces, not a claim that -those SDKs emit entity spans. +This table compares tracing in the application process of each Durable Task +SDK: +[durabletask-dotnet](https://github.com/microsoft/durabletask-dotnet/blob/main/src/Shared/Grpc/Tracing/TraceHelper.cs) +(gRPC), +[durabletask-python](https://github.com/microsoft/durabletask-python/blob/main/durabletask/internal/tracing.py), +and [durabletask-js](https://github.com/microsoft/durabletask-js) +(`@microsoft/durabletask-js`). It doesn't cover Azure Functions host telemetry. + +| Feature | Go | .NET gRPC | Python | JavaScript | +| --- | --- | --- | --- | --- | +| Enabled by default | No. Opt in with an injected provider | Yes. `ActivitySource` is always on; spans are exported when the app adds the source | Yes, with the global provider. Opt out with `emit_trace_spans=False` | Yes, with the global `@opentelemetry/api` provider | +| 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 | +| 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 | +| Orchestrator sends event | PRODUCER | PRODUCER | PRODUCER | PRODUCER | +| Event receipt | No CONSUMER span | No CONSUMER span | No CONSUMER span | No CONSUMER span | +| Orchestrator calls or signals entity | `entity::` CLIENT or PRODUCER | No spans | No spans | `call_entity:` CLIENT, or `signal_entity:` PRODUCER with zero duration | +| Entity operation execution | `entity::` SERVER for calls, CONSUMER for signals | No spans | `entity::` SERVER for calls and signals | No spans | +| Client signals entity | No span. Sampled caller context is propagated | No span. Caller context is propagated | No span | `signal_entity:` PRODUCER | +| Entity locks | No spans | No spans | No spans | `entity:lock_request` INTERNAL | +| Success status | Unset | Unset | Unset | OK | +| Span reconstruction | Public ID-generator and sampler wrappers | `Activity` reconstruction helpers | Deferred spans through OpenTelemetry SDK internals | Not applicable, spans are per dispatch | + +Go's entity span names, kinds, and `durabletask.task.operation` values follow +DurableTask.Core, which also emits the full caller and execution set. +Go also adds the `durabletask.entity.operation` attribute that the Python and +JavaScript SDKs use. ## Limitations -- Event messages have no trace context. Receipt emits no CONSUMER span, and - sending an event does not reparent or link the receiving orchestration. -- V2 entity operations have no propagated parent trace context. Execution spans - are independent roots sampled by the provider's root policy, not a joined - orchestration/entity tree. There are no synthetic request-ID links. -- Telemetry is **not exactly-once**. Abandoned dispatches emit no reconstructed - orchestration telemetry, but a successfully accepted completion retried by the - backend can export again. Live activity spans describe attempts, even when a - result is not accepted. -- Reconstruction requires the backend to return persisted orchestration trace - identity on subsequent dispatches. Service-side telemetry remains separate - and may overlap in operation names with enabled application-process spans. - -## End-to-end coverage - -`tests/durabletaskscheduler/dts_tracing_enabled_test.go` uses an explicit provider -and an in-memory exporter to assert client/orchestration/activity/sub-orchestration/ -timer/event parentage and independent entity roots, including entity failures -and a client signal that emits no client-side span. -The existing disabled-mode tests continue to assert propagation without SDK span -emission. - -Run these against a DTS emulator with `DTS_EMULATOR_ENDPOINT` or a configured -`DTS_CONNECTION_STRING`. They skip when neither is set. PR validation supplies -the pinned DTS emulator endpoint. +- **Telemetry is best effort in both directions, not exactly once.** + - Retried or redelivered work can export the same spans again. + - If the backend accepts a completion but the reply is lost, and the retry + reports the work item gone, that completion's spans are lost. + - Abandoned orchestration dispatches export no orchestration telemetry. + - Live activity spans describe attempts, even when the result isn't accepted. +- **Events carry no trace context.** Receipt emits no CONSUMER span, and a send + doesn't reparent or link the receiving orchestration. +- **V2 entity operations carry no parent trace context.** Entity execution spans + are independent roots that the provider's root sampler samples. They don't + form a joined orchestration and entity tree, and the SDK adds no synthetic + parents or links. +- **Entity-started work doesn't join the trace on DTS.** Signals and + orchestration starts from an entity carry the operation's trace context on + the action, but DTS doesn't currently forward it. +- **No PRODUCER spans for entity-started work.** The SDK doesn't emit + DurableTask.Core's entity-to-entity signal or orchestration-start PRODUCER + spans (`StartActivityForEntityStartingAnOrchestration`). +- **Span reconstruction depends on the backend.** The backend must return the + persisted orchestration trace context on later dispatches. diff --git a/tracing/tracing.go b/tracing/tracing.go index 4f613e79..e8392ca4 100644 --- a/tracing/tracing.go +++ b/tracing/tracing.go @@ -1,11 +1,16 @@ // Package tracing configures opt-in OpenTelemetry spans for Durable Task // clients and workers. // -// The tracing README contains the span catalog, OTLP sample, and a parity -// comparison with durabletask-python and durabletask-dotnet's gRPC SDK. +// The tracing guide at +// https://github.com/microsoft/durabletask-go/blob/main/tracing/README.md +// describes the span catalog, logical orchestration spans, service-side +// telemetry, and parity with the Durable Task .NET, Python, and JavaScript +// SDKs. The samples/distributedtracing module in the same repository exports +// these spans to an OTLP collector. // // By default clients and workers only propagate W3C trace context and emit no -// spans. Enable worker spans with client.WithWorkerTracerProvider and a +// spans. Enable worker spans with +// [github.com/microsoft/durabletask-go/client.WithWorkerTracerProvider] and a // provider built with [WithIDGenerator] and [WithSampler]: // // provider := sdktrace.NewTracerProvider( @@ -15,11 +20,12 @@ // ) // worker, err := durabletaskscheduler.NewWorker(..., client.WithWorkerTracerProvider(provider)) // -// Enable client spans with client.WithTracerProvider. Client spans are -// started live and never reconstructed, so any provider works, including -// otel.GetTracerProvider(), the global delegating provider. The client and -// worker can also share one provider configured with [WithIDGenerator] and -// [WithSampler]: +// Enable client spans with +// [github.com/microsoft/durabletask-go/client.WithTracerProvider]. Client +// spans are started live and never reconstructed, so any provider works, +// including otel.GetTracerProvider(), the global delegating provider. The +// client and worker can also share one provider configured with +// [WithIDGenerator] and [WithSampler]: // // c, err := durabletaskscheduler.NewClient(ctx, options, logger, client.WithTracerProvider(provider)) //