Aviary

API reference

Every public member of WorkflowCtx, the authoring decorators, WorkflowService, the WorkflowEngine's selected surface, DurableModuleOptions, the thrown error classes, and the run/checkpoint status enums — one line each, distilled from source.

This page is a flat lookup table of the public API — the WorkflowCtx, the engine, the errors, the scheduler, and the @dudousxd/nestjs-durable decorators. It is deliberately terse — for the why behind any entry, follow its linked concept/authoring/reliability page.

WorkflowCtx

The context handed to a workflow's run(ctx, input). Every interaction with the outside world goes through it so the engine can checkpoint — the body itself stays deterministic (see Durability & replay).

Properties

MemberSignatureNotes
runIdreadonly runId: stringThis run's id.

Steps

MemberSignatureNotes
stepstep<TIn, TOut>(handler: StepRef<TIn, TOut>, input: TIn, opts?: StepDispatchOpts & { compensate?: StepRef<StepUndo<TIn, TOut>, unknown> | string }): Promise<TOut>Dispatch a durable step by typed @Step method reference — the ONE step primitive, always engine-scheduled. compensate registers a dispatched saga undo for this call. See Workflows & steps.
step (by name)step<TOut = unknown, TIn = unknown>(name: string, input: TIn, opts?: StepDispatchOpts & { compensate?: StepRef<StepUndo<TIn, TOut>, unknown> | string }): Promise<TOut>Same dispatch, by string name — for a cross-runtime handler (e.g. a Python @step) with no JS reference.
localSteplocalStep<TOut>(name: string, fn: (log: StepLogger) => Promise<TOut>, options?: StepOptions): Promise<TOut>Escape hatch: a checkpointed step whose body runs in-process (not dispatched), so it can carry an in-memory compensate for sagas.
transactiontransaction<TOut>(name: string, fn: (tx: unknown) => Promise<TOut>): Promise<TOut>Exactly-once DB step: runs fn and writes the checkpoint in ONE store transaction (business write + "done" marker are atomic). Needs a SQL store; throws otherwise.

Time

MemberSignatureNotes
sleepsleep(duration: string | number): Promise<void>Durable sleep for a relative duration ('30s', '2h', ms) — zero compute, resumes across restarts. See Sleep & signals.
sleepUntilsleepUntil(when: Date | number): Promise<void>Durable sleep to an absolute deadline; the wake time is fixed on first run (replay-stable).
nownow(): Promise<number>Deterministic epoch-ms clock read — records on first run, replays the same value. Use instead of Date.now() inside a workflow body.

Signals & events

MemberSignatureNotes
waitForSignalwaitForSignal<T>(token: string, opts?: { timeoutMs?: number }): Promise<T>Suspend until an external engine.signal(token, payload) arrives; timeoutMs bounds the wait and throws SignalTimeoutError on expiry.
waitForAnywaitForAny<C extends Record<string, WaitCondition>>(name: string, conditions: C): Promise<WaitAnyResult<C>>Suspend until the first condition happens; resolves { key, value } typed per key, journaled under name. Only the winning signal is consumed. See waitForAny.
signalWait / timer / childWaitsignalWait<T>(token), timer(duration | { until }), childWait<T>(runId)The conditions waitForAny takes: a signal (value: payload), a deadline counted from when the wait is first reached (value: null), a run settling (value: its output; a failed run throws).
waitForEventwaitForEvent<T>(name: string, opts?: { match?: Record<string, unknown>; timeoutMs?: number }): Promise<T>Suspend for a named pub/sub event published via engine.publishEvent; match filters which publishes resolve this run.
waitForRunwaitForRun<TOutput>(runId: string, opts?: { timeoutMs?: number | string }): Promise<WorkflowLifecycleEvent<unknown, TOutput>>, or waitForRun(WorkflowClass, runId, opts?): Promise<LifecycleEventOf<C>>Suspend until any run settles and resume with its status and output or error. Resolves at once for a settled run; timeoutMs throws SignalTimeoutError; an unknown id fails with a non-retryable run <id> not found. See Waiting for another run to finish.
setEventsetEvent<T>(key: string, value: T): Promise<void>Publish a queryable value, readable externally via engine.getEvent(runId, key) while the run is in flight. See Queries & updates.
onUpdateonUpdate<TArg>(name: string, opts?: { timeoutMs?: number }): Promise<TArg>Expose a run-scoped update point; suspends until engine.update(runId, name, arg) delivers arg, gated by any registered validator.

Children

MemberSignatureNotes
childchild<C extends WorkflowClass>(workflow: C, input: WorkflowInputOf<C>, options?: string | ChildCallOptions): Promise<WorkflowOutputOf<C>>Start (or reattach to) a child run and suspend — zero compute — until it's terminal, then resume with its output (throws FatalError if the child failed). See Child workflows.
child (by name)child<TOut>(workflow: string, input: unknown, options?: string | ChildCallOptions): Promise<TOut>Same, for a cross-runtime child by name.
startChildstartChild<C extends WorkflowClass>(workflow: C, input: WorkflowInputOf<C>, options?: string | ChildCallOptions): Promise<string>Fire-and-forget: dispatch a child once and return its run id immediately; the parent keeps running.
allall<C extends WorkflowClass>(workflow: C, inputs: WorkflowInputOf<C>[], opts?: AllOptions): Promise<WorkflowOutputOf<C>[]>Run N children of the SAME workflow in parallel and await all of them, in input order. waitAll (default) aggregates failures into GatherError; failFast throws on the first and cancels the surviving siblings (best-effort, observed at their next checkpoint). concurrency caps how many children run at once. Also takes a workflow name (all<TOut>(workflow: string, …)). See Child workflows.
all (over a step)all<TIn, TOut>(step: StepRef<TIn, TOut>, inputs: TIn[], opts?: AllStepsOptions): Promise<TOut[]>One durable step per input, joined once: the parent wakes once per settled wave, not once per result. Outputs in input order; failures as GatherError. A @Step that declares timeoutMs, or a queue option, is rejected. See The same step over many inputs.
allSettledallSettled<C extends WorkflowClass>(workflow: C, inputs: WorkflowInputOf<C>[], opts?: { concurrency?: number }): Promise<Settled<WorkflowOutputOf<C>>[]>The same fan as all in waitAll mode, resolving with one { status: 'fulfilled', value } | { status: 'rejected', id, error } per input instead of throwing. Also takes a @Step reference. See Child workflows.

External

MemberSignatureNotes
tasktask<T>(name: string, dispatch: () => Promise<void>, options?: StepOptions): Promise<T>An external task with async completion: run dispatch once, then suspend until engine.completeTask/failTask reports back.
webhookwebhook<TPayload>(): DurableWebhook<TPayload>Mint a durable callback handle (token + optional public url); await handle.wait({ timeoutMs? }) suspends until the third party's callback lands as engine.signal(token, body) — or throws SignalTimeoutError past the deadline. See Durable webhooks.
callEntitycallEntity<TResult = unknown>(name: string, key: string, op: string, arg?: unknown): Promise<TResult>Call a durable entity op (serialized per key) and await its result. See Durable entities.
signalEntitysignalEntity(name: string, key: string, op: string, arg?: unknown): Promise<void>Send an entity op fire-and-forget (no result awaited).

State & metadata

