Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:<name>[@(<version>)]` for `ScheduleNewOrchestration`, parenting the new orchestration, and `orchestration_event:<name>` for `RaiseEvent`. `durabletaskscheduler.NewClient` accepts trailing `client.TaskHubGrpcClientOption` values.
- With worker tracing enabled, `OrchestrationContext.SendEvent` emits an `orchestration_event:<name>` 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:<name>:<operation>` 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

Expand Down
68 changes: 65 additions & 3 deletions client/client_grpc_tracing_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package client
import (
"context"
"errors"
"fmt"
"testing"

"github.com/stretchr/testify/require"
Expand All @@ -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(
Expand Down Expand Up @@ -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())
}
37 changes: 20 additions & 17 deletions client/grpc_worker_processor.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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())
Expand All @@ -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(
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -791,19 +792,21 @@ 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
})
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) {
Expand Down
Loading