From 6ba3b68fe5917dd85238b86505326a400da1e4e1 Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Fri, 20 Nov 2026 11:23:24 -0700 Subject: [PATCH 1/5] Add opt-in client PRODUCER spans for scheduling orchestrations and raising events Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- client/client_grpc.go | 42 ++++-- client/client_grpc_tracing_test.go | 212 +++++++++++++++++++++++++++++ durabletaskscheduler/client.go | 18 ++- internal/dttrace/client.go | 71 ++++++++++ tracing/tracing.go | 19 ++- 5 files changed, 345 insertions(+), 17 deletions(-) create mode 100644 client/client_grpc_tracing_test.go create mode 100644 internal/dttrace/client.go diff --git a/client/client_grpc.go b/client/client_grpc.go index 63d9b011..ef08441c 100644 --- a/client/client_grpc.go +++ b/client/client_grpc.go @@ -16,6 +16,7 @@ import ( "google.golang.org/protobuf/types/known/wrapperspb" "github.com/microsoft/durabletask-go/api" + "github.com/microsoft/durabletask-go/internal/dttrace" "github.com/microsoft/durabletask-go/internal/failure" "github.com/microsoft/durabletask-go/internal/helpers" "github.com/microsoft/durabletask-go/internal/largepayload" @@ -30,6 +31,7 @@ type TaskHubGrpcClient struct { largePayloads *api.LargePayloadOptions defaultVersion string converter api.DataConverter + tracer *dttrace.ClientTracer listenerMu sync.Mutex listener *TaskHubGrpcWorker @@ -72,6 +74,23 @@ func WithDataConverter(converter api.DataConverter) TaskHubGrpcClientOption { } } +// WithTracerProvider enables Durable Task PRODUCER spans for +// ScheduleNewOrchestration ("create_orchestration:") and RaiseEvent +// ("orchestration_event:"). Spans are children of the span in the call's +// context, and a scheduled orchestration is parented to its +// create_orchestration span. Failed calls mark the span as an error. +// +// Any provider is accepted; tracing.WithIDGenerator and tracing.WithSampler are +// required only for worker tracing, and a provider configured with them can be +// shared with the worker. The application owns the provider's configuration and +// shutdown. Without this option, or with a nil provider, the client emits no +// spans and only propagates the caller's sampled trace context. +func WithTracerProvider(provider trace.TracerProvider) TaskHubGrpcClientOption { + return func(c *TaskHubGrpcClient) { + c.tracer = dttrace.NewClientTracer(provider) + } +} + // NewTaskHubGrpcClient creates a client that can be used to manage orchestrations over a borrowed gRPC connection. // The caller retains ownership of the connection; this client neither closes nor recreates it. DTS applications that // want an owned, resilient management channel should use durabletaskscheduler.NewClient. @@ -89,7 +108,7 @@ func NewTaskHubGrpcClient(cc grpc.ClientConnInterface, logger api.Logger, opts . } // ScheduleNewOrchestration schedules a new orchestration instance with a specified set of options for execution. -func (c *TaskHubGrpcClient) ScheduleNewOrchestration(ctx context.Context, orchestrator string, opts ...api.NewOrchestrationOptions) (api.InstanceID, error) { +func (c *TaskHubGrpcClient) ScheduleNewOrchestration(ctx context.Context, orchestrator string, opts ...api.NewOrchestrationOptions) (_ api.InstanceID, err error) { req := &protos.CreateInstanceRequest{Name: orchestrator} for _, configure := range opts { if err := configure(req, c.converter); err != nil { @@ -110,16 +129,19 @@ func (c *TaskHubGrpcClient) ScheduleNewOrchestration(ctx context.Context, orches req.InstanceId = uuid.NewString() } } - var err error + var span trace.Span + if c.tracer != nil { + ctx, span = c.tracer.StartCreateOrchestration(ctx, req.Name, req.Version.GetValue(), + req.InstanceId, req.ExecutionId.GetValue()) + defer func() { dttrace.EndClientSpan(span, err) }() + } req.Input, err = largepayload.Externalize(ctx, c.largePayloads, req.Input) if err != nil { return api.EmptyInstanceID, fmt.Errorf("failed to externalize orchestration input: %w", err) } - // Propagate the caller's distributed trace context so the service can parent the - // orchestration's trace to the code that scheduled it. Without this, every - // orchestration starts a brand new, disconnected trace. Unsampled callers - // propagate too, so their sampling decision is kept downstream. + // Propagate the PRODUCER span when tracing is enabled, or the caller's span + // otherwise. Unsampled contexts preserve the sampling decision downstream. if req.ParentTraceContext == nil { req.ParentTraceContext = helpers.TraceContextFromSpanContext(trace.SpanContextFromContext(ctx)) } @@ -222,14 +244,18 @@ func (c *TaskHubGrpcClient) TerminateOrchestration(ctx context.Context, id api.I } // RaiseEvent sends an asynchronous event notification to a waiting orchestration. -func (c *TaskHubGrpcClient) RaiseEvent(ctx context.Context, id api.InstanceID, eventName string, opts ...api.RaiseEventOptions) error { +func (c *TaskHubGrpcClient) RaiseEvent(ctx context.Context, id api.InstanceID, eventName string, opts ...api.RaiseEventOptions) (err error) { req := &protos.RaiseEventRequest{InstanceId: string(id), Name: eventName} for _, configure := range opts { if err := configure(req, c.converter); err != nil { return fmt.Errorf("failed to configure raise event request: %w", api.WrapInvalidArgument(err)) } } - var err error + if c.tracer != nil { + var span trace.Span + ctx, span = c.tracer.StartRaiseEvent(ctx, eventName, string(id)) + defer func() { dttrace.EndClientSpan(span, err) }() + } req.Input, err = largepayload.Externalize(ctx, c.largePayloads, req.Input) if err != nil { return fmt.Errorf("failed to externalize event payload: %w", err) diff --git a/client/client_grpc_tracing_test.go b/client/client_grpc_tracing_test.go new file mode 100644 index 00000000..623f4315 --- /dev/null +++ b/client/client_grpc_tracing_test.go @@ -0,0 +1,212 @@ +package client + +import ( + "context" + "errors" + "testing" + + "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" + "google.golang.org/grpc" + + "github.com/microsoft/durabletask-go/api" + "github.com/microsoft/durabletask-go/internal/helpers" + "github.com/microsoft/durabletask-go/internal/protos" + "github.com/microsoft/durabletask-go/task" + "github.com/microsoft/durabletask-go/tracing" +) + +type tracingSchedulerClient struct { + protos.TaskHubSidecarServiceClient + start *protos.CreateInstanceRequest + event *protos.RaiseEventRequest + err error +} + +func (c *tracingSchedulerClient) StartInstance( + _ context.Context, + req *protos.CreateInstanceRequest, + _ ...grpc.CallOption, +) (*protos.CreateInstanceResponse, error) { + c.start = req + if c.err != nil { + return nil, c.err + } + return &protos.CreateInstanceResponse{InstanceId: req.InstanceId}, nil +} + +func (c *tracingSchedulerClient) RaiseEvent( + _ context.Context, + req *protos.RaiseEventRequest, + _ ...grpc.CallOption, +) (*protos.RaiseEventResponse, error) { + c.event = req + if c.err != nil { + return nil, c.err + } + return &protos.RaiseEventResponse{}, nil +} + +func newTracedClient(fake *tracingSchedulerClient, opts ...TaskHubGrpcClientOption) *TaskHubGrpcClient { + client := &TaskHubGrpcClient{client: fake, logger: api.DefaultLogger(), converter: api.DefaultDataConverter()} + for _, configure := range opts { + configure(client) + } + return client +} + +func TestClientTracingProducerSpans(t *testing.T) { + recorder := tracetest.NewSpanRecorder() + provider := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(recorder)) + fake := &tracingSchedulerClient{} + client := newTracedClient(fake, WithTracerProvider(provider)) + caller, _ := newTraceParent(trace.FlagsSampled) + ctx := trace.ContextWithRemoteSpanContext(context.Background(), caller) + + id, err := client.ScheduleNewOrchestration(ctx, "Orch", + api.WithInstanceID("instance-1"), api.WithVersion("1.0")) + require.NoError(t, err) + require.NoError(t, client.RaiseEvent(ctx, id, "Approved")) + + spans := recorder.Ended() + require.Len(t, spans, 2) + create, event := spans[0], spans[1] + + require.Equal(t, "create_orchestration:Orch@(1.0)", create.Name()) + require.Equal(t, trace.SpanKindProducer, create.SpanKind()) + require.Equal(t, caller.SpanID(), create.Parent().SpanID()) + require.Equal(t, caller.TraceID(), create.SpanContext().TraceID()) + require.Equal(t, "orchestration", spanAttribute(create, "durabletask.type")) + require.Equal(t, "Orch", spanAttribute(create, "durabletask.task.name")) + require.Equal(t, "1.0", spanAttribute(create, "durabletask.task.version")) + require.Equal(t, "instance-1", spanAttribute(create, "durabletask.task.instance_id")) + require.Equal(t, codes.Unset, create.Status().Code) + // The orchestration is parented to the PRODUCER span, keeping tracestate. + propagated := helpers.SpanContextFromTraceContext(fake.start.ParentTraceContext) + require.Equal(t, create.SpanContext().SpanID(), propagated.SpanID()) + require.Equal(t, caller.TraceState().String(), propagated.TraceState().String()) + + require.Equal(t, "orchestration_event:Approved", event.Name()) + require.Equal(t, trace.SpanKindProducer, event.SpanKind()) + require.Equal(t, caller.SpanID(), event.Parent().SpanID()) + require.Equal(t, "event", spanAttribute(event, "durabletask.type")) + require.Equal(t, "Approved", spanAttribute(event, "durabletask.task.name")) + require.Equal(t, "instance-1", spanAttribute(event, "durabletask.event.target_instance_id")) + require.Equal(t, codes.Unset, event.Status().Code) +} + +func TestClientTracingFailedCallsMarkSpansAsErrors(t *testing.T) { + recorder := tracetest.NewSpanRecorder() + provider := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(recorder)) + fake := &tracingSchedulerClient{err: errors.New("unavailable")} + client := newTracedClient(fake, WithTracerProvider(provider)) + + _, err := client.ScheduleNewOrchestration(context.Background(), "Orch") + require.Error(t, err) + require.Error(t, client.RaiseEvent(context.Background(), "instance-1", "Approved")) + + spans := recorder.Ended() + require.Len(t, spans, 2) + for _, span := range spans { + require.Equal(t, codes.Error, span.Status().Code, span.Name()) + require.Contains(t, span.Status().Description, "unavailable") + require.Len(t, span.Events(), 1) + require.Equal(t, "exception", span.Events()[0].Name) + } + require.Equal(t, "create_orchestration:Orch", spans[0].Name()) + require.Empty(t, spanAttribute(spans[0], "durabletask.task.version")) +} + +func TestClientTracingUnsampledCallerPropagatesProducerContext(t *testing.T) { + recorder := tracetest.NewSpanRecorder() + provider := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(recorder)) + fake := &tracingSchedulerClient{} + client := newTracedClient(fake, WithTracerProvider(provider)) + caller, _ := newTraceParent(0) + ctx := trace.ContextWithRemoteSpanContext(context.Background(), caller) + + _, err := client.ScheduleNewOrchestration(ctx, "Orch") + require.NoError(t, err) + + require.Empty(t, recorder.Ended()) + propagated := helpers.SpanContextFromTraceContext(fake.start.ParentTraceContext) + require.True(t, propagated.IsValid()) + require.False(t, propagated.IsSampled()) + require.Equal(t, caller.TraceID(), propagated.TraceID()) + require.NotEqual(t, caller.SpanID(), propagated.SpanID()) +} + +func TestClientTracingParentsWorkerOrchestrationSpan(t *testing.T) { + sampledCaller, _ := newTraceParent(trace.FlagsSampled) + for name, caller := range map[string]trace.SpanContext{ + "caller-span": sampledCaller, + "root": {}, + } { + t.Run(name, func(t *testing.T) { + // The client accepts the provider configuration the worker requires, + // so applications can share one provider. + recorder := tracetest.NewSpanRecorder() + provider := sdktrace.NewTracerProvider( + tracing.WithIDGenerator(nil), + tracing.WithSampler(nil), + sdktrace.WithSpanProcessor(recorder), + ) + fake := &tracingSchedulerClient{} + client := newTracedClient(fake, WithTracerProvider(provider)) + ctx := context.Background() + if caller.IsValid() { + ctx = trace.ContextWithRemoteSpanContext(ctx, caller) + } + _, err := client.ScheduleNewOrchestration(ctx, "Linked", api.WithInstanceID("linked")) + require.NoError(t, err) + create := recorder.Ended()[0] + if caller.IsValid() { + require.Equal(t, caller.SpanID(), create.Parent().SpanID()) + } else { + require.False(t, create.Parent().IsValid()) + } + + registry := task.NewTaskRegistry() + require.NoError(t, registry.AddOrchestratorN("Linked", func(*task.OrchestrationContext) (any, error) { + return nil, nil + })) + h := newTracingHarness(t, registry, true) + backend := newFakeOrchestrationBackend("linked", helpers.NewExecutionStartedEvent( + "Linked", "linked", nil, nil, fake.start.ParentTraceContext, nil)) + backend.dispatch(t, h) + + orchestration := spansNamed(h.spans(), "orchestration:Linked") + require.Len(t, orchestration, 1) + require.Equal(t, create.SpanContext().TraceID(), orchestration[0].SpanContext().TraceID()) + require.Equal(t, create.SpanContext().SpanID(), orchestration[0].Parent().SpanID()) + }) + } +} + +func TestClientTracingDisabledKeepsPropagationOnly(t *testing.T) { + for name, opts := range map[string][]TaskHubGrpcClientOption{ + "default": nil, + "nil-provider": {WithTracerProvider(nil)}, + } { + t.Run(name, func(t *testing.T) { + fake := &tracingSchedulerClient{} + client := newTracedClient(fake, opts...) + require.Nil(t, client.tracer) + + sampled, wire := newTraceParent(trace.FlagsSampled) + ctx := trace.ContextWithRemoteSpanContext(context.Background(), sampled) + _, err := client.ScheduleNewOrchestration(ctx, "Orch") + require.NoError(t, err) + require.Equal(t, wire.GetTraceParent(), fake.start.ParentTraceContext.GetTraceParent()) + + unsampled, _ := newTraceParent(0) + ctx = trace.ContextWithRemoteSpanContext(context.Background(), unsampled) + _, err = client.ScheduleNewOrchestration(ctx, "Orch") + require.NoError(t, err) + require.Nil(t, fake.start.ParentTraceContext) + }) + } +} diff --git a/durabletaskscheduler/client.go b/durabletaskscheduler/client.go index c8bc7520..44e77884 100644 --- a/durabletaskscheduler/client.go +++ b/durabletaskscheduler/client.go @@ -25,8 +25,15 @@ type Client struct { // NewClient creates an independently owned management connection and validates // it with a deadline-bound Hello call. -// A nil logger uses [api.DefaultLogger]. -func NewClient(ctx context.Context, options *Options, logger api.Logger) (*Client, error) { +// A nil logger uses [api.DefaultLogger]. clientOptions are applied after the +// options derived from options, so they take precedence; for example, pass +// client.WithTracerProvider to enable client spans. +func NewClient( + ctx context.Context, + options *Options, + logger api.Logger, + clientOptions ...durabletaskclient.TaskHubGrpcClientOption, +) (*Client, error) { if logger == nil { logger = api.DefaultLogger() } @@ -59,15 +66,16 @@ func NewClient(ctx context.Context, options *Options, logger api.Logger) (*Clien prepared.ChannelRecreateMinInterval, logger, ) - clientOptions := []durabletaskclient.TaskHubGrpcClientOption{ + configuredOptions := []durabletaskclient.TaskHubGrpcClientOption{ durabletaskclient.WithLargePayloads(prepared.LargePayloads), durabletaskclient.WithDataConverter(prepared.DataConverter), } if prepared.Versioning != nil && prepared.Versioning.DefaultVersion != "" { - clientOptions = append(clientOptions, durabletaskclient.WithDefaultVersion(prepared.Versioning.DefaultVersion)) + configuredOptions = append(configuredOptions, durabletaskclient.WithDefaultVersion(prepared.Versioning.DefaultVersion)) } + configuredOptions = append(configuredOptions, clientOptions...) return &Client{ - TaskHubGrpcClient: durabletaskclient.NewTaskHubGrpcClient(connection, logger, clientOptions...), + TaskHubGrpcClient: durabletaskclient.NewTaskHubGrpcClient(connection, logger, configuredOptions...), connection: connection, converter: api.NormalizeDataConverter(prepared.DataConverter), }, nil diff --git a/internal/dttrace/client.go b/internal/dttrace/client.go new file mode 100644 index 00000000..0db8cd8c --- /dev/null +++ b/internal/dttrace/client.go @@ -0,0 +1,71 @@ +package dttrace + +import ( + "context" + + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/codes" + "go.opentelemetry.io/otel/trace" +) + +// AttrEventTargetInstanceID identifies the orchestration that receives an event. +const AttrEventTargetInstanceID = attribute.Key("durabletask.event.target_instance_id") + +const ( + typeEvent = "event" + typeCreateOrchestration = "create_orchestration" + typeOrchestrationEvent = "orchestration_event" +) + +// ClientTracer emits live client PRODUCER spans. Unlike [Tracer] it never +// reconstructs spans, so any provider is accepted. +type ClientTracer struct { + tracer trace.Tracer +} + +// NewClientTracer returns nil for a nil provider, which disables client spans. +func NewClientTracer(provider trace.TracerProvider) *ClientTracer { + if provider == nil { + return nil + } + return &ClientTracer{tracer: provider.Tracer(ScopeName)} +} + +// StartCreateOrchestration starts the PRODUCER span for scheduling an +// orchestration as a child of the span in ctx. The returned context carries +// the new span so it becomes the orchestration's parent trace context. +func (t *ClientTracer) StartCreateOrchestration( + ctx context.Context, + name, version, instanceID, executionID string, +) (context.Context, trace.Span) { + attrs := taskAttributes(typeOrchestration, name, version, instanceID) + if executionID != "" { + attrs = append(attrs, AttrExecutionID.String(executionID)) + } + return t.tracer.Start(ctx, SpanName(typeCreateOrchestration, name, version), + trace.WithSpanKind(trace.SpanKindProducer), + trace.WithAttributes(attrs...), + ) +} + +// StartRaiseEvent starts the PRODUCER span for raising an event to an +// orchestration as a child of the span in ctx. +func (t *ClientTracer) StartRaiseEvent(ctx context.Context, eventName, instanceID string) (context.Context, trace.Span) { + return t.tracer.Start(ctx, SpanName(typeOrchestrationEvent, eventName, ""), + trace.WithSpanKind(trace.SpanKindProducer), + trace.WithAttributes( + AttrType.String(typeEvent), + AttrName.String(eventName), + AttrEventTargetInstanceID.String(instanceID), + ), + ) +} + +// EndClientSpan records err, if any, and ends span. +func EndClientSpan(span trace.Span, err error) { + if err != nil { + span.RecordError(err) + span.SetStatus(codes.Error, err.Error()) + } + span.End() +} diff --git a/tracing/tracing.go b/tracing/tracing.go index eb695b63..4d940371 100644 --- a/tracing/tracing.go +++ b/tracing/tracing.go @@ -1,9 +1,9 @@ // Package tracing configures opt-in OpenTelemetry spans for Durable Task -// workers. +// clients and workers. // -// By default workers only propagate W3C trace context and emit no spans. -// Enable spans with client.WithWorkerTracerProvider and a provider built with -// [WithIDGenerator] and [WithSampler]: +// 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]: // // provider := sdktrace.NewTracerProvider( // tracing.WithIDGenerator(nil), @@ -12,6 +12,17 @@ // ) // worker, err := durabletaskscheduler.NewWorker(..., client.WithWorkerTracerProvider(provider)) // +// Enable client spans with client.WithTracerProvider, which accepts any +// provider: +// +// c, err := durabletaskscheduler.NewClient(ctx, options, logger, client.WithTracerProvider(provider)) +// +// The client emits a PRODUCER span named "create_orchestration:" (with +// an "@()" suffix when versioned) for each ScheduleNewOrchestration +// call and parents the new orchestration to it, and a PRODUCER span named +// "orchestration_event:" for each RaiseEvent call. Both are children of +// the span in the call's context, and failed calls record an error status. +// // The application owns the provider's resource, sampling policy, processors, // exporter, and shutdown. Spans use the "Microsoft.DurableTask" // instrumentation scope, like the Durable Task .NET, JavaScript, and Java SDKs. From 3d9062986d43368e9a7193c7e341e42b8a1c3842 Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Mon, 23 Nov 2026 12:05:36 -0700 Subject: [PATCH 2/5] Address client tracing review feedback Clarify that durabletaskscheduler.NewClient client options are for settings Options does not cover, document global and shared providers for client spans, cover payload externalization failures and constructor option forwarding, and add a changelog entry for client PRODUCER spans. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 1 + client/client_grpc.go | 3 +- client/client_grpc_tracing_test.go | 66 ++++++++++++++------ durabletaskscheduler/client.go | 8 ++- durabletaskscheduler/client_tracing_test.go | 67 +++++++++++++++++++++ internal/dttrace/client.go | 3 +- tracing/tracing.go | 10 ++- 7 files changed, 132 insertions(+), 26 deletions(-) create mode 100644 durabletaskscheduler/client_tracing_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 7fac8ba4..57788bc7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -47,6 +47,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - 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 `task.IsCompleted`, a non-blocking check that reports whether an orchestration task has succeeded, failed, or been canceled, without consuming its result or advancing history. It observes completion at the current replay position: after `WhenAny` or `Select` wakes on a completion, only the selected task is guaranteed complete. It panics for nil or custom `Task` implementations, matching `OnTask`, and outside an orchestration coroutine, matching `Select`. The `Task` interface is unchanged. - 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. Scheduling an orchestration or signaling an entity now propagates an unsampled caller context, with its tracestate, instead of dropping it, so an unsampled caller no longer starts a new, independently sampled trace. The `durabletasktest` in-memory service persists the orchestration span identity between dispatches, as DTS does. +- 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. ### Removed diff --git a/client/client_grpc.go b/client/client_grpc.go index ef08441c..180bfebd 100644 --- a/client/client_grpc.go +++ b/client/client_grpc.go @@ -80,7 +80,8 @@ func WithDataConverter(converter api.DataConverter) TaskHubGrpcClientOption { // context, and a scheduled orchestration is parented to its // create_orchestration span. Failed calls mark the span as an error. // -// Any provider is accepted; tracing.WithIDGenerator and tracing.WithSampler are +// Any provider is accepted, including otel.GetTracerProvider(); +// tracing.WithIDGenerator and tracing.WithSampler are // required only for worker tracing, and a provider configured with them can be // shared with the worker. The application owns the provider's configuration and // shutdown. Without this option, or with a nil provider, the client emits no diff --git a/client/client_grpc_tracing_test.go b/client/client_grpc_tracing_test.go index 623f4315..db9142e1 100644 --- a/client/client_grpc_tracing_test.go +++ b/client/client_grpc_tracing_test.go @@ -77,6 +77,7 @@ func TestClientTracingProducerSpans(t *testing.T) { require.Equal(t, "create_orchestration:Orch@(1.0)", create.Name()) require.Equal(t, trace.SpanKindProducer, create.SpanKind()) + require.Equal(t, "Microsoft.DurableTask", create.InstrumentationScope().Name) require.Equal(t, caller.SpanID(), create.Parent().SpanID()) require.Equal(t, caller.TraceID(), create.SpanContext().TraceID()) require.Equal(t, "orchestration", spanAttribute(create, "durabletask.type")) @@ -99,25 +100,54 @@ func TestClientTracingProducerSpans(t *testing.T) { } func TestClientTracingFailedCallsMarkSpansAsErrors(t *testing.T) { - recorder := tracetest.NewSpanRecorder() - provider := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(recorder)) - fake := &tracingSchedulerClient{err: errors.New("unavailable")} - client := newTracedClient(fake, WithTracerProvider(provider)) - - _, err := client.ScheduleNewOrchestration(context.Background(), "Orch") - require.Error(t, err) - require.Error(t, client.RaiseEvent(context.Background(), "instance-1", "Approved")) - - spans := recorder.Ended() - require.Len(t, spans, 2) - for _, span := range spans { - require.Equal(t, codes.Error, span.Status().Code, span.Name()) - require.Contains(t, span.Status().Description, "unavailable") - require.Len(t, span.Events(), 1) - require.Equal(t, "exception", span.Events()[0].Name) + failingStore := &failingPayloadBackend{storeErr: errors.New("store unavailable")} + for name, test := range map[string]struct { + fake *tracingSchedulerClient + opts []TaskHubGrpcClientOption + errorContains string + }{ + "rpc": { + fake: &tracingSchedulerClient{err: errors.New("unavailable")}, + errorContains: "unavailable", + }, + "payload-externalization": { + fake: &tracingSchedulerClient{}, + opts: []TaskHubGrpcClientOption{WithLargePayloads(&api.LargePayloadOptions{ + Store: failingStore, + Resolver: failingStore, + ThresholdBytes: 1, + MaxPayloadBytes: 1024, + })}, + errorContains: "store unavailable", + }, + } { + t.Run(name, func(t *testing.T) { + recorder := tracetest.NewSpanRecorder() + provider := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(recorder)) + client := newTracedClient(test.fake, append(test.opts, WithTracerProvider(provider))...) + + _, err := client.ScheduleNewOrchestration(context.Background(), "Orch", api.WithRawInput("input")) + require.ErrorContains(t, err, test.errorContains) + err = client.RaiseEvent(context.Background(), "instance-1", "Approved", api.WithRawEventData("data")) + require.ErrorContains(t, err, test.errorContains) + + spans := recorder.Ended() + require.Len(t, spans, 2) + for _, span := range spans { + require.Equal(t, codes.Error, span.Status().Code, span.Name()) + require.Contains(t, span.Status().Description, test.errorContains) + require.Len(t, span.Events(), 1) + require.Equal(t, "exception", span.Events()[0].Name) + } + require.Equal(t, "create_orchestration:Orch", spans[0].Name()) + require.Empty(t, spanAttribute(spans[0], "durabletask.task.version")) + require.Equal(t, "orchestration_event:Approved", spans[1].Name()) + if test.fake.err == nil { + require.Nil(t, test.fake.start, "no RPC after a payload failure") + require.Nil(t, test.fake.event, "no RPC after a payload failure") + } + }) } - require.Equal(t, "create_orchestration:Orch", spans[0].Name()) - require.Empty(t, spanAttribute(spans[0], "durabletask.task.version")) } func TestClientTracingUnsampledCallerPropagatesProducerContext(t *testing.T) { diff --git a/durabletaskscheduler/client.go b/durabletaskscheduler/client.go index 44e77884..e6421c3a 100644 --- a/durabletaskscheduler/client.go +++ b/durabletaskscheduler/client.go @@ -25,9 +25,11 @@ type Client struct { // NewClient creates an independently owned management connection and validates // it with a deadline-bound Hello call. -// A nil logger uses [api.DefaultLogger]. clientOptions are applied after the -// options derived from options, so they take precedence; for example, pass -// client.WithTracerProvider to enable client spans. +// A nil logger uses [api.DefaultLogger]. clientOptions configure client +// behavior that Options does not cover, such as client.WithTracerProvider to +// enable client spans. Configure data conversion, large payloads, and the +// default version through Options rather than the equivalent client options; +// for example, ScheduledTasks always encodes with Options.DataConverter. func NewClient( ctx context.Context, options *Options, diff --git a/durabletaskscheduler/client_tracing_test.go b/durabletaskscheduler/client_tracing_test.go new file mode 100644 index 00000000..0041528f --- /dev/null +++ b/durabletaskscheduler/client_tracing_test.go @@ -0,0 +1,67 @@ +package durabletaskscheduler + +import ( + "context" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/require" + sdktrace "go.opentelemetry.io/otel/sdk/trace" + "go.opentelemetry.io/otel/sdk/trace/tracetest" + "google.golang.org/protobuf/types/known/emptypb" + + "github.com/microsoft/durabletask-go/api" + durabletaskclient "github.com/microsoft/durabletask-go/client" + "github.com/microsoft/durabletask-go/internal/helpers" + "github.com/microsoft/durabletask-go/internal/protos" + "github.com/microsoft/durabletask-go/task" +) + +type startRecordingServer struct { + protos.UnimplementedTaskHubSidecarServiceServer + mu sync.Mutex + start *protos.CreateInstanceRequest +} + +func (*startRecordingServer) Hello(context.Context, *emptypb.Empty) (*emptypb.Empty, error) { + return &emptypb.Empty{}, nil +} + +func (s *startRecordingServer) StartInstance( + _ context.Context, + req *protos.CreateInstanceRequest, +) (*protos.CreateInstanceResponse, error) { + s.mu.Lock() + defer s.mu.Unlock() + s.start = req + return &protos.CreateInstanceResponse{InstanceId: req.InstanceId}, nil +} + +func TestNewClientAppliesTrailingClientOptions(t *testing.T) { + server := new(startRecordingServer) + listener, stop := startBufconnServer(t, server) + defer stop() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + options := insecureBufconnOptions(t, listener) + options.Versioning = &task.VersioningOptions{DefaultVersion: "1.0"} + recorder := tracetest.NewSpanRecorder() + provider := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(recorder)) + + client, err := NewClient(ctx, options, api.DefaultLogger(), durabletaskclient.WithTracerProvider(provider)) + require.NoError(t, err) + defer func() { require.NoError(t, client.Close()) }() + _, err = client.ScheduleNewOrchestration(ctx, "Orch", api.WithInstanceID("instance-1")) + require.NoError(t, err) + + spans := recorder.Ended() + require.Len(t, spans, 1) + // The default version comes from Options, so both option sources apply. + require.Equal(t, "create_orchestration:Orch@(1.0)", spans[0].Name()) + server.mu.Lock() + defer server.mu.Unlock() + require.Equal(t, "1.0", server.start.GetVersion().GetValue()) + propagated := helpers.SpanContextFromTraceContext(server.start.ParentTraceContext) + require.Equal(t, spans[0].SpanContext().SpanID(), propagated.SpanID()) +} diff --git a/internal/dttrace/client.go b/internal/dttrace/client.go index 0db8cd8c..cdf9f7e2 100644 --- a/internal/dttrace/client.go +++ b/internal/dttrace/client.go @@ -33,7 +33,8 @@ func NewClientTracer(provider trace.TracerProvider) *ClientTracer { // StartCreateOrchestration starts the PRODUCER span for scheduling an // orchestration as a child of the span in ctx. The returned context carries -// the new span so it becomes the orchestration's parent trace context. +// the new span so it becomes the orchestration's parent trace context. An +// empty executionID, the usual case, omits the execution ID attribute. func (t *ClientTracer) StartCreateOrchestration( ctx context.Context, name, version, instanceID, executionID string, diff --git a/tracing/tracing.go b/tracing/tracing.go index 4d940371..9c609ea9 100644 --- a/tracing/tracing.go +++ b/tracing/tracing.go @@ -12,8 +12,11 @@ // ) // worker, err := durabletaskscheduler.NewWorker(..., client.WithWorkerTracerProvider(provider)) // -// Enable client spans with client.WithTracerProvider, which accepts any -// 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]: // // c, err := durabletaskscheduler.NewClient(ctx, options, logger, client.WithTracerProvider(provider)) // @@ -21,7 +24,8 @@ // an "@()" suffix when versioned) for each ScheduleNewOrchestration // call and parents the new orchestration to it, and a PRODUCER span named // "orchestration_event:" for each RaiseEvent call. Both are children of -// the span in the call's context, and failed calls record an error status. +// the span in the call's context, and failed calls, including payload +// externalization failures, record an error status. // // The application owns the provider's resource, sampling policy, processors, // exporter, and shutdown. Spans use the "Microsoft.DurableTask" From 84a2abd93b1890804befac60b2526a6bc993cf56 Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Mon, 30 Nov 2026 15:19:39 -0700 Subject: [PATCH 3/5] Record client span errors for rejected request options Start the create-orchestration and raise-event PRODUCER spans before applying request options so serialization and validation failures, such as an unserializable payload or a reserved instance ID, are recorded as span errors. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- client/client_grpc.go | 28 ++++++++++++++++----------- client/client_grpc_tracing_test.go | 31 ++++++++++++++++++++++++++++++ tracing/tracing.go | 5 +++-- 3 files changed, 51 insertions(+), 13 deletions(-) diff --git a/client/client_grpc.go b/client/client_grpc.go index 180bfebd..036d9e30 100644 --- a/client/client_grpc.go +++ b/client/client_grpc.go @@ -111,18 +111,18 @@ func NewTaskHubGrpcClient(cc grpc.ClientConnInterface, logger api.Logger, opts . // ScheduleNewOrchestration schedules a new orchestration instance with a specified set of options for execution. func (c *TaskHubGrpcClient) ScheduleNewOrchestration(ctx context.Context, orchestrator string, opts ...api.NewOrchestrationOptions) (_ api.InstanceID, err error) { req := &protos.CreateInstanceRequest{Name: orchestrator} + var configErr error for _, configure := range opts { - if err := configure(req, c.converter); err != nil { - return api.EmptyInstanceID, fmt.Errorf( - "failed to configure orchestration request: %w", - api.WrapInvalidArgument(err), - ) + if configErr = configure(req, c.converter); configErr != nil { + break } } if req.Version == nil && c.defaultVersion != "" { req.Version = wrapperspb.String(c.defaultVersion) } - if req.InstanceId == "" { + // A failed option, such as an invalid instance ID, leaves the ID unset + // rather than tagging the span with a generated ID that was never used. + if req.InstanceId == "" && configErr == nil { u, err := uuid.NewV7() if err == nil { req.InstanceId = u.String() @@ -136,6 +136,12 @@ func (c *TaskHubGrpcClient) ScheduleNewOrchestration(ctx context.Context, orches req.InstanceId, req.ExecutionId.GetValue()) defer func() { dttrace.EndClientSpan(span, err) }() } + if configErr != nil { + return api.EmptyInstanceID, fmt.Errorf( + "failed to configure orchestration request: %w", + api.WrapInvalidArgument(configErr), + ) + } req.Input, err = largepayload.Externalize(ctx, c.largePayloads, req.Input) if err != nil { return api.EmptyInstanceID, fmt.Errorf("failed to externalize orchestration input: %w", err) @@ -246,17 +252,17 @@ func (c *TaskHubGrpcClient) TerminateOrchestration(ctx context.Context, id api.I // RaiseEvent sends an asynchronous event notification to a waiting orchestration. func (c *TaskHubGrpcClient) RaiseEvent(ctx context.Context, id api.InstanceID, eventName string, opts ...api.RaiseEventOptions) (err error) { + if c.tracer != nil { + var span trace.Span + ctx, span = c.tracer.StartRaiseEvent(ctx, eventName, string(id)) + defer func() { dttrace.EndClientSpan(span, err) }() + } req := &protos.RaiseEventRequest{InstanceId: string(id), Name: eventName} for _, configure := range opts { if err := configure(req, c.converter); err != nil { return fmt.Errorf("failed to configure raise event request: %w", api.WrapInvalidArgument(err)) } } - if c.tracer != nil { - var span trace.Span - ctx, span = c.tracer.StartRaiseEvent(ctx, eventName, string(id)) - defer func() { dttrace.EndClientSpan(span, err) }() - } req.Input, err = largepayload.Externalize(ctx, c.largePayloads, req.Input) if err != nil { return fmt.Errorf("failed to externalize event payload: %w", err) diff --git a/client/client_grpc_tracing_test.go b/client/client_grpc_tracing_test.go index db9142e1..3cbd4593 100644 --- a/client/client_grpc_tracing_test.go +++ b/client/client_grpc_tracing_test.go @@ -150,6 +150,37 @@ func TestClientTracingFailedCallsMarkSpansAsErrors(t *testing.T) { } } +func TestClientTracingOptionFailuresMarkSpansAsErrors(t *testing.T) { + recorder := tracetest.NewSpanRecorder() + provider := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(recorder)) + fake := &tracingSchedulerClient{} + client := newTracedClient(fake, WithTracerProvider(provider)) + unserializable := make(chan int) + + _, err := client.ScheduleNewOrchestration(context.Background(), "Orch", api.WithInput(unserializable)) + require.ErrorIs(t, err, api.ErrInvalidArgument) + _, err = client.ScheduleNewOrchestration(context.Background(), "Orch", api.WithInstanceID("@counter@key")) + require.ErrorIs(t, err, api.ErrInvalidArgument) + err = client.RaiseEvent(context.Background(), "instance-1", "Approved", api.WithEventPayload(unserializable)) + require.ErrorIs(t, err, api.ErrInvalidArgument) + + spans := recorder.Ended() + require.Len(t, spans, 3) + for _, span := range spans { + require.Equal(t, trace.SpanKindProducer, span.SpanKind(), span.Name()) + require.Equal(t, codes.Error, span.Status().Code, span.Name()) + require.Len(t, span.Events(), 1) + require.Equal(t, "exception", span.Events()[0].Name) + } + require.Equal(t, "create_orchestration:Orch", spans[0].Name()) + require.Equal(t, "create_orchestration:Orch", spans[1].Name()) + require.Empty(t, spanAttribute(spans[1], "durabletask.task.instance_id"), "no generated ID for a rejected request") + require.Equal(t, "orchestration_event:Approved", spans[2].Name()) + require.Equal(t, "instance-1", spanAttribute(spans[2], "durabletask.event.target_instance_id")) + require.Nil(t, fake.start, "no RPC after an option failure") + require.Nil(t, fake.event, "no RPC after an option failure") +} + func TestClientTracingUnsampledCallerPropagatesProducerContext(t *testing.T) { recorder := tracetest.NewSpanRecorder() provider := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(recorder)) diff --git a/tracing/tracing.go b/tracing/tracing.go index 9c609ea9..4b1123cb 100644 --- a/tracing/tracing.go +++ b/tracing/tracing.go @@ -24,8 +24,9 @@ // an "@()" suffix when versioned) for each ScheduleNewOrchestration // call and parents the new orchestration to it, and a PRODUCER span named // "orchestration_event:" for each RaiseEvent call. Both are children of -// the span in the call's context, and failed calls, including payload -// externalization failures, record an error status. +// the span in the call's context, and failed calls, including invalid options, +// payload serialization, and payload externalization failures, record an error +// status. // // The application owns the provider's resource, sampling policy, processors, // exporter, and shutdown. Spans use the "Microsoft.DurableTask" From 3600e1a31e7b73f6c53e9a03eab7a44c869b6e07 Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Mon, 30 Nov 2026 15:44:24 -0700 Subject: [PATCH 4/5] Align client tracing with unsampled parent propagation Preserve unsampled caller propagation and verify it with standard and worker-compatible tracer providers. Cover request metadata on option failures. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- client/client_grpc.go | 3 +- client/client_grpc_tracing_test.go | 49 +++++++++++++++++++----------- 2 files changed, 32 insertions(+), 20 deletions(-) diff --git a/client/client_grpc.go b/client/client_grpc.go index 036d9e30..30650883 100644 --- a/client/client_grpc.go +++ b/client/client_grpc.go @@ -120,8 +120,7 @@ func (c *TaskHubGrpcClient) ScheduleNewOrchestration(ctx context.Context, orches if req.Version == nil && c.defaultVersion != "" { req.Version = wrapperspb.String(c.defaultVersion) } - // A failed option, such as an invalid instance ID, leaves the ID unset - // rather than tagging the span with a generated ID that was never used. + // Do not generate an ID for a request rejected by an option. if req.InstanceId == "" && configErr == nil { u, err := uuid.NewV7() if err == nil { diff --git a/client/client_grpc_tracing_test.go b/client/client_grpc_tracing_test.go index 3cbd4593..9a3b30bc 100644 --- a/client/client_grpc_tracing_test.go +++ b/client/client_grpc_tracing_test.go @@ -157,7 +157,8 @@ func TestClientTracingOptionFailuresMarkSpansAsErrors(t *testing.T) { client := newTracedClient(fake, WithTracerProvider(provider)) unserializable := make(chan int) - _, err := client.ScheduleNewOrchestration(context.Background(), "Orch", api.WithInput(unserializable)) + _, err := client.ScheduleNewOrchestration(context.Background(), "Orch", + api.WithInstanceID("input-id"), api.WithVersion("2.0"), api.WithInput(unserializable)) require.ErrorIs(t, err, api.ErrInvalidArgument) _, err = client.ScheduleNewOrchestration(context.Background(), "Orch", api.WithInstanceID("@counter@key")) require.ErrorIs(t, err, api.ErrInvalidArgument) @@ -169,10 +170,12 @@ func TestClientTracingOptionFailuresMarkSpansAsErrors(t *testing.T) { for _, span := range spans { require.Equal(t, trace.SpanKindProducer, span.SpanKind(), span.Name()) require.Equal(t, codes.Error, span.Status().Code, span.Name()) + require.Contains(t, span.Status().Description, "failed to configure") require.Len(t, span.Events(), 1) require.Equal(t, "exception", span.Events()[0].Name) } - require.Equal(t, "create_orchestration:Orch", spans[0].Name()) + require.Equal(t, "create_orchestration:Orch@(2.0)", spans[0].Name()) + require.Equal(t, "input-id", spanAttribute(spans[0], "durabletask.task.instance_id")) require.Equal(t, "create_orchestration:Orch", spans[1].Name()) require.Empty(t, spanAttribute(spans[1], "durabletask.task.instance_id"), "no generated ID for a rejected request") require.Equal(t, "orchestration_event:Approved", spans[2].Name()) @@ -182,22 +185,30 @@ func TestClientTracingOptionFailuresMarkSpansAsErrors(t *testing.T) { } func TestClientTracingUnsampledCallerPropagatesProducerContext(t *testing.T) { - recorder := tracetest.NewSpanRecorder() - provider := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(recorder)) - fake := &tracingSchedulerClient{} - client := newTracedClient(fake, WithTracerProvider(provider)) - caller, _ := newTraceParent(0) - ctx := trace.ContextWithRemoteSpanContext(context.Background(), caller) + for name, opts := range map[string][]sdktrace.TracerProviderOption{ + "standard": nil, + "worker-compatible": {tracing.WithIDGenerator(nil), tracing.WithSampler(nil)}, + } { + t.Run(name, func(t *testing.T) { + recorder := tracetest.NewSpanRecorder() + provider := sdktrace.NewTracerProvider(append(opts, sdktrace.WithSpanProcessor(recorder))...) + fake := &tracingSchedulerClient{} + client := newTracedClient(fake, WithTracerProvider(provider)) + caller, _ := newTraceParent(0) + ctx := trace.ContextWithRemoteSpanContext(context.Background(), caller) - _, err := client.ScheduleNewOrchestration(ctx, "Orch") - require.NoError(t, err) + _, err := client.ScheduleNewOrchestration(ctx, "Orch") + require.NoError(t, err) - require.Empty(t, recorder.Ended()) - propagated := helpers.SpanContextFromTraceContext(fake.start.ParentTraceContext) - require.True(t, propagated.IsValid()) - require.False(t, propagated.IsSampled()) - require.Equal(t, caller.TraceID(), propagated.TraceID()) - require.NotEqual(t, caller.SpanID(), propagated.SpanID()) + require.Empty(t, recorder.Ended()) + propagated := helpers.SpanContextFromTraceContext(fake.start.ParentTraceContext) + require.True(t, propagated.IsValid()) + require.False(t, propagated.IsSampled()) + require.Equal(t, caller.TraceID(), propagated.TraceID()) + require.NotEqual(t, caller.SpanID(), propagated.SpanID()) + require.Equal(t, caller.TraceState().String(), propagated.TraceState().String()) + }) + } } func TestClientTracingParentsWorkerOrchestrationSpan(t *testing.T) { @@ -262,12 +273,14 @@ func TestClientTracingDisabledKeepsPropagationOnly(t *testing.T) { _, err := client.ScheduleNewOrchestration(ctx, "Orch") require.NoError(t, err) require.Equal(t, wire.GetTraceParent(), fake.start.ParentTraceContext.GetTraceParent()) + require.Equal(t, wire.GetTraceState().GetValue(), fake.start.ParentTraceContext.GetTraceState().GetValue()) - unsampled, _ := newTraceParent(0) + unsampled, unsampledWire := newTraceParent(0) ctx = trace.ContextWithRemoteSpanContext(context.Background(), unsampled) _, err = client.ScheduleNewOrchestration(ctx, "Orch") require.NoError(t, err) - require.Nil(t, fake.start.ParentTraceContext) + require.Equal(t, unsampledWire.GetTraceParent(), fake.start.ParentTraceContext.GetTraceParent()) + require.Equal(t, unsampledWire.GetTraceState().GetValue(), fake.start.ParentTraceContext.GetTraceState().GetValue()) }) } } From ec0f8b1d3ca108f438554e145de8944fe85e60b6 Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Mon, 30 Nov 2026 16:27:55 -0700 Subject: [PATCH 5/5] Correct disabled client tracing propagation docs Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- client/client_grpc.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/client/client_grpc.go b/client/client_grpc.go index 30650883..62c04efc 100644 --- a/client/client_grpc.go +++ b/client/client_grpc.go @@ -85,7 +85,8 @@ func WithDataConverter(converter api.DataConverter) TaskHubGrpcClientOption { // required only for worker tracing, and a provider configured with them can be // shared with the worker. The application owns the provider's configuration and // shutdown. Without this option, or with a nil provider, the client emits no -// spans and only propagates the caller's sampled trace context. +// spans and only propagates the caller's valid trace context, sampled or +// unsampled, including its tracestate. func WithTracerProvider(provider trace.TracerProvider) TaskHubGrpcClientOption { return func(c *TaskHubGrpcClient) { c.tracer = dttrace.NewClientTracer(provider)