MemberSignatureNotes
patchedpatched(id: string): Promise<boolean>Guard an in-place workflow change without a new version: true for a fresh run (takes the new branch), false for a run whose history predates the guard. See Versioning & determinism.
continueAsNewcontinueAsNew(input?: unknown): Promise<never>End this run and start a fresh execution of the same workflow with clean history (id <runId>~N). Always throws — terminal.
sideEffectsideEffect<T>(fn: () => T | Promise<T>): Promise<T>Deterministic capture: run fn once, checkpoint the result, replay returns the SAME value without re-running fn (e.g. uuidv7(), Math.random()).
upsertSearchAttributesupsertSearchAttributes(attrs: SearchAttributes): Promise<void>Shallow-merge typed, queryable metadata onto this run's searchAttributes — exactly-once (skipped on replay).
breakpointbreakpoint(label?: string): Promise<void>Pause the run here until a human resumes it (engine.continue(runId) or the dashboard) — a durable debugger breakpoint.

Supporting option types

TypeShapeNotes
StepDispatchOpts{ queue?, priority?, fairnessKey?, transport?, retries?, backoff?, backoffMs?, backoffMaxMs?, jitter?, timeoutMs? }Per-call override of a @Step-declared policy for a dispatched ctx.step. queue routes to a flow-control queue; priority/fairnessKey apply within it. ctx.step's own opts additionally accepts compensate?: StepRef<StepUndo<TIn, TOut>, unknown> | string (not part of StepDispatchOpts itself) — registers a dispatched saga undo for this call, retried per the undo's OWN @Step config (never this call's opts); no queue/admission and no timeoutMs liveness window apply to the undo's dispatch.
StepOptions{ retries?, backoff?, backoffMs?, backoffMaxMs?, jitter?, timeoutMs?, compensate? }Options for ctx.task/ctx.localStep. compensate: () => Promise<void> registers an in-process saga undo, retried up to the module-level compensationRetries (default 1). See Sagas & compensation.
StepUndo<TIn, TOut>{ input: TIn; output: TOut }The one argument a dispatched saga undo is called with — the compensated call's own input and result.
UndoOf<H>H extends (input: infer I, ...rest: never[]) => infer R ? StepUndo<I, Awaited<R>> : neverDerives a dispatched undo's expected argument from the ORIGINAL step method's type, so a compensate ref is compile-checked against the call it undoes: async cancelBooking(undo: UndoOf<FlightService['book']>) { ... }.
AllOptions{ mode?: 'waitAll' | 'failFast'; concurrency?: number }For ctx.all over children. concurrency sends waves of floor(concurrency / 2), two at a time. Part of the fan's identity: don't change it under an in-flight run.
AllStepsOptionsOmit<StepDispatchOpts, 'queue' | 'timeoutMs'> & { mode?: 'waitAll' | 'failFast'; concurrency?: number }For ctx.all over a @Step. The retry/backoff/priority options apply to every step of the fan. concurrency sends strict waves of that size. failFast stops sending without cancelling steps already in flight.
ChildCallOptions{ childId?, priority?, version? }Options for ctx.child/ctx.startChild (a bare string is shorthand for { childId }). priority only affects a remote child. version pins the child to that exact registered version — pass a constant, see Versioning.

DynamicWorkflowCtx<A> — the non-overloaded view

WorkflowCtx minus its four overloaded methods, re-declared with ONE string-addressed signature each: step(name, input, opts?), child(workflow, input, options?), startChild(workflow, input, options?), all(workflow, inputs, opts?). Every WorkflowCtx<A> is assignable to it without a cast. Depend on it (or a Pick of it) in code that drives the ctx by names — a graph interpreter — and in test fakes, where satisfying every overload of the full WorkflowCtx is impractical:

type InterpreterCtx = Pick<DynamicWorkflowCtx, 'runId' | 'localStep' | 'child' | 'all' | 'sleep'>;
new Interpreter(ctx /* WorkflowCtx */); // accepts InterpreterCtx — no `as unknown as`

Decorators

From @dudousxd/nestjs-durable.

@Workflow(options)

Marks a provider class as a durable workflow; its run(ctx, input) becomes the replayed body.

OptionTypeNotes
namestringRequired. Registered workflow name.
versionstringDefault '1'. Old runs keep resuming on the version they started on.
deadLetterWorkflowWorkflowRefRoute this workflow's dead runs to another registered workflow (class or name). Superseded by an inline @DeadLetter() method on the same class. See Dead-letter queue.
tagsstring[]Static labels stamped on every run, merged with per-run start tags.
singletonSingletonConfig<InferWorkflowInput<S>> ({ key, limit?, maxQueueDepth? })Durable FIFO mutex per key. With an input schema, key takes and receives the parsed input; without one, unknown. See Singleton workflows.
concurrencyConcurrencyConfig<InferWorkflowInput<S>> ({ key, limit, countStatuses? })Start-time quota per key (shared across workflows); an over-limit start throws ConcurrencyLimitError. key is typed like singleton's. See Concurrency quotas.
executionTimeoutstring | numberMax wall-clock lifetime, counted from createdAt; an overrunning run — pending, blocked, running or suspended — is cancelled (execution_timeout) by the timer poller. See Guard the run.
inputS extends IoSchema (Standard Schema | class-validator DTO class)Input schema. Checked at start (invalid input creates no run); the run stores the input as sent, and run(), validateInput and the singleton/concurrency keys receive the parsed value, re-parsed before every turn. InferWorkflowInput<typeof Schema> is its type, for run's parameter. See Guard the run.
outputIoSchemaOutput schema. run()'s return value is parsed before the run completes; a mismatch fails it with invalid_output.
validateInput(input: InferWorkflowInput<S>) => void | Promise<void>Extra check at start (throw to reject), run after input parses, on the parsed value.
onEventArray<string | { event: string; where?: (payload) => boolean; input?: (payload) => unknown }>Start a fresh run whenever any of these events is published. where filters per payload, input builds the run's input from it. Merged with @OnDurableEvent, @OnWorkflowCompleted and @OnWorkflowFailed.
debouncestring | numberCoalesce onEvent triggers: fire once quiet for this long, with the last payload.
batch{ maxSize: number; within: string | number }Coalesce onEvent triggers: fire on size or window, with all payloads.

@Step(nameOrOptions?)

Marks a provider method as a durable step handler, routed BY NAME (derived Class.method, or explicit).

FormNotes
@Step()Bare — name derived as `${ClassName}.${method}`.
@Step('custom:name')Explicit name override.
@Step({ name?, input?, output?, retries?, backoff?, backoffMs?, backoffMaxMs?, jitter?, timeoutMs? })Object form — input/output are opt-in runtime schemas (a Standard Schema such as zod, or a class-validator DTO class — the same forms @Workflow takes) validated at the serve boundary, and the method receives the parsed input; retries/backoff/backoffMs/backoffMaxMs/jitter/timeoutMs are the def-level dispatch policy ctx.step reads (a per-call opts overrides field-by-field). See Retries & backoff.
StepOptions fieldTypeNotes
namestringExplicit routing name override.
inputz.ZodTypeRuntime input schema.
outputz.ZodTypeRuntime output schema.
retriesnumberMax attempts before the step (and run) fails.
backoff'fixed' | 'exp'Constant or doubling delay between retries.
backoffMsnumberBase delay in ms.
backoffMaxMsnumberUpper bound on the (exponential) delay.
jitterbooleanRandom 50–100% jitter to avoid thundering herds.
timeoutMsnumberLiveness window; no result/heartbeat within it fails the dispatch with RemoteStepTimeout (retryable).

@DeadLetter()

Marks a method on a @Workflow class as its inline dead-letter handler — registered as <workflow>.dlq, receives a DeadLetter payload ({ deadRunId, workflow, input, error? }) when a run of the class is moved to dead. Takes precedence over deadLetterWorkflow. See Dead-letter queue.

@OnError(match?)

Marks a method on a @Workflow class as the handler workflow for a failure of its runs: when a run ends failed with an error whose code matches (an error class with a static code, or the code string; no argument for the catch-all), the engine starts the method as <workflow>.onError.<method> with an OnErrorInput and the run settles with its outcome. Typed against run's input and output; stackable. @Workflow({ onError: [{ code?, workflow }] }) routes to a separate workflow, and the engine's register / registerRemote take the same onError option. See Routing a run's failure.

@Entity(options) / @On(op)

@Entity({ name }) marks an @Injectable() class as a durable entity (a keyed virtual object, constructible with no arguments); @On(op) marks a method as the handler for operation op, run serialized per key over durable state. Drive with EntityService or ctx.callEntity/signalEntity. See Durable entities.

@OnDurableEvent(...events)

Class decorator subscribing a @Workflow to one or more events — equivalent to @Workflow({ onEvent }); multiple declarations and the option are merged. Named "durable" to avoid clashing with @nestjs/event-emitter's @OnEvent. Each event is a name or a { event, where, input } entry. See Event-driven workflows.

@OnWorkflowCompleted(workflow, options?) / @OnWorkflowFailed(workflow, options?)

Class decorators that start the decorated @Workflow whenever a run of workflow (a class or a registered name) completes, or ends failed, cancelled or dead. They subscribe to the lifecycle events run.completed:<workflow> / run.failed:<workflow> (runCompletedEvent / runFailedEvent). Exactly once per settled run and subscriber. See Reacting to another workflow finishing.

OptionTypeNotes
where(event: LifecycleEventOf<C>) => booleanStart only for the settled runs it accepts.
input(event: LifecycleEventOf<C>) => TRunInputThe started run's input. Default: the WorkflowLifecycleEvent itself.
statusesArray<'failed' | 'cancelled' | 'dead'>@OnWorkflowFailed only. The endings that start it; default all three.
debounce{ windowMs: number | string; key?: (input: TRunInput) => string }Start once events have been quiet for windowMs, per key when given. Sets the workflow's coalescing; not with batch, and a different @Workflow({ debounce | batch }) fails at registration. Two decorators on one workflow must agree; keys compare by source text (key.toString()), so keys written differently fail.
batch{ maxSize: number; windowMs: number | string; key?: (input: TRunInput) => string }Start with { events: TRunInput[] } once maxSize arrive or windowMs passes, per key when given. Same rules as debounce.

With a class ref, the decorated workflow's run must accept TRunInput (or the event), or the decorator does not compile. Links: triggeredRuns(runId), lifecycleSourceOf(run), lifecycleRunId(sourceRunId, kind, subscriber), triggeredRunsOf(run), parseLifecycleEvent(event) ({ workflow, kind } for a run.completed:* / run.failed:* name). LIFECYCLE_TRIGGER_FAILED_TAG_PREFIX (durable:trigger_failed:) tags a settled run once per subscriber whose start from its lifecycle event failed (read with triggerFailedSubscribersOf(tags); a later successful start removes it). LIFECYCLE_COALESCED_TAG_PREFIX (durable:coalesced:) tags it once per subscriber whose debounce/batch accumulator the event was routed into (read with coalescedSubscribersOf(tags)). isLifecycleTag covers both, so they stay out of the event's tags. LIFECYCLE_TRACE_TAG_PREFIX (durable:lifecycle:trace:) is the tag holding a run's root span traceparent (written with its first suspend or its terminal write), read with lifecycleTraceparentOf(tags). The subscription registry: LIFECYCLE_REGISTRY_WORKFLOW (__lifecycle_registry), lifecycleRegistryRunId(instanceId), LifecycleRegistryEntry ({ instanceId, runtime: 'node', engineNamespace: string | null, subscriptions: { workflow, events }[] }, a registry run's input; engineNamespace is null for an engine with no namespace), lifecycleRegistrySubscriptions(input), lifecycleRegistryNamespace(input, rowNamespace) (the namespace whose runs owe to a registry run's subscriptions, null for every namespace; a row without engineNamespace stored under default reads as every namespace), LIFECYCLE_REGISTRY_TAG (durable:lifecycle:registry), LIFECYCLE_REGISTRY_HEARTBEAT_MS (10s), LIFECYCLE_REGISTRY_TTL_MS (35s), LIFECYCLE_REGISTRY_STALE_MS (10 min), and retentionKeeps(tags), which a store's pruneTerminalRuns checks so it keeps owed and registry runs. LIFECYCLE_PENDING_TAG with no owed tag marks a run whose owed set is unresolved (settled with no usable read of the fleet's announcements); the first publish with a good read resolves it. LIFECYCLE_HEAL_WINDOW_MS (2 min) is how long after settle the sweep still heals a run that missed a newly announced subscriber. triggeredSubscribersOf(tags) reads a run's durable:triggered:* subscribers. ACCUMULATOR_SEEN_MAX (1000) is how many routed event ids a debounce/batch accumulator remembers across bursts, so a lifecycle event published twice counts once.

@StepInterceptor()

Marks an @Injectable() class implementing intercept(invocation: StepInvocation, next: () => Promise<unknown>): Promise<unknown> as onion middleware around every LOCAL step's real execution (first-declared runs outermost). Fires only when a step actually executes, never on replay.

WorkflowHandler<TInput, TOutput, A>

Optional, TYPES-ONLY contract (exported from @dudousxd/nestjs-durable-core) for a @Workflow class's run method: implements WorkflowHandler<TInput, TOutput, A> pins the signature against TInput/TOutput/the run's SearchAttributes shape A, so a wrong signature (renamed method, swapped/missing param, wrong return type) is a compile error at the class instead of a runtime discovery failure or a silently wrong type flowing out of ctx.child/engine.start. Nothing reads it at runtime — registration is still via @Workflow + reflected metadata; a class that skips it works exactly as before.

MemberSignatureNotes
runrun(ctx: WorkflowCtx<A>, input: TInput): Promise<TOutput> | TOutputThe pinned workflow body. Pass A (see InferSearchAttributes) to narrow ctx.upsertSearchAttributes inside the body when paired with a @Workflow({ searchAttributes }) schema.

implements WorkflowHandler does not contextually infer run's parameter types the way an object literal assigned to a typed variable would — annotate ctx/input on the method yourself. The interface only checks that what you wrote is assignable; it doesn't write the annotations for you.

DurableWorkflow (class-first statics)

Optional base class — @Workflow classes that extend it start from the class itself, with input/output types inferred from their own run signature. See Class-first starts.

MemberSignatureNotes
startstatic start<C>(this: C, input: WorkflowInputOf<C>, opts?: { id?: string } & StartOptions): Promise<RunResult>Fire-and-forget everywhere: engine.start outside a workflow; ctx.startChild (parent-linked, checkpointed) inside one. opts.id pins the run/child id.
executestatic execute<C>(this: C, input: WorkflowInputOf<C>, opts?: { id?: string; timeoutMs?: number } & StartOptions): Promise<WorkflowOutputOf<C>>Run-and-await everywhere: ctx.child inside a workflow; start + wait-until-terminal outside (throws FatalError if the run didn't complete). timeoutMs bounds the outside wait.

Related helpers: currentWorkflowCtx() returns the ambient WorkflowCtx on the executing body's async path (or undefined outside one); bindWorkflowClass(ctor, client) is what the registrar calls at boot to bind each class to the engine that registered it.

Ambient step logger

Context-local access to the running step's StepLogger, so code deep inside a handler can record events without the logger being threaded through every signature. See Emitting from deep inside a step.

MemberSignatureNotes
currentStepcurrentStep(): StepLogger | undefinedThe logger of the step running on this async path — undefined outside one. Concurrent steps each see their own.
runInStepLoggerrunInStepLogger<T>(logger: StepLogger, fn: () => T): TEngine-internal: binds the SAME logger the step body receives as its second argument.
debug info warn error(message: string, data?: unknown): voidPer-level shortcuts, one per method on StepLogger. The idiomatic form when the level is known at the call site. No-op outside a step.
loglog(level: 'debug' | 'info' | 'warn' | 'error', message: string, data?: unknown): voidSame emission with the level as a value — literal twin of the Python SDK's log(level, …). Reach for it when the level is computed. No-op outside a step.
subsub(name: string, status: 'ok' | 'failed' | 'skipped', message?: string, data?: unknown): voidNo-op outside a step.
subEventsubEvent(e: { id; name; group?; phase?; status?; message?; data? }): voidNo-op outside a step.
subProcesssubProcess<T>(name: string, body: (sp: SubProcessHandle) => Promise<T> | T, opts?: { group?; id? }): Promise<T>Outside a step the body still runs (and still gets a handle); only the emission disappears.

WorkflowService

Injectable NestJS-facing entry point (packages/nestjs/src/workflow.service.ts) — a thin pass-through to the WorkflowEngine it wraps.

MemberSignatureNotes
startstart<C extends WorkflowClass>(workflow: C, input: WorkflowInputOf<C>, runId?: string, opts?: StartOptions): Promise<RunResult>Enqueue a run (pending) and return immediately; a worker executes the body. runId defaults to a random id — pass your own for idempotent starts.
resumeresume(runId: string): Promise<RunResult>Resume a run's next turn. Explicit: it also re-drives a failed run (a manual retry — prefer the engine's requeue, which resets the failure state first). The engine's own implicit wake-ups (signals, step results, timers, redelivered dispatches) never re-drive a failed run. Completed/cancelled/dead runs are never re-executed.
waitForRunwaitForRun(runId: string, opts?: { timeoutMs?: number; until?: 'settled' | 'terminal' }): Promise<RunResult>Resolve once the run settles (terminal or suspended); until: 'terminal' waits past suspensions until completed/failed/cancelled/dead. Pair with start when a request needs the outcome.
signalsignal(token: string, payload: unknown, opts?: { id?: string; idTtl?: string | number }): Promise<RunResult | null>Deliver an external signal to the run waiting on token. Resolves with the run's state after its turn; while the engine consumes a run queue, once the wake is queued (use waitForRun for the outcome). With id, a re-send with the same token and id is dropped and resolves null (dedupe). On a tenant it is a run request to the control plane, scoped to the tenant's partition and never buffered (tenant).
signalWithStartsignalWithStart<C extends WorkflowClass>(workflow: C, input: WorkflowInputOf<C>, runId: string, signal: { token: string; payload?: unknown }, opts?: StartOptions): Promise<{ runId: string }>Ensure the run exists, then signal it — race-free (buffered if the run isn't waiting yet). The durable-entity / accumulator pattern. On a tenant the signal is buffered only when its token contains runId (tenant).
publishEventpublishEvent(name: string, payload: unknown, opts?: { id?: string }): Promise<number>Resume every run parked on ctx.waitForEvent(name, …) and start every @Workflow({ onEvent }) subscriber; returns the count touched. On a tenant: starts the app's own subscribers and resumes its partition's waiting runs, buffering nothing.
triggeredRunstriggeredRuns(runId: string): Promise<string[]>The runs this run's settling started through a lifecycle event, read from its durable:triggered:* tags. Empty while it has not settled.
republishLifecyclerepublishLifecycle(target: RepublishLifecycleTarget): Promise<RepublishLifecycleResult>Publish settled runs' lifecycle events again, without the marker. target is { runId, subscriber? } or { workflow, kind?, since?, until?, subscriber?, limit?, namespace? } (limit a positive integer, default 1000; namespace defaults to the engine's own, and one other than a namespaced engine's is rejected). Subscribers already started are not started again; a subscriber that does not subscribe to a run's event in its namespace is reported in failed and never written as owed. Backfills a subscriber that came up more than LIFECYCLE_HEAL_WINDOW_MS after the runs settled. Returns { runs, started, failed: { runId, subscriber, error }[] }.

WorkflowEngine (selected public surface)

WorkflowService and the decorators cover most app code; reach for the engine directly (injectable) for dashboard/control-plane operations. This is a curated subset, not the full class.

MemberSignatureNotes
startstart(workflow: WorkflowRef, input: unknown, runId: string, opts?: StartOptions): Promise<RunResult>Create + enqueue a run. Idempotent by runId — a redelivered runId returns the existing run's state. opts.version starts that exact registered version instead of the newest (throws if it isn't registered — never falls back). opts.startAt (epoch ms or Date) delays the start: the run is parked suspended on its durable wake timer until then (see Delayed start).
signalsignal(token: string, payload: unknown, opts?: { id?: string; idTtl?: string | number }): Promise<RunResult | null>Deliver a signal; buffers it if no run is waiting yet (reliable regardless of arrival order). While the engine consumes a run queue it resolves once the wake is queued. id deduplicates per token for signalIdTtl (default 7 days).
signalWithStartsignalWithStart(workflow: WorkflowRef, input: unknown, runId: string, signal: { token: string; payload?: unknown }, opts?: StartOptions): Promise<{ runId: string }>Ensure-then-signal, race-free.
updateupdate(runId: string, name: string, arg: unknown): Promise<UpdateResult>Deliver a validated update to a run waiting at ctx.onUpdate(name). Runs the registered validator first; rejection never touches the run.
registerUpdateValidatorregisterUpdateValidator<TArg>(workflow: string, name: string, validate: UpdateValidator<TArg>): voidRegister (or replace) the validator gating update for a (workflow, name) pair. See Queries & updates.
getEventgetEvent<T = unknown>(runId: string, key: string): Promise<T | undefined>Side-effect-free read of the latest value a run published via ctx.setEvent.
publishEventpublishEvent(name: string, payload: unknown, opts?: { id?: string }): Promise<number>Same as WorkflowService.publishEvent.
cancelcancel(runId: string, opts?: { compensate?: boolean }): Promise<RunResult | null>Cancel a run. { compensate: true } resumes it first so registered saga undos run in reverse (status cancelling in the interim) before it settles cancelled. Terminal runs are immutable: on a completed/failed/cancelled/dead run (a timed-out run is cancelled) it is a no-op that returns the current state and never cascades to the run's children.
cancelWherecancelWhere(filter: Omit<RunQuery, 'limit' | 'offset'>, opts?: { compensate?: boolean }): Promise<RunResult[]>Bulk-cancel every run matching a RunQuery filter (workflow/status/tag/search-attribute), each through cancel.
retryWithInputretryWithInput(runId: string, input: unknown, newRunId?: string): Promise<{ runId: string } | null>Fix-and-replay: start a NEW run (default id <runId>~retry~<uuid>) with corrected input, clean history; the original stays inspectable.
schedulesScheduleClient — create/upsert/get/list/pause/resume/trigger/delete/tickPersisted, runtime-managed schedules (cron + timezone or interval, jitter, overlap, catch-up), multi-worker safe. See Persisted schedules.
deleteRundeleteRun(runId: string): Promise<number>Hard-delete a run and its whole child subtree (cascades depth-first). Returns the count removed. Prefer cancel for a still-live run.
purgeRunspurgeRuns(scope: RunScope, opts?: { batchSize?, cancelLive?, children? }): Promise<number>Hard-delete every run matching scope (namespace/tags/workflows/attributes) with their child subtrees, in batches; live runs are cancelled first. Rejects an empty scope. See Retention.
purgeNamespacepurgeNamespace(namespace: string, opts?): Promise<number>purgeRuns({ namespace }) — every run a tenant/partition owns.
getRunChildrengetRunChildren(parentRunId: string): Promise<string[]>Ids of the runs this run spawned (awaited ctx.child + fire-and-forget ctx.startChild), stable even after they finish.
waitForRunwaitForRun(runId: string, opts?: { timeoutMs?: number }): Promise<RunResult>Same as WorkflowService.waitForRun.
completeTaskcompleteTask(runId: string, name: string, result: unknown): Promise<RunResult | null>Report a ctx.task(name, …)'s async result back to its run.
failTaskfailTask(runId: string, name: string, error: string): Promise<RunResult | null>Report a ctx.task failure — the run resumes and throws a FatalError at the task.
onDeadonDead(listener: (run: WorkflowRun) => void): () => voidSubscribe to dead-lettered runs (moved to dead past maxRecoveryAttempts or unregisteredWorkflowGraceMs). Returns an unsubscribe fn.
onEnqueuedonEnqueued(listener: (runId: string) => void): () => voidSubscribe to runs enqueued on ANOTHER instance (control-plane broadcast) — a worker can pick them up immediately instead of waiting for its next poll.
runEnqueuedrunEnqueued(runId: string): voidRun an announced run here if it is still pending, at most 256 at once per instance. The onEnqueued handler the Nest module installs.
consumeRunsconsumeRuns(): (() => Promise<void>) | undefinedConsume the transport's run queue and, from then on, queue the runs this engine starts there instead of running them in-process. The Nest module calls it on every driving operator; call it yourself only on an engine you build by hand. Returns a stop function, or undefined when no transport carries a run queue.
onCancelonCancel(listener: (runId: string) => void): () => voidSubscribe to cancellations on ANY instance — for cooperative in-flight abort.
onStalledonStalled(listener: (info: StalledRunInfo) => void): () => voidPager hook for stranded runs, swept by the timer poller once a minute and reported once per stranded episode. See Stalled runs.
sweepStalledsweepStalled(now?: number): Promise<StalledRunInfo[]>Detect stranded runs and notify onStalled listeners. Throttled to a pass a minute; a no-op without listeners or while draining.
listStalledRunslistStalledRuns(opts?: { thresholdMs?, scan?, now? }): Promise<StalledRunInfo[]>The stranded runs right now, in this engine's namespace, without notifying anyone. The standalone findStalledRuns(store, opts) runs the same query on a bare store.
listCheckpointslistCheckpoints(runId: string): Promise<StepCheckpoint[]>A run's checkpoint timeline (pass-through to the store), e.g. for captureHistory.
draindrain(timeoutMs?: number): Promise<void>Graceful shutdown: stop picking up new runs, wait for in-flight executions up to timeoutMs (default 10000). On timeout, releases (owner-scoped) and fences the leases of the runs still executing so another instance recovers them at once.
workerHealthworkerHealth(extra?: string[]): Promise<GroupHealth[]>Per-group queue backlog + live worker heartbeats (only transports that support introspection, e.g. BullMQ).
recoverIncompleterecoverIncomplete(nowMs?: number): Promise<RunResult[]>Resume every run left running by a crash/deploy. Call on boot.
sweepLifecycleEventssweepLifecycleEvents(nowMs?: number, limit?: number): Promise<number>Publish the lifecycle event of settled runs still tagged durable:lifecycle:pending to the owed subscribers this instance has (the settling process died, or did not have them), resolving the owed set of a run marked unresolved, leaving runs settled in the last 30s to the live publish. Then heals runs settled in the last LIFECYCLE_HEAL_WINDOW_MS that missed a subscriber this engine first saw in that window (one listRuns with updatedAfter per source workflow, at most 100 runs). Each run is published under its lease (tryLockRun), so concurrent publishers never overwrite each other's tags; a run whose lease another publisher holds waits for the next tick. Drops owed subscribers nobody announces 24h after settle (run.trigger_failed), and delivers ctx.waitForRun waits whose run settled (sweepRunWaits). Pages through the marked runs (limit per page, default 100), skipping the ones it cannot act on, until it has acted on limit runs or examined 1000. Subscribers only live workers announce are started here too when the engine can reach them by name (a live worker group of that name). Refreshes this engine's lifecycle registry run first (heartbeatLifecycleRegistry). Called by the timer poller. Returns how many runs it published.
heartbeatLifecycleRegistryheartbeatLifecycleRegistry(): Promise<void>At most once per 10s: write this engine's onEvent subscriptions as its __lifecycle_registry:<instanceId> run (completed, subscriptions in input, updatedAt the heartbeat; nothing for an engine with no subscriptions), and delete registry runs not refreshed for 10 minutes. Other engines count a registry run refreshed in the last 35s as announced subscriptions, whatever the transport. Called by sweepLifecycleEvents.
sweepRunWaitssweepRunWaits(limit?: number): Promise<number>Resume ctx.waitForRun waiters whose run settled without resuming them: checks waited-on runs in waiter order, skipping unsettled ones, until it has resumed the waiters of limit runs (default 100) or checked 1000. Returns how many waiters it resumed. Called by sweepLifecycleEvents.
republishLifecyclerepublishLifecycle(target): Promise<RepublishLifecycleResult>See the WorkflowService row above. Subscribers registered here start here; one only another worker announces is owed the event again, for that worker's sweep.
workflowLifecycleworkflowLifecycle(workflow: string, opts?: { namespace?: string }): Promise<WorkflowLifecycleLinks>With namespace, only that namespace's subscriptions (registry runs in it, worker descriptors serving it, this engine's own when it is that namespace's engine; no namespace counts as default). Who starts whom, for one workflow: { workflow, startsOnSettle, startedBy }, each a LifecycleSubscriptionLink[] of { workflow, kind, local, announced, where, input, coalesce?: { mode, keyed } }, from this engine's registry and the live fleet's announcements. What the dashboard's workflow page lists.
setRunTraceparentsetRunTraceparent(provider: ((runId: string) => string | undefined) | undefined): voidInstall (or remove) the function answering a run's span traceparent in this process. attachDurableOtel installs one. With it, the terminal write of a run some workflow subscribes to records a durable:lifecycle:trace:<traceparent> tag, and a lifecycle-started run's run.started event carries sourceTraceparent.
lifecycleSubscriberslifecycleSubscribers(workflow: string, kind: 'completed' | 'failed', namespace?: string): Promise<string[]>The workflows a run of workflow in namespace settling as kind owes its lifecycle event to (without namespace, any namespace's): registered here when this engine publishes that namespace's runs (an engine with no namespace publishes every namespace's), or announced for that namespace by the fleet: the fresh lifecycle registry runs in the state store of engines in that namespace or with none, and subscribes on live worker descriptors serving it where the transport reads them; read at most every 5s.
resumeDueTimersresumeDueTimers(nowMs?: number): Promise<RunResult[]>Resume suspended runs whose durable timer is due: at most timerBatchSize per pass (a WorkflowEngine constructor option, default 500), most overdue first, walked in shuffled order. Call periodically.
runPendingrunPending(nowMs?: number): Promise<RunResult[]>Pick up and execute every pending run (poll-based dispatch for a broker-less worker pod).
sweepTimeoutssweepTimeouts(now?: number): Promise<void>Cancel in-flight runs that outlived their @Workflow({ executionTimeout }), cascading to their children exactly as cancel does.
continuecontinue(runId: string): Promise<RunResult | null>Resume a run paused at ctx.breakpoint (the dashboard "continue" button). null if not paused there.
getRungetRun(runId: string): Promise<WorkflowRun | null>Read a run's current persisted state.
registerEntityregisterEntity<S>(name: string, config: EntityConfig<S>): voidRegister a durable entity's handlers + initial state.
useuse(interceptor: StepInterceptor): () => voidRegister a StepInterceptor (onion middleware around real local-step execution).
subscribesubscribe(listener: EngineListener): () => voidSubscribe to every EngineEvent (lifecycle events) the engine emits.

engine.runSchedules is not a method — runSchedules(engine, schedules, nowMs, opts?) is a standalone function (exported from @dudousxd/nestjs-durable, and from -core) that starts each ScheduledWorkflow's current time-bucket run id (idempotent via engine.start) and returns the ids it started — a window that already has a run is skipped, and not returned. The NestJS module's schedules option wires it to the timer poller automatically; call it yourself to fire schedules from your own trigger. scheduleRunIdAt(schedule, nowMs) returns the run id of a schedule's window at nowMs, for looking a window's run up with getRun.

DurableModuleOptions

Options for DurableModule.forRoot / forRootAsync. The role (operator / thin worker / operator + co-located worker) is inferred from which of store / connection are set.

OptionTypeDefaultNotes
storeStateStore—Set to play the operator role. See State stores.
transportTransport—Single task transport. Required alongside store. See Transports.
transportsNamedTransport[]—Ordered pool for failover / multi-broker, instead of transport.
controlPlaneControlPlanefirst broadcast-capable transportCross-instance lifecycle-event + cancellation pub/sub.
timerPollMsnumber1000Durable-timer poller interval; 0 disables it. Operator only.
maxIdleIntervalMsnumber5000Longest wait between timer polls while idle: the wait doubles from timerPollMs up to this after polls that find nothing, never past the next due timer, blocked-run poll or schedule window, and drops back to timerPollMs on any run event or enqueue nudge. Only recovery (crashed runs, execution timeouts, housekeeping sweeps) waits up to this long. At or below timerPollMs, or without a control plane or run queue, the tick stays fixed. Operator only.
owedLifecycleSweepMsnumber10000How often the poller lists settled runs that still owe a lifecycle event (and heals runs that missed a new subscriber); run waits are still swept every poll. A failed listing is retried on the next poll. 0 lists on every poll. Operator only.
autoSchemabooleantrueAuto-create durable tables via store.ensureSchema() on boot. Turn off in production; migrate instead.
namespacestringunset = operatorWorker-pool partition; poll paths only act on runs in this namespace. See Tenancy.
leaseMsnumber30000Multi-instance recovery-lease duration. Operator only.
instanceIdstringrandomUnique id for this instance (leases, worker heartbeats).
maxRecoveryAttemptsnumberunlimitedCap recovery attempts before a poison-pill run moves to dead. See Dead-letter queue.
unregisteredWorkflowGraceMsnumber24hHow long a run may stay due with its workflow@version registered nowhere before it moves to dead (workflow_not_registered). 0 disables. See Dead-letter queue.
remoteAdvanceSilenceMsnumberreconcileMs for a dispatched turn, else unboundedLiveness deadline for a remote (polyglot or tenant) workflow advance; each heartbeat rearms it. A turn dispatched over a broker falls back to reconcileMs, so a run whose worker died mid-turn is re-driven. Operator only.
reconcileMsnumber300000Fallback re-drive for a run suspended on an event whose wake-up was lost, and the default window of a dispatched workflow turn; 0 disables both. Operator only.
remoteRedispatchMsnumberoffLease of a dispatched remote step with no timeoutMs: past it with no result or heartbeat, the step is dispatched again (up to remoteRedispatchMax, default 10). Off by default because it re-runs a slow step; the step must be idempotent. See Retries. Operator only.
stalledAfterMsnumber900000Idle time before a stranded run is reported to onStalled listeners (floored at 60000). Operator only.
onStalled(info: StalledRunInfo) => voidnoneRegistered as engine.onStalled(...); the timer poller of a driving operator sweeps once a minute. See Stalled runs.
timerBatchSizenumber500Most due timers one timer-poll pass loads and drives, most overdue first. A non-finite or sub-1 value falls back to 500. Operator only.
eventBufferTtlMsnumberkeep until consumedRetention for a buffered event no waitForEvent claims; pruned by the reconcile pass. Operator only.
blockedPollMsnumber5000How often a run parked blocked (no capable live worker) re-checks the fleet. Operator only.
trackStepStartbooleantruePersist a running checkpoint when a local step starts; false halves checkpoint writes on hot paths. Operator only.
deadLetterWorkflowWorkflowRefnoneDefault DLQ target for workflows without their own. On a tenant, announced as the route of its workflows without their own, which the control plane starts on the tenant.
drivebooleantrueWhether this operator instance actively drives runs (poll/recover/resume/prune/consume). false = dashboard/dispatch-only.
shutdownTimeoutMsnumber10000Max ms to wait for in-flight runs on shutdown. Operator only.
schedulesScheduledWorkflow[]noneRecurring workflows (fixed interval or cron), fired by the timer poller on driving instances (on a tenant, announced to the control plane, which fires them). Each workflow is a @Workflow class (resolved at boot; ScheduledWorkflow<typeof X> types input) or a registered name. See Scheduling.
persistedSchedulesbooleanfalseFire the runtime-managed engine.schedules (stored in durable_schedules) on each timer-poll tick. See Persisted schedules.
announcedSchedulesboolean | { syncMs?, graceMs? }onControl plane: adopt and fire the schedules tenant apps announce (needs a store that persists schedules and a transport that reads worker descriptors). syncMs 15 s, graceMs 10 min before a schedule no longer announced is paused. See Schedules on a tenant.
retentionDurableRetentionOptions ({ policies, sweepInterval?, batchSize? })keep all historyHard-prune terminal run history on an interval. See Run retention & pruning.
webhookUrl(token: string) => stringnone (build your own)Builds DurableWebhook.url for ctx.webhook(). Operator only.
queuesQueueConfig[]noneFlow-control queues registered on the engine at startup. See Flow control.
admissionAdmissionBackendin-process capsBackend for queues — pass a Redis-backed one to make limits fleet-global. Operator only.
traceparent() => string | undefinednoneCurrent W3C traceparent to stamp on dispatched remote tasks. Operator only.
context() => Record<string, unknown> | undefinedauto-fed from @dudousxd/nestjs-context if installed, else noneOpaque context carrier (tenant/user/correlation ids) stamped on dispatched step tasks and workflow turns. The auto-fed carrier is Context.serialize(), so nestjs-context's carrier: [...] allowlist decides what reaches the broker. A worker role (co-located or thin) with @dudousxd/nestjs-context restores it around each dispatched turn and step through Context.deserialize, so your deserialize decides what a handler sees. The engine applies a turn's decision under the carrier it stamped on that turn (kept in memory, so a decision applied by another instance gets that instance's own context) and never reads one back from a worker. Trace continuity is first-turn only: a later turn (after a step result, a signal or a timer) carries a fresh carrier from wherever it is dispatched. Operator only.
compensationRetriesnumber1Attempts per IN-PROCESS (ctx.localStep) saga compensation on run failure. A dispatched (ctx.step) compensation retries per its own @Step config instead. Operator only.
scopeReadsbooleanfalseConfine the store's reads to namespace (tenant-boundary view) instead of the operator (all-namespaces) view. Needs a store with withScope.
connectionstring | Record<string, unknown>—ioredis connection for a thin worker or a co-located worker consumer. Set to play a worker role.
partitionstring'default'Isolation partition a worker role serves/dispatch-suffixes (<name>@<partition>). Required with topology: 'tenant'; on topology: 'control-plane' it also becomes the namespace the control plane drives. Ignored for a plain operator.
prefixstring'durable'Key prefix namespacing the durable queues for a worker role's consumer. Ignored for a plain operator.
concurrencyConcurrencyOption (number | 'adaptive' | { mode: 'adaptive', ... })1Tasks a worker role's consumer runs concurrently per subscribed queue. Ignored for a plain operator.
concurrencyByHandlerRecord<string, ConcurrencyOption>falls back to concurrencyPer-name BullMQ concurrency for a worker role's consumer (co-located or thin). The key is the exact @Workflow({ name }) / @Step(name) string, namespace included (e.g. agent.opencode.run). Each overridden queue reports its own limit and in-flight count on the heartbeat; a name this process does not register is ignored with one warning per process.
lockDurationnumber (ms)300_000BullMQ lockDuration of a worker role's consumer. Also how long a dead worker's task waits before BullMQ redelivers it. Ignored for a plain operator.
stalledIntervalnumber (ms)BullMQ's (30_000)BullMQ stalledInterval of a worker role's consumer. Ignored for a plain operator.
maxStalledCountnumberBullMQ's (1)BullMQ maxStalledCount of a worker role's consumer. Ignored for a plain operator.
runGatewayTimeoutMsnumber10000Timeout for a thin worker's RunGateway round-trip over transport (also its signal, signalWithStart and publishEvent). Ignored for an operator.
verifyTenantTenantVerifier | TenantVerifierContract, a class implementing it, or a lazy import of onenone = wire tenant trusted verbatimOperator. Verifies the signed token a tenant presents in the wire tenant field of each run request and start-run, and derives the tenant from it. Invalid/absent tokens get an unauthorized reply (run requests) or create nothing (start-runs). Use hmacTenantVerifier(secret | secrets[]), or see Authenticate tenants. A class is built once through Nest DI.
tenantTokenstring | () => string | Promise<string> | TenantCredentialsContract, a class implementing it, or a lazy import of onenone = raw partition is sentTenant worker. Signed token (from signTenantToken) presented in the tenant field of every proxied run request and engine.start. Every form but the string is called before each request and owns its caching. Live-tail stays keyed by the partition.
topology'standalone' | 'control-plane' | 'tenant''standalone' = role inferred from store/connectionNames the process role and validates its options; 'tenant' forbids store at compile time. See Roles & config.

Run detail and fan types

Exported from @dudousxd/nestjs-durable-core. Used by the RunGateway and the dashboard.

Type / functionShapeNotes
RunDetail{ run, timeline, children, fans?, childCount?, triggered?, triggeredBy?, lifecycleSubscribers?, workflowLifecycle?, lifecycleDeliveries?, waitsFor?, awaitedBy?, etag?, notModified? }What getRunDetail returns. triggeredBy is a LifecycleSource ({ runId, kind, status?, namespace?, traceId? }); lifecycleDeliveries a LifecycleDelivery per subscriber of a settled run ({ subscriber, state: 'started' | 'owed' | 'coalesced' | 'failed' | 'not-started', runId?, status?, namespace?, owedSince?, orphanAt?, error? }; failed is read from a durable:trigger_failed:<subscriber> tag, and error is left unset since the message is not stored, built by lifecycleDeliveriesOf(run, { subscribers, live, coalesced }) with engine.coalescedSubscribers(run)); waitsFor / awaitedBy the ctx.waitForRun waits on either side (RunWaitLink: { runId, seq, status?, namespace? }). When summarized, timeline omits the members of each summarized fan, fans holds one FanSummary per fan, and children lists at most 200 ids with childCount as the total. etag is set when the gateway can version the detail without reading the timeline. notModified: true means ifNoneMatch matched it: only run was read, and timeline and children are empty.
RunGateway.workflowLifecycleworkflowLifecycle?(workflow: string, opts?: { namespace?: string }): Promise<WorkflowLifecycleLinks>Optional on the port: the store-backed gateway and the tenant proxy implement it (same version-skew error as republishLifecycle). Over the proxy the operator scopes it, and a run detail's workflowLifecycle / lifecycleSubscribers, to the tenant's namespace. The dashboard's GET workflows/:name/lifecycle calls it (501 without it), and RunDetail.workflowLifecycle carries the same for the run's workflow.
RunGateway.lifecycleSubscriberslifecycleSubscribers?(workflow: string, kind: LifecycleKind, namespace: string): Promise<string[]>Optional on the port: the store-backed gateway implements it with engine.lifecycleSubscribers. The run-request responder checks a tenant republish's subscriber against it (falling back to the tenant's workflowLifecycle links).
RunGateway.republishLifecyclerepublishLifecycle?(target: RepublishLifecycleTarget): Promise<RepublishLifecycleResult>Optional on the port: the store-backed gateway and the tenant proxy implement it. Over the proxy a { runId } target is refused for another tenant's run (cross-tenant) and a { workflow } one is read over the tenant's namespace only, with at most 1000 runs (a larger limit is lowered to it); a limit that is not a positive integer, or a subscriber that does not subscribe to the workflow in the tenant's namespace, is refused with code bad-request (BAD_RUN_REQUEST; the dashboard answers 400; the cap is TENANT_REPUBLISH_MAX_LIMIT); an operator too old for the verb fails it with a RunGatewayError whose code is unsupported-request (the dashboard answers 501). The dashboard's POST runs/:id/republish-lifecycle calls it, behind the same gate as retry and cancel. lifecycleSubscribers on a settled run's detail lists who it would publish to.
RunDetailOptions{ summarizeFansOver?: number; ifNoneMatch?: string }Summarize every fan with more than this many members, or declared wider than that. Unset returns the full detail. ifNoneMatch is an HTTP If-None-Match value. A gateway that cannot version the detail ignores it.
FanSummary{ group, label, firstSeq, lastSeq, size, total?, notStarted?, failFast, counts, startedAt?, finishedAt?, failures }label is the members' step name, or child runs. size counts members started (a folded checkpoint counts as the children it stands for); total is the declared size from the group; notStarted is total - size. counts is per status, with a failed child counted as failed. failures holds the first 20 failed members.
FanPageQuery{ offset?, limit?, failedOnly?, ifNoneMatch? }offset defaults to 0; limit to 100, clamped to 1–500. ifNoneMatch works as on RunDetailOptions.
FanPage{ items: StepCheckpoint[]; total: number; etag?; notModified? }One page of a fan's members in seq order; total counts every member matching the query. etag and notModified work as on RunDetail. A notModified page carries no members: items is empty and total is 0 as placeholders.
summarizeTimeline(timeline, over)→ { timeline, fans }Split a run's checkpoints into the listed ones and the summarized fans.
summarizeFan(group, members)→ FanSummarySummarize one fan's members.
pageFan(timeline, group, query)→ FanPageOne page of a fan out of a run's checkpoints.
childIdsOf(timeline)→ string[]The child run ids a run's checkpoints reference.
CheckpointStat{ group, status, nameKind, count, minSeq, maxSeq, minName, maxName, minEnqueuedAt, minStartedAt, maxStartedAt, maxFinishedAt, sumAttempts }One bucket of StateStore.checkpointStats. group is null for ungrouped checkpoints; nameKind is child, folded, spawn or step.
CheckpointQuery{ group?, excludeGroups?, statuses?, namePrefixes?, offset?, limit? }What StateStore.queryCheckpoints selects, in seq order.
summarizeRunFromStore(store, runId, over, stats?)→ Promise<{ timeline, fans, children, childCount }>The summarized detail, built from the store's aggregates. Equal to summarizeTimeline plus childIdsOf over a full read.
pageFanFromStore(store, runId, group, query, stats?)→ Promise<FanPage>pageFan, read one page at a time from the store.
checkpointStatsOf(checkpoints, { group? }) / queryCheckpointsOf(checkpoints, query)→ CheckpointStat[] / → StepCheckpoint[]The in-memory references a store's checkpointStats and queryCheckpoints must agree with.
runDetailEtag(run, stats, over) / fanPageEtag(group, stats, query)→ stringThe ETags StoreRunGateway sends.
extendEtag(etag, extras)→ stringetag extended with a fingerprint of extras (what a detail reads from outside the run row and its checkpoints, such as a linked run's status); etag itself when extras is undefined.
etagMatches(ifNoneMatch, etag)→ booleanWeak If-None-Match comparison, * included.

A fan's parallelGroup is all:<firstSeq>:n<size>[:failFast] for children (older runs may carry all:<firstSeq>[:failFast]) and steps:<firstSeq>:<size>[:failFast] for steps.

Errors

All exported from @dudousxd/nestjs-durable-core.

ErrorThrown when
FatalErrornew FatalError(message, code?, details?) — thrown BY YOU inside a step/workflow for an unrecoverable business failure (e.g. a declined card) — the engine never retries it, in a local or a dispatched step, and fails the run immediately. code and details travel with the failure to the run's error, a parent's allSettled item or ctx.child catch, and an onError handler.
SignalTimeoutErrorctx.waitForSignal / ctx.waitForEvent / ctx.onUpdate's timeoutMs deadline passes before delivery. Catchable in the workflow to take a default branch.
SchemaValidationErrorA value failed a declared schema: @Workflow({ input, output }), @Step({ input, output }), or a searchAttributes schema (thrown by ctx.upsertSearchAttributes). A FatalError, never retried, whose code is invalid_input, invalid_output or (search attributes) schema_validation. issues and details.issues hold { message, path: string[] }[]; the message is invalid <what>: <path>: <message>; …. Its static code is schema_validation, and an onError route for it also catches invalid_input and invalid_output no route of their own matches. Same class, codes and shape as in @adonis-agora/durable.
NonDeterminismErrorOn resume, the step at a logical position has a different name/kind than its checkpoint — the workflow code changed under an in-flight run without a new @Workflow version. See Versioning & determinism.
NestedWorkflowCallErrorA ctx primitive (ctx.startChild/child/step/sleep/sideEffect/…, or a MyWorkflow.start()/.execute() static via the ambient ctx) was called from INSIDE a step body (ctx.localStep/transaction/sideEffect/now). Thrown at the call site, as a FatalError (code nested_workflow_call). See Troubleshooting.
ConcurrencyLimitErrorstart whose concurrency quota key already has limit runs in flight (key, limit, active, workflow). Nothing was created — shed load / answer 429. See Concurrency quotas.
SingletonQueueFullErrorstart on a singleton workflow whose in-flight + gated backlog already equals limit + maxQueueDepth. Back-pressure — retry later. See Singleton workflows.
GatherErrorctx.all — one or more children or steps of a fan failed; carries per-item { index, id, error } failures, where index is the input's position. Under failFast it carries the first failure seen.
RemoteStepTimeoutA dispatched step produces no result/heartbeat within its timeoutMs — the worker is presumed dead. Retryable, subject to the step's retries.
RemoteWorkflowTimeoutA remote WorkflowExecutor.advance produces no decision/heartbeat within its configured timeoutMs. Recoverable, not a run failure — the engine releases the lease and lets recoverIncomplete re-drive.
ContinueAsNewThrown internally by ctx.continueAsNew(input) to unwind the current run and hand off to a fresh execution. A control-flow signal — a workflow's catch must rethrow it untouched.
WorkflowSuspendedInternal control signal the engine throws to stop execution and persist wakeAt/suspension state. A control-flow signal — never throw or catch-and-handle it yourself; rethrow untouched.

Control-flow signals

WorkflowSuspended/ContinueAsNew above (and @dudousxd/durable-worker's Suspend, the thin worker's equivalent) are thrown internally to unwind the current turn — a durable sleep, a still-pending step, ctx.continueAsNew — never real failures. Because they're thrown with the same JS exception mechanism a real step failure uses, a workflow's own try/catch around a ctx.step/ctx.sleep/etc. can observe one — and MUST rethrow it untouched before running any cleanup/compensation, or the cleanup gets recorded as an extra history command during what replay will later see as a plain suspend, corrupting the run (NonDeterminismError on resume). See Sagas: the control-flow-signal pitfall and Troubleshooting.

ExportSignatureNotes
CONTROL_FLOW_SIGNALconst CONTROL_FLOW_SIGNAL: unique symbolSymbol.for('aviary:durable:control-flow') — the shared, global-registry marker stamped on every control-flow signal class, across package/module-instance boundaries. Rarely used directly; prefer isWorkflowControlFlowSignal.
isWorkflowControlFlowSignalisWorkflowControlFlowSignal(error: unknown): booleantrue for WorkflowSuspended, ContinueAsNew, or the thin worker's Suspend — regardless of which runtime threw it. Not true for Cancelled (a terminal, legitimately-catchable outcome) or a StepFailed/ordinary step rejection (a real failure a saga's catch is meant to compensate for).

Both are exported from @dudousxd/nestjs-durable-core and re-exported by @dudousxd/nestjs-durable.

Statuses

Run status (RunStatus)

StatusMeaning
pendingCreated + enqueued by start, not yet picked up.
runningA worker is actively executing (or replaying) this run's body.
suspendedParked with zero compute — on a sleep, a signal/event/update, an awaited step or child.
cancellingA compensating cancel({ compensate: true }) is in progress (saga undo running). Non-terminal.
completedFinished successfully. Terminal.
failedFinished with an unrecovered error. Terminal.
cancelledCancelled (with or without compensation). Terminal.
deadDead-lettered: crash-recovery gave up after maxRecoveryAttempts (a poison pill), or the run's workflow version stayed registered nowhere past unregisteredWorkflowGraceMs. Terminal.

Only completed / failed / cancelled / dead are terminal — eligible for retention pruning and never transition on their own again.

Checkpoint status (StepCheckpoint['status'])

StatusMeaning
pendingA remote step dispatched and awaiting its worker's result; the run is durably suspended.
runningA local step's body is executing in-process right now.
completedSettled successfully — short-circuits on replay (the step is NOT re-executed).
failedSettled with an error — re-awaited (remote) or re-run (local) on replay unless retries are exhausted.

On this page