Skip to content

Workflows API reference (taskq-py[flows])

The flow API — the authoring surface over the DAG engine. The import law: import taskq never imports this package; the only sanctioned entry is import taskq.workflows (or a submodule) by a caller that opted into the taskq-py[flows] extra. The engine is core-deps-only; the extra carries no requirements of its own.

The guides are the tutorial; this page is the dictionary — every verb row below is taught, with runnable fences, in the workflows guide (the wiring, the joins, the routes, the retry ladder, the deps seam, the body's three input channels); the rate-limiting guide owns the rate_limits= authoring face and WHICH execution door honors the buckets; the progress guide owns the run display + the listener faces. Start there if this page is your first contact with the engine.

The thirty-second tour

from pydantic import BaseModel
from taskq.workflows import Promise, StepContext, WorkflowApp, build, gather, sink, step

app = WorkflowApp()


class Ingest(BaseModel):  # plain types for DATA
    doc_id: str


class Report(BaseModel):
    ref: str


@app.actor(queue="cpu")  # the workflow decorator — NOT taskq.actor
async def fetch(ctx: StepContext, params: Ingest) -> Report:
    return Report(ref=f"r-{params.doc_id}")


@app.actor(queue="cpu")
async def summarize(ctx: StepContext, reports: list[Report]) -> dict[str, int]:
    return {"count": len(reports)}


@app.workflow("doc_ingest")  # the per-workflow declaration
def doc_ingest() -> Promise[object]:  # SYNC and PURE — the compile-time wiring
    # THE PLACEMENT LAW: the NODE's queue is the wiring's decision —
    # `step(queue=…)` — defaulting to "default". The decorator's
    # `queue="cpu"` declares the handle's own cohort (what the boot
    # projection and a workflow-only worker register); it does not place
    # the node. Pass `step(..., queue="cpu")` to run a node on the cpu
    # queue.
    fetched = step(fetch, Ingest(doc_id="d1"))  # Promise[Report]
    both = gather([fetched])  # the ALL-upstream join
    return build(step(summarize, both))  # the completeness point


compiled = app.get("doc_ingest")
compiled.validate()  # the checker-independent validator
print(compiled.mermaid())  # the compile-time Mermaid emission

Promise[T] is the wiring: a promise consumed downstream is an edge; a call with several promise arguments is the fan-in join whose user body IS that node's body. Plain types travel as data; nothing about the tree is STORED — the graph is spelled by the wiring and compiled fresh (same module → same compile, byte-stable).

The wiring verbs

verb signature notes
step(body, *args, key=None, actor="wf", queue="default", on_failure="fail_closed", max_attempts=None, retry_kind=None, skip=None, gates=(), progress_schema=None, rate_limits=(), max_concurrent=None, reservations=(), result_ttl=None, priority=None, start_to_close=None, cache=False, cache_ttl=None) → Promise[R] where R is the body's declared return promise args become the node's incoming edges (several = the fan-in); plain args are the node's data (in signature order). max_attempts=None is the UNSET sentinel: the wired actor handle's DECLARED max_attempts applies (the decorator's own default is not a declaration), else the three-attempt default — omitting and explicitly passing 3 are different declarations, and the step's explicit count overrides the handle's. skip is the DISPATCH-TIME predicate (refused on a fan-out source — map_source / route — as E22-skip-fan-out-source: skipping it never spawns the fork, so return [] from the source body instead). progress_schema= is the node's DECLARED progress payload schema (the body's ctx.progress emissions are validated against it). priority= is the node rows' claim ORDER (the value stamped into the jobs.priority column, which the dispatch claim's priority DESC orders by; None = the actor's declaration applies, or the column default 0 — the precedence law: the per-call run/create_flow override > the step's declaration > the actor's declaration > the default). THE CAPACITY TERMS (the same surface @app.actor declares — the explicit step param overrides the handle's, never the reverse): rate_limits= stamps the node's bucket names onto the row's metadata (honored at the fleet's dispatch claim; a denial snoozes the row budget-free); max_concurrent= is the per-round admission DAMPER seeded on the cohort's actor_config — NOT a strict cap (declare reservations= when the bound must hold); reservations= is the STRICT slots (a list of ConcurrencyReservation — the boot materializes their slot rows in the ensure-slots pass; an unnamed/malformed entry parks the row fail-closed, LOUD); result_ttl= is the node result's in-DB TTL in seconds (stamped on the SUCCEEDED terminal row from the cohort's stored term). max_pending is deliberately absent — the engine's inserts bypass the enqueue admission and a claim-side gate would wedge the backlog, so the knob stays vanilla-actor-only (never a dead knob). cache=True is the CROSS-RUN CACHE opt-in (see the guide's cache section): the result serves a later run over the same body + input; cache_ttl is the in-DB expiry's seconds (default 24h). THE CACHE HAZARDS (each refused at the wiring — E17/E18/E19/E20): the address covers the body's OWN source + the WIRED args — a changed HELPER is invisible to it (bump the body's own source when the closure changes); the FLOW input (ctx.input) never enters it (a body reading ctx.input is refused — the cross-tenant leak); a typed-route SOURCE carrying cache=True is refused (the hit path cannot rebuild the route fork — the wedged-forever run); an Exit-returning body is refused (the silent no-op); an unverifiable body source is refused (the silently-uncached step).
gather(promises, *, on_failure="fail_closed") list[Promise[A]] → Promise[list[A]] the ALL-upstream join, the FLAT shape — the ELEMENT TYPE PRESERVED (a homogeneous join over Promise[Report]s is a Promise[list[Report]]; a heterogeneous join upcasts to Promise[list[object]] honestly). gather([]) is refused at the verb (the stranded invisible join).
route(source, arms, *, queue="default", on_failure="fail_closed", max_attempts=3, aggregate=None, child_driven=False) Promise[list[S]] × Mapping[type, RouteArm[R] \| Callable] → Promise[list[R]] the TYPED ROUTE: the source's body returns the elements' list (list[Image \| Audio]), and arms keys the union MEMBERS' types to the arm bodies — each element runs ITS type's arm as a FRESH job (<source>.item:<module.qualname>), the arm's placement stamps its children's queue/actor, and the derived <source>.join packs the arms' returns VERBATIM (the typed sum — an arm returning list[X] packs that list as ONE element; see the guide's nesting note). Totality is fenced at three doors: the verb refuses a non-total route (RouterNotTotal at runtime for a body that lied), E15-route-totality re-proves it from the compiled graph, and the runtime door raises. Takes a LIST source — a single-value Promise[A\|B] is refused at build ("the route is a MAP face"; the chain step's in-body Route is the single-value routing face). aggregate= is the user's DECLARED read-side fn over the children's decoded results (progress aggregation — evaluated AT READ TIME, writes nothing; taskq.workflows.read_map_aggregate evaluates it). child_driven=True is the fan-in bound's escape (the join counts its terminal children from the edge ledger). Per-arm placement/admission: RouteArm(body=fn, actor=None, queue=None, rate_limits=(), max_concurrent=None, reservations=(), result_ttl=None, priority=None, start_to_close=None, capacity_owner="operator") — queue=None inherits the route's queue=, actor=None the source's actor; a bare Callable arm normalizes to RouteArm(body=fn); the capacity fields are the arm's OWN declaration (a capped handle wired under this arm's actor override has its terms re-declared here, and an override that would silently drop a capped handle's terms is refused at the wiring); priority=None = the arm does not override (the SOURCE node's resolution applies — the arm overrides DOWN from the source, graph-DIRECTION, not a value ceiling: the arm's value may raise or lower freely, and the JOIN keeps the source's resolution); capacity_owner is the arm's own owner declaration — an overriding arm whose body handle carries capacity_owner="code" must re-declare it HERE (per-arm: the other arms and the join never inherit it).
chain_source(chain, source_body, *args, key=None, actor="wf", queue="default", max_attempts=3, policy=None) Chain × BodyFn → Promise[None] the streaming chain's source: source_body is the paged generator (each ctx.emit_batch yield = one page's emit tx); the chain's step rows exist only from the emit onward (never graph nodes — the runner routes them from the compiled chain).
chain_barrier(source, *, actor=None, queue=None) Promise[ChainBarrierSummary] the ALL-EMITTED barrier over a chain_source: the derived <source.key>.barrier node arms at create with its dependency reserved (no edge from the source), and hands a ChainBarrierSummary (source_key, emitted_records, succeeded_records, failed_records, cancelled_records, cursor) downstream once the source has finished emitting and every emitted record's chain branch is terminal. Fail-closed only (no on_failure collection mode). actor=None / queue=None inherit the source's resolved placement; an explicit value overrides that field alone, and empty values are refused at build. The barrier and every static node downstream do not occupy the run's in-flight budget while their dependencies are pending, so a barrier behind a full-capacity page cannot deadlock its own chain.
map_source(source, body, *, queue="default", on_failure="fail_closed", max_attempts=3, aggregate=None, rate_limits=(), child_driven=False) Promise[list[T]] × body → Promise[list[R]] the map: the source's finalize forks N children (fresh jobs, per-item ledger identity); the join collects. One map per source (a node finalizes once). The join key is DERIVED (<source>.join) — the engine's fork addresses the map join by the source's own key; a custom join key is refused, never silently ignored. aggregate= is the user's DECLARED read-side fn over the children's decoded results (progress aggregation — evaluated AT READ TIME, writes nothing; taskq.workflows.read_map_aggregate evaluates it). rate_limits= stamps the CHILDREN's admission terms (the buckets' names ride each child row's metadata — honored at the FLEET's dispatch claim, see the rate-limiting guide's doors note). child_driven=True is the fan-in bound's escape (the join counts its terminal children from the edge ledger). The DICT form ({Type: arm}) is the typed route — the same lowering as route.
sink(*promises) → None explicit fire-and-forget — RECORDED in the compiled metadata, never silent.
build(result, *residuals) Promise[R] × Promise[Never] → Promise[R] the terminal completeness point: names the result and accounts for every residual. The residual slot is Promise[Never] — a produces-nothing body's handle (-> NoReturn); because Promise is covariant, every REAL data handle in the slot is the checker's error (the static half of E2-produced-never-consumed).
loop(name, body, *, initial=None, carry_type=None, until=None, max_iterations=None, budget_s=None, on_exhausted="escalate", escalates_to=None, gates=()) → Promise[Any] the LOOP node (see the section below — the carry contract, the two walls, the named exhaustion). initial= is the initial carry VALUE, carry_type= the DECLARED carrier-type (derived from the instance when initial= is a model); until is AWAITED per iteration (Callable[[], Awaitable[bool]]); gates= declares the body's HOLD gates for the admin's resolve/deliver doors.

Typed chain execution policy

Step[Record, Outcome] preserves its body's record and outcome types and accepts policy=ExecutionPolicy(...). Chain(default_policy=...) supplies record-leaf defaults; a source's chain_source(policy=...) remains its own declaration. None means inherit at every layer; CLEAR_POLICY is the explicit clearing sentinel. Equivalent compatibility/policy redeclarations are accepted, contradictory ones raise WorkflowPolicyError (E21-execution-policy) before a row exists.

ExecutionPolicy is frozen and typed: placement uses strings; reservations/rate limits reuse their existing declarations; capacity ownership is the existing CapacityOwner; priority and start_to_close use their existing domains; retry is RetrySpec, which wraps the shared validated RetryPolicy. Its typed exception map supports specific subclass precedence and None as an explicit default-policy result. RetrySpec also accepts an isolated classifier. The workflow-only WorkflowRetryOverride may advertise delay=..., consume_budget=False without changing vanilla Retry, RetryDecision, or RetryOverride. Such classifications require positive finite RetrySpec.non_consuming_limit and increment the durable metadata.wf_retry.non_consuming_count under the existing claim-fenced row law; the limit has its own terminal RetryDeferralBudgetExceeded and never advances a source's logical failure ordinal or consumes max_attempts. New workflow policies reject time_budget and indefinite with actionable validation; saved legacy rows are not reinterpreted. Generic legacy Snooze/non-consuming RetryAfter remain compatibility behavior, not a newly claimed bounded path.

Dynamic chain reservations whose keys vary per record must declare FiniteReservationCohort(ref=..., keys=(...)). The existing key function decides each concrete name deterministically, emit/fork refuses names outside the finite set, and worker boot registers/materializes exactly those existing reservation slots. No process-hash/modulo identity or arbitrary-cardinality per-record slot creation is a supported policy path.

Step.outcomes still accepts the enum or type-union route vocabulary. The Chain.steps container is heterogeneous by design; each individual Step carries its own record/outcome typing. ExecutionPolicy itself has no terminal-effect callback field: a terminal effect is declared only through RetrySpec(on_exhaustion=TerminalEffect(...)) (documented below), and retry configuration never silently implies one.

The complete precedence, retry, strict-reservation, capacity-owner, deadline, legacy default, and failure-boundary law is in the workflows guide.

Emit backpressure (max_in_flight, EmitBackpressure)

@app.workflow(name, ..., max_in_flight=N) declares the run's whole-page materialization bound (None is the explicit unbounded; the unset default is 1000). Every ctx.emit_batch call admits its WHOLE page against the run's real rows as they stand at the moment of the call — the other live rows plus their valid page-width reservations, with the running source's own row excluded — once outside the transaction, then again inside it under the run's intent/admission lock, so concurrent emitters of one run cannot both admit past the bound.

Only a compiled chain_source node owns this face. It is the one node kind carrying the durable wf_source_logical_attempt the park restores, so its replay resumes at the same ctx.attempt the run's wait answers were minted under. Calling ctx.emit_batch from any other body (step, a map_source source or item, a route source or arm, or a Chain step) — or letting an EmitBackpressure escape one, directly, inside an ExceptionGroup, or through an explicit __cause__ — fails closed deterministically with taskq.workflows.EmitOutsideChainSourceError: no emit child, edge, or cursor is written, nothing parks, and the node terminal-fails on its first attempt with that class on the record (unless another deterministic authoring failure in the same exception tree takes precedence). A loop body carries no claim view at all, so ctx.emit_batch there raises WorkflowRunError ("without this node's claim view") before the emit face, and a raised EmitBackpressure exhausts the loop as a body failure whose record names EmitOutsideChainSourceError. The remedy is in the message: move the emit into a chain_source(...) body.

When the page does not fit, emit_batch raises taskq.workflows.EmitBackpressure — a typed capacity control, not an error: no child, edge, or cursor row exists when it escapes. The source runner then PARKS the claimed source: status='scheduled' with scheduled_at holding the PARK INSTANT (not a due date — no lease, no worker slot, no heartbeat), the physical attempt refunded so max_attempts is never consumed, the current ledger claim resting awaited (never failed), and the exact marker (metadata.blocking_reason='backpressure' plus the typed deferral and the version-1 record) carrying the page width, bound, outstanding count, and deferrals/wakes counters. The body's ctx.attempt does not move.

Wake is a threshold-created durable intent and an event-driven drain: each terminal/park event probes the exact marker once; only a marker-positive event whose oldest fitting waiter newly fits creates the durable promotion intent (plus its accelerator notification) in the same transaction. The drain — the producing route's own post-commit call, the maintenance leader's notification/leadership/reconnect arms, or the bounded maintenance-interval fallback — promotes the oldest fitting real waiter pending under the run's advisory lock and attaches a durable page-width RESERVATION, removing the marker atomically. A reserved replay may present fewer records than its reservation and may not present more: the excess raises the public taskq.workflows.EmitReservationExceededError — nothing is written, and the source terminalizes on the first violation through the deterministic grant-violation route (no retry budget spent), its reservation removed in the same winning terminal statement. That error is distinct from a genuine PageDivergedError — an idempotency arbiter collision whose remedy is a cursor re-sync; a width comparison never claims an arbiter collision. A parked source under a terminal root is never re-armed; an operator cancel terminalizes and fences it. Real failures (body errors, diverged cursors, poisoned pages) are unaffected and still consume the ladder. A committed terminal-root failure after a genuine child failure exhausted its retry policy — while an exact parked source still holds un-emitted work, including the first page when no cursor has committed (the absent key means zero pages have committed, not that the park is empty) — fences the parked source with durable error_class='WorkflowNotDrainingError' (a string value, not an importable class). The admin surface renders a parked source as scheduled with the backpressure marker — deferred (backpressure) with the park time as the parked-at time, never a next fire — and never as a failure.

ctx.emit_batch(..., backpressure_timeout_s=...) is accepted for compatibility and is diagnostic-age input only: no value of it turns healthy saturation into a failure. A page whose width alone can never fit under the declared bound raises the immediate ValueError (shrink the page or raise the bound).

The streaming source's caller-owned transaction (conn=, EmitTransactionError)

ctx.cursor(conn=conn) and ctx.emit_batch(children, cursor=..., conn=conn) join a transaction the source body already owns: pass an open asyncpg connection with an active transaction, and your application writes, the page's chain-start children, their edges, and the cursor checkpoint commit or roll back together.

from taskq.workflows import StepContext, chain_start


async def import_page(ctx: StepContext) -> None:
    async with app_pool.acquire() as conn:
        async with conn.transaction():
            seen = await ctx.cursor(conn=conn)  # committed checkpoint
        raw_page = seen.get("page", -1)
        start = raw_page + 1 if isinstance(raw_page, int) and not isinstance(raw_page, bool) else 0
        for page in range(start, len(pages)):
            async with conn.transaction():  # one commit per page
                await stage_application_rows(conn, pages[page])
                await ctx.emit_batch(
                    [
                        chain_start(CHAIN, record, map_index=index, trace_id=f"row-{index}")
                        for index, record in pages[page]
                    ],
                    cursor={"page": page},
                    conn=conn,
                )

asyncpg-only. conn must be an asyncpg.Connection or asyncpg.pool.PoolConnectionProxy. Other wrappers (such as SQLAlchemy's AsyncConnection) are refused with taskq.workflows.EmitTransactionError; unwrap to .driver_connection or open the transaction on an asyncpg connection/pool.

One-round-trip preflight. Before taking any lock or writing, emit_batch and ctx.cursor(conn=...) inspect conn using pg_catalog-qualified reads (immune to a caller-modified search_path): transaction_isolation, transaction_read_only, current_database(), and (pg_control_system()).system_identifier, together with asyncpg's is_closed() and is_in_transaction(). Anything other than an asyncpg-owned, open, READ COMMITTED, read-write transaction on the pool's own database and PostgreSQL cluster raises EmitTransactionError (a deterministic WorkflowRunError subclass — never retried, never parked). Raw-SQL BEGIN (a transaction asyncpg did not open) is refused by the managed savepoint just below, which converts asyncpg's InterfaceError; roles without pg_control_system access are refused fail-closed too. Transport or aborted-transaction errors propagate as-is.

Cluster identity is (current_database(), system_identifier), resolved once per pool and cached. It is primed ahead of a chain_source body, so the page's own conn= call resolves it from the cache and performs no pool acquire. If the pool cannot be read, the prime is a logged best-effort miss and never fails the body. What a page that then passes conn= sees depends on why the prime missed: a restricted pg_control_system role is an authoring/config error and is refused deterministically with EmitTransactionError, while a saturated pool is transient and raises the builtin TimeoutError after the 1-second bounded checkout — the runner's retry ladder retries it once the pool frees a connection, so pool pressure never terminal-fails a source on its first attempt. A page that does not pass conn= is unaffected either way. A writable physical clone (pg_basebackup / PITR) preserves system_identifier, so this check cannot distinguish one from the primary cluster: point conn at the pool's own cluster yourself.

Guarantees and caller responsibilities:

  • Single-task connection ownership. asyncpg maintains one top-level transaction per connection; a concurrent async with conn.transaction() silently becomes a nested savepoint whose commit only runs RELEASE SAVEPOINT. TaskQ refuses an overlapping in-flight conn= call on the same connection (keyed on the connection object), so one connection serves one unit of work at a time. Parallel pages need one connection each.
  • Savepoint isolation. Each conn= page executes inside async with conn.transaction() (a SAVEPOINT within your open transaction). If EmitFencedError, PageDivergedError, or MapIndexExhaustedError is raised and caught, the savepoint rolls back and committing your outer transaction leaves no leaked children, edges, or cursor mutations.
  • No TaskQ pool acquires. Every emit and cursor statement runs on conn. The pool's own (database, cluster) identity is the one thing read from the pool, and it is cached per pool and primed before a chain_source body runs; a page never acquires a connection from the pool whose connection it holds.
  • Whole-page poison refusal. Under conn=, any map_index past the schema's ceiling raises MapIndexExhaustedError before any write, so a partial page is never committed.
  • Admission lock ordering. After confirming the page fits, a conn= page acquires pg_catalog.pg_advisory_xact_lock(hashtext(<flow_id>)) before touching the source row on both reserved-replay and unreserved paths, preventing lock-order inversion across multi-page transactions. If a locked recheck rejects the page inside its savepoint, rolling back the savepoint releases the lock immediately; an admitted page's RELEASE SAVEPOINT holds the lock until your outer commit or rollback, serializing sibling emitters and the promotion drain for that run.
  • Codecs and search_path safety. JSONB parameters are bound text-first (::text::jsonb, ::text[]::jsonb[]), so custom jsonb codecs on your pool cannot corrupt payloads or cursors, and all emit statements are pg_catalog-qualified. The INSERT INTO jobs also fires the invoker-rights notify_job_insert trigger under your session's search_path: keep pg_catalog reachable and unshadowed (a schema defining its own text or convert_to ahead of pg_catalog breaks the trigger). That misconfiguration is refused deterministically as EmitTransactionError and rolls the page savepoint back whole.
  • Lease refresh without session GUCs. The cursor checkpoint refreshes last_heartbeat_at and lock_expires_at from the claim's lease and leaves a one-lease reclaim deferral on commit so a caller that commits slightly past its emit-time lease is not reclaimed mid-page. TaskQ never issues SET LOCAL (such as transaction_timeout) on conn, as it would leak past RELEASE SAVEPOINT into your outer transaction.
  • Capacity control still applies. If the page does not fit, EmitBackpressure is raised with nothing written, and your transaction remains usable. Let it escape the caller body. The park — and the resume from the last committed checkpoint — happens only because that control signal reaches the runner. Catching and swallowing it returns your body normally, the source then finalizes succeeded with its previous cursor, and the refused page is silently omitted from the run: nothing raises, and nothing retries it.

Keep transactions short. Heartbeats renew other jobs with SKIP LOCKED, so holding the source row does not stall sibling renewals on the worker, but the source row's own lease cannot be renewed until your transaction commits. Long caller transactions also hold the run's admission lock and, past lock_lease, trigger TaskQRunningLeaseExpired (see the runbook).

Fleet-only. Re-stamping the claim lease requires a real lease. workflows.run() constructs FlowRunner without lock_lease=, so conn= emits under it raise EmitTransactionError. Run under a fleet worker or an explicit FlowRunner(..., lock_lease=...).

The all-emitted chain barrier (chain_barrier, ChainBarrierSummary)

chain_barrier(src) wires a derived <src.key>.barrier node over a chain_source. It resolves once the source has succeeded and every emitted record's chain branch has reached a terminal state, passing a ChainBarrierSummary downstream.

from taskq.workflows import (
    ChainBarrierSummary,
    Promise,
    StepContext,
    build,
    chain_barrier,
    chain_source,
    step,
)


async def commit_import(ctx: StepContext, summary: ChainBarrierSummary) -> dict[str, object]:
    await write_import_manifest(summary.source_key, summary.emitted_records, summary.cursor)
    return summary.model_dump()


@app.workflow("durable_import", max_in_flight=2)
def durable_import() -> Promise[dict[str, object]]:
    src = chain_source(CHAIN, source_body, key="import", actor="import-runner", queue="import-q")
    return build(step(commit_import, chain_barrier(src), key="commit_import"))

Summary shape:

ChainBarrierSummary(
    source_key: str,             # the source node's key
    emitted_records: int,        # chain-start rows the source emitted
    succeeded_records: int,
    failed_records: int,
    cancelled_records: int,
    cursor: dict[str, object],   # the source's final committed checkpoint
)

emitted == succeeded + failed + cancelled holds exactly (a record with both a failed and a succeeded hop counts once, in failed_records). The barrier body verifies conservation, zero live records, and one group per emitted record before returning, failing the barrier on any discrepancy.

Placement and capacity. actor=None and queue=None inherit the source's resolved placement; explicit non-empty values override individually (empty or whitespace-only values fail at build). The barrier and all static nodes downstream of it are marked post-barrier at create and do not count against max_in_flight while pending, so a barrier behind a full page cannot deadlock its own chain.

Fail-closed only. There is no on_failure= collection mode. If the source fails, crashes, or poisons a page, or any emitted record's chain step fails, in-flight siblings drain without a peer-cancel storm, the barrier is fenced failed_parent, the run fails with UnabsorbedNodeFailure on the root, and downstream steps do not run. For partial-success workflows, route degraded records to a fallback step inside the chain or query the chain rows directly.

Wait scope. The barrier waits for every emitted record's chain steps to terminalize, including steps parked in ctx.wait_signal(...), ctx.wait_until(...), or an awaited ctx.spawn_flow(...).wait() child flow. It does not wait for detached fire-and-forget spawn_flow children or asynchronous terminal effects (RetrySpec(on_exhaustion=...)).

Runtime mechanics and build refusals. The barrier is created armed (deps_pending=1, metadata.blocking_reason='chain_barrier') with no wf_edge from the source. The engine releases it reactively in the finalizing transaction of the last branch (or the source itself when zero records were emitted) with one wf_join_fire row, and the workflow sweep heals any missed release. Operator retry re-arms a failed_parent or flow_dead barrier; run cancellation fences it like any waiting row. Build-time refusals: a non-chain_source parent, a second barrier on the same source, a cross-graph source, or a downstream consumer incompatible with ChainBarrierSummary.

The loop (wf.loop, Done, Refine)

loop(name, body, ...) wires a LOOP node: each iteration is FRESH jobs (the iteration-scoped step keys <loop>.iter<i> keep the idempotency ledger per-iteration). The body receives (ctx, carry) and returns the CONTROL UNION:

  • Done(payload) — the typed EXIT: the loop stops; the payload is the loop node's result.
  • Refine(feedback) — the typed CONTINUE: the feedback threads the carry into the NEXT iteration, advanced EXACTLY ONCE per iteration in the ADVANCE statement — one atomic write shared with the CAP GUARD (iteration < max_iterations is the same statement's WHERE leg); a carry advanced at hold/retry time is the optimistic-apply dragon, kept red forever.
  • anything else is the TYPED SHAPE ERROR — LoopBodyShapeError: the iteration's ledger terminal records it FAILED (the ledger records the truth; a wrong-shape return is never laundered into a succeeded row the memo replay would re-thread as a Refine), the loop exhausts with the named class, and the flow terminalizes.

The carry's type is the contract: the type-only declaration's initial carry is the empty None — the body receives None until its first Refine commits one. Every COMMITTED carry is revalidated at each boundary — the advance, a resume, the memo replay (carry_type=, or derived from the initial= model instance, is re-applied at the ONE point a carry reaches the body; the jsonb round-trip is typeless, so the driver re-hydrates through the declared type's validator: a pydantic model, a dict subclass, or a JSON-native type). A declared type the jsonb boundary cannot honor is the loud LoopCarryContractError — a silent type change is refused, and a committed None against a declared model or dict is the same refusal (the pre-first-carry seed is the only None the contract passes; a JSON-native declared type keeps the untyped None). The compile side is E8 (the carrier-type check).

The two walls are different: max_iterations bounds TOTAL SPAWNS (the iteration cap); budget_s is the TIME wall — and it is BLIND while the loop holds on a human (budget_paused — holds are free). Exhaustion is NAMED, never silent: the cap or the budget wall terminates the loop into the iteration_cap_exhausted / budget_exhausted state (the metadata's iteration_state + the typed failure class IterationLimitExhausted / LoopBudgetExhausted) and the FLOW TERMINALIZES in the same transaction. The ADVANCE and EXHAUST statements carry the claim identity's fence (worker + attempt + claim_epoch — the same legs every other terminal write carries): a zombie driver's stale advance or exhaust is refused, never a killed healthy loop, never a backward counter.

on_exhausted="escalate" (the default) enqueues the escalation through the same outbox the fired joins use, addressed to the workflow's REGISTERED escalation step (loop.escalation — escalates_to= declares the body, the framework's default warns and records otherwise). The escalation consumer is DISPATCHABLE after the flow's terminal: a flow's death must not orphan its pages-a-human duty (the dispatch fence's escalation-kind exemption — the ONE workflow row a terminal flow's claim still admits). on_exhausted="fail" terminal-fails the flow and enqueues NOTHING.

The workflow declaration: @app.workflow(name, *, capture="none" | "errors-only" | "all" = "errors-only", redact=None, run_reservations=None, max_active_runs=None, unique_for=None, unique_states=("pending", "scheduled", "running", "succeeded"), on_terminal=None) — §10.3's policies per workflow, plus bounded admission and windowed dedupe: max_active_runs= caps how many non-terminal runs of the workflow may exist at once (None = unbounded, 0 refuses every fresh run), and unique_for=/unique_states= declare the windowed-dedupe terms a create's identity_key= dedupes against (a window without an identity_key is a warned no-op; see create_flow below). The three producer edges' access paths are among the 01.00.46 pre-migration indexes (upgrade guide); the creates answer correctly without them and scan more. run_reservations= declares buckets the whole RUN holds instead of one claimed node (a bucket name, a ConcurrencyReservation, a KeyedReservationRef resolved from the run's input, or a FiniteReservationCohort): create_flow resolves them once from the run's input, stamps the sorted concrete names on the root (metadata.run_reservations, which root_metadata_extra= may not write), and stamps required_worker_schema = 3 so a pre-upgrade worker refuses the run instead of ignoring its exclusion. The root also carries metadata.wf_run_reservation_lineage (engine-owned): it marks the run as part of a reservation lineage, which is how a spawned descendant inherits the schema-3 floor even when the run that declared the reservation has since been archived by retention. The seat is a reservation_slots row keyed by the run's root id with NO worker lease and NO expiry: it is held from the run's first admitted node to its root's terminal — across worker crashes, drains, retry backoff, human holds and timers — released by the root-terminalising doors (and eagerly by the node whose terminal leaves no live work), stolen by the next acquisition when its run is dead, and swept by the maintenance leader's wf_run_reservation_reclaim. Every release honours the cooperative-cancel barrier: the root must be terminal and no reservation-scoped node may still be running under a live lease. A run-level bucket that overlaps one the graph's own nodes, route arms, chain steps or terminal effects acquire is refused at compile (E23-run-reservation-overlap); a child spawned under a live ancestor holding one of its buckets is refused at ctx.spawn_flow with RunReservationAncestorConflictError (see below). A guarded run is FLEET-ONLY: FlowRunner.drive(execute=True) refuses it with WorkflowWorkerCapabilityError, and a denied waiter parks as a capacity denial on the capped jittered ladder (1s → 30s, ±20%) keyed on its row's rate_limit_blocked_count.

taskq.workflows.RunReservationAncestorConflictError — the typed refusal of a nested run that would wait on a bucket its own live ancestor holds. Two faces, one class: ctx.spawn_flow raises it BEFORE the child's rows exist when the child's buckets resolve at spawn time, and the admission gate raises it for a child whose bucket only resolves at run time (a per-record/chain step) once the ancestor walk proves the deadlock — every link waiting on the child below through an unbounded ChildHandle.wait() and the ancestors holding every slot of the denied bucket. In the runtime case the child's node fails on its FIRST attempt (snooze_count stays 0, no retry budget spent) and the child run terminalises failed, which wakes the waiting parent's join with ChildFailed. The walk is full-depth and cycle-safe; a fire-and-forget spawn, a bounded or expired wait, a terminal ancestor, or a non-ancestor slot holder are ordinary contention instead. The redact hook post-composes on the default chain's output (chain → hook, unconditional): it can only redact MORE, never less — a hook that returns raw fixture text still lands a MASKED row (the pin: an un-redacted canary never reaches a row).

@app.actor is a DIFFERENT decorator from taskq.actor but projects into the SAME registry/config-sync surface (the config-drift machinery, the deregistration guards, the admin's actors page, and TASKQ_QUEUES_STRICT's fail-fast all see workflow actors — no second, invisible actor population). The vanilla path stays byte-identical. Its landed signature:

@app.actor(fn=None, /, *, name=None, queue="default", max_attempts=3, retry_kind="transient", capture_policy="none" | "errors-only" | "all" = "errors-only", redact=None, max_concurrent=None, reservations=None, result_ttl=None, priority=None, capacity_owner="operator")

The capacity terms are the step surface's own (see the wiring verbs table): max_concurrent the per-round damper, reservations the strict slots (a ConcurrencyReservation list — a keyed-rate-limit object here is the loud ValueError at the declaration site, never a silently-dropped cap), result_ttl the cohort's in-DB result expiry. priority= is the actor's declared claim-order DEFAULT for its nodes' rows (the step's own priority= overrides it, the per-call override overrides both — the precedence law in the wiring verbs table). capacity_owner= is the stored-capacity ownership: "operator" (the default) is the seed-only law — the operator owns the row thereafter, a later literal change logs a mismatch, never writes; "code" hands max_concurrent/result_ttl to the declaration — the boot sync REWRITES them from the literal on every boot (the queue and max_pending stay operator-owned under both owners). max_pending is not on the surface (the engine's inserts bypass the enqueue admission; a claim-side gate would wedge the backlog). The declaration seeds the cohort's actor_config row and the ONE-CAP-PER-ACTOR law refuses two different declarations for one actor name.

wf.validate() — the checker-independent validator

Runs in pytest, CI, and at worker boot; RETURNS the diagnostics — the one-pass report as a tuple of validation errors, EMPTY when clean (the zero-warning budget a doc example claims is assertable against the return); the ERROR-class diagnostics also raise. The THIRTY-ONE rules shipped (read from taskq/workflows/api/_validate.py's _run_rules — E1–E20, E22–E25, W1, the two W2 faces, W3, W4, W5, and W6), each classified — the zero-false-positive doctrine: over-refusing valid graphs is the compile's version of over-rejection.

rule class rejects
E1-acyclicity error a cyclic wiring (owned UNCONDITIONALLY here — the checker claim is dead errata)
E2-produced-never-consumed error a promise nobody consumes, sinks, or terminals — work that will never be acknowledged
E3-edgeless-join error a join with zero incoming edges (the stranded invisible join)
E4-unannotated-step error a body without a return annotation — the annotation IS the wiring
E5-incompatible-consumer error an unrelated payload model consumed (the checker-independent half of the typing story)
E6-fan-in-bound error a join over MAX_FAN_IN_PER_JOIN (1000) parents
E7-cross-graph-promise error a promise wired from ANOTHER app's recorder — two apps' graphs spliced invisibly
E8-carrier-type error the loop's declared carry_type= model (or the model instance passed as initial=) vs the body's Refine[...] feedback type — unrelated carrier models: the thread promises data the next iteration cannot receive
E9-ctx-annotation error a body whose ctx annotation is not StepContext (or a subclass) — the annotation is verification, not documentation; the fabricated stand-in is refused at compile
E10-arity error a body's params (beyond ctx) not matching the wired sources' count — the wiring's own promise, refused at compile, never a mid-flow ladder discovery
E11-loop-promise-carry error a promise handle wired as the loop's initial= — the initial carry is a VALUE, never a handle (the handle cannot ride the row; wire the parent's result through a first step's return, or read it in the body)
E12-deps-contract error a body declaring the deps shape (one param beyond ctx + the wired sources — the DI capability's opt-in) where the app binds NO deps (WorkflowApp(deps=…) never ran), or whose declared deps type the bound instance does not satisfy — under a deps_factory= binding the check reads the factory's PRODUCT TYPE from its return annotation WITHOUT invoking it (() -> T, () -> Awaitable[T], -> AsyncContextManager[T] / -> AsyncIterator[T] / -> AsyncGenerator[T, None], a class factory, a concrete async-CM class via its __aenter__ result); unverifiable products (Any, object, unannotated, a union, a non-runtime-checkable protocol) SKIP the check — the zero-false-positive doctrine — the message names the fix (and, on the factory arm, both type names): bind ONE instance at the door, or drop the parameter (it is never a fourth data source)
E13-gate-door error a node's gates= carrying the channel's BOUND-DOOR object (app.channel().gate(Model)'s TypedGate — the runtime delivery handle) where the DECLARATION (GateDecl(name=…, payload_models=…, timeout_s=…)) belongs — the declaration is what the compile's hold nodes, the timeout warning and the delivery runtime read
E14-gate-wiring error the gate seat and the bodies' waits, walked against each other (E2's analog for the hold wiring), BOTH provable directions: a DECLARED gate whose body carries no wait_signal reference at all (the hold seat with no waiter), and a body's wait_signal with NO declared gate (the hold the compile's surfaces cannot see — the Mermaid hold nodes, W1's read, the admin's resolve/deliver doors). The conditional-interior wait is not statically provable — the loop-kind mis-index face is W5's
E15-route-totality error THE TOTALITY FENCE AT THE GRAPH LEVEL: the typed route's arms walked against the source's declared union, BOTH provable directions — the arms' keys must cover the union's members EXACTLY (a MISSING member would route NOTHING — the silent drop the route exists to refuse: the skipped-both-arms run that terminalized succeeded-having-routed-nothing; an UNKNOWN member would never fire), and every arm body declares its arm's MODEL on the item param (the decode's target — a duck-typed arm (dict/unannotated/Any) consumes the element UNVALIDATED; the declared model must be the EXACT union member — a superclass passes the old issubclass fence and the runtime decode drops the subclass's own fields (extra='ignore', the silent data loss); an unrelated model is the wiring promising data the arm cannot accept). The wiring verbs refuse the same breaches at the wiring site; this rule re-proves the fence from the compiled graph itself (public, mutable data — E3's precedent). The runtime door for the body that LIED about its union is RouterNotTotal
E16-union-discriminator error/warning THE CONSUMER DISCRIMINATOR LAW: a body param decoded as a UNION of models (the typed sum's consumer face — the join's downstream reads list[ImageResult \| AudioResult]) is decoded by the codec's left-to-right smart union — the FIRST member whose required fields the payload satisfies WINS. Picked by the reads (the members' declared fields are the only evidence): FIELD-IDENTICAL required faces are the hard refusal (the mispick is guaranteed and silent — every payload decodes as the first member); the one-directional SUBSET relation is the warning naming the mispick risk; distinct members (each requires a field the other lacks) are clean — the thinner validation fails, the union falls through to the true member. The fix either way: a Literal discriminator field on each member (kind: Literal['image']), so the union decodes by the tag, never by field-count luck
E17-cache-route-source error cache=True on a typed-route SOURCE — at the first cache hit the hit path cannot rebuild the route fork (the arm dispatch reads the element's runtime type; the cached envelope carries only encoded dicts), so the route's children and join never spawn and the run WEDGES FOREVER with the source reading succeeded wearing a wf_cache_hit receipt. Cache the route's arms' work, not the fork-spawning source
E18-cache-ctx-input error cache=True on a body reading ctx.input — the flow input never enters the address (the wired args do): the cached answer produced under one flow input would serve a LATER run whose input differs (the cross-tenant leak — A's answer delivered to B, terminal-success, audits clean). The fix it names: lift the flow input into the dataflow with an UNcached upstream step and wire its result as a param
E19-cache-exit-body error cache=True on an Exit-returning body — the sentinel terminalizes through the exit finalize, which the success-only store never sees: the cache silently no-ops (every run re-executes the body while the operator believes it caches)
E20-cache-unverifiable-source error cache=True on a body whose own source is not verifiable (a builtin, a partial, an exec'd fragment) — the address requires the code-version canon and the pre-refusal shape was the SILENTLY uncached step: the wiring accepted cache=True, every run re-executed the body, the only trace a log line. The refusal is deterministic (the claim path's hash reads the same source through the same seam)
E22-skip-fan-out-source error skip= on a fan-out SOURCE (a node carrying map_item/map_arms, or the parent of the derived map_join the fork writes) — the first time the predicate returns true the dispatch-time skip finalizes the source succeeded WITHOUT spawning its fork, so the derived <source>.join row never exists: a downstream consumer reserved on that join waits forever (the root stands running with no error row anywhere), and a terminal map reads succeeded over a result() of None. Refused at the map_source / route attachment; the runner's graph-aware guard terminal-fails a graph mutated after construction. Return [] from the source body instead (the empty join fires immediately with the honest [])
E23-run-reservation-overlap error a workflow's run_reservations bucket that overlaps one its own nodes, route arms, chain steps or terminal effects acquire — the run holds its run-level buckets for as long as it lives, so the node waits on a bucket its own run holds: a self-deadlock no retry, sweep or operator action can break. Checked as an exact bucket-name collision, as a keyed base name against a concrete bucket under it (tenant covers tenant:foo, in either direction), and over a finite cohort's own declared keys
E24-chain-barrier-source error kind == 'chain_barrier' exactly when barrier_source names a chain_source node in this graph. A step carrying a barrier_source would consume the source's promise without arming a wait; a barrier with no source (or one naming a non-chain_source) would arm a wait nothing resolves. The wiring verbs build both fields together; this rule re-proves them on the compiled graph, which stays publicly mutable
E25-run-terminal-effect error a workflow's on_terminal effect must resolve its own placement from the declaration alone: it is stamped on the run root at create_flow and carries no payload, so a payload-keyed rate limit or reservation could never name its bucket and the hook job would be admitted under nothing. The declaration door refuses the same shape with WorkflowPolicyError; this rule re-proves it from the compiled graph
W6-actor-queue-cohort warning THE DERIVED JOIN'S COHORT LAW (the docshelf adoption team's F3): a ROUTE attachment whose derived join (the verb's queue=, default default) differs from the SOURCE NODE's own queue under the SAME actor splits one actor name over two queues — actor_config is keyed by actor (one queue per actor), so a FLEET deployment's boot projection will refuse the graph (or strand its rows) at 3am. This rule reports the conflict AT THE WIRING instead (the W2 precedent's severity: probably wrong, never a refusal — the boot projection's one-queue law stays the refusal door). The remedy for a fleet deployment: DISTINCT actor names per queue (the arm's RouteArm(actor=..., queue=...)), or wire the route's queue= to the source's own. The plain map's explicit queue= (the doc-ingest guide's Shape-4 knob) is an explicit author placement, not the ambush — it stays silent here
W1-eternal-wait warning a gate with no declared timeout — "a workflow that waits forever on a human is a support ticket"
W2-unknown-queue warning a node projected onto a queue this app cannot see (the actor-not-found parking shape, named at validate)
W2-join-for-progress warning a join SUNK for display only — the DAG still blocks on it; declare the map's aggregate= fn instead
W3-eternal-loop warning a loop with no until= and neither wall set (max_iterations/budget_s) — a loop that can never stop on its own; declare the bound explicitly
W4-gate-timeout-split warning the double-sourced gate timeout cross-checked where it is cross-checkable: the GateDecl.timeout_s and the body's statically-readable literal wait timeout_s= DISAGREE — both values named in the message. The precedence: the WAIT SITE's value arms the runtime (the hold's expiry), the DECLARATION feeds the compile surfaces (the Mermaid face, W1) and never arms the runtime
W5-loop-wait-shape warning the loop's shape law, NAMED (never prose): a LOOP body whose wait_signal sits in a conditional interior mis-indexes the answer cursor (the row's iteration counter IS the cursor — an iteration that does not wait drifts the sequence). The unconditional wait is the shape kept — a plain STEP's conditional wait is the claim-scoped cursor's honest replay

The report is ONE-PASS (tsc-style): every rule's verdict, not the first failure alone. The mutation matrix (each mutation flips exactly one rule, nothing else) is pinned in tests/test_wf_validate_pins.py.

The Mermaid emission

compiled.mermaid() — a pure function of the wiring, byte-stable, golden-testable. Node shapes by kind: stadium ([]) = map source, hexagon {{}} = the collapsed map's join, rectangle [] = plain actor, [[...]] = the gather join, ([(...)]) = the HITL hold nodes (rendered with their gate name + timeout policy — the hold gate consumes the same declaration). Edge labels = the promise types. The diagram-lies property is pinned: every compiled node/edge appears in the emission, nothing else does.

Authored terminal effects

RetrySpec(on_exhaustion=TerminalEffect(body, policy=ExecutionPolicy(...))) is the typed terminal-effect declaration. The independent policy explicitly names its handler actor/queue and may carry ordinary bounded retry, admission, deadline and priority terms. Its invocation is (ctx, event: ExhaustionEvent) plus the standard optional dependency tail. ExhaustionEvent is a validated Pydantic model containing flow/workflow/node keys, map_index, claim attempt, positive durable run_epoch, trace, current record, ErrorInfo, and the reason.

A policy-owned terminal commits the failed node, current attempt ledger, and one stable effect intent atomically; exactly one ordinary effect job materializes through the physical idempotency keys. The effect runs with ordinary bounded retry after its own node's failed terminal and may execute after the run root is already failed or cancelled; root maintenance derives root status from graph node rows and may derive failed while the durable effect intent is still undelivered and before an effect job exists, so a terminal root does not prove that the effect has settled. The stable effect key guarantees exactly one durable intent and exactly one ordinary effect-job materialization, while callback execution and external effects are at-least-once rather than exactly-once. An operator cancel that commits first terminalises the root cancelled; a committed intent survives it and then runs on that cancelled root. Cancellation before the winning terminal prevents intent. Missing handlers stay visibly unclaimed. Same-DB completed-once domain settlement requires the application's marker and effects in one transaction. The engine never claims arbitrary/external exactly-once execution. These guarded flows require the capability, run-epoch and intent PRE migrations (see the upgrade guide's 01.00.38 + 01.00.41 section) and capable fleet workers; direct execution refuses them.

The run-level terminal hook

@app.workflow(name, on_terminal=TerminalEffect(body, policy=ExecutionPolicy(...))) declares the run-level hook: the same typed TerminalEffect an on_exhaustion declaration uses, delivered to body(ctx, event: RunTerminalEvent) once the RUN — not one node — reaches a quiescent terminal state (succeeded, failed or cancelled). It is an ordinary bounded job materialized through the same wf_outbox, addressed at its own actor/queue and carrying the declaration's rate-limit, reservation, deadline, priority and retry terms.

The event is a frozen snapshot of the run's own terminal row:

field content
flow_id, flow_name, run_key, identity_key the run's identity (the last is the create's identity_key=)
outcome RunTerminalOutcome: "succeeded", "failed" or "cancelled"
run_epoch the incarnation's epoch (a manual retry opens a new one)
trace_id the run root's trace, when it has one
error the root's terminal cause (ErrorInfo), None for a clean success
failed_node_key, terminal_node_key the newest failure-class member (failed / crashed / abandoned) and the newest member that reached a terminal state
started_at, finished_at the run's create instant and its terminal stamp

Settlement is pure row work. create_flow stamps the declaration's resolved placement and policy on the run root (metadata.wf_on_terminal) together with a settlement marker (metadata.wf_on_terminal_pending), so a leader settles a run whose workflow it never compiled. A run settles when its root is terminal AND nothing ordinary can still work (post-terminal effect leaves and loop escalation rows are excluded by construction — they run after the run). Settlement writes exactly one intent per (flow_id, run_epoch) and strips the marker in one statement; the intent is then drained into the ordinary job.

Because the hook is per incarnation, a run reopened by retry_workflow_node settles the epoch it is about to leave before advancing run_epoch, and re-arms the marker on the reopened root, so epoch 1 and epoch 2 each deliver their own event. A reopen that cannot settle the prior epoch (a peer still working) is refused rather than abandoning it; an effect-only retry never reopens the run.

Boundaries: exactly one intent and one consumer row per (flow_id, run_epoch); the body, any external I/O and provider effects are at-least-once; the hook is scoped to its own run; a run reclaimed/abandoned by the engine still reports the verdict the derivation gave it. The declaration's own placement must resolve from the declaration alone, so a payload-keyed rate limit or reservation is refused (WorkflowPolicyError, compile rule E25-run-terminal-effect). A workflow declaring one stamps required_worker_schema = 4 on its run, so a pre-4 worker refuses the claim instead of running a hook it cannot settle. Direct in-process execution (drive(execute=True) or run(execute=True)) refuses the guarded run too; use capable fleet workers. The fleet-first rollout is the upgrade guide's schema-4 section. Retention holds a terminal root whose marker is still set, preserving the root's identity and binding template until the durable intent exists. Node rows are not held; if retention archives them first, the event's node-key fields can be None.

The runner (create / drive / result)

FlowRunner(compiled, pool, schema) — the API's reference worker and the test/demo driver:

  • create_flow(*, input=None, key=None, run_key=None, root_metadata_extra=None, priority=None, max_active_runs=None, max_active_runs_lock_timeout_ms=5000.0, identity_key=None, unique_for=None, unique_states=None, unique_for_lock_timeout_ms=5000.0) → RunClaim — the run carries its INPUT on the root row (cut #7: cross-flow data never dies in a Python closure); bodies read ctx.input. root_metadata_extra= is extra keys stamped onto the root row's metadata in the SAME create transaction (the child flows' provenance pointers land atomically with the root — never a post-create UPDATE). priority= is the per-call claim-order override: EVERY row this create materializes lands at the value in the jobs.priority column, and the root's metadata stamps it (wf_priority) so the rows materialized later (the map/route children a worker forks) resolve the same override — the precedence: this override > the step's declaration > the actor's declaration > the column default 0. The claim reports created (vs an existing run over the same run_key).

max_active_runs= tightens (never raises) the workflow's declared non-terminal-run cap for this one create; a fresh run at the cap raises MaxActiveRunsExceededError, a lock-wait expiry MaxActiveRunsLockTimeoutError (both BackpressureError subclasses, both counted on taskq.backpressure.errors). identity_key= names the business entity the run belongs to, unique_for= is the dedupe window for this create (overriding the workflow's declaration), and unique_states= is the set of run states the window matches (default: pending, scheduled, running, succeeded). With both an identity_key and a window, a run of that identity created inside the window is returned instead of a second one being created — RunClaim(created=False, dedup_reason="unique_for"), never refused by a full max_active_runs window because it consumes no capacity. An explicit run_key always outranks the window when it names a run (dedup_reason="run_key") and does not pre-empt it when it does not. A window without an identity_key is a documented no-op that warns once per runner (workflow_unique_for_ignored), exactly as the vanilla enqueue does. - drive(flow_id, *, until="held" | "terminal", tick, max_ticks, execute=True) → str — the driver (cut #10): no consumer hand-rolls a dispatch-poll loop; the drive is BOUNDED (max_ticks — a hang is a defect with no stack trace). The return is the verdict — check it: "terminal" (the flow row reached succeeded/failed/cancelled), "held" (only with until="held" — a node waits on a human/deadline), or "max_ticks" (the tick budget SPENT WITHOUT reaching until — not a status, a bounded give-up). A "max_ticks" return with rows still running means the run's work is not moving under THIS driver: the in-process drive runs NO lock-reclaim sweep (that is the worker maintenance leader's), so a killed process's running rows never re-pend through drive(execute=True) — the drive ticks to max_ticks silently and changes nothing. Resume a crashed run through the FLEET door (execute=False + a real worker — see the rate-limiting guide's doors note and the runbooks' mid-run crash page), not by re-driving in-process. tick is the IDLE poll's starting interval: an iteration that runs no node spaces its next poll out (up to a bounded ceiling) so a waiting drive is not a 50 Hz query loop, and running a node returns it to tick immediately. - result(flow_id) — the terminal node's result, DECODED (cuts #14/#19: never a raw jsonb string). A FAILED run's read raises the typed WorkflowRunError carrying the failing node's error class + message — the failure face is AT the read.

The packaged verbs (re-exported at taskq.workflows' top level — the ID-ADDRESSED doors that need no FlowRunner in hand):

  • run(flow, pool, schema, *, input=None, key=None, run_key=None, until="terminal", max_ticks=5000, execute=True, deps=None, deps_factory=None, deps_teardown=None, priority=None, max_active_runs=None, max_active_runs_lock_timeout_ms=5000.0, identity_key=None, unique_for=None, unique_states=None, unique_for_lock_timeout_ms=5000.0, cancel_state=None, prefer_sql=None) → WorkflowRunResult — the ONE-CALL door: create the run (key is the run key; run_key= rides as the alias), drive it to until, and return the claim + the drive's outcome + the decoded result. execute=True (the default) runs the bodies in THIS process (the dev loop); execute=False is the orchestration-only pass — the fleet's workers execute the rows. deps= overrides the DI binding for this call (the app's bound instance is the default); deps_factory= (with its optional deps_teardown=) is the same seam's lazy arm — the factory runs on this call's event loop at the first body execution and releases when the call returns, on the success and the failure path alike; deps= and deps_factory= together are refused (the deps seam section below). priority= is the per-call claim-order override (the create_flow face above); prefer_sql=None (default) keeps the PG 18 floor render safe behind a transaction-mode pooler (pass prefer_sql=False on a known direct PG 19 pool to use ON CONFLICT DO SELECT).
  • retry_workflow_node(pool, *, schema, flow_id, node_key, reason=None, principal=None) → int — the ID-ADDRESSED manual resume (the ExitOps' own CAS statements for the caller holding no compiled definition): re-arms the node's terminal-FAILED rows, re-opens the run, and re-arms its exit-skipped branches — pending, the skip envelope cleared — in one transaction. A cancelled run REFUSES (the cancel was deliberate). Returns the number of NODE ROWS re-armed (0 when nothing was resumable — a map's failed children share one step key, so one grant re-arms every failed row of the key at once); the action is audited (the row).
  • cancel_workflow_run(pool, *, schema, flow_id, reason=None, principal=None) → int — the ID-ADDRESSED cancel: the flow flip is the linearization point, every non-terminal node + held signal resolves in the same snapshot, and the children's cancels follow iteratively (the worklist walk, never Python recursion). Idempotent (cancel twice = one cancel); "who cancelled this" is a ROW, not a log line. Returns the sum over every run the cascade visited (the root + each cascaded child) of that run's held signals cancelled plus one — an already-terminal run contributes 0 (the idempotent no-op): a family of two runs holding 3 and 1 signals returns 6; a terminal run returns 0.

The dispatch contract: bodies resolve from the REGISTERED DEFINITION (the registry is the only body source); the claim is fenced; the finalize is the engine's two-tx shape; a body exception ladders (attempt failures emit NO terminal — P3 rule 7) with retry_kind routing ("permanent" takes no ladder) and per-node max_attempts.

The body context's cancellation surface (StepContext)

StepContext composes the cancellation mixin: the members below are the body-visible face of an operator cancel (cancel_workflow_run, above) or a deploy's drain. Every read is LIVE through the attempt's cancel carrier (the worker's JobContext on the fleet path; an injected CancelState on the direct door), never a snapshot — a mid-body origin transition is observed the instant it lands.

Member Signature Contract
cancellation_requested bool property the live "is a cancel in flight" read (cancel_event.is_set()) — non-blocking, safe in tight loops
cancel_event asyncio.Event set the moment a shutdown, an isolate or an operator cancel reaches this attempt. Read-only for step bodies: await it, hand it to asyncio.wait/TaskGroup, never set() it — the writers stamp the origin first, and a body-set event raises RuntimeError from cancel_origin/wait_cancelled rather than reporting a cancel nobody owns
wait_cancelled() async () → CancelOrigin suspends until cancellation, returns the origin at WAKE time. Every writer stamps the origin and then sets the event in one step, so the waiter wakes on the transition itself; a wake after an operator cancel over an earlier shutdown signal reports OPERATOR
cancel_origin CancelOrigin who asked — NONE / OPERATOR / SHUTDOWN, the live read; RuntimeError if the event was set with NONE
cancel_reason str \| None the operator's reason, None when no operator metadata is present. UNTRUSTED INPUT: operator free text. The fleet record is shape-bounded only (control characters escaped, length capped by bound_reason); a direct-door CancelState carries its embedder's values as supplied. Neither path output-encodes — escape it for the sink that renders it
cancel_principal str \| None who asked for the operator cancel, same rule — fleet-bounded or embedder-supplied, and the same untrusted-input terms

The origin vocabulary rides the package root — from taskq.workflows import CancelOrigin, StepContext (CancelOrigin is the taskq.context enum re-exported: NONE = 0, OPERATOR = 1, SHUTDOWN = 2). The disposition each origin routes to — the drain's release-vs-terminalize law, the resume contracts, the observation-latency guarantee — is the workflows guide's cancellation surface section; the vanilla-row face of the same channels is cancellation.md.

CancelState — the direct door's mutable carrier — is exported for embedders driving run(...) / FlowRunner without a worker. Pass it as cancel_state= to either door, then call request_cancel(origin, *, reason=None, principal=None): that stamps the origin BEFORE the event sets (a woken body always reads coherent state), is repeatable, refuses CancelOrigin.NONE, and never downgrades an operator origin to a later shutdown signal.

Direct injection is an observation seam, not the durable operator verb: it does not flip the run root, write a cancel request, or invoke the worker's shutdown release. An embedder that needs the operator's terminal verdict must call cancel_workflow_run for the durable request and signal the carrier to wake the direct body; the guide's release-vs-terminalize table is the fleet path's contract.

The deps seam (deps= / deps_factory=)

The body's dependency door (the DI capability): declare a deps type per app, bodies opt in with a last deps:-annotated parameter, and the door binds ONE instance. The authoring guidance — when to pick each face, the shapes, the lifecycle order, the scope — is the workflows guide's deps seam section; this page is the contracts.

The declaration surfaces and their deps-binding kwargs:

  • WorkflowApp(deps=None, deps_factory=None, deps_teardown=None, deps_generation=None) — the app's ONE binding, carried by the compile into every door (the worker-hosted execution door and the packaged run(...) read it from the compiled object).
  • FlowRunner(compiled, pool, schema, *, worker_id=None, deps=None, deps_factory=None, deps_teardown=None, deps_generation=None, default_start_to_close=None, cancel_state=None) — the direct door: an explicit deps= / deps_factory= OVERRIDES the compiled binding (the E12 validation re-runs against the effective binding); passing both is refused.
  • run(flow, pool, schema, *, …, deps=None, deps_factory=None, deps_teardown=None) — the packaged one-call door (the runner face above; the instance releases when the call returns).

Declaration-site refusals (ValueError): deps= and deps_factory= together; deps_teardown= or deps_generation= without a deps_factory=; an async context-manager (or async generator) factory paired with deps_teardown=. Non-callable factory, teardown, or generation arguments are TypeError at the same boundary. The resolve-time refusal covers the shape the declaration cannot see: a plain factory that produces an async context manager while deps_teardown= is also given. At rotation, a generation source that answers any other type produces a TypeError through the rotation's error channel, and the current instance keeps serving.

The factory shapes and the ONE teardown-owner precedence (at most one teardown attempt per resolved instance):

  1. async context manager / async generator factory (including a plain factory whose product IS an async context manager) — its __aexit__ / finalisation is the sole owner;
  2. plain sync/async factory + deps_teardown=callback — the callback is the sole owner even when the product exposes aclose();
  3. plain factory with no callback — the product's aclose() when it has one, otherwise no teardown.

The factory is invoked LAZILY — never at declaration, compile, or validation time — on the running event loop at the first body execution that declares the deps shape, serialized by an asyncio.Lock (concurrent first claims run it exactly once). A failing factory caches nothing: the exception propagates to that body and the next claim retries.

The scope: the worker-hosted door resolves the app's factory once per (declared binding, worker identity, event loop) — every workflow of the app on that worker shares the instance, workgroup children (separate loops) and co-resident workers each resolve their own, and one worker's teardown never reaches another's. The direct door is per-runner (each drive-created child runner owns its own).

The lifecycle order on the worker (graceful shutdown and the crash unwind where the exit stack runs): TaskGroup drain → every already-resolved factory-created deps instance released exactly once, each with its own bounded attempt → the PG role pools close. Every reload (SIGHUP / request_reload() / scheduled) runs the deps hand-off BEFORE any pool swap: the generation is re-read, in-flight bodies drain bounded, the superseded instance releases once, and — when the generation advanced — the cached runners are evicted. A hard- killed worker (SIGKILL/OOM) runs no teardown.

The drain bound is not an unlimited clean-completion promise: clean-completion protection ends at the drain bound. A changed generation's superseded instance is released anyway; old-pool closure also proceeds after its own bounded claim drain, and a body or finalize still running after that point can fail and follows ordinary durable job-failure recovery. Its later unwind runs no second teardown, and the worker emits workflow-deps-drain-timeout.

Direct-door disposal and rotation: FlowRunner is an async context manager (async with FlowRunner(…) / await runner.aclose() — releases the resolution it minted plus every child runner, each owner attempted even when an earlier one fails; a failure propagates after every owner has been attempted), and await runner.reload_deps(drain_timeout=…) rotates the binding to its current generation (DepsRotation, exported at taskq.workflows: rotated, generation, previous_generation, had_instance, drained, error). It returns drained=False when the bound expired before releasing the superseded instance anyway; a body still using that instance can then fail and follows ordinary durable job-failure recovery. A generation-source or superseded-release failure is returned in error, not raised. The call is refused only when neither the runner nor any drive-created child has a factory binding, or when the runner's resolution is worker-owned.

Telemetry: On the worker-hosted door, the structured log events workflow-deps-resolved, workflow-deps-torn-down, workflow-deps-rotated, workflow-deps-drain-timeout, workflow-deps-resolve-failed, workflow-deps-teardown-timeout, workflow-deps-teardown-error, and workflow-deps-rotate-failed carry workflow, worker_id and generation. taskq.workflows.deps_resolved carries workflow and generation; taskq.workflows.deps_torn_down adds outcome (ok / failed) — worker_id stays off the metrics, never a metric dimension (the cardinality contract).