Expand description
§Durable Workflow Rust SDK
durable-workflow is the first-party Rust client and worker SDK for
Durable Workflow. Rust applications can start
and inspect workflows, run workflow and activity handlers, and exchange typed
Avro values with PHP, Python, and Rust workers through one durable runtime.
Use the SDK with a self-hosted Durable Workflow Server or a managed Durable Workflow Cloud namespace. Your workers remain ordinary Rust processes and scale independently from the runtime.
§Install
Rust 1.86 or newer is required.
cargo add durable-workflowApplications using Tokio entry points should also enable the Tokio features they need:
cargo add tokio --features macros,rt-multi-thread§Run the example
examples/hello_world.rs is a complete typed
workflow and activity example. It starts a workflow, runs two activities,
demonstrates retry and failure handling, waits for completion, and prints the
result.
Start a bootstrapped self-hosted Server, then run the example from this repository:
DURABLE_WORKFLOW_SERVER_URL=http://127.0.0.1:8080 \
DURABLE_WORKFLOW_TOKEN=dev-token \
cargo run --example hello_worldPass the Server origin without a trailing /api. TASK_QUEUE changes the
default rust-workers queue, and GREETING_NAME changes the example input.
For a provisioned Cloud namespace, use the exact runtime URL and the separate client and worker credentials shown in Cloud:
DURABLE_WORKFLOW_RUNTIME_URL=https://cloud.durable-workflow.com/api/runtime/v1/namespaces/your-namespace-id \
DURABLE_WORKFLOW_RUNTIME_NAMESPACE=your.namespace \
DURABLE_WORKFLOW_CLIENT_TOKEN=your-client-token \
DURABLE_WORKFLOW_WORKER_TOKEN=your-worker-token \
cargo run --example hello_worldThe namespace runtime URL is already complete. Do not append another /api.
§Migrate from Rust SDK 3
Nexus calls add Error::NexusOperationFailed and
CancellationCallKind::ServiceOperation. Both enums are now non_exhaustive.
Include a fallback arm when matching either enum outside this crate so future
error or cancellation kinds can be handled without another exhaustive-match
migration. Handle a Nexus failure at its original durable call; a committed
admission is separate from a synchronous completion.
WorkflowTask, ActivityTask and QueryTask retain optional, untrusted
observability metadata. ActivityTask also exposes optional workflow, run and
activity execution identities supplied by the runtime. When constructing task
structs directly, initialize the new optional fields to None. Receiving these
fields does not enable tracing, authorize work or invent missing correlation.
Task structs remain directly constructible. Future additions to their public
fields require another major release; extensible metadata inside the existing
optional JSON fields does not require new task literal fields.
Existing workflow histories are unchanged. Preserve the workflow’s recorded command sequence and verify representative histories before deployment. Nexus authoring requires explicit worker opt-in and an installed Server capability; ordinary worker registration does not enable it.
§Core API
Clientstarts, signals, queries, updates, cancels, terminates, describes, and awaits workflow executions.Workerregisters workflow, activity, query and update handlers, declares workflow signals, and long-polls task queues.WorkflowContextprovides durable activities, timers, conditions, child workflows, side effects, version markers, parallel operations, selection, sagas, message streams, memo, search attributes, and continue-as-new.- Typed registration and result helpers preserve Serde request and result types over the fixed Avro Value protocol.
- Activity options cover retries, start-to-close, schedule-to-start, schedule-to-close, heartbeat timeouts, cancellation, and heartbeats.
§Signal and update request IDs
Every signal and update sends a request_id body field: the key you pass to a
*_with_request_id method or update_workflow, or one generated per call. The
receipt carries it. The SDK never resends a signal or update by itself, so keep
the key (Client::generate_signal_request_id() gives you one up front) to retry
after a lost response.
On a Server that advertises capabilities.command_request_keys in
Client::cluster_info() (native 3.9.0 and later), the key is a durable command
key on the workflow instance. A retry with the same name, arguments and run
target returns the original receipt. The same key with a different name,
arguments or run target is refused with HTTP 409 request_id_conflict, and
nothing is written. Detect it with Error::request_id_conflict(), which names
the differing parts (name, arguments or target_or_arguments), the
retained_command_id and the key you sent. Don’t retry it unchanged: send the
original input to recover the receipt, or use a new key.
match client
.signal_workflow_with_request_id("order-1", "approve", ["Grace"], "approve-order-1")
.await
{
Err(error) if error.is_request_id_conflict() => {
let conflict = error.request_id_conflict().expect("conflict details");
eprintln!("{} is already {:?}", conflict.request_id, conflict.retained_command_id);
}
other => {
other?;
}
}Older Servers (PHP Server 2.x and native up to 3.8) don’t compare input under a key: a repeated signal key records a second signal, and an update retried with changed arguments returns the original receipt.
§Pending updates and reading an outcome later
update_workflow waits for the update to complete. If the Server’s wait ends
first, it answers HTTP 202 with no result, and the SDK returns
Error::UpdateStillPending with the update_id, request_id, current
run_id and full receipt. A handler that returned null is still Ok(Null).
On a Server that advertises capabilities.update_outcome_reads in
Client::cluster_info() (native 3.6.0 and later),
Client::update_outcome(workflow_id, update_id, wait_timeout_seconds) reads
the same update by its id without submitting it again. It waits for the
outcome and returns the decoded result, or Error::UpdateStillPending again
while the update is still running. A failed update is Error::Http with status
422, and an unknown or pruned update id is 404 update_not_found
(Error::is_update_not_found()), which does not prove the update was never
admitted. update_outcome_receipt returns the raw receipt and can answer at
once with UpdateWaitStage::Accepted. Workflow and update ids must each be one
path segment (not empty, . or ..), and an answer that is not a receipt for
the requested update is Error::UnrecognizedUpdateOutcome, never a result.
On any other Server, update_outcome returns
Error::UpdateOutcomeReadsUnavailable before reading anything; the SDK never
resubmits an update in place of reading it. There, call update_workflow again
with the same request_id to keep waiting.
use durable_workflow::Error;
let result = match client
.update_workflow("order-1", "rename", ["Grace"], Some("rename-order-1"))
.await
{
Err(Error::UpdateStillPending(pending)) => {
let update_id = pending.update_id.expect("Server receipt names the update");
client.update_outcome("order-1", &update_id, Some(30)).await?
}
other => other?,
};§Condition predicate identities
wait_condition! derives the recorded predicate identity from the call site’s
module path and the predicate’s Rust tokens. Moving or renaming the workflow
module changes the identity even when the predicate behaves the same. Rust also
allows stringify! output to change between compiler versions.
The SDK’s minimum-supported and stable Rust CI jobs pin representative macro
fingerprints to detect that change before a toolchain upgrade is accepted.
Keep the module path and predicate identity stable while affected waits are
open, or drain those runs before moving the workflow. For workflows that need
identities independent of module moves, use
ConditionWaitOptions::new("approval", "approval-rule-v1") from the start.
An explicit identity must still change when predicate behavior changes.
Switching an existing macro fingerprint to a new label does not migrate its
recorded history; preserve the original fingerprint for those runs or drain
them first.
§Private certificate authorities
The SDK trusts bundled Mozilla public roots by default. It does not load the
operating system trust store or SSL_CERT_FILE. For a self-hosted Server or a
proxy using a private certificate authority, add its PEM root certificates:
use durable_workflow::Client;
let client = Client::builder("https://workflow.internal")
.additional_root_certificates_pem(std::fs::read("company-ca.pem")?)?
.build()?;The bundle can contain multiple certificates, and repeated calls add more roots. Bundled public roots remain enabled. The same configured HTTP client handles control requests, worker polling and external payload transfers. Certificate-chain and hostname verification remain enabled. A private CA does not make a certificate for the wrong hostname valid. Client certificates (mTLS) are not configured by this option.
If a certificate cannot be verified at all, .danger_accept_invalid_certs(true)
turns off certificate and hostname verification for every request the client
makes. It defaults to false. With it on, anyone on the network path can read
and change traffic, including bearer tokens, so prefer a private CA root.
§Raw Server requests
Typed Client methods are the API for applications. Tools that must reach
every Server route and report the Server’s response unchanged, such as the
dw CLI, can send raw requests over the same configured transport:
use durable_workflow::{Client, RawRequest};
let response = client
.control_plane_request(
RawRequest::get(["workflows", "order/42", "runs"]).query("page_size", "50"),
)
.await?;
if let Some(refusal) = response.refusal() {
eprintln!("refused: {:?}", refusal.reason);
}
let body = response.error_for_status()?.json()?;The SDK percent-encodes each path segment, keeps any path prefix in the base
URL, and sends the namespace, the plane’s token and both version headers.
Every HTTP status comes back as a RawResponse with its exact body bytes and
headers. A raw request makes one attempt and never rewrites its body.
worker_plane_request also requires 2xx responses to echo a same-major,
equal-or-newer-minor worker protocol version.
§Worker concurrency
Worker::max_concurrent_workflow_tasks(...) and
Worker::max_concurrent_activity_tasks(...) each default to 10. run and
run_until keep up to those limits active independently for workflows and
activities. Each family has one long poll. After a claim is validated and
hydrated, the poller can fill another free slot while earlier tasks execute or
report completion. Use a value of 1 for serial execution within a task family.
Clones share their configured capacity, including concurrent run_once calls.
Heartbeats report unused slots from actual claimed tasks, including input and history loading, callback execution and settlement. An empty long poll keeps its capacity available. Success, failure, refusal and cancellation release the local slot. Inline local activities occupy their workflow-task slot and bypass the remote activity pool. Queries retain their separate polling lane.
Handlers run as async futures on Tokio and must yield. Use
tokio::task::spawn_blocking or a separate process for blocking work, with its own
cancellation boundary. A concurrency setting does not provide CPU isolation or
make blocking code cancellable.
§Query execution authority
On a runtime advertising query_task_authority with worker protocol 1.20,
Worker captures the original query claim before loading external inputs. It
checks ownership without renewing the lease during loading and execution, before
calling the handler, and before submitting its outcome. The original caller
deadline and lease bound the entire operation. Expiry, shutdown or an unavailable
observation drops the work without sending a completion or failure for it.
Use Worker::require_query_task_authority(true) to refuse registration unless
worker-authenticated discovery advertises this support. Without this requirement,
older runtimes and explicit protocol 1.19 keep compatibility: disclosed original
timing supplies a local bound, while deliveries without timing retain legacy
behavior. This path cannot observe live revocation and never calls the 1.20
query-status endpoint.
Async handlers must yield to Tokio to be cancelled promptly. Synchronous or
CPU-bound callbacks cannot be interrupted while they block, but their late result
is fenced before submission. Query handlers should avoid side effects. Direct
Client completion and failure methods remain available for inspecting an
original committed receipt.
§Handler registration
Register each workflow and activity wire name once per Worker. Named query and update handlers are also scoped to their workflow type. Dynamic, typed, Avro and replayed adapters share these namespaces. Repeating a registration, including the same callback, is an error. Different Workers or handler kinds may reuse a name, and queries or updates on different workflow types may reuse a name.
Registration methods keep their existing signatures. A duplicate preserves the
first handler and invalidates that Worker. Call worker.validate_registration()?
after configuring it for a local check. register, run, run_until and
run_once also reject it before contacting Server with Error::WorkerLoop
and a duplicate_registration diagnostic. Local validation returns the typed
DuplicateRegistrationError, exposing the handler kind, wire name, optional
workflow scope, and both source locations and authoring adapters. It converts
into the existing worker-error variant when used with ?, preserving exhaustive
matches on the SDK’s existing Error enum.
Construct a new Worker to correct an invalid configuration. Choose the desired
handler before registration instead of relying on replacement order.
After registering a workflow, declare every signal name it reads through
wait_signal or signals before starting the worker:
worker.declare_workflow_signals("orders", &["finish", "changed"])?;Server records those names and positional argument contracts when starting a run. Changing worker declarations does not change existing runs.
The SDK writes Avro payloads only. The fixed recursive Value schema preserves nulls, booleans, signed 64-bit integers, finite doubles, bytes, UTF-8 strings, lists, and string-keyed maps across official SDKs without customer-managed schemas or a registry.
Large payloads are uploaded automatically when the namespace advertises runtime
storage. The SDK follows its inline threshold and upload limit, including batches
that exceed the ordinary request limit. Uploads and downloads use the same
runtime URL, namespace, and credential role, with size and SHA-256 verification.
Client::builder(...).max_external_payload_bytes(...) limits unique downloaded
bytes per response (64 MiB by default). Provider credentials are not needed;
payload fetches never follow redirects.
Workers confirm and renew the exact workflow task claim while loading external inputs and paged history, then confirm it again before replay. Loading stops on lost authority or Worker shutdown without executing workflow code. Pending cooperative cancellation retains its original identity and cleanup deadline.
External activity inputs retain their original lease and execution deadline bounds while loading. Without the optional lease-renewal capability, protocol 1.20 observes the exact activity attempt before, during and after the transfer, and immediately before callback entry. Unconfirmed authority stops loading without invoking the callback. These observations do not renew the lease or record application heartbeats. Explicit protocol 1.19 uses the original local lease/deadline bounds and completion fencing; it cannot observe live revocation or ownership. Live authority supervision requires 1.20. Shutdown and dropping a poll stop its loading and observation together.
The optional Client::renew_activity_task_lease request is available only when
actual runtime discovery advertises activity_lease_renewal=true. Pass the
original task ID, attempt ID, lease owner and a positive request window of at
most five seconds. Discovery and renewal share that window and use worker
credentials. This request records no application progress. Validate the full
original identity, granted lease and business deadlines before using its reply
to extend local authority. Direct Client users manage their own renewal lifecycle.
When registration, cluster discovery or the actual poll advertises that boolean
capability, Worker confirms and automatically maintains the original activity
claim throughout input loading, the yielding callback and terminal publication.
Missing or changed task, attempt, holder or run identity prevents callback entry.
Lost authority, exhausted original timeouts or managed shutdown drop the callback
future and fence retained callback Clients against late completion, failure,
heartbeat or result upload. Retryable renewal errors grant no additional time.
Older runtimes keep their existing path.
Runtime lease pings do not record application progress or satisfy a configured
heartbeat timeout. Continue calling ctx.heartbeat(...) for real progress; only
acknowledged same-attempt progress advances that recorded interval. Session-bound
activities also require an acknowledged same-holder session grant and retain
their original absolute TTL. The maintainer starts before callback entry, so
a spare executor thread can keep it running if a callback temporarily blocks.
Callbacks must still yield to Tokio: maintenance cannot progress if every
executor thread is blocked. Use tokio::task::spawn_blocking for blocking I/O
and CPU work, and give that work its own cancellation or process boundary.
Dropping an async callback cannot stop detached threads or reverse external
side effects.
Completion still uses the runtime’s attempt fence. Server 2.6.1 refuses superseded attempts but can accept an expired, unreclaimed attempt; see Workflow #769.
The Client’s default 60-second HTTP timeout includes connection and the complete
response body. Client::builder(...).timeout(Duration::from_secs(120)) selects a
larger total budget before starting a Worker. Claimed input and history loading
share that budget across all pages. Lease renewals do not restart it. Low-level
cooperative polls retain their long-poll timeout plus five seconds, and explicit
canonical cancellation refreshes retain their five-second budget.
§Testing without a Server
testing::WorkflowEnvironment runs registered workflows and activities in the
current process. Use from_worker(worker) to reuse your application’s complete
registration set, or register test callbacks directly. worker_mut() exposes
the existing typed and replayed-state registration APIs.
use durable_workflow::{json, testing::WorkflowEnvironment};
let mut env = WorkflowEnvironment::new()?;
env.register_activity("greet", |_, args| async move {
Ok(json!(format!("Hello, {}!", args[0].as_str().unwrap())))
});
env.register_workflow("hello", |ctx, args| async move {
ctx.activity("greet", args).await
});
assert_eq!(env.run_activity("greet", "Ada").await?, json!("Hello, Ada!"));
env.mock_activity("greet", |_, _| async { Ok(json!("mock greeting")) });
assert_eq!(env.run_workflow("hello", "Ada").await?, json!("mock greeting"));Workflow execution uses the worker’s cold-replay engine, codec and activity
adapters. Real or mocked remote/local activity failures become the same typed
Error::ActivityFailed inside workflow code, including exception type, attempt
number and non-retryable marker. Retry policies apply before workflow code
receives a terminal failure. Timer and retry delays are skipped; activity
callbacks still execute normally and must yield. An uncaught workflow error is
returned with its original Rust error variant. Direct run_activity executes
one attempt. Heartbeats are captured locally and closed when the attempt ends.
The *_avro_value methods preserve fixed-Avro bytes, integers and other values
that have no lossless JSON representation.
The executor handles activities, local activities, timers, side effects,
version markers, memo/search-attribute upserts and ordered parallel commands.
Parallel callbacks run in command order. Activity timeout simulation, new select
races, signals, child workflows, services, sessions, continue-as-new and cancellation require
integration tests; unsupported commands return Error::Testing explicitly.
This environment does not simulate queues, leases or deployment behavior.
max_steps(n) bounds durable turns, commands and attempts (default 10,000);
use tokio::time::timeout to bound asynchronous callbacks as well.
§Replay before deploying changed workflow code
Load a self-contained JSON bundle from dw workflow:history-export or
Client::export_workflow_history(workflow_id, run_id).await?, register the
candidate workflow code, then replay without a Server:
use durable_workflow::testing::{WorkflowEnvironment, WorkflowHistory};
let export = serde_json::from_slice(&std::fs::read("workflow-history.json")?)?;
let history = WorkflowHistory::from_export(export)?;
let report = env.replay(&history)?;
assert!(report.completed); // A running snapshot can remain durably pending.For the raw history API, combine all pages and call
WorkflowHistory::from_history("hello", original_input, response)?.
Set .task_queue("original-queue") if that context is absent. Exports must
include original input and required recorded results. Redacted/pruned payloads,
unresolved external references and remaining page tokens are refused. The SDK
export helper resolves payload references while downloading; replay itself
never contacts a Server. env.last_history() captures a new in-process run and
can be exported for regression tests, including after an execution error.
Replay uses the worker’s decoding, side-effect, version-marker and persisted
select-resolution paths. Activity callbacks do not run. Reordered or changed
commands return Error::NonDeterministicReplay(ReplayFailure) with sequence,
expected and actual. New commands beyond the snapshot also fail; use a
fresh in-process run to test new logic. A report contains the reconstructed
terminal commands or an empty decision for a recorded pending operation.
Keep workflow command order deterministic:
| Pattern | Durable replacement |
|---|---|
Iterating a HashMap while scheduling | Sort keys first or use a BTreeMap |
| Reading the system clock, randomness or a UUID | ctx.side_effect(...) for a recorded snapshot, or an activity |
tokio::time::sleep, std::thread::sleep | ctx.sleep(...) / ctx.start_timer(...) |
tokio::select!, racing ordinary futures | ctx.select(...) / ctx.select_keyed(...) |
| Untracked concurrent durable calls | SDK ctx.parallel(...) with stable input ordering |
| Network, filesystem or other external I/O | A registered activity |
| Changing existing command order on deployment | A stable ctx.get_version(...) branch, checked against recorded history |
See the runnable workflow_testing example and
workflow_testing tests.
§Workflow logging
Use ctx.logger() for observations written from workflow code. It sends events
to the application’s existing tracing subscriber with the target
durable_workflow::workflow and SDK-bound namespace, workflow_instance_id
and workflow_run_id fields. No global subscriber is installed.
let mut worker = Worker::new(client, "orders");
worker.register_workflow("order", |ctx, _input| async move {
ctx.logger().info("processing order");
let result = ctx.activity("charge", json!([])).await?;
ctx.logger().info("charge completed");
Ok(result)
});Ordinary tracing calls execute again when a worker reconstructs a workflow.
The workflow logger suppresses the committed prefix, query/offline replay and
completed histories, including after a cold worker replacement. It emits when
execution reaches new code beyond that prefix. ctx.replay_state() exposes
that live boundary as WorkflowReplayState; a retained context outside its
invocation is Unavailable. Use the logger for observations and keep durable
command order independent of the observation state.
This is process logging. A log from an uncommitted task attempt can repeat if that attempt crashes or retries. It is not an exactly-once outbox. Keep host handlers bounded and nonblocking, for example with an application-owned logging queue, so they do not stall the worker. Unwinding subscriber panics are isolated from the workflow result; aborting processes and blocking handlers remain the application’s responsibility.
§Inspect a run’s activities
Use Client::get_run_activities(workflow_id, run_id) next to the selected run’s
description to inspect its activities, attempts and last heartbeat:
let description = client.describe_workflow_run("workflow-id", "run-id").await?;
let view = client.get_run_activities("workflow-id", "run-id").await?;
println!("run status: {}", description.status.as_deref().unwrap_or("unavailable"));
for activity in view.activities {
println!(
"activity {:?}: status {:?}, attempts {:?}, last heartbeat {:?}",
activity.activity_type,
activity.status,
activity.attempt_count,
activity.last_heartbeat_at,
);
}The result belongs to that exact run in the client’s namespace. Optional
metadata stays None when unavailable; zero attempts and false flags remain
explicit values. An omitted attempt list is distinct from an empty list.
Unsupported, diagnostic and future status strings are preserved, and unknown
response fields remain in each model’s raw map. Heartbeat progress retains its
structured JSON types. Attempt flags describe the received snapshot and do not
grant worker authority. This read does not fetch or decode workflow payloads.
A handle with a selected run also offers WorkflowHandle::get_activities();
it refuses a missing run ID instead of following the instance’s current run.
§Workflow lists and complete run history
Client::list_workflows(WorkflowListOptions) and
Client::get_workflow_history(workflow_id, run_id, WorkflowHistoryOptions)
each return one page. Inspect next_page_token to resume manually, or use
the lazy iterators for complete reads. These methods wrap the published Server
APIs and preserve their filters, validation and namespace scope; they add no
Server query fields or grammar.
For example, find an open run by a registered keyword search attribute:
use durable_workflow::WorkflowListOptions;
let mut matches = client.iter_workflows(
WorkflowListOptions::new()
.workflow_type("payments")
.status("running")
.query("OrderRef = 'order-42'")
.page_size(2),
);
match (matches.next().await?, matches.next().await?) {
(Some(run), None) => println!("open run: {} / {}", run.workflow_id, run.run_id),
(None, _) => println!("no open run"),
_ => println!("multiple open runs; refine the query"),
}The Server’s status=running filter selects the active status bucket,
including runs whose raw status is pending or waiting. WorkflowSummary
preserves status, status_bucket, is_terminal, search attributes and unknown
metadata in raw. Search attributes do not impose a uniqueness constraint.
Create the client with the intended namespace before constructing the iterator;
the same namespace and filters are retained across every opaque token.
Read an entire selected run without loading every page at once:
use durable_workflow::WorkflowHistoryOptions;
let mut events = client.iter_workflow_history(
"payment-42", "selected-run-id", WorkflowHistoryOptions::new().page_size(100),
);
while let Some(event) = events.next().await? {
println!("{}", event.event_type);
}Similarly, iter_workflows(options) yields each WorkflowSummary through
next().await. Both iterators also provide into_stream() for standard
futures_util::TryStreamExt consumers; pin the returned stream before polling.
Constructing an iterator performs no I/O. It fetches only when
the current page is exhausted, holds one page, and ends on a null or empty
continuation token. Empty pages with a continuation are followed. Repeated or
cyclic tokens produce Error::Pagination using bounded token state. A page
failure is returned with its original typed error; that iterator then ends.
Handle the error rather than treating a partial read as a complete result.
Iterating history keeps the original workflow/run identity and does not follow
continue-as-new into another run. It enumerates available history rather than
subscribing indefinitely. History payloads retain their wire envelopes and
lossless event metadata. For offline replay, use the existing
Client::export_workflow_history and testing::WorkflowHistory::from_export
instead of passing a partial page to the replay API.
Published Server 2.11 defaults to 50 list rows (maximum 200) and 100 history
events (maximum 1,000) per page. Page sizes are sent unchanged for Server
validation. Stop the iterator when you have enough results, choose an appropriate
page size, and bound work with your application’s timeout. List pagination
inherits the Server’s ordering/consistency contract; it does not add snapshot
isolation while runs change concurrently. See the read-only
workflow_pagination example.
§Examples
§Activity retry policies
ActivityRetryPolicy::new(max_attempts).backoff_intervals(...) preserves the
complete explicit list, including entries that the attempt budget will not use.
One attempt uses no retry delay. The server repeats the last entry when further
retries are allowed, while the attempt budget still limits execution. Replay
compares the complete stored list and the other known policy fields exactly;
changing an unused entry is also a policy change. The default remains one
attempt with an empty backoff list.
Activity handlers can use ctx.activity_execution_id() as the logical Server
activity key, stable across retries, and read its workflow_id() and run_id().
These immutable optional accessors preserve the original claim. An older Server
can omit an ID; use an application business key in that case. Task IDs and attempt
IDs identify individual attempts and are not substitutes for a logical key.
worker.register_activity("charge", |ctx, _| async move {
let key = ctx.activity_execution_id();
// Pass the available key (or an explicit business key) to your payment API.
Ok(json!({"activity_key": key, "workflow": ctx.workflow_id(), "run": ctx.run_id()}))
});Worker-session activities expose the same received IDs. Inline local activities expose their parent workflow/run IDs when present, but have no Server activity execution ID before their command is recorded. Server-free activity/workflow tests report no Server IDs. Use application business keys for those paths rather than inferring a key from a task or attempt ID.
In a service activity, ctx.retry_info() exposes the original attempt number
and immutable Server retry snapshot. Use the configured budget for a final-attempt
fallback:
worker.register_activity("charge", |ctx, _| async move {
if ctx.retry_info().is_last_configured_attempt() == Some(true) {
// Select a final-attempt fallback or record an application alert.
}
Ok(json!({"attempt": ctx.retry_info().attempt_number()}))
});ActivityAttemptLimit::Bounded(n) includes the first attempt. Unlimited requires
an explicit max_attempts: null in the received policy object. Omitted policies,
root null and missing or invalid limits are Unknown; policy() retains their
original JSON, including unknown fields. is_last_configured_attempt() returns
None for unknown metadata, Some(false) for unlimited, and checks whether the
original attempt has reached the bounded limit. A remaining budget does not
promise a retry: non-retryable failures, cancellation, workflow closure and elapsed
deadlines can end execution earlier. Local activities and direct run_activity
tests have no received Server snapshot and report unknown policy; fresh
run_workflow tests expose the modeled snapshot recorded in their history.
Activity handlers can return an application-defined failure type with
ActivityError. The same type, message and retry marker are reported for remote
and local activities, including cooperative workers:
use durable_workflow::{ActivityError, Worker};
worker.register_activity("charge", |_, _| async {
Err(ActivityError::new("PaymentDeclined", "card declined")
.non_retryable(true)
.into())
});ActivityError::new(...) is retryable by default. An activity’s
ActivityRetryPolicy::non_retryable_error_types(["PaymentDeclined"]) also stops
retries when the returned type matches exactly. Setting .non_retryable(true)
stops retries regardless of that list. Workflow code receives the terminal
Error::ActivityFailed with its exception_type, non_retryable and attempt
number. Application types must contain 1 to 255 bytes and cannot be blank;
invalid types produce a non-retryable ActivityFailureMetadataError.
Other errors retain the generic RustActivityFailure type for remote execution
and RustActivityError for local execution. Use ActivityError when a retry
policy must match the same application failure in both modes.
§Failure report limits
Outgoing failure reports use a 64 KiB message budget, reserving 2 KiB for
published Server timeline prefixes, so message content including its marker is
at most 62 KiB. They bound stacks to 128 KiB and
combined serialized details, diagnostics and optional metadata to 64 KiB. The
complete encoded request is at most 1 MiB, including JSON escaping, markers,
identity and every other field, or less when a lower transport limit is known.
Oversized messages include a visible truncation marker. Existing
diagnostics.sdk_failure_truncation records original byte sizes and omitted
fields. Workflow/query-task schemas without diagnostics and plain command
messages carry original sizes and omissions in the message marker instead.
Small reports keep their original content. Incoming history is never truncated.
Client::fail_activity_task_with_failure and
Client::fail_workflow_task_with_failure accept the published Server failure
schema for low-level task consumers. Keep details as valid Avro envelopes or
runtime references. Oversized details are omitted whole and marked, never cut as
base64. Original type and retry flags are preserved. Claim identity is exact;
Error::FailureReporting refuses a report whose required data cannot fit.
This reporting failure does not decide the application’s retry outcome.
Local failures are bounded before returning to workflow code, with the published Server’s whitespace/NUL trimming applied to the observed outcome. The final request check never rewrites already observed local messages or unrelated business payloads; if those fixed inputs cannot fit, reporting refuses explicitly.
§Workflow task completion size
A workflow task’s commands travel to the Server in one completion request.
The SDK reads the optional limits.max_workflow_task_completion_bytes from
Server discovery for the completion’s encoded JSON request size. Each command’s
arguments still obey the per-payload limit. An explicit positive aggregate cap
allows individually valid values to remain in one inline batch when namespace
payload storage is unconfigured, disabled or unsupported. Configured storage
retains its upload and lease checks.
Without that discovery field, the planner conservatively uses the ordinary request cap. It can require external storage for an aggregate above that cap even if the Server would accept the batch inline. The field’s publication and installed fan-out qualification are tracked in Server #1136 and SDK #254.
A completion above the Server’s aggregate allowance is refused with HTTP 413,
reason: "payload_too_large" and limit_kind: "workflow_task_completion_bytes".
Automatic structural failure requires the HTTP 413 to reach the worker. A current native Server transport defect can close an over-limit request before that response is read. In that case the SDK reports a transport error, and the run is not yet guaranteed to fail structurally. Follow the aggregate transport correction and published fan-out acceptance before relying on automatic recovery from an over-limit completion.
When the typed refusal reaches the SDK, it is a structural limit. It
never resends the oversized completion. Client::complete_workflow_task returns
Error::WorkflowTaskCompletionTooLarge, which carries the Server’s limit, the
encoded request size the SDK sent, and the Server’s message. A Worker
completes the same task once with a non-retryable fail_workflow command whose
message starts with Structural limit exceeded: workflow_task_completion_bytes:
and names both sizes, so the run fails with failure category
structural_limit instead of retrying the task forever or parking the run. The
failure’s exception properties record structural_limit_kind,
structural_limit_value (the request size) and structural_limit_configured
(the limit); the Server’s message is not copied into workflow history.
Other 413 responses and 5xx responses are unchanged.
To stay under the limit, split the fan-out into smaller batches across workflow tasks, move groups of work into child workflows, or continue as new; offload large payloads with external payload storage.
§Local activities
Enable inline local execution with Worker::new(client, queue).local_activities(true).
Register the callback with the ordinary activity registration methods, then call
ctx.local_activity(...), local_activity_typed(...) or
local_activity_avro_value(...) from workflow code. LocalActivityOptions sets
bounded retries and start-to-close, schedule-to-close and heartbeat timeouts.
Local activities run in the workflow worker and bypass the activity queue. Server records their attempts, heartbeat details and terminal result. Committed results replay without running the callback. A worker lost before completion is acknowledged can execute the callback again, so external effects must be idempotent.
Callbacks must yield to Tokio. Timeout or lost workflow lease drops the async callback without requiring application heartbeats. Blocking work needs separate process supervision. Inline local execution and cooperative prepared local supervision use separate worker profiles. Registration rejects combining them. Database-generated execution and failure IDs become available after Server commits history. Use the failure kind, timeout kind and attempt number to branch during fresh execution, rather than testing whether an ID has been assigned.
Available since SDK 3.1.0. Default workers keep local execution disabled. Opted-in workers negotiate their local capability during registration.
§Worker sessions
Enable Worker::worker_sessions(true) and declare the resource requirements that
the worker actually satisfies with capabilities(...). Route a remote call with
ctx.activity(...).in_worker_session(options) and use .typed::<Output>() or
.avro_value() for its result. A parallel group’s in_worker_session(...) applies
the same routing to each activity leaf.
Server creates a session on the first admitted activity. After registration,
worker.worker_session(options) also provides an explicit shared handle for
create(), renew() and close(reason). ActivityContext::worker_session() exposes
the current handle. Heartbeats renew the holder lease without extending the
absolute TTL. Graceful worker shutdown drains activities and closes held sessions
before deregistering.
lease_seconds(...) bounds holder authority and ttl_seconds(...) bounds the
session’s total lifetime. Reacquisition retains the original TTL deadline. Renew
the handle explicitly while keeping an idle resource alive. Activity heartbeats
also renew the lease. An async callback is dropped when its locally observed lease
or TTL ends, even without application heartbeats. Callbacks must yield to Tokio.
Set max_concurrent_worker_sessions(...) to bound the worker’s session registry
and max_concurrent_activities(...) on the options to bound each session’s activity
concurrency. Uncreated or failed handles release their local slot when dropped.
An admitted session keeps its slot while its holder lease is active.
Session memory is process-local. A replacement holder must rebuild its resources, and an interrupted activity can execute again. Use idempotency and attempt fencing for external side effects. Committed results replay from history without rebuilding resources or rerunning callbacks. Changing recorded session options fails replay. Local activities cannot use session routing.
The runnable session example uses a real process-local cache and prints its resource generation. Use Server 2.5.1 / Native 2.4.1 for session history and original TTL preservation. Session support starts with SDK 3.2.0.
§Bounded sticky execution
Enable a durable-history cache explicitly on a Worker:
use durable_workflow::{Client, Result, StickyCacheOptions, Worker};
use std::time::Duration;
fn configure(client: Client) -> Result<Worker> {
Worker::new(client, "rust-workers")
.build_id("orders-v1")
.sticky_cache(StickyCacheOptions::new(32)
.max_history_bytes(8 * 1024 * 1024)
.ttl(Duration::from_secs(60)))
}Caching is disabled by default. A positive capacity opts in, and zero disables it. The defaults are 16 MiB of retained encoded history and a 300-second TTL. Set whole-second TTLs between 1 and 3600 seconds. Registration must confirm the worker, queue, namespace, build and sticky capability before it can poll with caching. Use Server 2.5.10 or newer. SDK support starts with 3.4.0.
The cache retains immutable wire histories, never live workflow instances or session resources. Replays decode a fresh snapshot. Entry and encoded-byte bounds use LRU eviction, and reads do not extend expiry. Decoding, replay, keys and cursor metadata use additional memory. Size the cache within your worker’s memory budget.
A warm replay validates the inline prefix and fetches the retained tail cursor under the current task’s lease and attempt. Missing, expired, changed or invalid entries fall back to complete durable history. Worker replacement needs no cache transfer. Committed side effects replay, and cancellation delivery remains governed by canonical Server history. Terminal completion and worker shutdown clear entries.
worker.sticky_cache_metrics() reports hits, misses, evictions, forced cold
replays, retained entries and encoded history bytes. This reduces history fetching
for warm runs. Measure CPU, memory and completion rate with your own workloads.
An explicit build_id(...) pins new runs to that deployment build. A different
build cannot take an existing pinned run. Omit it to retain unversioned routing.
The runnable example below prints its result and cache counters.
§Deploying workflow patches
Use a stable change ID with ctx.patched(...) or ctx.get_version(...) to
preserve deployment decisions through replay. An old unmarked history selects
the legacy version -1 if the next durable operation was already recorded.
New executions record one decision per change ID, even when code asks again.
Some older workers recorded a marker for every repeated call. Rust replays
consistent markers at their original positions, retaining the recorded history
and timestamps. Keep those call boundaries, or replace them with
ctx.deprecate_patch(...), while such histories remain active. Replay consumes
one matching historical marker per call and never skips an intervening activity,
timer or side effect. Conflicting recorded versions and unsupported current
ranges remain replay errors.
§Recovering from Server outages
For a long-running service worker, enable .recover_transient_outages(true)
on Worker. Retryable poll and worker-heartbeat failures then keep retrying
with capped exponential backoff. A retried poll keeps its original request ID.
run_until interrupts retry waits when shutdown arrives and settles any poll
response already in flight.
The default preserves bounded retries. run_once remains bounded in either
mode, and WorkerRetryPolicy.max_retries = 0 disables ordinary retries.
Authentication, protocol, codec, handler and task settlement failures still
return an error. Registration and deregistration are outside this recovery
option. Keep a process supervisor for startup failures and process crashes.
§Runnable examples
| Example | Demonstrates |
|---|---|
hello_world.rs | Typed worker, workflow, activities, retries, and completion |
activity_options.rs | Activity retry and timeout policies |
local_activities.rs | Explicit local execution, retries, durable timers and remote work |
worker_sessions.rs | Typed activity routing, holder-local resources and graceful session close |
sticky_execution.rs | Opt-in bounded history, signal replay and cache counters |
condition_search_attributes.rs | Durable conditions and typed search attributes |
continue_as_new.rs | Bounded histories and continue-as-new |
parallel_saga.rs | Deterministic parallel work and saga compensation |
§Client and worker metrics
The SDK implements the shared SDK recorder contract.
The default is a no-op. Supply an Arc<dyn metrics::MetricsRecorder> with
increment(name, count, tags) and record(name, seconds, tags) methods; the
client, its clones and newly constructed workers inherit the recorder.
Worker::metrics_recorder overrides worker poll/task observations while client
request observations retain the client’s recorder. Recorders must be fast and
handle exporter failures locally. Unwinding recorder panics are isolated from
SDK results; process aborts and blocking exporters cannot be repaired by a hook.
Every observed client request, worker poll and claimed-task dispatch increments its counter by one and records one nonnegative monotonic duration in seconds. The paired recorder names are:
| Counter | Duration histogram |
|---|---|
durable_workflow_client_requests | durable_workflow_client_request_duration_seconds |
durable_workflow_worker_polls | durable_workflow_worker_poll_duration_seconds |
durable_workflow_worker_tasks | durable_workflow_worker_task_duration_seconds |
Revision 2 also records durable_workflow_worker_task_schedule_to_start_seconds
for workflow and activity claims when the Server advertises
claimed_task_ready_age. It converts the Server’s integer ready_age_ms to
seconds and uses only task_kind and task_queue, without a paired counter or
outcome label. A real zero is retained; missing, malformed or out-of-range
producer values are omitted. This measures Server eligibility-to-claim time,
without estimating missing values from the worker’s clock.
Client tags are exactly method, route, plane, status_code, outcome.
Worker tags are exactly task_kind, task_queue, outcome. Reviewed route
placeholders exclude IDs, query strings, payloads and credentials; unknown paths
use unknown. Queue names are application-controlled: use bounded names rather
than a queue per run. The SDK’s tests verify the exact vendored revision-2 JSON
from the pinned shared contract above.
One client observation includes its internal transport/storage-admission retries
and response/payload handling. Separate application/worker-managed calls remain
separate client observations. A lazy iterator observes each requested page, not
one operation for the whole iteration. Worker poll observations include managed
retry/backoff and distinguish task, empty, backpressure, error. Task
observations describe processing of workflow, activity and query dispatches:
completed, failed and expired do not assert a workflow’s terminal state.
These are process observations, not durable counts, billing units or
schedule-to-start latency. Abrupt process loss can prevent a final observation.
Client outcomes include ok, http_error, bridge_rejected, TransportError,
TimeoutError, SdkError and pending (a cancelled future). A decimal HTTP
status is retained when observed, otherwise status_code=none. Language-specific
exception outcomes need not match Python names. Renaming an adopted name, type,
unit or tag key requires a major release; additions and new tag values are
announced in the changelog.
§Prometheus export
Enable the optional adapter in your application:
[dependencies]
durable-workflow = { version = "=4.7.0", features = ["metrics-prometheus"] }
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }metrics::PrometheusMetrics::new() owns a dedicated registry backed by the
official Prometheus Rust client.
Pass an Arc of it to ClientBuilder::metrics_recorder, and serve its
encode() bytes from your application’s metrics route with content type
text/plain; version=0.0.4. The adapter installs no listener or global registry;
applications choose scrape authentication/network exposure, exporter resources
and shutdown. Counter exports append _total; histograms expose standard
bucket/sum/count series without changing the recorder contract. registry()
allows application-owned collection and additional metrics.
The runnable example previews actual exported health-request observations:
DURABLE_WORKFLOW_SERVER_URL=http://localhost:8080 \
DURABLE_WORKFLOW_AUTH_TOKEN=your-token \
cargo run --features metrics-prometheus --example metrics_prometheusFor OpenTelemetry, implement MetricsRecorder with the application’s existing
meter: create count-unit (1) counters for increment and second-unit (s)
histograms for record, using the exact names and tags above. Provider,
aggregation, resource labels and exporter lifecycle stay with the application.
§Optional execution telemetry
Enable the telemetry Cargo feature and configure your application’s
OpenTelemetry provider, exporter, sampling and bounded export timeouts before
constructing the worker. Configure the application’s global W3C propagator
before making admission calls or starting workers:
use durable_workflow::{Client, Worker};
use durable_workflow::telemetry::ExecutionTelemetry;
opentelemetry::global::set_text_map_propagator(
opentelemetry_sdk::propagation::TraceContextPropagator::new(),
);
let client = Client::builder("http://localhost:8080").build()?;
let worker = Worker::new(client, "orders").telemetry(ExecutionTelemetry::new());The default build has no OpenTelemetry dependency. The optional feature needs the API and official W3C propagators supplied by the OpenTelemetry SDK crate; the application owns provider/exporter configuration and shutdown. If the application already uses a composite propagator, retain its other propagators and include W3C trace context. A missing propagator leaves task spans independent even when the Server supports carriers. The SDK does not replace the application’s global configuration. Servers without the exact optional capability use independent task traces. When available, a valid run origin parents task spans; task-bound dispatch and validated command/outcome contexts become links. The original poll identity, generation and existing hydration, query and cooperative fences precede their use. Missing or insufficient authority omits propagation without changing business execution. Actual remote/local activity attempts have separate child spans. Use the configured Server/SDK tuple qualified in Workflow #773. Replay emits workflow work spans without pretending completed activities ran again. No span stays open during durable waiting.
Configure admission/command clients with client.with_telemetry(telemetry) and
use existing client.cluster_info().await discovery during setup. Worker startup
can perform one bounded optional discovery; its failure does not refuse business
registration or add business retries. Only the exact supported
worker_protocol.server_capabilities.observability_context object enables
carriers. No mandatory protocol floor or Server version inference is added.
Caller capture precedes HTTP transport. Worker child/continue commands capture
their actual workflow scope before settlement and preserve business arguments
and request keys.
Official W3C propagation validates the agreed byte limits. Baggage defaults empty;
with_baggage_allowlist retains explicit keys only on run parents. Links never
carry baggage. Envelopes are bounded to 4096 bytes and at most 32 links. Malformed
metadata is ignored with fixed discarded/filtered span diagnostics. Use
with_enabled(false) to disable spans and propagation explicitly.
Use telemetry::current_log_context() in a logging adapter, or wrap an existing
OpenTelemetry logger provider in telemetry::ExecutionLoggerProvider before
passing it to your application’s logging bridge. It adds bounded namespace,
worker, queue, task and available workflow/attempt IDs; trace/span IDs follow
the current application child span. Request IDs and log messages remain owned
by the application. The SDK installs no global logging bridge or provider.
Tokio contexts attach during each poll and restore on yield, completion, panic
and cancellation. Spawned application tasks must explicitly propagate their
context when that is intended. Export failures do not change business results;
applications must bound exporter I/O and drain their providers during shutdown.
Abrupt process death may lose spans; telemetry is not exactly-once delivery.
§Documentation
- Rust SDK landing page
- Generated API reference
- Rust SDK guide
- Self-hosted Server guide
- Cloud early access
§Nexus service calls
Await a catalog operation from workflow code with Avro arguments:
let reply = ctx.call_nexus_service("billing", "invoices", "create", invoice).await?;
let receipt: Receipt = reply.result.deserialize()?;The default synchronous call waits for its committed result. Cold replay resumes
the original call without admitting it again. NexusServiceOptions selects a
target namespace, idempotency key, async mode or acceptance-only waiting. Async
and acceptance-only calls return the original admission, even when a terminal
result appears later. Committed failures use Error::NexusOperationFailed.
Calls currently run in the root workflow scope.
Enable Worker::nexus_cooperative_cancellation(true) for cooperative service
waits. It enables ordinary cooperation and requires the installed Server to
advertise protocol 1.20, both cancellation capabilities and a workflow_run
binding. Cancellation reaches the original synchronous completion wait after
owned target cleanup, preserving the original request and cleanup deadline.
Use a cancellation shield for durable cleanup. See
examples/nexus_cooperation.rs for caller and
target workers. Ordinary cooperative workers keep their existing registration
behavior when Nexus cooperation is disabled.
§Compatibility
The SDK supports cooperative requests and bounded,
replayable cleanup. Enable Worker::cooperative_cancellation(true) against a
Server that advertises protocol 1.20 and the required capabilities. This profile
supervises async Activity futures independently of application heartbeats.
Independently cancellable scopes remain disabled. See the
cancellation guide
and v3 migration guide.
The crate publishes its supported Server and worker-protocol ranges in
[package.metadata.durable-workflow] in Cargo.toml. Runtime
capability manifests, not matching package version strings, determine protocol
compatibility. Stable releases follow semantic versioning.
supported-server-release-baselines maps supported Server majors to minimum
stable releases. A reader validates the whole map before selecting a major and
refuses an unlisted major, a malformed entry or a contradiction with the legacy
supported-server-versions 2.x baseline. Without the additive map, existing
same-major baseline behavior remains. The legacy scalar and the separate 2.x
qualification identity are preserved for older readers. Protocol and capability
negotiation remain required for individual features.
§Development
cargo fmt --all --check
cargo test --locked --all-targets --all-features
cargo doc --locked --all-features --no-deps
cargo package --lockedThe committed lockfile records the dependency graph used by CI and packaging. Fresh-consumer checks resolve dependencies independently to verify the published crate also builds for new consumers. Release verification runs tooling pinned to the workflow commit against a separate immutable source tag. For older tags that ignored the lockfile, it restores only the missing lock from the checksum-verified published crate, then requires the complete regenerated archive to match.
Replay and codec defects require a minimal regression fixture. See
CONTRIBUTING.md for the corpus rules.
§License
Durable Workflow Rust SDK is released under the MIT License.
Re-exports§
pub use pagination::PaginationError;pub use pagination::WorkflowHistoryIterator;pub use pagination::WorkflowHistoryOptions;pub use pagination::WorkflowHistoryPage;pub use pagination::WorkflowIterator;pub use pagination::WorkflowListOptions;pub use pagination::WorkflowListPage;pub use pagination::WorkflowSummary;
Modules§
- metrics
- Stable client/worker metrics, with application-owned recording and export.
- pagination
- Namespace-scoped one-page reads and lazy, bounded-memory enumeration.
- telemetry
- Optional execution spans and application log correlation.
- testing
- Server-free workflow replay and in-process workflow/activity tests.
Macros§
- json
- Construct a
serde_json::Valuefrom a JSON literal. - wait_
condition - Create a durable condition wait whose predicate definition is fingerprinted from its inline Rust tokens.
Structs§
- Activity
Call - Activity
Context - Activity
Error - An application failure returned by an activity handler.
- Activity
Failure - A stable, machine-readable terminal activity failure.
- Activity
Heartbeat Response - Activity
Options - Options recorded atomically on one deterministic
schedule_activitycommand. - Activity
Options Error - A machine-readable activity-options validation failure.
- Activity
Retry Info - Original attempt identity and retry policy, captured before invoking a handler.
- Activity
Retry Policy - Durable server-side retry policy for one activity execution.
- Activity
Task - Activity
Task Rejection - A worker-side activity settlement or heartbeat rejected by durable state.
- Cancel
Durable Operation Call - Future returned by
DurableOperationHandle::cancel. - Cancellation
Context - Original cancellation metadata restored from canonical request history.
- Cancellation
Delivery - One committed delivery marker, bound to the original cancellation request.
- Cancellation
Delivery Receipt - A delivery acknowledgment bound to one workflow task and durable run.
- Cancellation
History - Validated canonical cancellation state for one workflow run.
- Cancellation
Lineage - One immutable local request in the ordered cancellation lineage.
- Cancellation
Request - The Server’s original request identity and immutable cleanup deadline.
- Cancellation
Scope Open Receipt - A scope opening proved against complete history on its original claim. This proof does not advertise scoped workflow execution support.
- Cancellation
Shield - A workflow-local cleanup scope. Dropping it restores cancellation checks.
- Child
Workflow Avro Result - Lossless successful child result for fixed Avro Value workflows.
- Child
Workflow Call - Future returned by
WorkflowContext::start_child_workflow. - Child
Workflow Failure - A stable, machine-readable child workflow failure delivered to its parent.
- Child
Workflow Options - Options recorded with a child-workflow command.
- Child
Workflow Result - A successful child result together with its durable parent-child identity.
- Child
Workflow Retry Policy - Durable retry policy for one child workflow invocation.
- Client
- Client
Builder - Condition
Wait Call - Future returned by
WorkflowContext::wait_condition. - Condition
Wait Options - Stable identity and optional durable timeout for a condition wait.
- Continue
AsNew Options - Optional routing overrides for a continue-as-new transition.
- Continue
AsNew Options Error - A stable validation error raised before a continue-as-new command is emitted.
- Cooperative
Cancellation Options - Optional reason and runtime-owned cleanup limit for a cooperative request.
- Cooperative
Cancellation Requested - Cancellation delivered at its committed authored call, with original identity.
- Cooperative
Workflow Task - One actual protocol 1.20 claim and its original pending observation.
- Cooperative
Workflow Task Poll - An explicit cooperative poll, including ordinary idle and stop outcomes.
- Duplicate
Registration Error - Ambiguous local configuration, rejected before contacting Server.
- Durable
Operation Await Call - Future returned by
DurableOperationHandle::await_result. - Durable
Operation Cancelled - Typed result of explicitly awaiting a cancelled non-winning operation.
- Durable
Operation Handle - Stable reference to one member of a durable selection group.
- Handler
Registration - The authoring adapter and source location of a handler registration.
- History
Event - Http
Refusal - The decoded body of a refused (non-2xx) Server request.
- Local
Activity Options - Retry and timeout settings for an activity executed by the workflow worker.
- Message
Stream - Message
Stream Message - Nexus
Operation Failure - A committed service failure delivered at the original authored call.
- Nexus
Operation Result - The original durable service identity and its observed outcome.
- Nexus
Service Call - Future returned by
WorkflowContext::call_nexus_service. - Nexus
Service Options - Optional routing and waiting policy for an authored Nexus call.
- Parallel
Call - Future returned by
WorkflowContext::parallel. - Parallel
Completion - One successful leaf retained when another parallel member failed.
- Parallel
Failure - A deterministic join failed after some siblings had already completed.
- Parallel
Group Error - Stable validation error returned before an invalid group emits commands.
- Parallel
Group Metadata - Stable identity for one enclosing deterministic parallel group.
- Payload
Envelope - Poll
Activity Task Response - Poll
Query Task Response - Poll
Workflow Task Response - Protocol
Failure - A stable failure returned when a server rejects an SDK protocol version.
- Query
Context - Immutable state supplied to a registered query handler.
- Query
Failure - A stable, machine-readable workflow query or query-task settlement failure.
- Query
Signal - One decoded signal in the committed workflow-history snapshot.
- Query
Task - An ephemeral server-routed query task.
- RawRequest
- A Server API request addressed by path segments under
{base_url}/api. - RawResponse
- A Server response, unchanged, for any HTTP status.
- Register
Worker Response - Replay
Failure - A stable, machine-readable failure raised when workflow code no longer reconstructs the durable command stream recorded in history.
- Request
IdConflict - A refused signal or update whose caller command key is already retained for a command with a different intent.
- Saga
- Workflow-local deterministic saga compensation helper.
- Saga
Compensation Failure - A forward saga failure followed by a terminal compensation failure.
- Scoped
Cancellation Context - Original scope ancestry carried by a candidate cooperative child request. Reading this immutable metadata does not authorize entering a scope body.
- Scoped
Cancellation Lineage - One immutable scope address and its bounded cleanup deadline.
- Search
Attribute Update - Validated typed workflow-side search-attribute mutation.
- Select
Call - Future returned by
WorkflowContext::select. - Selection
Result - The one winner committed for a durable selection group.
- Signal
Call - Sticky
Cache Metrics - Replay counters and retained encoded history. Decoding/replay memory is additional.
- Sticky
Cache Options - Opt-in bounds for a worker’s durable-history cache.
- Timer
Call - Future returned by
WorkflowContext::sleep. - Update
Pending - An update the Server accepted that had not completed when the wait ended.
- Uuid
- A Universally Unique Identifier (UUID).
- Worker
- Worker
Deregistration Envelope - Result of gracefully removing a worker-plane registration.
- Worker
Heartbeat Observation - Worker
Retry Policy - Bounded retry policy for worker poll acquisition and worker heartbeats.
- Worker
Session - One worker’s acknowledged session lease.
- Worker
Session Options - Routing and lifetime options for one worker-held session.
- Workflow
Activity - A run’s activity metadata. Missing or null optional fields stay unavailable.
- Workflow
Activity Attempt - Recorded attempt state. These flags describe visibility, not action grants.
- Workflow
Activity List - Activity and attempt visibility returned for one selected run.
- Workflow
Activity Metadata Error - A malformed or misdirected run-activity response.
- Workflow
Cancellation Request - Acknowledgment of a request targeting the current durable run.
- Workflow
Cancellation Requested - Cooperative workflow cancellation observed at an author-controlled point.
- Workflow
Command Options - Optional structured fields for a cancellation or termination request.
- Workflow
Command Rejection - A stable rejection returned by instance- or selected-run lifecycle commands.
- Workflow
Command Result - The accepted, machine-readable result of a lifecycle command.
- Workflow
Context - Workflow
Description - Workflow
Handle - Workflow
History Budget - Public history-budget information attached to the current workflow task.
- Workflow
Identity - The identity of one durable workflow execution.
- Workflow
Instance - Typed local state owned by one deterministic workflow invocation.
- Workflow
Logger - Replay-aware host logging with SDK-bound namespace/workflow/run fields.
- Workflow
Redrive Result - A new run continuing a failed run from its recorded activity boundary.
- Workflow
Result Options - Workflow
Start Options - Server-enforced timeout policy for a workflow start.
- Workflow
Stream Append Item - One item for direct or replay-safe append.
- Workflow
Stream Append Result - Durable acceptance and deduplication outcome for an append request.
- Workflow
Stream Description - Lifecycle and backlog metadata for one run-scoped Workflow Stream.
- Workflow
Stream Item - One durable item at its stable zero-based offset.
- Workflow
Stream Page - One bounded at-least-once subscription page.
- Workflow
Task - Workflow
Task Completion TooLarge - A workflow-task completion the Server refused as larger than its aggregate
completion limit (HTTP 413,
reason: "payload_too_large",limit_kind: "workflow_task_completion_bytes"). - Workflow
Task Heartbeat - Successful renewal of the exact workflow-task claim with optional observation.
- Workflow
Terminal Outcome - A typed terminal workflow outcome with durable identity and failure metadata.
Enums§
- Activity
Attempt Limit - The configured attempt budget in an activity’s retry snapshot.
- Activity
Backoff - Backoff intervals for one durable activity retry policy.
- Activity
Failure Kind - Stable terminal categories returned when an awaited activity does not succeed.
- Activity
Options Error Kind - Stable validation categories for
ActivityOptions. - Avro
Value - Native adapter for the fixed language-neutral Avro Value schema.
- Cancellation
Call Kind - The authored durable call where canonical cancellation is delivered.
- Cancellation
Cause - Why a cooperative cancellation request was delivered to this run.
- Cancellation
Delivery Reply - Delivery either commits or parks the parent until canonical child cleanup.
- Cancellation
Policy - Cancellation at an awaiting operation. Activities default to Try, children to Abandon.
- Child
Workflow Failure Kind - Stable terminal categories returned when an awaited child does not succeed.
- Condition
Wait Options Error - Validation failure for a durable condition-wait definition.
- Condition
Wait Result - Unambiguous terminal result of a durable condition wait.
- Error
- Failure
Report Error - Failure reporting refused locally; this is not an application failure decision.
- Handler
Kind - The registered handler family reported by
Error::HandlerType. - Handler
Value Kind - Whether a typed handler failed to adapt its input or result.
- Nexus
Operation Mode - The catalog operation’s execution mode.
- Nexus
Wait For - Resume from durable admission or wait for the committed service result.
- Parallel
Avro Result - Lossless fixed-Avro counterpart to
ParallelResult. - Parallel
Operation - A deferred durable leaf or nested group for
WorkflowContext::parallel. - Parallel
Result - One input-ordered result returned by
WorkflowContext::parallel. - Parent
Close Policy - Server behavior when a parent closes while its child is still open.
- RawMethod
- HTTP method of a
RawRequest. - Registration
Kind - Handler namespaces checked independently within a Worker.
- Search
Attribute Update Error - Validation failure for a typed workflow search-attribute update.
- Search
Attribute Value - One public typed search-attribute value.
- Selection
Key - Stable user-facing identity for one member of a durable selection group.
- Update
Wait Stage - How long an update outcome read waits before the Server answers.
- Value
- Represents any valid JSON value.
- Worker
Poll Outcome - Stable classification for worker poll responses.
- Worker
Protocol Version - Select the worker request protocol without enabling optional capabilities.
- Workflow
Command Kind - The lifecycle command sent to a workflow execution.
- Workflow
Replay State - The live execution region for workflow observations.
- Workflow
Terminal Kind - Stable terminal categories returned by
WorkflowHandle::result.
Constants§
- AVRO_
VALUE_ SCHEMA_ FINGERPRINT - AVRO_
VALUE_ SCHEMA_ FINGERPRINT_ HEX - AVRO_
VALUE_ SCHEMA_ JSON - Canonical Avro Value schema packaged with the crate and parsed by the runtime.
- CONDITION_
WAIT_ MINIMUM_ WORKER_ PROTOCOL_ VERSION - First additive worker protocol that defines external durable condition waits.
- CONDITION_
WAIT_ OCCURRENCE_ IDENTITY_ CAPABILITY - Worker-registration capability for authored condition-wait occurrence identity.
- CONDITION_
WAIT_ OCCURRENCE_ IDENTITY_ MINIMUM_ WORKER_ PROTOCOL_ VERSION - First additive worker protocol that preserves authored condition-wait occurrences.
- CONTROL_
PLANE_ VERSION - DEFAULT_
CODEC - DURABLE_
SELECTION_ CAPABILITY - Worker-registration capability for persisted first-completion selection.
- DURABLE_
SELECTION_ MINIMUM_ WORKER_ PROTOCOL_ VERSION - First additive worker protocol that defines durable selection groups.
- MEMO_
UPSERTS_ CAPABILITY - Worker-registration capability for portable memo upserts.
- MEMO_
UPSERT_ MINIMUM_ WORKER_ PROTOCOL_ VERSION - First additive worker protocol that defines portable memo upserts.
- MESSAGE_
STREAMS_ CAPABILITY - Worker-registration capability for durable named input streams.
- MESSAGE_
STREAMS_ MINIMUM_ WORKER_ PROTOCOL_ VERSION - MESSAGE_
STREAM_ CURSOR_ SCHEMA - MESSAGE_
STREAM_ MAX_ BATCH - MESSAGE_
STREAM_ SCHEMA - MESSAGE_
STREAM_ SIGNAL - MINIMUM_
WORKER_ PROTOCOL_ VERSION - PORTABLE_
WORKER_ AFFINITY_ MINIMUM_ PROTOCOL_ VERSION - First additive worker protocol that defines portable worker-affinity features.
- QUERY_
TASKS_ CAPABILITY - Worker-registration capability for server-routed read-only queries.
- QUERY_
TASK_ MINIMUM_ WORKER_ PROTOCOL_ VERSION - First additive worker protocol that defines query-task transport.
- SDK_
VERSION - SEARCH_
ATTRIBUTE_ UPDATE_ MINIMUM_ WORKER_ PROTOCOL_ VERSION - First additive worker protocol that defines typed search-attribute upserts.
- TYPED_
SEARCH_ ATTRIBUTES_ CAPABILITY - Worker-registration capability for canonical typed search attributes.
- TYPED_
SEARCH_ ATTRIBUTES_ MINIMUM_ WORKER_ PROTOCOL_ VERSION - First additive worker protocol that preserves declared search-attribute types.
- WORKER_
PROTOCOL_ VERSION - WORKFLOW_
TASK_ COMPLETION_ BYTES_ LIMIT_ KIND - The
limit_kinda native Server (3.6.0 or later) reports when it refuses a workflow-task completion body as too large. - WORKFLOW_
UPDATES_ CAPABILITY - Worker-registration capability for synchronous workflow updates.
Functions§
- decode_
avro_ value - decode_
payload - encode_
avro_ value - encode_
payload - portable_
worker_ affinity_ capability_ manifest - Manifest for the default service-worker profile.
- worker_
protocol_ compatible - Whether a Server worker protocol version is compatible with the client’s:
same major, and a Server minor at least the client’s. Versions that are
not
major.minorintegers must match exactly. This is the CLI 2.x rule. - worker_
protocol_ supports_ message_ streams