Skip to content
Draft
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
9 changes: 5 additions & 4 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Added benchmarks for analyzer scaling and allocations across orchestrator count and call-graph depth, for `task.TaskRegistry` orchestrator, activity, versioned, snapshot, and concurrent lookups, and for client work-item filter construction, wire conversion, validation, and per-work-item matching.
- Added the preview top-level `exporthistory` package, which exports terminal orchestration histories to Azure Blob Storage as gzip-compressed JSONL. It provides a public client for creating, getting, listing, and per-job create/describe/delete operations; batch and continuous jobs; the `ExportJob` durable entity with `Pending`/`Active`/`Failed`/`Completed` lifecycle transitions; durable checkpoints; terminal-status filters; a per-batch instance limit; per-instance failure collection with implicit job failure when a checkpoint batch fails; delete-and-recreate rules; and typed validation, not-found, invalid-transition, and operation errors carrying stable cross-language error types. Each `Create` mints a nonempty run-generation token and reserves a generation-specific orchestration ID before signaling Run. Only the current generation can mutate job state, though older work may briefly remain in flight. Recreation performs no destructive cleanup and retains previous generations' histories. `Delete` atomically captures the removed generation's ID, and client cleanup targets only that typed result, preserving concurrent recreations even with custom data converters. Read `ExportJobDescription.OrchestratorInstanceID` instead of the removed job-name-only `GetOrchestratorInstanceID` helper. Legacy export-job state and mixed .NET/older Go export workers are not supported. Exported objects are stored as opaque gzip files, named `.jsonl.gz` with content type `application/gzip` and no `Content-Encoding`, so a reader always receives exactly the bytes the object name promises. The system entity, orchestrators, and activities are registered unversioned, and `exporthistory.WithExportHistory()` keeps them routable under strict worker versioning. Destination writes go through a narrow `exporthistory.Store` interface with a production `AzureBlobHistoryStore` implementation that validates containers and prefixes, rejects account URLs carrying userinfo, a query string, or a fragment, and creates each container once. The package is preview: its API, the serialized `ExportJob` state, and its system task names may change without a major version bump, and extended sessions remain unsupported.
- Added `client.WithUnversionedActivityNames` and `task.WithUnversionedActivityNames`, the activity counterparts of the existing unversioned-orchestrator allow-lists. An activity inherits its caller's version, so a system component whose orchestration runs unversioned schedules unversioned activities that a strict-version worker would otherwise refuse to accept and would advertise under its own version.
- Added 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.
- 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 an error that wraps `tracing.ErrUnsupportedTracerProvider` and names the failed check. Each orchestration execution exports one logical `orchestration:<name>` SERVER span, reconstructed with its persisted identity after the backend accepts the execution's completion; replays and individual dispatches emit no spans. Durable Task Scheduler persists and forwards trace context but doesn't emit durable spans, so SDK tracing is the supported way to get them into an application's backend. Telemetry is best effort in both directions: retried or redelivered work can export duplicate spans, and spans can be lost when the backend accepts a completion but its reply is lost. Without the option, the worker only propagates W3C trace context.
- 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.
- 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. A new send whose acknowledgement arrives in the same dispatch is exported with that dispatch. 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()`, so application spans started from it nest under the operation span. The signals and orchestrations an operation starts carry that context, but Durable Task Scheduler doesn't currently forward it. Successful entity operations leave the span status unset. 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.
- Added the [tracing guide](tracing/README.md), with the span catalog, logical orchestration spans, service-side telemetry and duplicate guidance, limitations, and a tracing parity table for the .NET, Python, and JavaScript SDKs. Added an enabled-tracing DTS emulator test, and the `distributedtracing` sample now exports SDK durable spans and application spans to an OTLP collector.

### Removed

Expand Down Expand Up @@ -118,7 +119,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `durabletaskscheduler` identity fields are now trimmed for every authentication mode, and blank `AdditionallyAllowedTenants` entries are dropped. Previously only `ManagedIdentity` trimmed `ClientID`, so padded values reached Azure Identity verbatim.
- `durabletaskscheduler` token scopes now trim whitespace and all trailing slashes from `Options.ResourceID`. Previously only one trailing slash was removed and untrimmed values produced a malformed scope.
- The owned DTS management client now observes both unary and streaming RPC outcomes for channel recreation. Caller cancellation, caller deadlines, and expected instance-wait deadlines are neutral and no longer reset or poison an existing transport-failure streak.
- `TaskHubGrpcClient.ScheduleNewOrchestration` now sends the caller's W3C trace context on `CreateInstanceRequest`, so the service can parent the `create_orchestration` span to it. Previously every orchestration scheduled over gRPC or the Durable Task Scheduler began a disconnected root trace instead of joining the caller's trace.
- `TaskHubGrpcClient.ScheduleNewOrchestration` now sends the caller's W3C trace context on `CreateInstanceRequest`, so the orchestration and its durable work join the caller's trace. Previously every orchestration scheduled over gRPC or the Durable Task Scheduler began a disconnected root trace instead of joining the caller's trace.
- `ContinueAsNew` with `task.WithKeepUnprocessedEvents` no longer drops an external event that arrives in the same work item after the orchestrator returns while a `WaitForSingleEvent` for that name is still pending, such as the loser of a `WhenAny` with a timer. Previously the event completed the unreachable wait and was missing from the next execution. Applications that re-sent such events to work around the loss can now see both copies. A failed or terminated completion no longer carries events forward when `ContinueAsNew` was called earlier in the turn.
- Rejected rewind histories now identify the Go SDK's history-rewrite limitation instead of implying that DTS does not support rewind. The shared unsupported-feature error message is neutral about the source of the limitation; `errors.Is(err, api.ErrFeatureNotSupported)` and rewind safety checks are unchanged.

Expand Down
116 changes: 90 additions & 26 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ Use these features for large systems or for special conditions.
| Data converters | Replace the default JSON serialization of your payloads. |
| Large payloads | Keep large payloads in Azure Blob Storage and send a reference token. |
| Tags and trace context | Attach user tags to actions. Send the caller trace context to DTS. |
| Distributed tracing | Emit OpenTelemetry spans from your process. DTS emits the durable spans. |
| [Distributed tracing](./tracing/README.md) | Opt in to replay-aware client and worker OpenTelemetry spans through your application's provider. DTS doesn't emit durable spans itself. |
| Replay-hazard analysis | Find nondeterministic orchestrator code with `cmd/orchestratorvet`. |
| History export (preview) | Copy terminal orchestration histories to Azure Blob Storage. |

Expand Down Expand Up @@ -530,7 +530,7 @@ Activity contexts expose the activity's own name, version, and task ID in
from native history fields, including after sub-orchestration starts and
ContinueAsNew version changes.

The client sends the sampled caller trace context when it schedules an orchestration or signals an entity. The worker adds separate action trace contexts for the service-owned activity and sub-orchestration spans. The worker does not emit duplicate local Durable Task spans. V2 entity requests do not carry per-operation trace context, so entity-emitted actions cannot inherit it.
The client sends the sampled caller trace context when it schedules an orchestration or signals an entity. By default, the worker propagates action trace contexts without emitting Durable Task spans. DTS persists and forwards trace context but doesn't emit durable spans either. Opt-in tracing adds replay-aware client and worker spans through your application's provider. V2 entity requests do not carry per-operation trace context, so entity execution spans are independent roots.

Use `task.OrchestrationOptions.MaxEventsPerTurn` to limit the new events in one turn. If the worker uses only part of a batch, it sets `numEventsProcessed`. DTS then keeps the remaining events for the next replay. This count obeys the DTS work-item rules. The orchestration control markers do not count against the limit.

Expand All @@ -555,45 +555,109 @@ accounts. See [large payload configuration](./durabletaskscheduler/README.md#lar

## Distributed tracing

The SDK sends the W3C trace context of a sampled caller when it schedules an orchestration. DTS owns the spans for the orchestrations, activities, timers, and sub-orchestrations. Your application code can use standard [OpenTelemetry](https://opentelemetry.io/) instrumentation. Use it for caller spans, custom activity spans, and outbound dependencies.

When DTS supplies an activity trace parent, the SDK restores it on
`ActivityContext.Context()` without creating another durable-operation span.
Application instrumentation can therefore attach outbound requests to the
service-owned trace.

This example sends the traces of your process to an [OpenTelemetry Collector](https://opentelemetry.io/docs/collector/) over OTLP/HTTP. Configure the DTS telemetry separately for the service-owned spans.
Tracing is opt-in. Without tracing options, the SDK propagates W3C trace context
but emits no spans. DTS persists and forwards that context, but it doesn't emit
durable orchestration, activity, or timer spans or export spans to your
backend. To see durable spans next to your application telemetry, enable SDK
tracing with an OpenTelemetry provider that your application owns:

```go
func ConfigureOTLPTracing(ctx context.Context) (*trace.TracerProvider, error) {
exp, err := otlptracehttp.New(
ctx,
func ConfigureOTLPTracing(ctx context.Context) (*sdktrace.TracerProvider, error) {
exp, err := otlptracehttp.New(ctx,
otlptracehttp.WithEndpoint("localhost:4318"),
otlptracehttp.WithInsecure(),
)
if err != nil {
return nil, err
}
res, err := resource.New(ctx,
resource.WithAttributes(semconv.ServiceName("sample-app")),
resource.WithFromEnv(),
resource.WithTelemetrySDK(),
)
if err != nil {
return nil, err
}

// NOTE: Do not use the simple span processor in production.
// Use the batch span processor in production.
processor := trace.NewSimpleSpanProcessor(exp)
// processor := trace.NewBatchSpanProcessor(exp)

tp := trace.NewTracerProvider(
trace.WithSpanProcessor(processor),
trace.WithSampler(trace.AlwaysSample()),
trace.WithResource(resource.NewWithAttributes(
"durabletask.io",
attribute.KeyValue{Key: "service.name", Value: attribute.StringValue("sample-app")},
)),
tp := sdktrace.NewTracerProvider(
sdktrace.WithBatcher(exp),
tracing.WithIDGenerator(nil),
tracing.WithSampler(sdktrace.ParentBased(sdktrace.AlwaysSample())),
sdktrace.WithResource(res),
)
otel.SetTracerProvider(tp)
return tp, nil
}
```

The [distributed tracing sample](./samples/distributedtracing) starts a caller span before `ScheduleNewOrchestration`. DTS then joins its service-side spans to the same trace. The sample also instruments an HTTP request from an activity.
Pass the provider to each surface you want to trace, and shut down in order:
the worker, then the client, then the provider.

```go
func run(ctx context.Context) (err error) {
tp, err := ConfigureOTLPTracing(ctx)
if err != nil {
return err
}
defer func() {
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
err = errors.Join(err, tp.Shutdown(shutdownCtx))
}()

worker, err := durabletaskscheduler.NewWorker(options, registry, logger,
durabletaskclient.WithWorkerTracerProvider(tp))
if err != nil {
return err
}
managementClient, err := durabletaskscheduler.NewClient(ctx, options, logger,
durabletaskclient.WithTracerProvider(tp))
if err != nil {
return err
}
defer func() { err = errors.Join(err, managementClient.Close()) }()
if err := worker.Start(ctx); err != nil {
return err
}
defer func() {
shutdownCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
err = errors.Join(err, worker.Shutdown(shutdownCtx))
}()

// Schedule and wait for orchestrations.
return nil
}
```

Deferred calls run in reverse order, so the worker shuts down first, the client
closes next, and the provider flushes last. The worker provider must use
**both** tracing wrappers. They let the worker reconstruct completed spans with
persisted identities and consistent sampling decisions across replay. The worker
rejects a provider that is missing either wrapper with an error that wraps
`tracing.ErrUnsupportedTracerProvider`.

The trace tree is caller -> create orchestration PRODUCER -> orchestration
SERVER -> activity or sub-orchestration CLIENT -> execution SERVER, plus timer
INTERNAL and event-send PRODUCER spans. Each orchestration execution has one
logical span that's exported when the execution finishes, not one span per
replay. Activity spans are active in `ActivityContext.Context()`, so your HTTP
and database spans nest under them. Telemetry is best effort in both
directions: retried or redelivered work can export duplicate spans, and spans
can be lost if a completion is accepted but its reply is lost.

Entity spans follow DurableTask.Core names and kinds. V2 entity execution spans
are independent roots because entity operations carry no parent context. Event
receipt emits no CONSUMER span and doesn't join the sender's trace. If another
component also emits durable spans for the same work into your backend, enable
only one source.

The [tracing guide](./tracing/README.md) has the full span catalog, the
difference between logical and execution-turn spans, the limitations, and a
parity table for the .NET, Python, and JavaScript SDKs. The
[distributed tracing sample](./samples/distributedtracing) exports durable and
application HTTP spans to a real OTLP collector and verifies that the collector
received them.

## History export (preview)

Expand Down
2 changes: 1 addition & 1 deletion samples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ operation is not evidence that a feature works end to end.
| [observability](observability) | Tags/context, replay-safe logs and metric hooks | None |
| [worker](worker) | Concurrency, graceful drain, restart/recovery and connection ownership | None |
| [authentication](authentication) | Azure connection-string and programmatic identity authentication | Azure DTS and an authorized identity |
| [distributedtracing](distributedtracing) | Application spans, caller propagation and actual OTLP receipt | OTLP collector and readable trace capture |
| [distributedtracing](distributedtracing) | Opt-in SDK durable spans, application spans, caller propagation and actual OTLP receipt | OTLP collector and readable trace capture |
| [exporthistory](exporthistory) | Export jobs and downloaded JSON/JSONL objects | Blob storage and an explicitly isolated Go-only hub |
| [replayanalysis](replayanalysis) | Analyzer diagnostics and safe runnable counterparts | Local `cmd/orchestratorvet` sources |
| [serviceoperations](serviceoperations) | Hub-wide filtered purge and empty-entity maintenance | Deletes data; read the sample's warning |
Expand Down
Loading
Loading