From e308c935865d9545a1a2a1743042ec5261e70e7a Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Mon, 23 Nov 2026 12:42:09 -0700 Subject: [PATCH 1/4] Add replay-aware entity tracing with Core span semantics Entity spans are named "entity::" and carry the DurableTask.Core "durabletask.task.operation" attribute (call_entity or signal_entity) plus "durabletask.entity.operation" (the operation name) used by the Python and JavaScript SDKs. Orchestrations emit CLIENT spans for entity calls when a new completion is consumed and PRODUCER spans for entity signals when accepted, using the same replay and acknowledgement rules as SendEvent. Calls and signals store only minimal state until a span is queued, and replayed signals whose acknowledgement is already in the request are not recorded. Lock operations emit no spans. Entity operation executions emit SERVER (call) and CONSUMER (signal) spans. Each operation's root span identity and sampling decision are reserved before the batch runs; the handler context carries that identity as a non-recording span context, and signals and orchestrations started by the operation carry it as their parent trace context. The span is reconstructed with operation-result timestamps only after the backend accepts the batch completion, so rejected, abandoned, or lost batches export nothing. Success leaves the status unset; failures set an error status and "durabletask.entity.error_message". V2 entity messages carry no trace context, so execution spans are independent roots. Client SignalEntity emits no span and propagates only a sampled caller context, matching the .NET gRPC client. This squashes the original entity tracing series onto the reworked orchestration event layer. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 1 + client/client_grpc_tracing_test.go | 68 +++- client/grpc_worker_processor.go | 37 +- client/grpc_worker_tracing_test.go | 629 ++++++++++++++++++++++++++++- internal/dttrace/dttrace.go | 53 ++- internal/dttrace/entity.go | 332 +++++++++++++++ task/entity.go | 32 +- task/executor.go | 14 +- task/orchestrator.go | 4 + tracing/tracing.go | 38 +- 10 files changed, 1151 insertions(+), 57 deletions(-) create mode 100644 internal/dttrace/entity.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f368a96..b46732bd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -49,6 +49,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - 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. - 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. ### Removed diff --git a/client/client_grpc_tracing_test.go b/client/client_grpc_tracing_test.go index 9a3b30bc..8ddb3c98 100644 --- a/client/client_grpc_tracing_test.go +++ b/client/client_grpc_tracing_test.go @@ -3,6 +3,7 @@ package client import ( "context" "errors" + "fmt" "testing" "github.com/stretchr/testify/require" @@ -21,9 +22,22 @@ import ( type tracingSchedulerClient struct { protos.TaskHubSidecarServiceClient - start *protos.CreateInstanceRequest - event *protos.RaiseEventRequest - err error + start *protos.CreateInstanceRequest + event *protos.RaiseEventRequest + signal *protos.SignalEntityRequest + err error +} + +func (c *tracingSchedulerClient) SignalEntity( + _ context.Context, + req *protos.SignalEntityRequest, + _ ...grpc.CallOption, +) (*protos.SignalEntityResponse, error) { + c.signal = req + if c.err != nil { + return nil, c.err + } + return &protos.SignalEntityResponse{}, nil } func (c *tracingSchedulerClient) StartInstance( @@ -284,3 +298,51 @@ func TestClientTracingDisabledKeepsPropagationOnly(t *testing.T) { }) } } + +func TestClientSignalEntityPropagatesCallerWithoutCreatingSpan(t *testing.T) { + entityID := api.NewEntityID("Counter", "c1") + for _, enabled := range []bool{false, true} { + for _, sampled := range []bool{false, true} { + name := fmt.Sprintf("provider=%t/sampled=%t", enabled, sampled) + t.Run(name, func(t *testing.T) { + recorder := tracetest.NewSpanRecorder() + provider := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(recorder)) + t.Cleanup(func() { _ = provider.Shutdown(context.Background()) }) + fake := &tracingSchedulerClient{} + var opts []TaskHubGrpcClientOption + if enabled { + opts = append(opts, WithTracerProvider(provider)) + } + client := newTracedClient(fake, opts...) + var flags trace.TraceFlags + if sampled { + flags = trace.FlagsSampled + } + caller, wire := newTraceParent(flags) + ctx := trace.ContextWithRemoteSpanContext(context.Background(), caller) + + require.NoError(t, client.SignalEntity(ctx, entityID, "add")) + require.Equal(t, wire.GetTraceParent(), fake.signal.ParentTraceContext.GetTraceParent()) + require.Equal(t, wire.GetTraceState().GetValue(), fake.signal.ParentTraceContext.GetTraceState().GetValue()) + require.Empty(t, recorder.Ended()) + }) + } + } +} + +func TestClientSignalEntityPreservesOptionTraceContext(t *testing.T) { + recorder := tracetest.NewSpanRecorder() + provider := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(recorder)) + t.Cleanup(func() { _ = provider.Shutdown(context.Background()) }) + fake := &tracingSchedulerClient{} + client := newTracedClient(fake, WithTracerProvider(provider)) + _, explicit := newTraceParent(trace.FlagsSampled) + option := func(req *protos.SignalEntityRequest, _ api.DataConverter) error { + req.ParentTraceContext = explicit + return nil + } + + require.NoError(t, client.SignalEntity(context.Background(), api.NewEntityID("Counter", "c1"), "add", option)) + require.Equal(t, explicit, fake.signal.ParentTraceContext) + require.Empty(t, recorder.Ended()) +} diff --git a/client/grpc_worker_processor.go b/client/grpc_worker_processor.go index 8038ca39..2dd5f1b5 100644 --- a/client/grpc_worker_processor.go +++ b/client/grpc_worker_processor.go @@ -658,13 +658,21 @@ func (w *TaskHubGrpcWorker) processEntityV2( w.abandonEntity(ctx, client, completionToken) return } + var batchTrace *dttrace.EntityBatch + if w.options.tracer != nil { + batchTrace = w.options.tracer.NewEntityBatch(entityID, batch) + } if err := largepayload.TransformEntityBatchRequest(ctx, w.options.largePayloads, batch); err != nil { w.logger.Errorf("%s: failed to hydrate entity batch payloads: %v", request.GetInstanceId(), err) if entityProcessingCanceled(ctx, err) { w.abandonEntity(ctx, client, completionToken) return } - w.completeEntityBatchFailure(ctx, client, request.GetInstanceId(), completionToken, err) + failedAt := time.Now() + result := newEntityBatchFailure(completionToken, err) + if w.completeEntityBatchResult(ctx, client, request.GetInstanceId(), result) { + batchTrace.Emit(result, failedAt, failedAt) + } return } executor, ok := w.executor.(task.EntityExecutor) @@ -673,7 +681,9 @@ func (w *TaskHubGrpcWorker) processEntityV2( w.abandonEntity(ctx, client, completionToken) return } - result, err := executeEntitySafely(ctx, executor, batch) + entityStartedAt := time.Now() + result, err := executeEntitySafely(dttrace.WithEntityBatch(ctx, batchTrace), executor, batch) + entityEndedAt := time.Now() if err != nil { if entityProcessingCanceled(ctx, err) { w.logger.Warnf("%s: entity execution canceled; abandoning work item", request.GetInstanceId()) @@ -698,11 +708,12 @@ func (w *TaskHubGrpcWorker) processEntityV2( w.abandonEntity(ctx, client, completionToken) return } - w.completeEntityBatchFailure(ctx, client, request.GetInstanceId(), completionToken, err) - return + result = newEntityBatchFailure(completionToken, err) } - w.completeEntityBatchResult(ctx, client, request.GetInstanceId(), result) + if w.completeEntityBatchResult(ctx, client, request.GetInstanceId(), result) { + batchTrace.Emit(result, entityStartedAt, entityEndedAt) + } } func executeEntitySafely( @@ -741,16 +752,6 @@ func newEntityBatchFailure(completionToken string, err error) *protos.EntityBatc } } -func (w *TaskHubGrpcWorker) completeEntityBatchFailure( - ctx context.Context, - client protos.TaskHubSidecarServiceClient, - instanceID string, - completionToken string, - err error, -) { - w.completeEntityBatchResult(ctx, client, instanceID, newEntityBatchFailure(completionToken, err)) -} - func validateEntityBatchResult( result *protos.EntityBatchResult, operationInfos []*protos.OperationInfo, @@ -791,7 +792,7 @@ func (w *TaskHubGrpcWorker) completeEntityBatchResult( client protos.TaskHubSidecarServiceClient, instanceID string, result *protos.EntityBatchResult, -) { +) bool { err := w.executeRPCWithRetry(ctx, "complete entity task", func(callCtx context.Context) error { _, callErr := client.CompleteEntityTask(callCtx, result) return callErr @@ -799,11 +800,13 @@ func (w *TaskHubGrpcWorker) completeEntityBatchResult( if err != nil { if isWorkItemGone(err) { w.logger.Warnf("%s: entity work item was no longer available before completion", instanceID) - return + return false } w.logger.Errorf("%s: failed to complete entity work item: %v", instanceID, err) w.abandonEntity(ctx, client, result.CompletionToken) + return false } + return true } func orchestrationWorkItemIdentity(pastEvents, newEvents []*protos.HistoryEvent) (string, string, bool) { diff --git a/client/grpc_worker_tracing_test.go b/client/grpc_worker_tracing_test.go index d0d17bcb..045a1fb1 100644 --- a/client/grpc_worker_tracing_test.go +++ b/client/grpc_worker_tracing_test.go @@ -8,6 +8,7 @@ import ( "testing" "time" + "github.com/google/uuid" "github.com/stretchr/testify/require" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/codes" @@ -17,17 +18,22 @@ import ( "go.opentelemetry.io/otel/trace/noop" grpccodes "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/durationpb" "google.golang.org/protobuf/types/known/timestamppb" "google.golang.org/protobuf/types/known/wrapperspb" "github.com/microsoft/durabletask-go/api" "github.com/microsoft/durabletask-go/internal/helpers" + "github.com/microsoft/durabletask-go/internal/largepayload" "github.com/microsoft/durabletask-go/internal/protos" + "github.com/microsoft/durabletask-go/payload" "github.com/microsoft/durabletask-go/task" "github.com/microsoft/durabletask-go/tracing" ) type tracingHarness struct { + provider *sdktrace.TracerProvider recorder *tracetest.SpanRecorder client *fakeSchedulerClient worker *TaskHubGrpcWorker @@ -65,7 +71,7 @@ func newTracingHarnessWithProviderOptions( } worker := newFakeWorker(t, client, options...) worker.executor = task.NewTaskExecutor(registry, executorOptions...) - return &tracingHarness{recorder: recorder, client: client, worker: worker} + return &tracingHarness{provider: provider, recorder: recorder, client: client, worker: worker} } func (h *tracingHarness) spans() []sdktrace.ReadOnlySpan { @@ -75,11 +81,12 @@ func (h *tracingHarness) spans() []sdktrace.ReadOnlySpan { // fakeOrchestrationBackend persists history and orchestration trace context // between dispatches the way a Durable Task backend does. type fakeOrchestrationBackend struct { - instanceID string - history []*protos.HistoryEvent - traceContext *protos.OrchestrationTraceContext - scheduled map[int32]*protos.TraceContext - pending []*protos.HistoryEvent + instanceID string + history []*protos.HistoryEvent + traceContext *protos.OrchestrationTraceContext + scheduled map[int32]*protos.TraceContext + pending []*protos.HistoryEvent + entityParameters *protos.OrchestratorEntityParameters } func newFakeOrchestrationBackend(instanceID string, started *protos.HistoryEvent) *fakeOrchestrationBackend { @@ -106,6 +113,7 @@ func (b *fakeOrchestrationBackend) dispatch( PastEvents: append([]*protos.HistoryEvent(nil), b.history...), NewEvents: append([]*protos.HistoryEvent{helpers.NewOrchestratorStartedEvent()}, delivered...), OrchestrationTraceContext: b.traceContext, + EntityParameters: b.entityParameters, } before := len(h.client.orchestrationCompletions) h.worker.processOrchestration(context.Background(), h.client, "token", request) @@ -136,12 +144,621 @@ func (b *fakeOrchestrationBackend) dispatch( sent := action.GetSendEvent() b.history = append(b.history, helpers.NewSendEventEvent( action.Id, sent.GetInstance().GetInstanceId(), sent.GetName(), sent.GetData())) + case action.GetSendEntityMessage() != nil: + b.history = append(b.history, tracingEntitySent(action)) } } b.traceContext = response.OrchestrationTraceContext return response } +func tracingEntitySent(action *protos.OrchestratorAction) *protos.HistoryEvent { + event := &protos.HistoryEvent{EventId: action.Id, Timestamp: timestamppb.Now()} + message := action.GetSendEntityMessage() + if called := message.GetEntityOperationCalled(); called != nil { + event.EventType = &protos.HistoryEvent_EntityOperationCalled{ + EntityOperationCalled: proto.Clone(called).(*protos.EntityOperationCalledEvent), + } + } else if signal := message.GetEntityOperationSignaled(); signal != nil { + event.EventType = &protos.HistoryEvent_EntityOperationSignaled{ + EntityOperationSignaled: proto.Clone(signal).(*protos.EntityOperationSignaledEvent), + } + } else if lock := message.GetEntityLockRequested(); lock != nil { + event.EventType = &protos.HistoryEvent_EntityLockRequested{ + EntityLockRequested: proto.Clone(lock).(*protos.EntityLockRequestedEvent), + } + } else if unlock := message.GetEntityUnlockSent(); unlock != nil { + event.EventType = &protos.HistoryEvent_EntityUnlockSent{ + EntityUnlockSent: proto.Clone(unlock).(*protos.EntityUnlockSentEvent), + } + } + return event +} + +func TestWorkerTracingEntityLocksEmitNoSpans(t *testing.T) { + id := api.NewEntityID("counter", "key") + registry := task.NewTaskRegistry() + require.NoError(t, registry.AddOrchestratorN("Locker", func(ctx *task.OrchestrationContext) (any, error) { + unlock, err := ctx.LockEntities(id) + if err != nil { + return nil, err + } + _ = ctx.CallEntity(id, "get").Await(nil) + unlock() + return nil, ctx.WaitForSingleEvent("finish", -1).Await(nil) + })) + h := newTracingHarness(t, registry, true) + backend := newFakeOrchestrationBackend("locker", helpers.NewExecutionStartedEvent( + "Locker", "locker", nil, nil, nil, nil)) + backend.entityParameters = &protos.OrchestratorEntityParameters{EntityMessageReorderWindow: durationpb.New(0)} + + response := backend.dispatch(t, h) + require.Len(t, response.Actions, 1) + lock := response.Actions[0].GetSendEntityMessage().GetEntityLockRequested() + require.NotNil(t, lock) + granted := &protos.HistoryEvent{EventId: -1, Timestamp: timestamppb.Now(), + EventType: &protos.HistoryEvent_EntityLockGranted{ + EntityLockGranted: &protos.EntityLockGrantedEvent{CriticalSectionId: lock.CriticalSectionId}, + }} + response = backend.dispatch(t, h, granted) + var called *protos.EntityOperationCalledEvent + for _, action := range response.Actions { + if c := action.GetSendEntityMessage().GetEntityOperationCalled(); c != nil { + called = c + } + } + require.NotNil(t, called) + completed := &protos.HistoryEvent{EventId: -1, Timestamp: timestamppb.Now(), + EventType: &protos.HistoryEvent_EntityOperationCompleted{ + EntityOperationCompleted: &protos.EntityOperationCompletedEvent{RequestId: called.RequestId}, + }} + response = backend.dispatch(t, h, completed) + unlocked := false + for _, action := range response.Actions { + unlocked = unlocked || action.GetSendEntityMessage().GetEntityUnlockSent() != nil + } + require.True(t, unlocked) + backend.dispatch(t, h) + + // Lock acquisition and release emit no spans; calls in the critical section + // are traced once. + spans := h.spans() + require.Len(t, spans, 1) + require.Equal(t, "entity:counter:get", spans[0].Name()) + require.Equal(t, trace.SpanKindClient, spans[0].SpanKind()) +} + +func TestWorkerTracingEntityCallsAndSignalsReplay(t *testing.T) { + for _, mode := range []string{"enabled", "disabled", "unsampled", "failed-call"} { + t.Run(mode, func(t *testing.T) { + id := api.NewEntityID("counter", "key") + scheduled := time.Now().UTC().Add(time.Hour) + registry := task.NewTaskRegistry() + require.NoError(t, registry.AddOrchestratorN("EntityCaller", func(ctx *task.OrchestrationContext) (any, error) { + if err := ctx.SignalEntity(id, "add", task.WithSignalEntityScheduledTime(scheduled)); err != nil { + return nil, err + } + _ = ctx.CallEntity(id, "get").Await(nil) + return nil, ctx.WaitForSingleEvent("finish", -1).Await(nil) + })) + flags := trace.FlagsSampled + if mode == "unsampled" { + flags = 0 + } + _, parent := newTraceParent(flags) + backend := newFakeOrchestrationBackend("caller", helpers.NewExecutionStartedEvent( + "EntityCaller", "caller", nil, nil, parent, nil)) + backend.entityParameters = &protos.OrchestratorEntityParameters{EntityMessageReorderWindow: durationpb.New(0)} + h := newTracingHarness(t, registry, mode != "disabled") + response := backend.dispatch(t, h) + require.Len(t, response.Actions, 2) + var called *protos.EntityOperationCalledEvent + for _, action := range response.Actions { + if c := action.GetSendEntityMessage().GetEntityOperationCalled(); c != nil { + called = c + } + } + require.NotNil(t, called) + want := 1 + if mode == "disabled" || mode == "unsampled" { + want = 0 + } + require.Len(t, spansNamed(h.spans(), "entity:counter:add"), want) + backend.dispatch(t, h) + require.Len(t, spansNamed(h.spans(), "entity:counter:add"), want) + require.Empty(t, spansNamed(h.spans(), "entity:counter:get")) + completed := &protos.HistoryEvent{Timestamp: timestamppb.Now(), + EventType: &protos.HistoryEvent_EntityOperationCompleted{ + EntityOperationCompleted: &protos.EntityOperationCompletedEvent{RequestId: called.RequestId}, + }} + if mode == "failed-call" { + completed.EventType = &protos.HistoryEvent_EntityOperationFailed{ + EntityOperationFailed: &protos.EntityOperationFailedEvent{ + RequestId: called.RequestId, FailureDetails: &protos.TaskFailureDetails{ErrorMessage: "entity failed"}, + }} + } + backend.dispatch(t, h, completed) + require.Len(t, spansNamed(h.spans(), "entity:counter:get"), want) + if want != 0 { + signal := spansNamed(h.spans(), "entity:counter:add")[0] + call := spansNamed(h.spans(), "entity:counter:get")[0] + require.Equal(t, trace.SpanKindProducer, signal.SpanKind()) + require.Equal(t, trace.SpanKindClient, call.SpanKind()) + require.Equal(t, "signal_entity", spanAttribute(signal, "durabletask.task.operation")) + require.Equal(t, "call_entity", spanAttribute(call, "durabletask.task.operation")) + require.Equal(t, "add", spanAttribute(signal, "durabletask.entity.operation")) + require.Equal(t, "get", spanAttribute(call, "durabletask.entity.operation")) + requireTaskIDAttribute(t, signal, response.Actions[0].Id) + requireTaskIDAttribute(t, call, response.Actions[1].Id) + require.Equal(t, id.String(), spanAttribute(call, "durabletask.event.target_instance_id")) + require.Equal(t, scheduled.Format(time.RFC3339Nano), spanAttribute(signal, "durabletask.task.scheduled_time")) + require.Equal(t, response.OrchestrationTraceContext.GetSpanID().GetValue(), call.Parent().SpanID().String()) + require.Equal(t, helpers.SpanContextFromTraceContext(parent).TraceID(), call.SpanContext().TraceID()) + require.True(t, completed.Timestamp.AsTime().Equal(call.EndTime())) + if mode == "failed-call" { + require.Equal(t, codes.Error, call.Status().Code) + require.Equal(t, "entity failed", call.Status().Description) + } + } + backend.dispatch(t, h) + require.Len(t, spansNamed(h.spans(), "entity:counter:get"), want) + }) + } +} + +func TestWorkerTracingEntitySignalSameDispatch(t *testing.T) { + id := api.NewEntityID("counter", "key") + registry := task.NewTaskRegistry() + require.NoError(t, registry.AddOrchestratorN("Signal", func(ctx *task.OrchestrationContext) (any, error) { + if err := ctx.SignalEntity(id, "add"); err != nil { + return nil, err + } + return nil, ctx.WaitForSingleEvent("finish", -1).Await(nil) + })) + h := newTracingHarness(t, registry, true) + backend := newFakeOrchestrationBackend("caller", helpers.NewExecutionStartedEvent( + "Signal", "caller", nil, nil, nil, nil)) + backend.entityParameters = &protos.OrchestratorEntityParameters{EntityMessageReorderWindow: durationpb.New(0)} + response := backend.dispatch(t, h) + sent := tracingEntitySent(response.Actions[0]) + // A fresh worker receives the same initial history plus its signal acknowledgement. + h = newTracingHarness(t, registry, true) + request := &protos.OrchestratorRequest{ + InstanceId: "caller", EntityParameters: backend.entityParameters, + NewEvents: append(append([]*protos.HistoryEvent(nil), backend.history[:2]...), sent), + } + h.worker.processOrchestration(context.Background(), h.client, "token", request) + require.Empty(t, h.client.orchestrationCompletions[0].Actions) + require.Len(t, spansNamed(h.spans(), "entity:counter:add"), 1) + request.PastEvents, request.NewEvents = request.NewEvents, []*protos.HistoryEvent{helpers.NewOrchestratorStartedEvent()} + request.OrchestrationTraceContext = h.client.orchestrationCompletions[0].OrchestrationTraceContext + h.worker.processOrchestration(context.Background(), h.client, "token", request) + require.Len(t, spansNamed(h.spans(), "entity:counter:add"), 1) +} + +func TestWorkerTracingEntitySignalAfterResume(t *testing.T) { + id := api.NewEntityID("counter", "key") + registry := task.NewTaskRegistry() + require.NoError(t, registry.AddOrchestratorN("SignalAfterResume", func(ctx *task.OrchestrationContext) (any, error) { + if err := ctx.WaitForSingleEvent("next", -1).Await(nil); err != nil { + return nil, err + } + if err := ctx.SignalEntity(id, "add"); err != nil { + return nil, err + } + return nil, ctx.WaitForSingleEvent("finish", -1).Await(nil) + })) + h := newTracingHarness(t, registry, true) + backend := newFakeOrchestrationBackend("caller", helpers.NewExecutionStartedEvent( + "SignalAfterResume", "caller", nil, nil, nil, nil)) + backend.entityParameters = &protos.OrchestratorEntityParameters{EntityMessageReorderWindow: durationpb.New(0)} + backend.dispatch(t, h) + backend.dispatch(t, h, helpers.NewSuspendOrchestrationEvent("")) + backend.dispatch(t, h, helpers.NewEventRaisedEvent("next", nil)) + require.Empty(t, h.spans()) + + response := backend.dispatch(t, h, helpers.NewResumeOrchestrationEvent("")) + require.Len(t, response.Actions, 1) + require.NotNil(t, response.Actions[0].GetSendEntityMessage().GetEntityOperationSignaled()) + require.Len(t, spansNamed(h.spans(), "entity:counter:add"), 1) + backend.dispatch(t, h) + backend.dispatch(t, h, helpers.NewEventRaisedEvent("finish", nil)) + require.Len(t, spansNamed(h.spans(), "entity:counter:add"), 1) +} + +func TestWorkerTracingEntitySignalCanonicalNameAndAcknowledgement(t *testing.T) { + id := api.EntityID{Name: "Counter", Key: "key"} + registry := task.NewTaskRegistry() + require.NoError(t, registry.AddOrchestratorN("Signal", func(ctx *task.OrchestrationContext) (any, error) { + if err := ctx.SignalEntity(id, "add"); err != nil { + return nil, err + } + return nil, ctx.WaitForSingleEvent("finish", -1).Await(nil) + })) + h := newTracingHarness(t, registry, true) + backend := newFakeOrchestrationBackend("caller", helpers.NewExecutionStartedEvent( + "Signal", "caller", nil, nil, nil, nil)) + backend.entityParameters = &protos.OrchestratorEntityParameters{EntityMessageReorderWindow: durationpb.New(0)} + response := backend.dispatch(t, h) + require.Len(t, response.Actions, 1) + spans := spansNamed(h.spans(), "entity:counter:add") + require.Len(t, spans, 1) + require.Equal(t, id.String(), spanAttribute(spans[0], "durabletask.event.target_instance_id")) + + // Deliver the acknowledgement as new history after the signal was exported. + backend.history = backend.history[:len(backend.history)-1] + backend.dispatch(t, h, tracingEntitySent(response.Actions[0])) + require.Len(t, spansNamed(h.spans(), "entity:counter:add"), 1) +} + +func TestWorkerTracingEntitySignalAcknowledgementBeyondTurnBudget(t *testing.T) { + id := api.NewEntityID("counter", "key") + registry := task.NewTaskRegistry() + require.NoError(t, registry.AddOrchestratorN("Signal", func(ctx *task.OrchestrationContext) (any, error) { + if err := ctx.SignalEntity(id, "add"); err != nil { + return nil, err + } + return nil, ctx.WaitForSingleEvent("finish", -1).Await(nil) + })) + h := newTracingHarness(t, registry, true, + task.WithOrchestrationOptions(task.OrchestrationOptions{MaxEventsPerTurn: 1})) + backend := newFakeOrchestrationBackend("caller", helpers.NewExecutionStartedEvent( + "Signal", "caller", nil, nil, nil, nil)) + backend.entityParameters = &protos.OrchestratorEntityParameters{EntityMessageReorderWindow: durationpb.New(0)} + response := backend.dispatch(t, h) + require.Len(t, response.Actions, 1) + require.Len(t, spansNamed(h.spans(), "entity:counter:add"), 1) + + ack := tracingEntitySent(response.Actions[0]) + backend.history = backend.history[:len(backend.history)-1] + response = backend.dispatch(t, h, helpers.NewEventRaisedEvent("other", nil), ack) + require.NotNil(t, response.NumEventsProcessed) + require.Len(t, response.Actions, 1) + require.Len(t, spansNamed(h.spans(), "entity:counter:add"), 1) + + // The backend deduplicates the replayed action and redelivers its pending acknowledgement. + backend.history = backend.history[:len(backend.history)-1] + response = backend.dispatch(t, h) + require.Empty(t, response.Actions) + require.Len(t, spansNamed(h.spans(), "entity:counter:add"), 1) +} + +func TestWorkerTracingNewEntitySignalWithDeferredAcknowledgement(t *testing.T) { + id := api.NewEntityID("counter", "key") + registry := task.NewTaskRegistry() + require.NoError(t, registry.AddOrchestratorN("Signal", func(ctx *task.OrchestrationContext) (any, error) { + if err := ctx.SignalEntity(id, "add"); err != nil { + return nil, err + } + return nil, ctx.WaitForSingleEvent("finish", -1).Await(nil) + })) + backend := newFakeOrchestrationBackend("caller", helpers.NewExecutionStartedEvent( + "Signal", "caller", nil, nil, nil, nil)) + backend.entityParameters = &protos.OrchestratorEntityParameters{EntityMessageReorderWindow: durationpb.New(0)} + h := newTracingHarness(t, registry, true) + response := backend.dispatch(t, h) + require.Len(t, response.Actions, 1) + sent := tracingEntitySent(response.Actions[0]) + + h = newTracingHarness(t, registry, true, + task.WithOrchestrationOptions(task.OrchestrationOptions{MaxEventsPerTurn: 1})) + request := &protos.OrchestratorRequest{ + InstanceId: "caller", + EntityParameters: backend.entityParameters, + NewEvents: append(append([]*protos.HistoryEvent(nil), backend.history[:2]...), sent), + } + h.worker.processOrchestration(context.Background(), h.client, "token", request) + response = h.client.orchestrationCompletions[0] + require.NotNil(t, response.NumEventsProcessed) + require.Len(t, response.Actions, 1) + require.Len(t, spansNamed(h.spans(), "entity:counter:add"), 1) + + request.PastEvents = request.NewEvents[:2] + request.NewEvents = []*protos.HistoryEvent{helpers.NewOrchestratorStartedEvent(), sent} + request.OrchestrationTraceContext = response.OrchestrationTraceContext + h.worker.processOrchestration(context.Background(), h.client, "token", request) + require.Empty(t, h.client.orchestrationCompletions[1].Actions) + require.Len(t, spansNamed(h.spans(), "entity:counter:add"), 1) +} + +func TestWorkerTracingEntityOperationResults(t *testing.T) { + for _, mode := range []string{"enabled", "disabled", "unsampled", "rejected", "batch-failure", "malformed-results"} { + t.Run(mode, func(t *testing.T) { + var options []sdktrace.TracerProviderOption + if mode == "unsampled" { + options = append(options, tracing.WithSampler(sdktrace.NeverSample())) + } + h := newTracingHarnessWithProviderOptions(t, task.NewTaskRegistry(), mode != "disabled", options) + start, end := time.Now().UTC().Add(-time.Minute), time.Now().UTC().Add(-time.Second) + h.worker.executor = &recordingExecutor{executeEntity: func(context.Context, *protos.EntityBatchRequest) (*protos.EntityBatchResult, error) { + if mode == "batch-failure" { + return nil, errors.New("batch failed") + } + if mode == "malformed-results" { + return &protos.EntityBatchResult{Results: []*protos.OperationResult{nil, {}}}, nil + } + return &protos.EntityBatchResult{Results: []*protos.OperationResult{ + {ResultType: &protos.OperationResult_Success{Success: &protos.OperationResultSuccess{ + StartTimeUtc: timestamppb.New(start), EndTimeUtc: timestamppb.New(end), + }}}, + {ResultType: &protos.OperationResult_Failure{Failure: &protos.OperationResultFailure{ + FailureDetails: &protos.TaskFailureDetails{ErrorMessage: "operation failed"}, + StartTimeUtc: timestamppb.New(start), EndTimeUtc: timestamppb.New(end), + }}}, + }}, nil + }} + if mode == "rejected" { + h.client.entityCompletionErr = errors.New("completion failed") + } + request := newFakeEntitySignalRequest("add", nil) + request.OperationRequests = append(request.OperationRequests, &protos.HistoryEvent{ + EventType: &protos.HistoryEvent_EntityOperationCalled{EntityOperationCalled: &protos.EntityOperationCalledEvent{ + RequestId: uuid.NewString(), Operation: "get", ParentInstanceId: wrapperspb.String("caller"), + }}, + }) + h.worker.processEntityV2(context.Background(), h.client, "token", request) + if mode == "disabled" || mode == "unsampled" || mode == "rejected" { + require.Empty(t, h.spans()) + return + } + require.Len(t, h.spans(), 2) + signal, call := h.spans()[0], h.spans()[1] + require.Equal(t, "entity:counter:add", signal.Name()) + require.Equal(t, "entity:counter:get", call.Name()) + require.Equal(t, trace.SpanKindConsumer, signal.SpanKind()) + require.Equal(t, trace.SpanKindServer, call.SpanKind()) + require.False(t, signal.Parent().IsValid()) + require.False(t, call.Parent().IsValid()) + require.Equal(t, request.InstanceId, spanAttribute(call, "durabletask.task.instance_id")) + require.Equal(t, "counter", spanAttribute(call, "durabletask.task.name")) + switch mode { + case "malformed-results": + for _, span := range h.spans() { + require.Equal(t, codes.Error, span.Status().Code) + require.Contains(t, span.Status().Description, "without success or failure") + } + case "batch-failure": + require.Equal(t, codes.Error, signal.Status().Code) + require.Contains(t, signal.Status().Description, "batch failed") + default: + require.Equal(t, codes.Unset, signal.Status().Code) + require.Empty(t, spanAttribute(signal, "durabletask.entity.error_message")) + require.Equal(t, "add", spanAttribute(signal, "durabletask.entity.operation")) + require.Equal(t, "get", spanAttribute(call, "durabletask.entity.operation")) + require.True(t, start.Equal(signal.StartTime())) + require.True(t, end.Equal(call.EndTime())) + require.Equal(t, codes.Error, call.Status().Code) + require.Equal(t, "operation failed", call.Status().Description) + require.Equal(t, "operation failed", spanAttribute(call, "durabletask.entity.error_message")) + } + }) + } +} + +func TestWorkerTracingEntityExternalizationFailure(t *testing.T) { + for _, mode := range []string{"accepted", "rejected", "canceled"} { + t.Run(mode, func(t *testing.T) { + h := newTracingHarness(t, task.NewTaskRegistry(), true) + storeErr := errors.New("externalize failed") + if mode == "canceled" { + storeErr = context.Canceled + } + backend := &failingPayloadBackend{storeErr: storeErr} + h.worker.options.largePayloads = &api.LargePayloadOptions{ + Store: backend, Resolver: backend, ThresholdBytes: 1, MaxPayloadBytes: 1024, + } + h.worker.executor = &recordingExecutor{executeEntity: func(context.Context, *protos.EntityBatchRequest) (*protos.EntityBatchResult, error) { + return &protos.EntityBatchResult{EntityState: wrapperspb.String("large"), Results: []*protos.OperationResult{ + {ResultType: &protos.OperationResult_Success{Success: &protos.OperationResultSuccess{}}}, + }}, nil + }} + if mode == "rejected" { + h.client.entityCompletionErr = errors.New("completion rejected") + } + h.worker.processEntityV2(context.Background(), h.client, "token", newFakeEntitySignalRequest("run", nil)) + if mode != "accepted" { + require.Empty(t, h.spans()) + require.Equal(t, 1, h.client.entityAbandonAttempts) + return + } + require.Len(t, h.spans(), 1) + require.Equal(t, codes.Error, h.spans()[0].Status().Code) + require.Contains(t, h.spans()[0].Status().Description, "externalize failed") + require.Len(t, h.client.entityCompletions, 1) + require.NotNil(t, h.client.entityCompletions[0].FailureDetails) + }) + } +} + +func TestWorkerTracingEntityHydrationFailure(t *testing.T) { + for _, mode := range []string{"accepted", "rejected", "canceled"} { + t.Run(mode, func(t *testing.T) { + h := newTracingHarness(t, task.NewTaskRegistry(), true) + store := payload.NewMemoryStore() + input, err := largepayload.Externalize(context.Background(), + &api.LargePayloadOptions{Store: store, Resolver: store, ThresholdBytes: 1, MaxPayloadBytes: 1024}, + wrapperspb.String(`"large"`)) + require.NoError(t, err) + resolveErr := errors.New("hydrate failed") + if mode == "canceled" { + resolveErr = context.Canceled + } + h.worker.options.largePayloads = &api.LargePayloadOptions{ + Store: store, Resolver: &failingPayloadBackend{resolveErr: resolveErr}, ThresholdBytes: 1, MaxPayloadBytes: 1024, + } + if mode == "rejected" { + h.client.entityCompletionErr = errors.New("completion rejected") + } + h.worker.processEntityV2(context.Background(), h.client, "token", newFakeEntitySignalRequest("run", input)) + if mode != "accepted" { + require.Empty(t, h.spans()) + return + } + require.Len(t, h.spans(), 1) + span := h.spans()[0] + require.Equal(t, "entity:counter:run", span.Name()) + require.Equal(t, trace.SpanKindConsumer, span.SpanKind()) + require.Equal(t, codes.Error, span.Status().Code) + require.Contains(t, span.Status().Description, "hydrate failed") + }) + } +} + +func TestWorkerTracingEntityHandlerSpanContext(t *testing.T) { + for _, mode := range []string{"sampled", "unsampled", "disabled", "rejected"} { + t.Run(mode, func(t *testing.T) { + var h *tracingHarness + var handlerContext, appContext trace.SpanContext + registry := task.NewTaskRegistry() + require.NoError(t, registry.AddEntityN("counter", func(ctx *task.EntityContext) (any, error) { + handlerContext = trace.SpanContextFromContext(ctx.Context()) + _, span := h.provider.Tracer("app").Start(ctx.Context(), "app") + appContext = span.SpanContext() + span.End() + if err := ctx.SignalEntity(api.NewEntityID("other", "key"), "ping", nil); err != nil { + return nil, err + } + return nil, ctx.StartNewOrchestration("Started") + })) + var options []sdktrace.TracerProviderOption + if mode == "unsampled" { + options = append(options, tracing.WithSampler(sdktrace.NeverSample())) + } + h = newTracingHarnessWithProviderOptions(t, registry, mode != "disabled", options) + if mode == "rejected" { + h.client.entityCompletionErr = errors.New("completion rejected") + } + h.worker.processEntityV2(context.Background(), h.client, "token", newFakeEntitySignalRequest("add", nil)) + + require.Len(t, h.client.entityCompletions, 1) + result := h.client.entityCompletions[0] + require.Len(t, result.Actions, 2) + signal := result.Actions[0].GetSendSignal() + started := result.Actions[1].GetStartNewOrchestration() + entitySpans := spansNamed(h.spans(), "entity:counter:add") + if mode == "disabled" { + require.False(t, handlerContext.IsValid()) + require.Nil(t, signal.ParentTraceContext) + require.Nil(t, started.ParentTraceContext) + require.Empty(t, entitySpans) + return + } + require.True(t, handlerContext.IsValid()) + require.Equal(t, mode != "unsampled", handlerContext.IsSampled()) + want := helpers.TraceContextFromSpanContext(handlerContext) + require.True(t, proto.Equal(want, signal.ParentTraceContext)) + require.True(t, proto.Equal(want, started.ParentTraceContext)) + require.Equal(t, handlerContext.TraceID(), appContext.TraceID()) + switch mode { + case "unsampled": + require.Empty(t, h.spans()) + case "rejected": + require.Empty(t, entitySpans) + default: + require.Len(t, entitySpans, 1) + span := entitySpans[0] + require.Equal(t, handlerContext.TraceID(), span.SpanContext().TraceID()) + require.Equal(t, handlerContext.SpanID(), span.SpanContext().SpanID()) + require.False(t, span.Parent().IsValid()) + require.Equal(t, codes.Unset, span.Status().Code) + success := result.Results[0].GetSuccess() + require.True(t, success.StartTimeUtc.AsTime().Equal(span.StartTime())) + require.True(t, success.EndTimeUtc.AsTime().Equal(span.EndTime())) + app := spansNamed(h.spans(), "app") + require.Len(t, app, 1) + require.Equal(t, handlerContext.SpanID(), app[0].Parent().SpanID()) + } + }) + } +} + +func TestWorkerTracingEntityCallCompletionsExportOnce(t *testing.T) { + for _, mode := range []string{"turn-budget", "suspended"} { + t.Run(mode, func(t *testing.T) { + id := api.NewEntityID("counter", "key") + registry := task.NewTaskRegistry() + require.NoError(t, registry.AddOrchestratorN("Caller", func(ctx *task.OrchestrationContext) (any, error) { + first, second := ctx.CallEntity(id, "get"), ctx.CallEntity(id, "read") + if err := first.Await(nil); err != nil { + return nil, err + } + return nil, second.Await(nil) + })) + var options []task.TaskExecutorOption + if mode == "turn-budget" { + options = append(options, task.WithOrchestrationOptions(task.OrchestrationOptions{MaxEventsPerTurn: 1})) + } + h := newTracingHarness(t, registry, true, options...) + _, parent := newTraceParent(trace.FlagsSampled) + backend := newFakeOrchestrationBackend("caller", helpers.NewExecutionStartedEvent( + "Caller", "caller", nil, nil, parent, nil)) + backend.entityParameters = &protos.OrchestratorEntityParameters{EntityMessageReorderWindow: durationpb.New(0)} + response := backend.dispatch(t, h) + require.Len(t, response.Actions, 2) + var completions []*protos.HistoryEvent + for _, action := range response.Actions { + called := action.GetSendEntityMessage().GetEntityOperationCalled() + require.NotNil(t, called) + completions = append(completions, &protos.HistoryEvent{EventId: -1, Timestamp: timestamppb.Now(), + EventType: &protos.HistoryEvent_EntityOperationCompleted{ + EntityOperationCompleted: &protos.EntityOperationCompletedEvent{RequestId: called.RequestId}, + }}) + } + callSpans := func() int { + return len(spansNamed(h.spans(), "entity:counter:get")) + len(spansNamed(h.spans(), "entity:counter:read")) + } + if mode == "turn-budget" { + response = backend.dispatch(t, h, completions...) + require.NotNil(t, response.NumEventsProcessed) + require.Equal(t, 1, callSpans()) + backend.dispatch(t, h) + } else { + backend.dispatch(t, h, append([]*protos.HistoryEvent{helpers.NewSuspendOrchestrationEvent("")}, completions...)...) + require.Equal(t, 2, callSpans()) + backend.dispatch(t, h, helpers.NewResumeOrchestrationEvent("")) + } + require.Len(t, spansNamed(h.spans(), "entity:counter:get"), 1) + require.Len(t, spansNamed(h.spans(), "entity:counter:read"), 1) + require.Len(t, spansNamed(h.spans(), "orchestration:Caller"), 1) + }) + } +} + +func TestWorkerTracingEntityCallWithInvalidRecordedTarget(t *testing.T) { + for name, target := range map[string]*wrapperspb.StringValue{ + "missing": nil, + "malformed": wrapperspb.String("counter"), + } { + t.Run(name, func(t *testing.T) { + id := api.NewEntityID("counter", "key") + registry := task.NewTaskRegistry() + require.NoError(t, registry.AddOrchestratorN("Caller", func(ctx *task.OrchestrationContext) (any, error) { + return nil, ctx.CallEntity(id, "get").Await(nil) + })) + h := newTracingHarness(t, registry, true) + backend := newFakeOrchestrationBackend("caller", helpers.NewExecutionStartedEvent( + "Caller", "caller", nil, nil, nil, nil)) + backend.entityParameters = &protos.OrchestratorEntityParameters{EntityMessageReorderWindow: durationpb.New(0)} + backend.dispatch(t, h) + called := backend.history[len(backend.history)-1].GetEntityOperationCalled() + require.NotNil(t, called) + called.TargetInstanceId = target + response := backend.dispatch(t, h, &protos.HistoryEvent{EventId: -1, Timestamp: timestamppb.Now(), + EventType: &protos.HistoryEvent_EntityOperationCompleted{ + EntityOperationCompleted: &protos.EntityOperationCompletedEvent{RequestId: called.RequestId}, + }}) + + // The call completes normally; its CLIENT span is skipped because the + // recorded target is not an entity ID. + require.Len(t, response.Actions, 1) + require.Equal(t, protos.OrchestrationStatus_ORCHESTRATION_STATUS_COMPLETED, + response.Actions[0].GetCompleteOrchestration().GetOrchestrationStatus()) + require.Empty(t, spansNamed(h.spans(), "entity:counter:get")) + require.Len(t, spansNamed(h.spans(), "orchestration:Caller"), 1) + }) + } +} + func TestWorkerTracingEventSendAndReceipt(t *testing.T) { registry := task.NewTaskRegistry() require.NoError(t, registry.AddOrchestratorN("Sender", func(ctx *task.OrchestrationContext) (any, error) { diff --git a/internal/dttrace/dttrace.go b/internal/dttrace/dttrace.go index 8cbeb0ed..a9632cf5 100644 --- a/internal/dttrace/dttrace.go +++ b/internal/dttrace/dttrace.go @@ -43,6 +43,7 @@ const ( typeOrchestration = "orchestration" typeActivity = "activity" typeTimer = "timer" + typeEntity = "entity" ) // ErrUnsupportedTracerProvider reports a provider that cannot reconstruct spans @@ -310,6 +311,9 @@ type Orchestration struct { timers map[int32]createdTimer newSends map[int32]pendingSpan acceptedSends map[int32]struct{} + entityCalls map[string]entityCall + entitySignals map[int32]entitySignal + entityAcks map[entitySignalKey]struct{} pending []pendingSpan responseTime time.Time emitted bool @@ -345,6 +349,12 @@ func (t *Tracer) StartOrchestration( } o.acceptedSends[event.EventId] = struct{}{} } + if signaled := event.GetEntityOperationSignaled(); signaled != nil { + if o.entityAcks == nil { + o.entityAcks = make(map[entitySignalKey]struct{}) + } + o.entityAcks[entitySignalKey{eventID: event.EventId, requestID: signaled.RequestId}] = struct{}{} + } if started := event.GetExecutionStarted(); started != nil { o.started = true o.name = started.GetName() @@ -409,6 +419,7 @@ func (o *Orchestration) SpanContext() trace.SpanContext { rootTraceID(o.instanceID, o.executionID, o.spanID), o.spanID, SpanName(typeOrchestration, o.name, o.version), + trace.SpanKindServer, o.attributes(), ) o.logical = logical.WithRemote(true) @@ -416,23 +427,24 @@ func (o *Orchestration) SpanContext() trace.SpanContext { return o.logical } -// rootSpanContext asks the provider's sampler for a root orchestration span's -// sampling result. The Durable Task sampler drops the query span, so it never -// records, reaches span processors, or exports. The returned result, when the -// sampler answered, is reused for the span reconstructed in the same dispatch. -// The decision is re-evaluated on every dispatch, so it is only stable across -// dispatches for samplers whose root decision depends on the trace ID. +// rootSpanContext asks the provider's sampler for a root span's sampling +// result. The Durable Task sampler drops the query span, so it never records, +// reaches span processors, or exports. Zero IDs reserve new IDs from the +// provider's base ID generator. The result is reused when the span is +// reconstructed in the same dispatch. Across dispatches, the decision is only +// stable for samplers whose root decision depends on the trace ID. func (t *Tracer) rootSpanContext( traceID trace.TraceID, spanID trace.SpanID, name string, + kind trace.SpanKind, attrs []attribute.KeyValue, ) (trace.SpanContext, *sdktrace.SamplingResult) { query := &samplingQuery{} ctx := context.WithValue(withIDOverride(context.Background(), traceID, spanID), samplingQueryKey{}, query) - t.tracer.Start(ctx, name, + _, span := t.tracer.Start(ctx, name, trace.WithNewRoot(), - trace.WithSpanKind(trace.SpanKindServer), + trace.WithSpanKind(kind), trace.WithAttributes(attrs...), ) var flags trace.TraceFlags @@ -440,8 +452,8 @@ func (t *Tracer) rootSpanContext( flags = trace.FlagsSampled } spanContext := trace.NewSpanContext(trace.SpanContextConfig{ - TraceID: traceID, - SpanID: spanID, + TraceID: span.SpanContext().TraceID(), + SpanID: span.SpanContext().SpanID(), TraceFlags: flags, TraceState: query.result.Tracestate, }) @@ -516,6 +528,13 @@ func (o *Orchestration) Observe(event *protos.HistoryEvent, replaying bool) { o.timers[event.EventId] = createdTimer{start: timestamp, fireAt: event.GetTimerCreated().GetFireAt()} case event.GetTimerFired() != nil: o.fireTimer(event.GetTimerFired(), timestamp, replaying) + case event.GetEntityOperationCalled() != nil: + o.callEntity(event.EventId, event.GetEntityOperationCalled(), timestamp) + case event.GetEntityOperationCompleted() != nil: + o.completeEntity(event.GetEntityOperationCompleted().RequestId, timestamp, replaying, nil) + case event.GetEntityOperationFailed() != nil: + failed := event.GetEntityOperationFailed() + o.completeEntity(failed.RequestId, timestamp, replaying, failureOrDefault(failed.FailureDetails)) } } @@ -770,11 +789,15 @@ func (o *Orchestration) Emit(response *protos.OrchestratorResponse) { o.emitted = true logical := o.SpanContext() for _, action := range response.GetActions() { - if action.GetSendEvent() == nil { - continue - } - if span, ok := o.sendSpan(action); ok { - o.pending = append(o.pending, span) + switch { + case action.GetSendEvent() != nil: + if span, ok := o.sendSpan(action); ok { + o.pending = append(o.pending, span) + } + case action.GetSendEntityMessage().GetEntityOperationSignaled() != nil: + if span, ok := o.signalSpan(action); ok { + o.pending = append(o.pending, span) + } } } for _, span := range o.pending { diff --git a/internal/dttrace/entity.go b/internal/dttrace/entity.go new file mode 100644 index 00000000..12f06b23 --- /dev/null +++ b/internal/dttrace/entity.go @@ -0,0 +1,332 @@ +package dttrace + +import ( + "context" + "time" + + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/trace" + "google.golang.org/protobuf/types/known/timestamppb" + + "github.com/microsoft/durabletask-go/api" + "github.com/microsoft/durabletask-go/internal/helpers" + "github.com/microsoft/durabletask-go/internal/protos" +) + +// Entity attribute keys shared with the other Durable Task SDKs. +const ( + // AttrOperation is DurableTask.Core's entity request kind: "call_entity" + // or "signal_entity". + AttrOperation = attribute.Key("durabletask.task.operation") + // AttrEntityOperation is the entity operation name, as reported by the + // Python and JavaScript SDKs. + AttrEntityOperation = attribute.Key("durabletask.entity.operation") + // AttrScheduledTime is the RFC 3339 delivery time of a scheduled entity + // request. + AttrScheduledTime = attribute.Key("durabletask.task.scheduled_time") + // AttrEntityError is the failure message of a failed entity operation. + AttrEntityError = attribute.Key("durabletask.entity.error_message") +) + +func entitySpanName(id api.EntityID, operation string) string { + return typeEntity + ":" + helpers.ToLowerInvariant(id.Name) + ":" + operation +} + +func entityAttributes(signal bool, operation string) []attribute.KeyValue { + kind := "call_entity" + if signal { + kind = "signal_entity" + } + return []attribute.KeyValue{ + AttrType.String(typeEntity), + AttrOperation.String(kind), + AttrEntityOperation.String(operation), + } +} + +// EntityBatch holds the span identities reserved for one V2 entity batch. +// V2 entity messages carry no trace context, so every operation span is an +// independent root. Its identity and sampling decision are reserved before +// execution so handlers can see it, and the span is reconstructed only after +// the backend accepts the batch result. +type EntityBatch struct { + tracer *Tracer + operations []entityOperation +} + +type entityOperation struct { + requestID string + name string + kind trace.SpanKind + attrs []attribute.KeyValue + spanContext trace.SpanContext +} + +// NewEntityBatch reserves a root span context for each operation in request. +func (t *Tracer) NewEntityBatch(id api.EntityID, request *protos.EntityBatchRequest) *EntityBatch { + batch := &EntityBatch{tracer: t, operations: make([]entityOperation, len(request.GetOperations()))} + for i, operation := range request.GetOperations() { + if operation == nil { + continue + } + signal := request.GetProperties()[helpers.EntitySignalProperty(operation.RequestId)].GetBoolValue() + kind := trace.SpanKindServer + if signal { + kind = trace.SpanKindConsumer + } + name := entitySpanName(id, operation.Operation) + attrs := append(entityAttributes(signal, operation.Operation), + AttrInstanceID.String(id.String()), AttrName.String(id.Name)) + spanContext, _ := t.rootSpanContext(trace.TraceID{}, trace.SpanID{}, name, kind, attrs) + batch.operations[i] = entityOperation{ + requestID: operation.RequestId, + name: name, + kind: kind, + attrs: attrs, + spanContext: spanContext, + } + } + return batch +} + +type entityBatchKey struct{} + +// WithEntityBatch attaches an entity batch trace to an executor call. +func WithEntityBatch(ctx context.Context, batch *EntityBatch) context.Context { + if batch == nil { + return ctx + } + return context.WithValue(ctx, entityBatchKey{}, batch) +} + +// EntityOperationSpanContext returns the reserved, non-recording span context +// of the operation at index in the batch attached to ctx. It returns an invalid +// span context when tracing is disabled or requestID does not match. +func EntityOperationSpanContext(ctx context.Context, index int, requestID string) trace.SpanContext { + batch, _ := ctx.Value(entityBatchKey{}).(*EntityBatch) + if batch == nil || index < 0 || index >= len(batch.operations) || + batch.operations[index].requestID != requestID { + return trace.SpanContext{} + } + return batch.operations[index].spanContext +} + +// Emit exports the reserved operation spans. Call it only after the backend +// accepts result, so rejected or abandoned batches export nothing. start and +// end bound operations whose result has no timestamps. Unsampled operations +// export nothing. +func (b *EntityBatch) Emit(result *protos.EntityBatchResult, start, end time.Time) { + if b == nil { + return + } + for i, operation := range b.operations { + if !operation.spanContext.IsSampled() { + continue + } + opStart, opEnd, failure := operationOutcome(result, i, start, end) + attrs := operation.attrs + if failure != nil { + attrs = append(attrs[:len(attrs):len(attrs)], AttrEntityError.String(failure.GetErrorMessage())) + } + b.tracer.emit(operation.name, operation.kind, trace.SpanContext{}, + spanRoot{spanContext: operation.spanContext}, operation.spanContext.SpanID(), opStart, opEnd, attrs, failure) + } +} + +// operationOutcome returns the timestamps and failure of the operation at +// index. A batch failure fails every operation. +func operationOutcome( + result *protos.EntityBatchResult, + index int, + start, end time.Time, +) (time.Time, time.Time, *protos.TaskFailureDetails) { + if result.GetFailureDetails() != nil || index >= len(result.GetResults()) { + return start, end, failureOrDefault(result.GetFailureDetails()) + } + var failure *protos.TaskFailureDetails + var startTime, endTime *timestamppb.Timestamp + operationResult := result.GetResults()[index] + if failed := operationResult.GetFailure(); failed != nil { + failure = failureOrDefault(failed.FailureDetails) + startTime, endTime = failed.StartTimeUtc, failed.EndTimeUtc + } else if success := operationResult.GetSuccess(); success != nil { + startTime, endTime = success.StartTimeUtc, success.EndTimeUtc + } else { + failure = &protos.TaskFailureDetails{ + ErrorType: "InvalidEntityOperationResult", + ErrorMessage: "entity executor returned an operation result without success or failure", + } + } + if startTime != nil { + start = startTime.AsTime() + } + if endTime != nil { + end = endTime.AsTime() + } + return start, end, failure +} + +// entitySpan builds an orchestration's CLIENT span for an entity call or +// PRODUCER span for an entity signal. +func (o *Orchestration) entitySpan( + id api.EntityID, + operation string, + signal bool, + taskID int32, + start, end time.Time, + scheduled *timestamppb.Timestamp, + failure *protos.TaskFailureDetails, +) pendingSpan { + attrs := append(entityAttributes(signal, operation), + AttrEventTargetInstanceID.String(id.String()), + AttrInstanceID.String(o.instanceID), + AttrTaskID.Int(int(taskID))) + if scheduled != nil { + attrs = append(attrs, AttrScheduledTime.String(scheduled.AsTime().UTC().Format(time.RFC3339Nano))) + } + kind := trace.SpanKindClient + if signal { + kind = trace.SpanKindProducer + } + return pendingSpan{ + name: entitySpanName(id, operation), + kind: kind, + spanID: RandomSpanID(), + start: start, + end: end, + attrs: attrs, + failure: failure, + } +} + +// entityCall is the minimal state of an entity call awaiting its completion. +// Its span is built only when a completion is consumed as new. +type entityCall struct { + target string + operation string + taskID int32 + start time.Time + scheduled *timestamppb.Timestamp +} + +func (o *Orchestration) callEntity(eventID int32, called *protos.EntityOperationCalledEvent, at time.Time) { + if o.entityCalls == nil { + o.entityCalls = make(map[string]entityCall) + } + o.entityCalls[called.RequestId] = entityCall{ + target: called.GetTargetInstanceId().GetValue(), + operation: called.Operation, + taskID: eventID, + start: at, + scheduled: called.ScheduledTime, + } +} + +// completeEntity queues the CLIENT span of an entity call whose completion is +// consumed as new. A call whose recorded target is not a valid entity ID emits +// no span. +func (o *Orchestration) completeEntity( + requestID string, + end time.Time, + replaying bool, + failure *protos.TaskFailureDetails, +) { + call, ok := o.entityCalls[requestID] + if !ok { + return + } + delete(o.entityCalls, requestID) + if replaying { + return + } + id, err := api.EntityIDFromString(call.target) + if err != nil { + return + } + start, end := spanTimes(call.start, end) + o.pending = append(o.pending, + o.entitySpan(id, call.operation, false, call.taskID, start, end, call.scheduled, failure)) +} + +// entitySignal is the minimal state of a signal action. Its span is built +// only when the signal is queued for export. +type entitySignal struct { + id api.EntityID + signal *protos.EntityOperationSignaledEvent + at time.Time + replaying bool +} + +type entitySignalKey struct { + eventID int32 + requestID string +} + +// RecordEntitySignal records a signal action. Each signal exports one PRODUCER +// span with the accepted response that first carries or consumes it, following +// the same rules as event sends (see eventSpan): +// +// - A new signal still in the response exports with that response. +// - A new signal whose acknowledgement is consumed in the same dispatch is +// queued by ConfirmEntitySignal and exports with the response. DTS +// normally delivers the acknowledgement as a past event of a later +// dispatch, so this is defensive and best effort: the acknowledgement +// proves an earlier response carrying the signal was accepted, and the +// span exports twice if the worker that sent it also exported it. +// - A signal issued while replaying exports only if it is still in the +// response and no acknowledgement with its ID and request ID appears in +// the request. A buffered event can create a new action while the replay +// engine still reports replaying, and a turn budget can defer an +// acknowledgement, so the request rather than the replay flag decides. +func (o *Orchestration) RecordEntitySignal(action *protos.OrchestratorAction, id api.EntityID, replaying bool) { + if !o.Enabled() { + return + } + signal := action.GetSendEntityMessage().GetEntityOperationSignaled() + key := entitySignalKey{eventID: action.Id, requestID: signal.GetRequestId()} + if _, acknowledged := o.entityAcks[key]; acknowledged && replaying { + return + } + if o.entitySignals == nil { + o.entitySignals = make(map[int32]entitySignal) + } + recorded := entitySignal{id: id, signal: signal, replaying: replaying} + if !replaying { + recorded.at = time.Now() + } + o.entitySignals[action.Id] = recorded +} + +// ConfirmEntitySignal queues a signal consumed in the same dispatch only after +// the replay engine validates its action/history match. +func (o *Orchestration) ConfirmEntitySignal(eventID int32, replaying bool) { + if !o.Enabled() { + return + } + if recorded, ok := o.entitySignals[eventID]; ok && !recorded.replaying && !replaying { + o.pending = append(o.pending, o.signalSpanFor(eventID, recorded)) + } + delete(o.entitySignals, eventID) +} + +// signalSpan returns the span for a signal action left in an accepted +// response, or false when it was not recorded or was already exported. +func (o *Orchestration) signalSpan(action *protos.OrchestratorAction) (pendingSpan, bool) { + recorded, ok := o.entitySignals[action.Id] + if !ok { + return pendingSpan{}, false + } + return o.signalSpanFor(action.Id, recorded), true +} + +func (o *Orchestration) signalSpanFor(eventID int32, recorded entitySignal) pendingSpan { + at := recorded.at + if at.IsZero() { + at = o.responseTime + } + if at.IsZero() { + at = time.Now() + } + return o.entitySpan(recorded.id, recorded.signal.GetOperation(), true, eventID, + at, at, recorded.signal.GetScheduledTime(), nil) +} diff --git a/task/entity.go b/task/entity.go index 0d0cd383..7dfd5f94 100644 --- a/task/entity.go +++ b/task/entity.go @@ -12,6 +12,7 @@ import ( "github.com/microsoft/durabletask-go/api" "github.com/microsoft/durabletask-go/internal/helpers" "github.com/microsoft/durabletask-go/internal/protos" + "go.opentelemetry.io/otel/trace" "google.golang.org/protobuf/types/known/timestamppb" "google.golang.org/protobuf/types/known/wrapperspb" ) @@ -54,6 +55,9 @@ type EntityContext struct { actions []*protos.OperationAction actionIDSeq int32 currentTime time.Time + // spanContext is the operation's reserved span identity when tracing is + // enabled. Entity-started orchestrations and signals carry it. + spanContext trace.SpanContext ctx context.Context logger *slog.Logger converter api.DataConverter @@ -153,7 +157,9 @@ func (ctx *EntityContext) DeleteState() { ctx.state.hasValue = false } -// Context returns the Go context for the current entity operation. +// Context returns the Go context for the current entity operation. When worker +// tracing is enabled, it carries the operation's span context, so application +// spans started from it nest under the operation's span. func (ctx *EntityContext) Context() context.Context { if ctx.ctx == nil { return context.Background() @@ -204,11 +210,12 @@ func (ctx *EntityContext) signalEntity(entityID api.EntityID, operationName stri Id: ctx.nextActionID(), OperationActionType: &protos.OperationAction_SendSignal{ SendSignal: &protos.SendSignalAction{ - InstanceId: entityID.String(), - Name: operationName, - Input: rawInput, - RequestTime: timestampOrNil(ctx.currentTime), - ScheduledTime: timestampOrNil(scheduledTime), + InstanceId: entityID.String(), + Name: operationName, + Input: rawInput, + RequestTime: timestampOrNil(ctx.currentTime), + ScheduledTime: timestampOrNil(scheduledTime), + ParentTraceContext: helpers.TraceContextFromSpanContext(ctx.spanContext), }, }, } @@ -239,12 +246,13 @@ func (ctx *EntityContext) StartNewOrchestration(name string, opts ...EntityStart Id: ctx.nextActionID(), OperationActionType: &protos.OperationAction_StartNewOrchestration{ StartNewOrchestration: &protos.StartNewOrchestrationAction{ - InstanceId: options.instanceID, - Name: name, - Version: options.version, - Input: options.rawInput, - ScheduledTime: timestampOrNil(options.scheduledTime), - RequestTime: timestampOrNil(ctx.currentTime), + InstanceId: options.instanceID, + Name: name, + Version: options.version, + Input: options.rawInput, + ScheduledTime: timestampOrNil(options.scheduledTime), + RequestTime: timestampOrNil(ctx.currentTime), + ParentTraceContext: helpers.TraceContextFromSpanContext(ctx.spanContext), }, }, } diff --git a/task/executor.go b/task/executor.go index f57a779b..60bdcf53 100644 --- a/task/executor.go +++ b/task/executor.go @@ -15,6 +15,7 @@ import ( "github.com/microsoft/durabletask-go/internal/helpers" "github.com/microsoft/durabletask-go/internal/protos" "github.com/microsoft/durabletask-go/internal/tagcodec" + "go.opentelemetry.io/otel/trace" "google.golang.org/protobuf/types/known/timestamppb" "google.golang.org/protobuf/types/known/wrapperspb" ) @@ -413,7 +414,7 @@ func (te *taskExecutor) ExecuteEntity( Actions: make([]*protos.OperationAction, 0), } nextActionID := int32(0) - for _, operation := range req.Operations { + for i, operation := range req.Operations { if operation == nil { result.Results = append(result.Results, entityOperationFailure( fmt.Errorf("entity operation request must not be nil"), @@ -425,7 +426,9 @@ func (te *taskExecutor) ExecuteEntity( } startedAt := time.Now().UTC() isSignal := req.Properties[helpers.EntitySignalProperty(operation.RequestId)].GetBoolValue() - operationCtx := te.newEntityContext(ctx, entityID, operation, state, nextActionID, startedAt, isSignal) + spanContext := dttrace.EntityOperationSpanContext(ctx, i, operation.RequestId) + operationCtx := te.newEntityContext( + ctx, entityID, operation, state, nextActionID, startedAt, isSignal, spanContext) output, operationErr := invokeEntity(batch.Entity, operationCtx) endedAt := time.Now().UTC() @@ -477,8 +480,14 @@ func (te *taskExecutor) newEntityContext( nextActionID int32, currentTime time.Time, isSignal bool, + spanContext trace.SpanContext, ) *EntityContext { ctx = api.ContextWithFields(ctx, te.contextFields) + if spanContext.IsValid() { + // The operation span is reconstructed after the batch is accepted; + // handlers see its reserved, non-recording identity. + ctx = trace.ContextWithSpanContext(ctx, spanContext) + } ctx = api.WithEntityContextInfo(ctx, api.EntityContextInfo{ EntityID: entityID, Operation: operation.Operation, @@ -507,6 +516,7 @@ func (te *taskExecutor) newEntityContext( state: state, actionIDSeq: nextActionID, currentTime: currentTime, + spanContext: spanContext, ctx: ctx, logger: logger, converter: te.converter, diff --git a/task/orchestrator.go b/task/orchestrator.go index 9932b039..62b02ab1 100644 --- a/task/orchestrator.go +++ b/task/orchestrator.go @@ -1150,6 +1150,7 @@ func (ctx *OrchestrationContext) SignalEntity(entityID api.EntityID, operationNa options.scheduledTime, ) engine.pendingActions[action.Id] = action + engine.trace.RecordEntitySignal(action, entityID, engine.IsReplaying) return nil } @@ -1551,6 +1552,9 @@ func (ctx *OrchestrationContext) onEntityOperationSent(eventID int32, requestID if sentRequestID != requestID { return fmt.Errorf("entity operation request ID changed from %q to %q", sentRequestID, requestID) } + if message.GetEntityOperationSignaled() != nil { + ctx.trace.ConfirmEntitySignal(eventID, ctx.IsReplaying) + } delete(ctx.pendingActions, eventID) return nil } diff --git a/tracing/tracing.go b/tracing/tracing.go index 29a194f9..94e24a05 100644 --- a/tracing/tracing.go +++ b/tracing/tracing.go @@ -63,6 +63,40 @@ // - Event receipt does not emit a consumer span. The event protocol carries // no trace context, so sends cannot parent or link the receiving // orchestration to the sender's event span. +// - Entity spans are named "entity::" and carry the +// DurableTask.Core "durabletask.task.operation" attribute ("call_entity" +// or "signal_entity") and the "durabletask.entity.operation" attribute +// (the operation name) used by the Python and JavaScript SDKs. +// Orchestrator entity signals emit PRODUCER spans under the orchestration +// when accepted, following the same replay rules as SendEvent. Entity +// calls emit CLIENT spans when the dispatch that consumes their +// completion is accepted. Replayed history emits neither. +// - Entity operation executions emit SERVER spans for calls and CONSUMER +// spans for signals. Each operation's span identity and sampling decision +// are reserved before the batch runs, and the operation's handler context +// carries that identity as a non-recording span context, so application +// spans started from EntityContext.Context() nest under it. Signals and +// orchestrations started by the operation carry it as their parent trace +// context. The span itself is reconstructed with the operation's result +// timestamps and exported only after the backend accepts the batch +// result; rejected, abandoned, or lost batches export nothing, and spans +// the application started under it may then reference a parent that is +// never exported. Successful operations leave the status unset; failed +// operations and failed batches record an error status and the +// "durabletask.entity.error_message" attribute. Durable Task Scheduler +// does not currently forward the parent trace context of entity-started +// signals and orchestrations. +// - V2 entity messages carry no trace context, so entity execution spans are +// independent trace roots, sampled by the provider's root policy, rather +// than children of the calling orchestration or client span. Their IDs +// come from the base generator passed to [WithIDGenerator]. No synthetic +// parent or span link is added. +// - Client SignalEntity emits no span. It propagates the caller's trace +// context on the request only when that context is sampled, like the +// Durable Task .NET gRPC client. The Python SDK also emits no client span +// for signals; the JavaScript SDK emits a "signal_entity" PRODUCER span. +// - Entity lock acquisition and release emit no spans, matching +// DurableTask.Core; entity calls made inside a critical section are traced. // - Abandoned orchestration dispatches export no orchestration telemetry. // - Telemetry is best effort, not exactly once, in both directions. A // completion the backend retries may export its spans again. A completion @@ -126,8 +160,8 @@ func WithIDGenerator(base sdktrace.IDGenerator) sdktrace.TracerProviderOption { } // NewSampler wraps base so Durable Task can learn sampling decisions for -// reconstructed root orchestration spans without starting spans. All other -// spans are sampled exactly as base decides. A nil base uses +// reconstructed root orchestration and entity operation spans without starting +// spans. All other spans are sampled exactly as base decides. A nil base uses // sdktrace.ParentBased(sdktrace.AlwaysSample()), the OpenTelemetry SDK default. // The result must be the provider's top-level sampler: pass a composite such // as sdktrace.ParentBased as base instead of nesting this sampler inside it. From 6d07b2e089842b3598b71972b824801dc8e1f2a0 Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Mon, 30 Nov 2026 15:26:36 -0700 Subject: [PATCH 2/4] Preserve reserved entity sampling decisions Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- client/grpc_worker_tracing_test.go | 175 +++++++++++++++++++++++++++++ internal/dttrace/entity.go | 14 ++- internal/dttrace/idgen.go | 4 +- tracing/tracing.go | 25 +++-- 4 files changed, 199 insertions(+), 19 deletions(-) diff --git a/client/grpc_worker_tracing_test.go b/client/grpc_worker_tracing_test.go index 045a1fb1..3e89ed70 100644 --- a/client/grpc_worker_tracing_test.go +++ b/client/grpc_worker_tracing_test.go @@ -78,6 +78,32 @@ func (h *tracingHarness) spans() []sdktrace.ReadOnlySpan { return h.recorder.Ended() } +type testSamplerFunc func(sdktrace.SamplingParameters) sdktrace.SamplingResult + +func (s testSamplerFunc) ShouldSample(parameters sdktrace.SamplingParameters) sdktrace.SamplingResult { + return s(parameters) +} + +func (testSamplerFunc) Description() string { + return "test sampler" +} + +type testSpanStartHook func(context.Context, sdktrace.ReadWriteSpan) + +func (h testSpanStartHook) OnStart(ctx context.Context, span sdktrace.ReadWriteSpan) { + h(ctx, span) +} + +func (testSpanStartHook) OnEnd(sdktrace.ReadOnlySpan) {} + +func (testSpanStartHook) Shutdown(context.Context) error { + return nil +} + +func (testSpanStartHook) ForceFlush(context.Context) error { + return nil +} + // fakeOrchestrationBackend persists history and orchestration trace context // between dispatches the way a Durable Task backend does. type fakeOrchestrationBackend struct { @@ -672,6 +698,155 @@ func TestWorkerTracingEntityHandlerSpanContext(t *testing.T) { } } +func TestWorkerTracingEntityPreservesReservedSampling(t *testing.T) { + tests := []struct { + name string + reserved sdktrace.SamplingDecision + subsequent sdktrace.SamplingDecision + wantSampled bool + wantRecording bool + }{ + {"sample then drop", sdktrace.RecordAndSample, sdktrace.Drop, true, true}, + {"sample then change tracestate", sdktrace.RecordAndSample, sdktrace.RecordAndSample, true, true}, + {"record only then sample", sdktrace.RecordOnly, sdktrace.RecordAndSample, false, true}, + {"drop then sample", sdktrace.Drop, sdktrace.RecordAndSample, false, false}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + reservedState, err := trace.ParseTraceState("vendor=reserved") + require.NoError(t, err) + subsequentState, err := trace.ParseTraceState("vendor=subsequent") + require.NoError(t, err) + base := sdktrace.ParentBased(sdktrace.AlwaysSample()) + var entitySamples, appSamples, processorSamples int + reservedAttributes := []attribute.KeyValue{attribute.String("test.sampling", "reserved")} + sampler := testSamplerFunc(func(parameters sdktrace.SamplingParameters) sdktrace.SamplingResult { + if parameters.Name == "entity:counter:add" { + entitySamples++ + if entitySamples == 1 { + return sdktrace.SamplingResult{ + Decision: test.reserved, + Tracestate: reservedState, + Attributes: reservedAttributes, + } + } + return sdktrace.SamplingResult{ + Decision: test.subsequent, + Tracestate: subsequentState, + Attributes: []attribute.KeyValue{attribute.String("test.sampling", "subsequent")}, + } + } + if parameters.Name == "entity-app" { + appSamples++ + reservedAttributes[0] = attribute.String("test.sampling", "reused") + } + if parameters.Name == "processor-span" { + processorSamples++ + return sdktrace.SamplingResult{Decision: sdktrace.Drop} + } + return base.ShouldSample(parameters) + }) + + var h *tracingHarness + var handlerContext trace.SpanContext + var processorContext context.Context + registry := task.NewTaskRegistry() + require.NoError(t, registry.AddEntityN("counter", func(ctx *task.EntityContext) (any, error) { + handlerContext = trace.SpanContextFromContext(ctx.Context()) + _, span := h.provider.Tracer("app").Start(ctx.Context(), "entity-app") + span.End() + return nil, nil + })) + hook := testSpanStartHook(func(ctx context.Context, span sdktrace.ReadWriteSpan) { + if span.Name() == "entity:counter:add" { + processorContext = ctx + } + }) + h = newTracingHarnessWithProviderOptions(t, registry, true, + []sdktrace.TracerProviderOption{tracing.WithSampler(sampler), sdktrace.WithSpanProcessor(hook)}) + h.worker.processEntityV2(context.Background(), h.client, "token", newFakeEntitySignalRequest("add", nil)) + + require.Len(t, h.client.entityCompletions, 1) + require.True(t, handlerContext.IsValid()) + require.Equal(t, test.wantSampled, handlerContext.IsSampled()) + require.Equal(t, reservedState, handlerContext.TraceState()) + entitySpans := spansNamed(h.spans(), "entity:counter:add") + appSpans := spansNamed(h.spans(), "entity-app") + if test.wantRecording { + require.Len(t, entitySpans, 1) + entity := entitySpans[0] + require.Equal(t, handlerContext, entity.SpanContext()) + require.False(t, entity.Parent().IsValid()) + require.Equal(t, "reserved", spanAttribute(entity, "test.sampling")) + require.NotNil(t, processorContext) + _, processorSpan := h.provider.Tracer("app").Start(processorContext, "processor-span") + require.False(t, processorSpan.IsRecording()) + processorSpan.End() + require.Equal(t, 1, processorSamples) + } else { + require.Empty(t, entitySpans) + } + if test.wantSampled { + require.Len(t, appSpans, 1) + require.Equal(t, handlerContext, appSpans[0].Parent()) + require.Equal(t, reservedState, appSpans[0].SpanContext().TraceState()) + } else { + require.Empty(t, appSpans) + } + require.Equal(t, 1, entitySamples) + require.Equal(t, 1, appSamples) + }) + } +} + +func TestWorkerTracingEntityBatchSamplingResultsRemainIndependent(t *testing.T) { + base := sdktrace.ParentBased(sdktrace.AlwaysSample()) + calls := make(map[string]int) + sampler := testSamplerFunc(func(parameters sdktrace.SamplingParameters) sdktrace.SamplingResult { + if !strings.HasPrefix(parameters.Name, "entity:counter:") { + return base.ShouldSample(parameters) + } + calls[parameters.Name]++ + if calls[parameters.Name] > 1 { + return sdktrace.SamplingResult{Decision: sdktrace.Drop} + } + operation := strings.TrimPrefix(parameters.Name, "entity:counter:") + state, err := trace.ParseTraceState("vendor=" + operation) + require.NoError(t, err) + return sdktrace.SamplingResult{ + Decision: sdktrace.RecordAndSample, + Tracestate: state, + Attributes: []attribute.KeyValue{attribute.String("test.sampling", operation)}, + } + }) + contexts := make(map[string]trace.SpanContext) + registry := task.NewTaskRegistry() + require.NoError(t, registry.AddEntityN("counter", func(ctx *task.EntityContext) (any, error) { + contexts[ctx.Operation] = trace.SpanContextFromContext(ctx.Context()) + return nil, nil + })) + h := newTracingHarnessWithProviderOptions(t, registry, true, + []sdktrace.TracerProviderOption{tracing.WithSampler(sampler)}) + request := newFakeEntitySignalRequest("add", nil) + request.OperationRequests = append(request.OperationRequests, &protos.HistoryEvent{ + EventType: &protos.HistoryEvent_EntityOperationCalled{EntityOperationCalled: &protos.EntityOperationCalledEvent{ + RequestId: uuid.NewString(), Operation: "get", ParentInstanceId: wrapperspb.String("caller"), + }}, + }) + h.worker.processEntityV2(context.Background(), h.client, "token", request) + + require.Len(t, h.client.entityCompletions, 1) + for _, operation := range []string{"add", "get"} { + name := "entity:counter:" + operation + spans := spansNamed(h.spans(), name) + require.Len(t, spans, 1) + require.Equal(t, contexts[operation], spans[0].SpanContext()) + require.Equal(t, "vendor="+operation, spans[0].SpanContext().TraceState().String()) + require.Equal(t, operation, spanAttribute(spans[0], "test.sampling")) + require.Equal(t, 1, calls[name]) + } +} + func TestWorkerTracingEntityCallCompletionsExportOnce(t *testing.T) { for _, mode := range []string{"turn-budget", "suspended"} { t.Run(mode, func(t *testing.T) { diff --git a/internal/dttrace/entity.go b/internal/dttrace/entity.go index 12f06b23..95b04428 100644 --- a/internal/dttrace/entity.go +++ b/internal/dttrace/entity.go @@ -5,6 +5,7 @@ import ( "time" "go.opentelemetry.io/otel/attribute" + sdktrace "go.opentelemetry.io/otel/sdk/trace" "go.opentelemetry.io/otel/trace" "google.golang.org/protobuf/types/known/timestamppb" @@ -60,6 +61,7 @@ type entityOperation struct { kind trace.SpanKind attrs []attribute.KeyValue spanContext trace.SpanContext + sampling *sdktrace.SamplingResult } // NewEntityBatch reserves a root span context for each operation in request. @@ -77,13 +79,14 @@ func (t *Tracer) NewEntityBatch(id api.EntityID, request *protos.EntityBatchRequ name := entitySpanName(id, operation.Operation) attrs := append(entityAttributes(signal, operation.Operation), AttrInstanceID.String(id.String()), AttrName.String(id.Name)) - spanContext, _ := t.rootSpanContext(trace.TraceID{}, trace.SpanID{}, name, kind, attrs) + spanContext, sampling := t.rootSpanContext(trace.TraceID{}, trace.SpanID{}, name, kind, attrs) batch.operations[i] = entityOperation{ requestID: operation.RequestId, name: name, kind: kind, attrs: attrs, spanContext: spanContext, + sampling: sampling, } } return batch @@ -113,14 +116,14 @@ func EntityOperationSpanContext(ctx context.Context, index int, requestID string // Emit exports the reserved operation spans. Call it only after the backend // accepts result, so rejected or abandoned batches export nothing. start and -// end bound operations whose result has no timestamps. Unsampled operations -// export nothing. +// end bound operations whose result has no timestamps. Dropped operations +// record nothing. func (b *EntityBatch) Emit(result *protos.EntityBatchResult, start, end time.Time) { if b == nil { return } for i, operation := range b.operations { - if !operation.spanContext.IsSampled() { + if !operation.spanContext.IsValid() || (operation.sampling != nil && operation.sampling.Decision == sdktrace.Drop) { continue } opStart, opEnd, failure := operationOutcome(result, i, start, end) @@ -129,7 +132,8 @@ func (b *EntityBatch) Emit(result *protos.EntityBatchResult, start, end time.Tim attrs = append(attrs[:len(attrs):len(attrs)], AttrEntityError.String(failure.GetErrorMessage())) } b.tracer.emit(operation.name, operation.kind, trace.SpanContext{}, - spanRoot{spanContext: operation.spanContext}, operation.spanContext.SpanID(), opStart, opEnd, attrs, failure) + spanRoot{spanContext: operation.spanContext, sampling: operation.sampling}, operation.spanContext.SpanID(), + opStart, opEnd, attrs, failure) } } diff --git a/internal/dttrace/idgen.go b/internal/dttrace/idgen.go index 14af6d2e..968cf50a 100644 --- a/internal/dttrace/idgen.go +++ b/internal/dttrace/idgen.go @@ -103,8 +103,8 @@ type Sampler struct { Base sdktrace.Sampler } -// ShouldSample implements sdktrace.Sampler. For sampling queries it records the -// base decision and drops the query span, so processors never observe it. +// ShouldSample implements sdktrace.Sampler. Sampling queries record the base +// decision without recording a span; reconstruction can reuse that decision. func (s Sampler) ShouldSample(parameters sdktrace.SamplingParameters) sdktrace.SamplingResult { if parameters.ParentContext != nil { if override, ok := parameters.ParentContext.Value(samplingOverrideKey{}).(*samplingOverride); ok && !override.used { diff --git a/tracing/tracing.go b/tracing/tracing.go index 94e24a05..dba4970a 100644 --- a/tracing/tracing.go +++ b/tracing/tracing.go @@ -78,23 +78,23 @@ // spans started from EntityContext.Context() nest under it. Signals and // orchestrations started by the operation carry it as their parent trace // context. The span itself is reconstructed with the operation's result -// timestamps and exported only after the backend accepts the batch -// result; rejected, abandoned, or lost batches export nothing, and spans -// the application started under it may then reference a parent that is -// never exported. Successful operations leave the status unset; failed -// operations and failed batches record an error status and the -// "durabletask.entity.error_message" attribute. Durable Task Scheduler -// does not currently forward the parent trace context of entity-started -// signals and orchestrations. +// timestamps and reserved sampling result only after the backend accepts +// the batch result. Rejected, abandoned, or lost batches export nothing, +// so application spans may reference a parent that is never exported. +// Successful operations leave the status unset; failed operations and +// failed batches record an error status and the +// "durabletask.entity.error_message" attribute. Durable Task Scheduler does +// not currently forward the parent trace context of entity-started signals +// and orchestrations. // - V2 entity messages carry no trace context, so entity execution spans are // independent trace roots, sampled by the provider's root policy, rather // than children of the calling orchestration or client span. Their IDs // come from the base generator passed to [WithIDGenerator]. No synthetic // parent or span link is added. // - Client SignalEntity emits no span. It propagates the caller's trace -// context on the request only when that context is sampled, like the -// Durable Task .NET gRPC client. The Python SDK also emits no client span -// for signals; the JavaScript SDK emits a "signal_entity" PRODUCER span. +// context on the request, including unsampled contexts. The Python SDK +// also emits no client span for signals; the JavaScript SDK emits a +// "signal_entity" PRODUCER span. // - Entity lock acquisition and release emit no spans, matching // DurableTask.Core; entity calls made inside a critical section are traced. // - Abandoned orchestration dispatches export no orchestration telemetry. @@ -161,7 +161,8 @@ func WithIDGenerator(base sdktrace.IDGenerator) sdktrace.TracerProviderOption { // NewSampler wraps base so Durable Task can learn sampling decisions for // reconstructed root orchestration and entity operation spans without starting -// spans. All other spans are sampled exactly as base decides. A nil base uses +// spans. Reconstructed root spans reuse their reserved sampling results. +// Other spans are sampled exactly as base decides. A nil base uses // sdktrace.ParentBased(sdktrace.AlwaysSample()), the OpenTelemetry SDK default. // The result must be the provider's top-level sampler: pass a composite such // as sdktrace.ParentBased as base instead of nesting this sampler inside it. From 0e1263e2785815a3d498b8fc2bf7914c417db0fb Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Mon, 30 Nov 2026 16:15:53 -0700 Subject: [PATCH 3/4] Cover processor span identity isolation Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- client/grpc_worker_tracing_test.go | 35 ++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/client/grpc_worker_tracing_test.go b/client/grpc_worker_tracing_test.go index 3e89ed70..875304ee 100644 --- a/client/grpc_worker_tracing_test.go +++ b/client/grpc_worker_tracing_test.go @@ -799,6 +799,41 @@ func TestWorkerTracingEntityPreservesReservedSampling(t *testing.T) { } } +func TestWorkerTracingEntityProcessorSpansUseFreshIDs(t *testing.T) { + var processorContext context.Context + registry := task.NewTaskRegistry() + require.NoError(t, registry.AddEntityN("counter", func(*task.EntityContext) (any, error) { + return nil, nil + })) + hook := testSpanStartHook(func(ctx context.Context, span sdktrace.ReadWriteSpan) { + if span.Name() == "entity:counter:add" { + processorContext = ctx + } + }) + h := newTracingHarnessWithProviderOptions(t, registry, true, + []sdktrace.TracerProviderOption{sdktrace.WithSpanProcessor(hook)}) + h.worker.processEntityV2(context.Background(), h.client, "token", newFakeEntitySignalRequest("add", nil)) + + require.NotNil(t, processorContext) + entitySpans := spansNamed(h.spans(), "entity:counter:add") + require.Len(t, entitySpans, 1) + entity := entitySpans[0].SpanContext() + + t.Run("root", func(t *testing.T) { + _, span := h.provider.Tracer("app").Start(processorContext, "processor-root") + defer span.End() + require.NotEqual(t, entity.TraceID(), span.SpanContext().TraceID()) + require.NotEqual(t, entity.SpanID(), span.SpanContext().SpanID()) + }) + t.Run("child", func(t *testing.T) { + ctx := trace.ContextWithSpanContext(processorContext, entity) + _, span := h.provider.Tracer("app").Start(ctx, "processor-child") + defer span.End() + require.Equal(t, entity.TraceID(), span.SpanContext().TraceID()) + require.NotEqual(t, entity.SpanID(), span.SpanContext().SpanID()) + }) +} + func TestWorkerTracingEntityBatchSamplingResultsRemainIndependent(t *testing.T) { base := sdktrace.ParentBased(sdktrace.AlwaysSample()) calls := make(map[string]int) From c744bfc81dfb6298e0aae53ec30d64a77105150b Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Mon, 30 Nov 2026 16:17:35 -0700 Subject: [PATCH 4/4] Document backend-rewritten entity results Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- durabletasktest/tracing_test.go | 31 +++++++++++++++++++++++++++++++ tracing/tracing.go | 10 ++++++---- 2 files changed, 37 insertions(+), 4 deletions(-) diff --git a/durabletasktest/tracing_test.go b/durabletasktest/tracing_test.go index b45fce50..72a1b2f0 100644 --- a/durabletasktest/tracing_test.go +++ b/durabletasktest/tracing_test.go @@ -3,6 +3,7 @@ package durabletasktest_test import ( "context" "errors" + "strings" "sync" "sync/atomic" "testing" @@ -65,6 +66,36 @@ func requireLinkedTo(t *testing.T, span, target sdktrace.ReadOnlySpan) { require.Fail(t, "span is not linked to the orchestration", span.Name()) } +func TestTracingOversizedEntityBatchReportsWorkerOutcome(t *testing.T) { + registry := task.NewTaskRegistry() + require.NoError(t, registry.AddEntityN("large", func(*task.EntityContext) (any, error) { + return strings.Repeat("x", 5<<20), nil + })) + id := api.NewEntityID("large", "a") + require.NoError(t, registry.AddOrchestratorN("CallLarge", func(ctx *task.OrchestrationContext) (any, error) { + err := ctx.CallEntity(id, "get").Await(nil) + var failed *task.EntityOperationFailedError + if !errors.As(err, &failed) { + return nil, errors.New("expected an entity operation failure") + } + return string(failed.FailureDetails.ErrorType), nil + })) + host, recorder := newTracedHost(t, registry) + metadata := run(t, host, "CallLarge") + require.Equal(t, api.RUNTIME_STATUS_COMPLETED, metadata.RuntimeStatus) + var failureType string + require.NoError(t, metadata.ReadOutput(&failureType)) + require.Equal(t, "EntityResultTooLarge", failureType) + + var spans []sdktrace.ReadOnlySpan + require.Eventually(t, func() bool { + spans = tracedSpans(recorder, "entity:large:get", trace.SpanKindServer) + return len(spans) > 0 + }, 10*time.Second, 5*time.Millisecond) + require.Len(t, spans, 1) + require.Equal(t, codes.Unset, spans[0].Status().Code) +} + // orchestrationSpanWithStatus waits for an orchestration span: the worker // exports it after the backend accepts the completion, which can be after // the client observes the terminal status. diff --git a/tracing/tracing.go b/tracing/tracing.go index dba4970a..68de3ab6 100644 --- a/tracing/tracing.go +++ b/tracing/tracing.go @@ -82,10 +82,12 @@ // the batch result. Rejected, abandoned, or lost batches export nothing, // so application spans may reference a parent that is never exported. // Successful operations leave the status unset; failed operations and -// failed batches record an error status and the -// "durabletask.entity.error_message" attribute. Durable Task Scheduler does -// not currently forward the parent trace context of entity-started signals -// and orchestrations. +// worker-observed batch failures record an error status and the +// "durabletask.entity.error_message" attribute. If a backend replaces an +// accepted batch result, for example when it is too large, the completion +// response does not return the replacement, so span status reflects the +// worker's result. Durable Task Scheduler does not currently forward the +// parent trace context of entity-started signals and orchestrations. // - V2 entity messages carry no trace context, so entity execution spans are // independent trace roots, sampled by the provider's root policy, rather // than children of the calling orchestration or client span. Their IDs