From 3e2603489d3fd2586de3618af10942d136005550 Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Fri, 20 Nov 2026 11:41:56 -0700 Subject: [PATCH 1/5] Trace accepted orchestration event sends without replay duplication Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- client/grpc_worker_tracing_test.go | 200 +++++++++++++++++++++++++++++ internal/dttrace/dttrace.go | 50 ++++++++ task/orchestrator.go | 2 + tracing/tracing.go | 8 ++ 4 files changed, 260 insertions(+) diff --git a/client/grpc_worker_tracing_test.go b/client/grpc_worker_tracing_test.go index e829f603..d4675745 100644 --- a/client/grpc_worker_tracing_test.go +++ b/client/grpc_worker_tracing_test.go @@ -132,12 +132,212 @@ func (b *fakeOrchestrationBackend) dispatch( b.scheduled[action.Id] = created.ParentTraceContext b.history = append(b.history, helpers.NewSubOrchestrationCreatedEvent( action.Id, created.Name, created.Version, created.Input, created.InstanceId, created.ParentTraceContext)) + case action.GetSendEvent() != nil: + b.history = append(b.history, tracingEventSent(action)) } } b.traceContext = response.OrchestrationTraceContext return response } +func tracingEventSent(action *protos.OrchestratorAction) *protos.HistoryEvent { + sent := action.GetSendEvent() + return &protos.HistoryEvent{ + EventId: action.Id, Timestamp: helpers.NewOrchestratorStartedEvent().Timestamp, + EventType: &protos.HistoryEvent_EventSent{EventSent: &protos.EventSentEvent{ + InstanceId: sent.GetInstance().GetInstanceId(), Name: sent.GetName(), Input: sent.GetData(), + }}, + } +} + +func TestWorkerTracingEventSendAndReceipt(t *testing.T) { + registry := task.NewTaskRegistry() + require.NoError(t, registry.AddOrchestratorN("Sender", func(ctx *task.OrchestrationContext) (any, error) { + if err := ctx.SendEvent("receiver", "approval", "approved"); err != nil { + return nil, err + } + return nil, ctx.WaitForSingleEvent("finish", -1).Await(nil) + })) + require.NoError(t, registry.AddOrchestratorN("Receiver", func(ctx *task.OrchestrationContext) (any, error) { + var value string + err := ctx.WaitForSingleEvent("approval", -1).Await(&value) + return value, err + })) + parent, parentTrace := newTraceParent(trace.FlagsSampled) + started := helpers.NewExecutionStartedEvent("Sender", "sender", nil, nil, parentTrace, nil) + backend := newFakeOrchestrationBackend("sender", started) + h := newTracingHarness(t, registry, true) + response := backend.dispatch(t, h) + events := spansNamed(h.spans(), "orchestration_event:approval") + require.Len(t, events, 1) + span := events[0] + require.Equal(t, trace.SpanKindProducer, span.SpanKind()) + require.Equal(t, parent.TraceID(), span.SpanContext().TraceID()) + require.Equal(t, response.OrchestrationTraceContext.SpanID.GetValue(), span.Parent().SpanID().String()) + require.Equal(t, "vendor=value", span.SpanContext().TraceState().String()) + require.Equal(t, "durabletask", span.InstrumentationScope().Name) + require.Equal(t, "event", spanAttribute(span, "durabletask.type")) + require.Equal(t, "approval", spanAttribute(span, "durabletask.task.name")) + require.Equal(t, "sender", spanAttribute(span, "durabletask.task.instance_id")) + require.Equal(t, started.GetExecutionStarted().GetOrchestrationInstance().GetExecutionId().GetValue(), + spanAttribute(span, "durabletask.task.execution_id")) + require.Equal(t, "receiver", spanAttribute(span, "durabletask.event.target_instance_id")) + require.Empty(t, spanAttribute(span, "durabletask.task.task_id")) + require.Empty(t, spanAttribute(span, "durabletask.task.version")) + require.True(t, span.StartTime().Equal(span.EndTime())) + sent := response.Actions[0] + require.Equal(t, `"approved"`, sent.GetSendEvent().GetData().GetValue()) + + // An acknowledgement delivered as new history must not export the send a + // second time, even when replay regenerates the corresponding action. + backend.history = backend.history[:len(backend.history)-1] + backend.dispatch(t, h, tracingEventSent(sent)) + backend.dispatch(t, h, helpers.NewEventRaisedEvent("finish", nil)) + require.Len(t, spansNamed(h.spans(), "orchestration_event:approval"), 1) + + // Receipt stays in the receiver's independently scheduled trace. The + // protocol has no sender trace context to propagate or link here. + receiverParent := parent.WithTraceID(trace.TraceID{9}).WithSpanID(trace.SpanID{9}) + receiver := newFakeOrchestrationBackend("receiver", helpers.NewExecutionStartedEvent( + "Receiver", "receiver", nil, nil, helpers.TraceContextFromSpanContext(receiverParent), nil)) + receiver.dispatch(t, h, helpers.NewEventRaisedEvent("approval", sent.GetSendEvent().GetData())) + received := spansNamed(h.spans(), "orchestration:Receiver") + require.Len(t, received, 1) + require.Equal(t, receiverParent, received[0].Parent()) + require.Empty(t, received[0].Links()) + require.Len(t, spansNamed(h.spans(), "orchestration_event:approval"), 1) + for _, span := range h.spans() { + require.NotEqual(t, trace.SpanKindConsumer, span.SpanKind()) + } +} + +func TestWorkerTracingEventSendSameBatch(t *testing.T) { + registry := task.NewTaskRegistry() + require.NoError(t, registry.AddOrchestratorN("BatchSend", func(ctx *task.OrchestrationContext) (any, error) { + if err := ctx.SendEvent("receiver", "approval", nil); err != nil { + return nil, err + } + return nil, ctx.WaitForSingleEvent("finish", -1).Await(nil) + })) + _, parentTrace := newTraceParent(trace.FlagsSampled) + started := helpers.NewExecutionStartedEvent("BatchSend", "sender", nil, nil, parentTrace, nil) + sent := tracingEventSent(helpers.NewSendEventAction("receiver", "approval", wrapperspb.String(""))) + sent.EventId = 0 + h := newTracingHarness(t, registry, true) + request := &protos.OrchestratorRequest{ + InstanceId: "sender", + NewEvents: []*protos.HistoryEvent{helpers.NewOrchestratorStartedEvent(), started, sent}, + } + h.worker.processOrchestration(context.Background(), h.client, "token", request) + require.Empty(t, h.client.orchestrationCompletions[0].Actions) + require.Len(t, spansNamed(h.spans(), "orchestration_event:approval"), 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.Empty(t, h.client.orchestrationCompletions[1].Actions) + require.Len(t, spansNamed(h.spans(), "orchestration_event:approval"), 1) +} + +func TestWorkerTracingEventsBufferingAndTurnBudget(t *testing.T) { + for _, mode := range []string{"event-budget", "suspended", "buffered"} { + t.Run(mode, func(t *testing.T) { + registry := task.NewTaskRegistry() + require.NoError(t, registry.AddOrchestratorN("Relay", func(ctx *task.OrchestrationContext) (any, error) { + if mode == "buffered" { + if err := ctx.WaitForSingleEvent("ready", -1).Await(nil); err != nil { + return nil, err + } + } + for range 2 { + if err := ctx.WaitForSingleEvent("next", -1).Await(nil); err != nil { + return nil, err + } + if err := ctx.SendEvent("receiver", "forwarded", nil); err != nil { + return nil, err + } + } + return nil, ctx.WaitForSingleEvent("finish", -1).Await(nil) + })) + _, parentTrace := newTraceParent(trace.FlagsSampled) + backend := newFakeOrchestrationBackend("relay", helpers.NewExecutionStartedEvent( + "Relay", "relay", nil, nil, parentTrace, nil)) + h := newTracingHarness(t, registry, true, + task.WithOrchestrationOptions(task.OrchestrationOptions{MaxEventsPerTurn: 1})) + backend.dispatch(t, h) + if mode == "suspended" { + backend.dispatch(t, h, helpers.NewSuspendOrchestrationEvent("")) + } + backend.dispatch(t, h, helpers.NewEventRaisedEvent("next", nil), helpers.NewEventRaisedEvent("next", nil)) + want := 1 + if mode != "event-budget" { + want = 0 + } + require.Len(t, spansNamed(h.spans(), "orchestration_event:forwarded"), want) + backend.dispatch(t, h) + if mode == "suspended" { + require.Empty(t, h.spans(), "buffered receipts must not manufacture send spans") + backend.dispatch(t, h, helpers.NewResumeOrchestrationEvent("")) + } else if mode == "buffered" { + require.Empty(t, h.spans(), "receipts without a waiter must not manufacture send spans") + backend.dispatch(t, h, helpers.NewEventRaisedEvent("ready", nil)) + } + require.Len(t, spansNamed(h.spans(), "orchestration_event:forwarded"), 2) + backend.dispatch(t, h, helpers.NewEventRaisedEvent("finish", nil)) + require.Len(t, spansNamed(h.spans(), "orchestration_event:forwarded"), 2) + }) + } +} + +func TestWorkerTracingEventsDisabledOrMissingContext(t *testing.T) { + for _, mode := range []string{"disabled", "missing-context", "unsampled"} { + t.Run(mode, func(t *testing.T) { + registry := task.NewTaskRegistry() + require.NoError(t, registry.AddOrchestratorN("Send", func(ctx *task.OrchestrationContext) (any, error) { + return nil, ctx.SendEvent("receiver", "approval", 42) + })) + _, parentTrace := newTraceParent(trace.FlagsSampled) + if mode == "missing-context" { + parentTrace = nil + } else if mode == "unsampled" { + _, parentTrace = newTraceParent(0) + } + h := newTracingHarness(t, registry, mode != "disabled") + response := newFakeOrchestrationBackend("sender", helpers.NewExecutionStartedEvent( + "Send", "sender", nil, nil, parentTrace, nil)).dispatch(t, h) + if mode == "missing-context" { + // The orchestration roots a new trace and the send nests under it. + events := spansNamed(h.spans(), "orchestration_event:approval") + require.Len(t, events, 1) + require.Equal(t, response.OrchestrationTraceContext.SpanID.GetValue(), events[0].Parent().SpanID().String()) + require.Len(t, spansNamed(h.spans(), "orchestration:Send"), 1) + require.False(t, spansNamed(h.spans(), "orchestration:Send")[0].Parent().IsValid()) + } else { + require.Empty(t, h.spans()) + } + require.Len(t, response.Actions, 2) + require.Equal(t, "approval", response.Actions[0].GetSendEvent().GetName()) + require.Equal(t, "42", response.Actions[0].GetSendEvent().GetData().GetValue()) + }) + } +} + +func TestWorkerTracingDiscardedSendDoesNotExport(t *testing.T) { + registry := task.NewTaskRegistry() + require.NoError(t, registry.AddOrchestratorN("LargeSend", func(ctx *task.OrchestrationContext) (any, error) { + return nil, ctx.SendEvent("receiver", "approval", string(make([]byte, 4096))) + })) + _, parentTrace := newTraceParent(trace.FlagsSampled) + h := newTracingHarness(t, registry, true) + h.worker.options.maxOrchestratorCompletionBytes = 1024 + response := newFakeOrchestrationBackend("sender", helpers.NewExecutionStartedEvent( + "LargeSend", "sender", nil, nil, parentTrace, nil)).dispatch(t, h) + require.Len(t, response.Actions, 1) + require.Equal(t, protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED, + response.Actions[0].GetCompleteOrchestration().GetOrchestrationStatus()) + require.Empty(t, spansNamed(h.spans(), "orchestration_event:approval")) +} + func newTraceParent(flags trace.TraceFlags) (trace.SpanContext, *protos.TraceContext) { state, _ := trace.ParseTraceState("vendor=value") spanContext := trace.NewSpanContext(trace.SpanContextConfig{ diff --git a/internal/dttrace/dttrace.go b/internal/dttrace/dttrace.go index 9f1b7cd2..ec923a91 100644 --- a/internal/dttrace/dttrace.go +++ b/internal/dttrace/dttrace.go @@ -308,6 +308,7 @@ type Orchestration struct { // failure is in this dispatch's history, so their CLIENT span was exported. failedChildren map[int32]struct{} timers map[int32]createdTimer + sentEvents map[int32]pendingSpan pending []pendingSpan logicalOnce sync.Once @@ -330,6 +331,7 @@ func (t *Tracer) StartOrchestration( instanceID: instanceID, scheduled: make(map[int32]scheduledTask), timers: make(map[int32]createdTimer), + sentEvents: make(map[int32]pendingSpan), } for _, events := range eventLists { for _, event := range events { @@ -601,6 +603,44 @@ func (o *Orchestration) fireTimer(fired *protos.TimerFiredEvent, end time.Time, }) } +func (o *Orchestration) eventSpan(name, target string) pendingSpan { + now := time.Now() + attrs := taskAttributes(typeEvent, name, "", o.instanceID) + if o.executionID != "" { + attrs = append(attrs, AttrExecutionID.String(o.executionID)) + } + if target != "" { + attrs = append(attrs, AttrEventTargetInstanceID.String(target)) + } + return pendingSpan{ + name: SpanName(typeOrchestrationEvent, name, ""), kind: trace.SpanKindProducer, + spanID: RandomSpanID(), start: now, end: now, attrs: attrs, + } +} + +// RecordSendEvent remembers a non-replayed send in case its matching history +// is consumed in this dispatch instead of leaving an action in the response. +func (o *Orchestration) RecordSendEvent(action *protos.OrchestratorAction, replaying bool) { + if !o.Enabled() || replaying { + return + } + sent := action.GetSendEvent() + o.sentEvents[action.Id] = o.eventSpan(sent.GetName(), sent.GetInstance().GetInstanceId()) +} + +// ConfirmSendEvent queues a send only after the replay engine validates its +// history match. An acknowledgement of a send from an earlier dispatch emits +// nothing: that send was already exported with its accepted response. +func (o *Orchestration) ConfirmSendEvent(eventID int32, replaying bool) { + if !o.Enabled() { + return + } + if span, ok := o.sentEvents[eventID]; ok && !replaying { + o.pending = append(o.pending, span) + } + delete(o.sentEvents, eventID) +} + // PrepareResponse persists the orchestration span identity on response and // assigns scheduling span IDs to new activity and sub-orchestration actions. // Continue-as-new and rewind responses carry a fresh identity so the next @@ -677,6 +717,16 @@ func (o *Orchestration) Emit(response *protos.OrchestratorResponse) { return } logical := o.SpanContext() + for _, action := range response.GetActions() { + if sent := action.GetSendEvent(); sent != nil { + span, ok := o.sentEvents[action.Id] + if !ok { + span = o.eventSpan(sent.GetName(), sent.GetInstance().GetInstanceId()) + } + o.pending = append(o.pending, span) + } + } + o.sentEvents = nil for _, span := range o.pending { switch { case span.scheduled.IsValid() && span.scheduled.TraceID() != logical.TraceID(): diff --git a/task/orchestrator.go b/task/orchestrator.go index b11da118..9932b039 100644 --- a/task/orchestrator.go +++ b/task/orchestrator.go @@ -1264,6 +1264,7 @@ func (ctx *OrchestrationContext) SendEvent(instanceID api.InstanceID, eventName action := helpers.NewSendEventAction(string(instanceID), eventName, wrapperspb.String(string(raw))) action.Id = engine.getNextSequenceNumber() engine.pendingActions[action.Id] = action + engine.trace.RecordSendEvent(action, engine.IsReplaying) return nil } @@ -1447,6 +1448,7 @@ func (ctx *OrchestrationContext) onEventSent(eventID int32, event *protos.EventS ) } delete(ctx.pendingActions, eventID) + ctx.trace.ConfirmSendEvent(eventID, ctx.IsReplaying) return nil } diff --git a/tracing/tracing.go b/tracing/tracing.go index 4b1123cb..29a194f9 100644 --- a/tracing/tracing.go +++ b/tracing/tracing.go @@ -55,6 +55,14 @@ // reports the activity's own outcome, whether or not that outcome reaches // the backend. Work the worker rejects before running activity code, such // as a version mismatch with task.VersionFailureReject, exports no span. +// - Orchestrator SendEvent actions emit "orchestration_event:" +// PRODUCER spans under the sending orchestration when accepted. Replayed +// sends and later history acknowledgements emit nothing. A new send whose +// acknowledgement arrives in the same dispatch is exported with that +// dispatch. +// - 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. // - 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 From 8a3c40f03d1abb3fef862d8a11b8b005c8264817 Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Fri, 20 Nov 2026 12:07:40 -0700 Subject: [PATCH 2/5] Use switch statements in worker tracing tests Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- client/grpc_worker_tracing_test.go | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/client/grpc_worker_tracing_test.go b/client/grpc_worker_tracing_test.go index d4675745..6e54c84b 100644 --- a/client/grpc_worker_tracing_test.go +++ b/client/grpc_worker_tracing_test.go @@ -275,10 +275,11 @@ func TestWorkerTracingEventsBufferingAndTurnBudget(t *testing.T) { } require.Len(t, spansNamed(h.spans(), "orchestration_event:forwarded"), want) backend.dispatch(t, h) - if mode == "suspended" { + switch mode { + case "suspended": require.Empty(t, h.spans(), "buffered receipts must not manufacture send spans") backend.dispatch(t, h, helpers.NewResumeOrchestrationEvent("")) - } else if mode == "buffered" { + case "buffered": require.Empty(t, h.spans(), "receipts without a waiter must not manufacture send spans") backend.dispatch(t, h, helpers.NewEventRaisedEvent("ready", nil)) } @@ -297,9 +298,10 @@ func TestWorkerTracingEventsDisabledOrMissingContext(t *testing.T) { return nil, ctx.SendEvent("receiver", "approval", 42) })) _, parentTrace := newTraceParent(trace.FlagsSampled) - if mode == "missing-context" { + switch mode { + case "missing-context": parentTrace = nil - } else if mode == "unsampled" { + case "unsampled": _, parentTrace = newTraceParent(0) } h := newTracingHarness(t, registry, mode != "disabled") From f68b5b41b49e5252fc9e5d1865e7dfa7aeace1c1 Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Fri, 20 Nov 2026 13:00:19 -0700 Subject: [PATCH 3/5] Avoid duplicate event spans when acknowledgements are deferred Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- client/grpc_worker_tracing_test.go | 36 ++++++++++++++++++++++++++++++ internal/dttrace/dttrace.go | 26 ++++++++++++++------- 2 files changed, 54 insertions(+), 8 deletions(-) diff --git a/client/grpc_worker_tracing_test.go b/client/grpc_worker_tracing_test.go index 6e54c84b..d2a02082 100644 --- a/client/grpc_worker_tracing_test.go +++ b/client/grpc_worker_tracing_test.go @@ -211,6 +211,42 @@ func TestWorkerTracingEventSendAndReceipt(t *testing.T) { } } +func TestWorkerTracingEventSendAckDeferredByTurnBudget(t *testing.T) { + registry := task.NewTaskRegistry() + require.NoError(t, registry.AddOrchestratorN("Sender", func(ctx *task.OrchestrationContext) (any, error) { + if err := ctx.SendEvent("receiver", "approval", nil); err != nil { + return nil, err + } + return nil, ctx.WaitForSingleEvent("finish", -1).Await(nil) + })) + _, parentTrace := newTraceParent(trace.FlagsSampled) + backend := newFakeOrchestrationBackend("sender", helpers.NewExecutionStartedEvent( + "Sender", "sender", nil, nil, parentTrace, nil)) + h := newTracingHarness(t, registry, true, + task.WithOrchestrationOptions(task.OrchestrationOptions{MaxEventsPerTurn: 1})) + response := backend.dispatch(t, h) + require.Len(t, spansNamed(h.spans(), "orchestration_event:approval"), 1) + + // Deliver the accepted send's acknowledgement behind an unrelated event. + ack := backend.history[len(backend.history)-1] + require.NotNil(t, ack.GetEventSent()) + backend.history = backend.history[:len(backend.history)-1] + deferred := backend.dispatch(t, h, helpers.NewEventRaisedEvent("unrelated", nil), ack) + require.Equal(t, int32(1), deferred.GetNumEventsProcessed().GetValue()) + require.Len(t, deferred.Actions, 1) + require.Equal(t, response.Actions[0].Id, deferred.Actions[0].Id) + require.NotNil(t, deferred.Actions[0].GetSendEvent()) + require.Len(t, spansNamed(h.spans(), "orchestration_event:approval"), 1, + "a replayed send must not export again while its acknowledgement is deferred") + + // The real backend deduplicates the replayed send; retain only the original + // acknowledgement, still pending delivery, rather than the fake's new one. + backend.history = backend.history[:len(backend.history)-1] + backend.dispatch(t, h) + backend.dispatch(t, h, helpers.NewEventRaisedEvent("finish", nil)) + require.Len(t, spansNamed(h.spans(), "orchestration_event:approval"), 1) +} + func TestWorkerTracingEventSendSameBatch(t *testing.T) { registry := task.NewTaskRegistry() require.NoError(t, registry.AddOrchestratorN("BatchSend", func(ctx *task.OrchestrationContext) (any, error) { diff --git a/internal/dttrace/dttrace.go b/internal/dttrace/dttrace.go index ec923a91..dbf453bb 100644 --- a/internal/dttrace/dttrace.go +++ b/internal/dttrace/dttrace.go @@ -307,9 +307,10 @@ type Orchestration struct { // failedChildren holds the creation event IDs of sub-orchestrations whose // failure is in this dispatch's history, so their CLIENT span was exported. failedChildren map[int32]struct{} - timers map[int32]createdTimer - sentEvents map[int32]pendingSpan - pending []pendingSpan + timers map[int32]createdTimer + sentEvents map[int32]pendingSpan + acceptedSends map[int32]struct{} + pending []pendingSpan logicalOnce sync.Once logical trace.SpanContext @@ -327,14 +328,20 @@ func (t *Tracer) StartOrchestration( eventLists ...[]*protos.HistoryEvent, ) *Orchestration { o := &Orchestration{ - tracer: t, - instanceID: instanceID, - scheduled: make(map[int32]scheduledTask), - timers: make(map[int32]createdTimer), - sentEvents: make(map[int32]pendingSpan), + tracer: t, + instanceID: instanceID, + scheduled: make(map[int32]scheduledTask), + timers: make(map[int32]createdTimer), + sentEvents: make(map[int32]pendingSpan), + acceptedSends: make(map[int32]struct{}), } for _, events := range eventLists { for _, event := range events { + // An acknowledgement proves acceptance even when the turn budget + // prevents the replay engine from consuming it in this dispatch. + if event.GetEventSent() != nil { + o.acceptedSends[event.EventId] = struct{}{} + } if started := event.GetExecutionStarted(); started != nil { o.started = true o.name = started.GetName() @@ -721,6 +728,9 @@ func (o *Orchestration) Emit(response *protos.OrchestratorResponse) { if sent := action.GetSendEvent(); sent != nil { span, ok := o.sentEvents[action.Id] if !ok { + if _, accepted := o.acceptedSends[action.Id]; accepted { + continue + } span = o.eventSpan(sent.GetName(), sent.GetInstance().GetInstanceId()) } o.pending = append(o.pending, span) From a4c5a5373c8ff08fc95e4f11159c1b1ece2ec412 Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Mon, 23 Nov 2026 12:21:41 -0700 Subject: [PATCH 4/5] Clarify event send tracing and harden repeated emits Document the send span decision table, stamp fallback send spans when the response is prepared, make repeated Emit and late RecordSendEvent calls safe, cover rejected completions and same-turn continue-as-new, and add a changelog entry. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 1 + client/grpc_worker_test.go | 3 +- client/grpc_worker_tracing_test.go | 262 ++++++++++++++++++++--------- internal/dttrace/dttrace.go | 95 ++++++++--- 4 files changed, 251 insertions(+), 110 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 57788bc7..5f368a96 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - 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. +- 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. ### Removed diff --git a/client/grpc_worker_test.go b/client/grpc_worker_test.go index 6efb1ae7..977deba6 100644 --- a/client/grpc_worker_test.go +++ b/client/grpc_worker_test.go @@ -97,6 +97,7 @@ type fakeSchedulerClient struct { orchestrationCompletions []*protos.OrchestratorResponse activityCompletions []*protos.ActivityResponse entityCompletions []*protos.EntityBatchResult + completeOrchestratorErr error activityCompletionErr error entityCompletionErr error orchestrationAbandons int @@ -130,7 +131,7 @@ func (c *fakeSchedulerClient) CompleteOrchestratorTask( c.mu.Lock() defer c.mu.Unlock() c.orchestrationCompletions = append(c.orchestrationCompletions, response) - return &protos.CompleteTaskResponse{}, nil + return &protos.CompleteTaskResponse{}, c.completeOrchestratorErr } func (c *fakeSchedulerClient) CompleteActivityTask( diff --git a/client/grpc_worker_tracing_test.go b/client/grpc_worker_tracing_test.go index d2a02082..26791267 100644 --- a/client/grpc_worker_tracing_test.go +++ b/client/grpc_worker_tracing_test.go @@ -133,23 +133,15 @@ func (b *fakeOrchestrationBackend) dispatch( b.history = append(b.history, helpers.NewSubOrchestrationCreatedEvent( action.Id, created.Name, created.Version, created.Input, created.InstanceId, created.ParentTraceContext)) case action.GetSendEvent() != nil: - b.history = append(b.history, tracingEventSent(action)) + sent := action.GetSendEvent() + b.history = append(b.history, helpers.NewSendEventEvent( + action.Id, sent.GetInstance().GetInstanceId(), sent.GetName(), sent.GetData())) } } b.traceContext = response.OrchestrationTraceContext return response } -func tracingEventSent(action *protos.OrchestratorAction) *protos.HistoryEvent { - sent := action.GetSendEvent() - return &protos.HistoryEvent{ - EventId: action.Id, Timestamp: helpers.NewOrchestratorStartedEvent().Timestamp, - EventType: &protos.HistoryEvent_EventSent{EventSent: &protos.EventSentEvent{ - InstanceId: sent.GetInstance().GetInstanceId(), Name: sent.GetName(), Input: sent.GetData(), - }}, - } -} - func TestWorkerTracingEventSendAndReceipt(t *testing.T) { registry := task.NewTaskRegistry() require.NoError(t, registry.AddOrchestratorN("Sender", func(ctx *task.OrchestrationContext) (any, error) { @@ -164,51 +156,141 @@ func TestWorkerTracingEventSendAndReceipt(t *testing.T) { return value, err })) parent, parentTrace := newTraceParent(trace.FlagsSampled) - started := helpers.NewExecutionStartedEvent("Sender", "sender", nil, nil, parentTrace, nil) - backend := newFakeOrchestrationBackend("sender", started) + + t.Run("send", func(t *testing.T) { + started := helpers.NewExecutionStartedEvent("Sender", "sender", nil, nil, parentTrace, nil) + h := newTracingHarness(t, registry, true) + response := newFakeOrchestrationBackend("sender", started).dispatch(t, h) + events := spansNamed(h.spans(), "orchestration_event:approval") + require.Len(t, events, 1) + span := events[0] + require.Equal(t, trace.SpanKindProducer, span.SpanKind()) + require.Equal(t, parent.TraceID(), span.SpanContext().TraceID()) + require.Equal(t, response.OrchestrationTraceContext.SpanID.GetValue(), span.Parent().SpanID().String()) + require.Equal(t, "vendor=value", span.SpanContext().TraceState().String()) + require.Equal(t, "Microsoft.DurableTask", span.InstrumentationScope().Name) + require.Equal(t, "event", spanAttribute(span, "durabletask.type")) + require.Equal(t, "approval", spanAttribute(span, "durabletask.task.name")) + require.Equal(t, "sender", spanAttribute(span, "durabletask.task.instance_id")) + require.Equal(t, started.GetExecutionStarted().GetOrchestrationInstance().GetExecutionId().GetValue(), + spanAttribute(span, "durabletask.task.execution_id")) + require.Equal(t, "receiver", spanAttribute(span, "durabletask.event.target_instance_id")) + require.Empty(t, spanAttribute(span, "durabletask.task.task_id")) + require.Empty(t, spanAttribute(span, "durabletask.task.version")) + require.True(t, span.StartTime().Equal(span.EndTime())) + require.Equal(t, `"approved"`, response.Actions[0].GetSendEvent().GetData().GetValue()) + }) + + t.Run("acknowledgement-as-new-event", func(t *testing.T) { + // An acknowledgement delivered as new history must not export the send + // a second time, even when replay regenerates the corresponding action. + h := newTracingHarness(t, registry, true) + backend := newFakeOrchestrationBackend("sender", helpers.NewExecutionStartedEvent( + "Sender", "sender", nil, nil, parentTrace, nil)) + backend.dispatch(t, h) + ack := backend.history[len(backend.history)-1] + require.NotNil(t, ack.GetEventSent()) + backend.history = backend.history[:len(backend.history)-1] + backend.dispatch(t, h, ack) + backend.dispatch(t, h, helpers.NewEventRaisedEvent("finish", nil)) + require.Len(t, spansNamed(h.spans(), "orchestration_event:approval"), 1) + }) + + t.Run("receipt", func(t *testing.T) { + // Receipt stays in the receiver's independently scheduled trace. The + // protocol has no sender trace context to propagate or link here. + h := newTracingHarness(t, registry, true) + receiverParent := parent.WithTraceID(trace.TraceID{9}).WithSpanID(trace.SpanID{9}) + receiver := newFakeOrchestrationBackend("receiver", helpers.NewExecutionStartedEvent( + "Receiver", "receiver", nil, nil, helpers.TraceContextFromSpanContext(receiverParent), nil)) + receiver.dispatch(t, h, helpers.NewEventRaisedEvent("approval", wrapperspb.String(`"approved"`))) + received := spansNamed(h.spans(), "orchestration:Receiver") + require.Len(t, received, 1) + require.Equal(t, receiverParent, received[0].Parent()) + require.Empty(t, received[0].Links()) + require.Empty(t, spansNamed(h.spans(), "orchestration_event:approval")) + for _, span := range h.spans() { + require.NotEqual(t, trace.SpanKindConsumer, span.SpanKind()) + } + }) +} + +func TestWorkerTracingEventSendRejectedCompletionExportsNothing(t *testing.T) { + registry := task.NewTaskRegistry() + require.NoError(t, registry.AddOrchestratorN("Sender", func(ctx *task.OrchestrationContext) (any, error) { + if err := ctx.SendEvent("receiver", "approval", nil); err != nil { + return nil, err + } + return nil, ctx.WaitForSingleEvent("finish", -1).Await(nil) + })) + _, parentTrace := newTraceParent(trace.FlagsSampled) h := newTracingHarness(t, registry, true) - response := backend.dispatch(t, h) + h.client.completeOrchestratorErr = status.Error(grpccodes.InvalidArgument, "rejected") + h.worker.processOrchestration(context.Background(), h.client, "token", &protos.OrchestratorRequest{ + InstanceId: "sender", + NewEvents: []*protos.HistoryEvent{ + helpers.NewOrchestratorStartedEvent(), + helpers.NewExecutionStartedEvent("Sender", "sender", nil, nil, parentTrace, nil), + }, + }) + require.Len(t, h.client.orchestrationCompletions, 1) + require.NotNil(t, h.client.orchestrationCompletions[0].Actions[0].GetSendEvent()) + require.Equal(t, 1, h.client.orchestrationAbandons) + require.Empty(t, h.spans()) +} + +func TestWorkerTracingEventSendWithContinueAsNew(t *testing.T) { + registry := task.NewTaskRegistry() + require.NoError(t, registry.AddOrchestratorN("Relay", func(ctx *task.OrchestrationContext) (any, error) { + if err := ctx.SendEvent("receiver", "approval", nil); err != nil { + return nil, err + } + ctx.ContinueAsNew(nil) + return nil, nil + })) + _, parentTrace := newTraceParent(trace.FlagsSampled) + h := newTracingHarness(t, registry, true) + response := newFakeOrchestrationBackend("relay", helpers.NewExecutionStartedEvent( + "Relay", "relay", nil, nil, parentTrace, nil)).dispatch(t, h) + require.Len(t, response.Actions, 2) + require.NotNil(t, response.Actions[0].GetSendEvent()) + require.Equal(t, protos.OrchestrationStatus_ORCHESTRATION_STATUS_CONTINUED_AS_NEW, + response.Actions[1].GetCompleteOrchestration().GetOrchestrationStatus()) + orchestrations := spansNamed(h.spans(), "orchestration:Relay") + require.Len(t, orchestrations, 1) events := spansNamed(h.spans(), "orchestration_event:approval") require.Len(t, events, 1) - span := events[0] - require.Equal(t, trace.SpanKindProducer, span.SpanKind()) - require.Equal(t, parent.TraceID(), span.SpanContext().TraceID()) - require.Equal(t, response.OrchestrationTraceContext.SpanID.GetValue(), span.Parent().SpanID().String()) - require.Equal(t, "vendor=value", span.SpanContext().TraceState().String()) - require.Equal(t, "durabletask", span.InstrumentationScope().Name) - require.Equal(t, "event", spanAttribute(span, "durabletask.type")) - require.Equal(t, "approval", spanAttribute(span, "durabletask.task.name")) - require.Equal(t, "sender", spanAttribute(span, "durabletask.task.instance_id")) - require.Equal(t, started.GetExecutionStarted().GetOrchestrationInstance().GetExecutionId().GetValue(), - spanAttribute(span, "durabletask.task.execution_id")) - require.Equal(t, "receiver", spanAttribute(span, "durabletask.event.target_instance_id")) - require.Empty(t, spanAttribute(span, "durabletask.task.task_id")) - require.Empty(t, spanAttribute(span, "durabletask.task.version")) - require.True(t, span.StartTime().Equal(span.EndTime())) - sent := response.Actions[0] - require.Equal(t, `"approved"`, sent.GetSendEvent().GetData().GetValue()) - - // An acknowledgement delivered as new history must not export the send a - // second time, even when replay regenerates the corresponding action. - backend.history = backend.history[:len(backend.history)-1] - backend.dispatch(t, h, tracingEventSent(sent)) - backend.dispatch(t, h, helpers.NewEventRaisedEvent("finish", nil)) - require.Len(t, spansNamed(h.spans(), "orchestration_event:approval"), 1) + // The send belongs to the execution that made it, not the next execution + // whose fresh identity the response persists. + require.Equal(t, orchestrations[0].SpanContext().SpanID(), events[0].Parent().SpanID()) + require.NotEqual(t, response.OrchestrationTraceContext.SpanID.GetValue(), events[0].Parent().SpanID().String()) +} - // Receipt stays in the receiver's independently scheduled trace. The - // protocol has no sender trace context to propagate or link here. - receiverParent := parent.WithTraceID(trace.TraceID{9}).WithSpanID(trace.SpanID{9}) - receiver := newFakeOrchestrationBackend("receiver", helpers.NewExecutionStartedEvent( - "Receiver", "receiver", nil, nil, helpers.TraceContextFromSpanContext(receiverParent), nil)) - receiver.dispatch(t, h, helpers.NewEventRaisedEvent("approval", sent.GetSendEvent().GetData())) - received := spansNamed(h.spans(), "orchestration:Receiver") - require.Len(t, received, 1) - require.Equal(t, receiverParent, received[0].Parent()) - require.Empty(t, received[0].Links()) - require.Len(t, spansNamed(h.spans(), "orchestration_event:approval"), 1) - for _, span := range h.spans() { - require.NotEqual(t, trace.SpanKindConsumer, span.SpanKind()) - } +func TestWorkerTracingEventSendEmitsOnceAtResponseTime(t *testing.T) { + h := newTracingHarness(t, task.NewTaskRegistry(), true) + _, parentTrace := newTraceParent(trace.FlagsSampled) + o := h.worker.options.tracer.StartOrchestration("sender", nil, []*protos.HistoryEvent{ + helpers.NewExecutionStartedEvent("Sender", "sender", nil, nil, parentTrace, nil), + }) + recorded := helpers.NewSendEventAction("receiver", "recorded", nil) + recorded.Id = 0 + unrecorded := helpers.NewSendEventAction("receiver", "unrecorded", nil) + unrecorded.Id = 1 + o.RecordSendEvent(recorded, false) + response := &protos.OrchestratorResponse{Actions: []*protos.OrchestratorAction{recorded, unrecorded}} + o.PrepareResponse(response) + prepared := time.Now() + time.Sleep(20 * time.Millisecond) + + o.Emit(response) + o.Emit(response) + o.RecordSendEvent(recorded, false) + require.Len(t, spansNamed(h.spans(), "orchestration_event:recorded"), 1) + fallback := spansNamed(h.spans(), "orchestration_event:unrecorded") + require.Len(t, fallback, 1) + // A send without a recorded span is stamped when the response is prepared, + // not after the completion call and its retries. + require.False(t, fallback[0].StartTime().After(prepared)) } func TestWorkerTracingEventSendAckDeferredByTurnBudget(t *testing.T) { @@ -257,8 +339,7 @@ func TestWorkerTracingEventSendSameBatch(t *testing.T) { })) _, parentTrace := newTraceParent(trace.FlagsSampled) started := helpers.NewExecutionStartedEvent("BatchSend", "sender", nil, nil, parentTrace, nil) - sent := tracingEventSent(helpers.NewSendEventAction("receiver", "approval", wrapperspb.String(""))) - sent.EventId = 0 + sent := helpers.NewSendEventEvent(0, "receiver", "approval", wrapperspb.String("")) h := newTracingHarness(t, registry, true) request := &protos.OrchestratorRequest{ InstanceId: "sender", @@ -276,11 +357,30 @@ func TestWorkerTracingEventSendSameBatch(t *testing.T) { } func TestWorkerTracingEventsBufferingAndTurnBudget(t *testing.T) { - for _, mode := range []string{"event-budget", "suspended", "buffered"} { - t.Run(mode, func(t *testing.T) { + for name, test := range map[string]struct { + waitForReady bool + suspend bool + // release lets held receipts reach the orchestrator; nil when the turn + // budget alone defers the second receipt. + release *protos.HistoryEvent + heldMessage string + }{ + "event-budget": {}, + "suspended": { + suspend: true, + release: helpers.NewResumeOrchestrationEvent(""), + heldMessage: "buffered receipts must not manufacture send spans", + }, + "buffered": { + waitForReady: true, + release: helpers.NewEventRaisedEvent("ready", nil), + heldMessage: "receipts without a waiter must not manufacture send spans", + }, + } { + t.Run(name, func(t *testing.T) { registry := task.NewTaskRegistry() require.NoError(t, registry.AddOrchestratorN("Relay", func(ctx *task.OrchestrationContext) (any, error) { - if mode == "buffered" { + if test.waitForReady { if err := ctx.WaitForSingleEvent("ready", -1).Await(nil); err != nil { return nil, err } @@ -301,23 +401,19 @@ func TestWorkerTracingEventsBufferingAndTurnBudget(t *testing.T) { h := newTracingHarness(t, registry, true, task.WithOrchestrationOptions(task.OrchestrationOptions{MaxEventsPerTurn: 1})) backend.dispatch(t, h) - if mode == "suspended" { + if test.suspend { backend.dispatch(t, h, helpers.NewSuspendOrchestrationEvent("")) } backend.dispatch(t, h, helpers.NewEventRaisedEvent("next", nil), helpers.NewEventRaisedEvent("next", nil)) - want := 1 - if mode != "event-budget" { - want = 0 + want := 0 + if test.release == nil { + want = 1 } require.Len(t, spansNamed(h.spans(), "orchestration_event:forwarded"), want) backend.dispatch(t, h) - switch mode { - case "suspended": - require.Empty(t, h.spans(), "buffered receipts must not manufacture send spans") - backend.dispatch(t, h, helpers.NewResumeOrchestrationEvent("")) - case "buffered": - require.Empty(t, h.spans(), "receipts without a waiter must not manufacture send spans") - backend.dispatch(t, h, helpers.NewEventRaisedEvent("ready", nil)) + if test.release != nil { + require.Empty(t, h.spans(), test.heldMessage) + backend.dispatch(t, h, test.release) } require.Len(t, spansNamed(h.spans(), "orchestration_event:forwarded"), 2) backend.dispatch(t, h, helpers.NewEventRaisedEvent("finish", nil)) @@ -327,24 +423,28 @@ func TestWorkerTracingEventsBufferingAndTurnBudget(t *testing.T) { } func TestWorkerTracingEventsDisabledOrMissingContext(t *testing.T) { - for _, mode := range []string{"disabled", "missing-context", "unsampled"} { - t.Run(mode, func(t *testing.T) { + _, sampled := newTraceParent(trace.FlagsSampled) + _, unsampled := newTraceParent(0) + for name, test := range map[string]struct { + enabled bool + parent *protos.TraceContext + // wantRoot means the orchestration roots a new trace and the send nests + // under it; otherwise nothing is exported. + wantRoot bool + }{ + "disabled": {parent: sampled}, + "missing-context": {enabled: true, wantRoot: true}, + "unsampled": {enabled: true, parent: unsampled}, + } { + t.Run(name, func(t *testing.T) { registry := task.NewTaskRegistry() require.NoError(t, registry.AddOrchestratorN("Send", func(ctx *task.OrchestrationContext) (any, error) { return nil, ctx.SendEvent("receiver", "approval", 42) })) - _, parentTrace := newTraceParent(trace.FlagsSampled) - switch mode { - case "missing-context": - parentTrace = nil - case "unsampled": - _, parentTrace = newTraceParent(0) - } - h := newTracingHarness(t, registry, mode != "disabled") + h := newTracingHarness(t, registry, test.enabled) response := newFakeOrchestrationBackend("sender", helpers.NewExecutionStartedEvent( - "Send", "sender", nil, nil, parentTrace, nil)).dispatch(t, h) - if mode == "missing-context" { - // The orchestration roots a new trace and the send nests under it. + "Send", "sender", nil, nil, test.parent, nil)).dispatch(t, h) + if test.wantRoot { events := spansNamed(h.spans(), "orchestration_event:approval") require.Len(t, events, 1) require.Equal(t, response.OrchestrationTraceContext.SpanID.GetValue(), events[0].Parent().SpanID().String()) diff --git a/internal/dttrace/dttrace.go b/internal/dttrace/dttrace.go index dbf453bb..9cf29207 100644 --- a/internal/dttrace/dttrace.go +++ b/internal/dttrace/dttrace.go @@ -308,9 +308,11 @@ type Orchestration struct { // failure is in this dispatch's history, so their CLIENT span was exported. failedChildren map[int32]struct{} timers map[int32]createdTimer - sentEvents map[int32]pendingSpan + newSends map[int32]pendingSpan acceptedSends map[int32]struct{} pending []pendingSpan + responseTime time.Time + emitted bool logicalOnce sync.Once logical trace.SpanContext @@ -328,18 +330,19 @@ func (t *Tracer) StartOrchestration( eventLists ...[]*protos.HistoryEvent, ) *Orchestration { o := &Orchestration{ - tracer: t, - instanceID: instanceID, - scheduled: make(map[int32]scheduledTask), - timers: make(map[int32]createdTimer), - sentEvents: make(map[int32]pendingSpan), - acceptedSends: make(map[int32]struct{}), + tracer: t, + instanceID: instanceID, + scheduled: make(map[int32]scheduledTask), + timers: make(map[int32]createdTimer), } for _, events := range eventLists { for _, event := range events { // An acknowledgement proves acceptance even when the turn budget // prevents the replay engine from consuming it in this dispatch. if event.GetEventSent() != nil { + if o.acceptedSends == nil { + o.acceptedSends = make(map[int32]struct{}) + } o.acceptedSends[event.EventId] = struct{}{} } if started := event.GetExecutionStarted(); started != nil { @@ -610,8 +613,21 @@ func (o *Orchestration) fireTimer(fired *protos.TimerFiredEvent, end time.Time, }) } -func (o *Orchestration) eventSpan(name, target string) pendingSpan { - now := time.Now() +// eventSpan builds an "orchestration_event" PRODUCER span for a send. Each +// SendEvent action exports one such span with the accepted response that +// first carries or consumes it: +// +// - A new send recorded by RecordSendEvent and still in the response exports +// with that response. This is the normal path. +// - A new send whose EventSent is consumed in the same dispatch is queued by +// ConfirmSendEvent and exports with the response. DTS normally delivers +// EventSent as a past event of a later dispatch, so this is defensive. +// - A send issued while replaying that is still in the response exports +// unless an EventSent with its ID appears anywhere in the request, which +// proves an earlier accepted response already exported it, for example +// when the turn budget defers its acknowledgement. +// - A replayed send whose EventSent is consumed exports nothing. +func (o *Orchestration) eventSpan(name, target string, at time.Time) pendingSpan { attrs := taskAttributes(typeEvent, name, "", o.instanceID) if o.executionID != "" { attrs = append(attrs, AttrExecutionID.String(o.executionID)) @@ -620,19 +636,27 @@ func (o *Orchestration) eventSpan(name, target string) pendingSpan { attrs = append(attrs, AttrEventTargetInstanceID.String(target)) } return pendingSpan{ - name: SpanName(typeOrchestrationEvent, name, ""), kind: trace.SpanKindProducer, - spanID: RandomSpanID(), start: now, end: now, attrs: attrs, + name: SpanName(typeOrchestrationEvent, name, ""), + kind: trace.SpanKindProducer, + spanID: RandomSpanID(), + start: at, + end: at, + attrs: attrs, } } -// RecordSendEvent remembers a non-replayed send in case its matching history -// is consumed in this dispatch instead of leaving an action in the response. +// RecordSendEvent creates the span for a send made outside replay, timestamped +// when the orchestrator sends the event. The span is exported only if the +// dispatch's response is accepted. func (o *Orchestration) RecordSendEvent(action *protos.OrchestratorAction, replaying bool) { if !o.Enabled() || replaying { return } + if o.newSends == nil { + o.newSends = make(map[int32]pendingSpan) + } sent := action.GetSendEvent() - o.sentEvents[action.Id] = o.eventSpan(sent.GetName(), sent.GetInstance().GetInstanceId()) + o.newSends[action.Id] = o.eventSpan(sent.GetName(), sent.GetInstance().GetInstanceId(), time.Now()) } // ConfirmSendEvent queues a send only after the replay engine validates its @@ -642,10 +666,27 @@ func (o *Orchestration) ConfirmSendEvent(eventID int32, replaying bool) { if !o.Enabled() { return } - if span, ok := o.sentEvents[eventID]; ok && !replaying { + if span, ok := o.newSends[eventID]; ok && !replaying { o.pending = append(o.pending, span) } - delete(o.sentEvents, eventID) + delete(o.newSends, eventID) +} + +// sendSpan returns the span for a SendEvent action left in an accepted +// response, or false when an earlier response already exported it. +func (o *Orchestration) sendSpan(action *protos.OrchestratorAction) (pendingSpan, bool) { + if span, ok := o.newSends[action.Id]; ok { + return span, true + } + if _, ok := o.acceptedSends[action.Id]; ok { + return pendingSpan{}, false + } + at := o.responseTime + if at.IsZero() { + at = time.Now() + } + sent := action.GetSendEvent() + return o.eventSpan(sent.GetName(), sent.GetInstance().GetInstanceId(), at), true } // PrepareResponse persists the orchestration span identity on response and @@ -656,9 +697,10 @@ func (o *Orchestration) PrepareResponse(response *protos.OrchestratorResponse) { if response == nil || !o.Enabled() { return } + o.responseTime = time.Now() spanID, start := o.spanID, o.start if startsNewExecution(response) { - spanID, start = RandomSpanID(), time.Now() + spanID, start = RandomSpanID(), o.responseTime } response.OrchestrationTraceContext = &protos.OrchestrationTraceContext{ SpanID: wrapperspb.String(spanID.String()), @@ -718,25 +760,22 @@ func (o *Orchestration) renewFailedChildren(rewind *protos.RewindOrchestrationAc } // Emit exports spans for a response the backend accepted. Call it only after -// the completion succeeds so abandoned work never exports telemetry. +// the completion succeeds so abandoned work never exports telemetry. Only the +// first call exports; later calls do nothing. func (o *Orchestration) Emit(response *protos.OrchestratorResponse) { - if !o.Enabled() { + if !o.Enabled() || o.emitted { return } + o.emitted = true logical := o.SpanContext() for _, action := range response.GetActions() { - if sent := action.GetSendEvent(); sent != nil { - span, ok := o.sentEvents[action.Id] - if !ok { - if _, accepted := o.acceptedSends[action.Id]; accepted { - continue - } - span = o.eventSpan(sent.GetName(), sent.GetInstance().GetInstanceId()) - } + if action.GetSendEvent() == nil { + continue + } + if span, ok := o.sendSpan(action); ok { o.pending = append(o.pending, span) } } - o.sentEvents = nil for _, span := range o.pending { switch { case span.scheduled.IsValid() && span.scheduled.TraceID() != logical.TraceID(): From d51cdfc2905d866e0438332cb0d541b4fae77aee Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Mon, 30 Nov 2026 15:18:22 -0700 Subject: [PATCH 5/5] Clarify deferred event acknowledgement comments Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- client/grpc_worker_tracing_test.go | 7 +++++-- internal/dttrace/dttrace.go | 3 ++- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/client/grpc_worker_tracing_test.go b/client/grpc_worker_tracing_test.go index 26791267..d0d17bcb 100644 --- a/client/grpc_worker_tracing_test.go +++ b/client/grpc_worker_tracing_test.go @@ -310,6 +310,8 @@ func TestWorkerTracingEventSendAckDeferredByTurnBudget(t *testing.T) { require.Len(t, spansNamed(h.spans(), "orchestration_event:approval"), 1) // Deliver the accepted send's acknowledgement behind an unrelated event. + // DTS commits EventSent into history with the accepted response, so it + // never reaches the worker as a new event; this models a backend that does. ack := backend.history[len(backend.history)-1] require.NotNil(t, ack.GetEventSent()) backend.history = backend.history[:len(backend.history)-1] @@ -321,8 +323,9 @@ func TestWorkerTracingEventSendAckDeferredByTurnBudget(t *testing.T) { require.Len(t, spansNamed(h.spans(), "orchestration_event:approval"), 1, "a replayed send must not export again while its acknowledgement is deferred") - // The real backend deduplicates the replayed send; retain only the original - // acknowledgement, still pending delivery, rather than the fake's new one. + // Drop the fake's EventSent for the reissued action and keep only the + // original acknowledgement, still pending delivery. Whether a backend + // performs the reissued send is outside tracing; only one span is exported. backend.history = backend.history[:len(backend.history)-1] backend.dispatch(t, h) backend.dispatch(t, h, helpers.NewEventRaisedEvent("finish", nil)) diff --git a/internal/dttrace/dttrace.go b/internal/dttrace/dttrace.go index 9cf29207..8cbeb0ed 100644 --- a/internal/dttrace/dttrace.go +++ b/internal/dttrace/dttrace.go @@ -625,7 +625,8 @@ func (o *Orchestration) fireTimer(fired *protos.TimerFiredEvent, end time.Time, // - A send issued while replaying that is still in the response exports // unless an EventSent with its ID appears anywhere in the request, which // proves an earlier accepted response already exported it, for example -// when the turn budget defers its acknowledgement. +// when a backend delivers the acknowledgement as a new event and the turn +// budget defers it. DTS delivers EventSent as a past event instead. // - A replayed send whose EventSent is consumed exports nothing. func (o *Orchestration) eventSpan(name, target string, at time.Time) pendingSpan { attrs := taskAttributes(typeEvent, name, "", o.instanceID)