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 e829f603..d0d17bcb 100644 --- a/client/grpc_worker_tracing_test.go +++ b/client/grpc_worker_tracing_test.go @@ -132,12 +132,353 @@ 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: + 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 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) + + 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) + 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) + // 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()) +} + +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) { + 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. + // 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] + 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") + + // 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)) + 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) { + 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 := helpers.NewSendEventEvent(0, "receiver", "approval", wrapperspb.String("")) + 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 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 test.waitForReady { + 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 test.suspend { + backend.dispatch(t, h, helpers.NewSuspendOrchestrationEvent("")) + } + backend.dispatch(t, h, helpers.NewEventRaisedEvent("next", nil), helpers.NewEventRaisedEvent("next", nil)) + want := 0 + if test.release == nil { + want = 1 + } + require.Len(t, spansNamed(h.spans(), "orchestration_event:forwarded"), want) + backend.dispatch(t, h) + 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)) + require.Len(t, spansNamed(h.spans(), "orchestration_event:forwarded"), 2) + }) + } +} + +func TestWorkerTracingEventsDisabledOrMissingContext(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) + })) + h := newTracingHarness(t, registry, test.enabled) + response := newFakeOrchestrationBackend("sender", helpers.NewExecutionStartedEvent( + "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()) + 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..8cbeb0ed 100644 --- a/internal/dttrace/dttrace.go +++ b/internal/dttrace/dttrace.go @@ -307,8 +307,12 @@ 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 - pending []pendingSpan + timers map[int32]createdTimer + newSends map[int32]pendingSpan + acceptedSends map[int32]struct{} + pending []pendingSpan + responseTime time.Time + emitted bool logicalOnce sync.Once logical trace.SpanContext @@ -333,6 +337,14 @@ func (t *Tracer) StartOrchestration( } 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 { o.started = true o.name = started.GetName() @@ -601,6 +613,83 @@ func (o *Orchestration) fireTimer(fired *protos.TimerFiredEvent, end time.Time, }) } +// 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 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) + 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: at, + end: at, + attrs: attrs, + } +} + +// 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.newSends[action.Id] = o.eventSpan(sent.GetName(), sent.GetInstance().GetInstanceId(), time.Now()) +} + +// 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.newSends[eventID]; ok && !replaying { + o.pending = append(o.pending, span) + } + 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 // assigns scheduling span IDs to new activity and sub-orchestration actions. // Continue-as-new and rewind responses carry a fresh identity so the next @@ -609,9 +698,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()), @@ -671,12 +761,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 action.GetSendEvent() == nil { + continue + } + if span, ok := o.sendSpan(action); ok { + o.pending = append(o.pending, span) + } + } 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