Workflows — the DAG engine (taskq-py[flows])¶
START HERE, newcomer: the five-minute path is the next section — wire a DAG, run it, read the result, one fence. After it, this page is the engine's REFERENCE — it explains the machinery and pins every invariant. If you want the thirty-second tour of how to AUTHOR a flow (the verbs, the wiring, the hold), read the API reference first (
docs/api-reference/workflows.md, §"the thirty-second tour"), then the worked example (docs/examples/doc-ingest.md), then come back here for the internals.
The five-minute path¶
Everything you need to run a workflow: wire steps (the promise arguments
ARE the edges), fan items out with map_source, run ONE call, read the
decoded result. This fence runs as-is under the docs-example harness
(TASKQ_PG_DSN and TASKQ_SCHEMA_NAME supplied by the harness; set
TASKQ_PG_DSN yourself and the schema defaults to taskq — the same
default the settings carry):
import asyncio
import os
import asyncpg
from pydantic import BaseModel
import taskq.migrate
from taskq.workflows import (
Promise,
StepContext,
WorkflowApp,
build,
map_source,
run,
step,
)
class Batch(BaseModel):
doc_ids: list[str] = []
class Enriched(BaseModel):
doc_id: str
text: str
class Report(BaseModel):
published: list[str]
async def ingest_body(ctx: StepContext) -> list[str]:
# THE RUN INPUT'S DOOR: `run(input=…)` seeds ctx.input ONLY — it does
# NOT seed any body's wired params. The body re-hydrates the run's
# input through the declared model's own validator (the tenant
# pattern at THE BODY'S THREE INPUT CHANNELS below).
batch = Batch.model_validate(ctx.input)
return batch.doc_ids
async def enrich_item(ctx: StepContext, doc_id: str) -> Enriched:
return Enriched(doc_id=doc_id, text=f"the text of {doc_id}")
async def publish_body(ctx: StepContext, enriched: list[Enriched]) -> Report:
return Report(published=sorted(e.doc_id for e in enriched))
app = WorkflowApp()
@app.workflow("doc_pipeline")
def doc_pipeline() -> Promise[object]:
ingested = step(ingest_body, key="ingest") # no wired source: the body reads ctx.input
enriched = map_source(ingested, enrich_item) # the join: ingest.join
return build(step(publish_body, enriched, key="publish"))
async def main() -> None:
dsn = os.environ["TASKQ_PG_DSN"]
schema = os.environ.get("TASKQ_SCHEMA_NAME", "taskq")
await taskq.migrate.apply_pending_locked(dsn, schema=schema, phase="pre")
await taskq.migrate.apply_pending_locked(dsn, schema=schema, phase="post")
pool = await asyncpg.create_pool(dsn)
the_corpus = ["doc-1", "doc-2", "doc-3", "doc-4"]
outcome = await run(
app.get("doc_pipeline"),
pool,
schema,
input=Batch(doc_ids=the_corpus),
)
print(f"claim={outcome.claim.kind} outcome={outcome.outcome} result={outcome.result}")
# THE INPUT FLOWED (the fence's own assertion): the published list is
# the run input's list — a shape where `run(input=…)` does nothing
# (a body reading a wired seed instead of ctx.input) cannot pass
# here, because the output tracks the input exactly.
report = Report.model_validate(outcome.result)
assert report.published == the_corpus, (
f"the run input never reached the body: {report.published!r} != {the_corpus!r}"
)
asyncio.run(main())
Verified output (this guide's capture, on a fresh schema):
THE FENCE'S ONE LESSON, STATED WHERE THE FENCE IS (the full table is
THE BODY'S THREE INPUT CHANNELS
below): run(flow, input=…) seeds ctx.input only — the RUN's input,
the same value for every node of the run. It does NOT seed any body's
wired params: a body that declared a wired Batch param and ignored
ctx.input would run on the EMPTY seed forever (the wired param is the
node's OWN payload — a producer's decoded result, never the run input).
The fence's ingest_body reads ctx.input — the tenant pattern — and
its assertion makes the inert shape impossible: change the input, the
published list changes with it.
That is the whole loop: typed payloads in, a typed result out, every step a row you can inspect. Where to go next, by the question you're asking: the human gate → Agent fleets; the streaming fan-out → Event pipelines; what you get vs the other orchestrators → the pattern catalog. The rest of this page is the machinery those fences ride.
The workflow engine turns a fan-out/fan-in shape into queue rows with a
counter and a ledger: fork N children atomically, join when the ledger
says they are done, fire exactly once, deliver the declared consumers.
Nothing here is a second task system — every workflow row IS a jobs row,
dispatched by the vanilla claim path.
THE IMPORT LAW: import taskq never imports this package. The only
sanctioned entry is import taskq.workflows by a caller that opted into
the taskq-py[flows] extra. The engine is core-deps-only (tors, asyncpg,
uuid_utils); the extra exists as the operator-facing opt-in marker.
The join-wait representation¶
A joined node waits as status='pending' + deps_pending > 0 (+
metadata.blocking_reason='join'). No new ENUM value: pending is legal
in the vanilla machine, and the dispatch claim's AND deps_pending = 0
exclusion keeps join-wait rows unclaimable. When the counter hits 0 the
row becomes claimable by the claim predicate — no status write.
The two-transaction finalize¶
finalize_node = tx1 then tx2:
- tx1 — the result write, carrying the TERMINAL-MARK FENCE
(
status='running' AND locked_by_worker=… AND attempt=… AND claim_epoch=…). A row the reclaim flipped, or a fenced attempt, updates nothing. The fork's child INSERTs + edge rows + join node share tx1 (a kill at any statement boundary rolls the whole tx back; the reclaim re-forks). The step ledger's terminal write rides tx1 (the ledger-terminal-atomic rule), and the failure IO-capture rides tx1. The ledger's write keys the claim's OWN RETURNING id (or the full arbiter tuple withCOALESCE(map_index, -1)) — a map child's outcome can never overwrite its sibling's. tx2 runs ONLY when tx1's fenced UPDATE returned a row (the ROWCOUNT GATE): 50 duplicate finalizes → 1 decrement. - tx2 — the guarded decrement: one atomic
UPDATE jobs SET deps_pending = deps_pending - 1 WHERE deps_pending > 0over the edge ledger, with the flow-status EXISTS leg inside the statement; rows hitting 0 → the guarded fire → only the guard winner runs the reducer body (INSIDE tx2) and writes the outbox rows.
The reducer body's boundary¶
A raising reducer rolls tx2 back — the decrement, the fire row and the outbox rows all roll back — and the re-derivation re-fires: the body RE-RUNS. At-least-once body execution; exactly-once for DB-local effects (the ledger claim + the composite arbiter), the stated boundary.
The tx1→tx2 crash window keeps the same guarantee ACROSS PROCESSES: the
leader's maintenance sweep runs sweep_join_rederive, which re-derives
the counter from the edge ledger and fires the firable joins. The sweep
heals schema-wide — ANY leader heals ANY flow's join-wait rows. The fired
join's body resolves through one door, in a fixed order: the fire arm
consults the process-local reducer memo FIRST; on a miss, the flow
root's stamped workflow name (metadata.workflow — insert_flow_run
writes it at create) decides the record's face. A stamped name that
resolves to NO compiled graph in the healer's process (the definitions
not imported there — a deployment defect), and a root with no stamp at
all, are the LOUD face: the delivery CONTINUES, the row is stamped
blocking_reason='body_unavailable', and a WARNING names it. A stamped
name that resolves answers NO body: the registry never supplies a
reducer body on the fire path — a join has no body of its own (the
identity packer assembles its output from the parents' decoded
results), and a step's body executes at the row's CLAIM (the wired
args), never at the fire. No shipped finalize_node caller passes
reducers=, so the memo is never warmed and the healer never runs a
reducer body inside its transaction: the fire delivers, and every body
resolves from the registered definition at the fired row's CLAIM — the
durable leg (the BODY-FROM-DEFINITION discipline). The memo, when a
caller warms it, answers only in the process whose finalize warmed it;
it is bounded — the phantom reaper drops a terminal flow's entry at the
reap (a terminal flow's joins can never fire). A body that does run
inside the fire's transaction rolls the pass back on a raise, and the
next tick re-fires — the same at-least-once shape the finalize's tx2
states.
The fan-in bound + the two join shapes¶
The bound: ≤ 1000 declared parents per join (MAX_FAN_IN_PER_JOIN) —
enforced at validate (wf.validate() / the validators): a join declaring
more is REFUSED, the error naming the bound and the child-driven
alternative. The refusal's class is
FanInBoundExceededError (a ValueError subclass, exported from
taskq.workflows) — the class the operator meets: it is the fork's
DETERMINISTIC authoring failure (the run record carries
error_class='FanInBoundExceededError', the retry ladder never burns —
re-running cannot shrink the corpus), and its message carries the
remedy: the child-driven escape below, or partition the map. A map wired
on a join or gather counts the true item count, not the prefix the
join row spells under the size cap (below): past 1000 items it
terminal-fails FanInBoundExceededError unless the map declares
child_driven=True; on a widened (POST) schema — or at exactly 32,768
items on any schema — it terminal-fails even with child_driven on the
join counter's own FanInBoundExceededError.
While the identity carriers are still smallint, a map past 32,768
items fails first with error_class='MapIndexExhaustedError',
child_driven or not. Partition the source.
THE HONEST DERIVATION (never a line through points that don't share one): the three measured points — 200 → 14.9 ms, 1000 → 23.8 ms, 5000 → 39.3 ms — are sub-linear-in-log but NOT one line: an endpoint fit (~5.1 µs/edge + ~14 ms base) predicts 19.1 ms at 1000 against the measured 23.8 — the 1000 point is the outlier, named as such (least-squares gives ≈4.7 µs + 16.3 ms and still misses the endpoints). The landed implementation's own refit (the scale pin re-runs the measurement) reads ~1.7 µs/edge + ~2.7 ms base (the artifact's refit block: marginal 1.684, base 2.705, the refit at the 1000 bound 4.39 ms, the outlier residual −1.05 ms — the recorded points are 200 → 3.04 ms, 1000 → 3.34 ms, 5000 → 11.1 ms; the base-dominated criterion genuinely holds: base 2.7 ms vs the 1000-edge marginal term ~1.7 ms), with the same shape. THE GOVERNING BUDGET, STATED HONESTLY: at the ~3-16 ms BASE term no fan-in meets a 5 ms-class budget; the declared-edge cost is dominated by the BASE (paid once per sweep pass regardless of fan-in), not the edges — the marginal edge cost is µs-class. The bound stands on that BASE-COST argument — what it bounds is the PER-JOIN marginal work inside one pass, not a per-edge cost comparison.
The child-driven escape (child_driven=True on map_source /
route — the authoring verbs' own param; the engine-level spelling is
JoinSpec(child_driven=True)): past the
bound, the join does not trust the per-joined-row counter cache — the
fire counts its terminal children FROM THE EDGE LEDGER (each child's
finalize names its join target; the choice is RECORDED on the joined
node's metadata.join_shape='child_driven'). The exactly-once pins
(duplicate-finalize, double-fire PK) hold on BOTH shapes. OPERATIONAL
GUIDANCE: prefer partitioning the map over the escape — a fan-in past
32767 cannot even carry its count in the smallint counter cache (the
cache is a cache; the ledger is the truth — a >32767-unterminal recount
needs the counter's own widening before it can reconcile), so a genuinely
huge fan-in is a schema conversation, not a knob.
The unreachable join: a cancelled parent¶
A parent that terminalizes cancelled resolves NO edge: a cancel is not a
result, so neither the fire nor the counter's reconciliation may treat it as
one, on any failure policy. That leaves a pending join-wait row nothing can
progress — so the sweep resolves it explicitly. The cancelled_parent arm
in REDERIVE_SWEEP_SQL terminalizes the join row:
status='cancelled',finished_atset,deps_pendingrecording the write-time unresolved-edge count;error_class='CancelledByCancelledParent'— the graph origin, never the operator'sWorkflowCancelled(see cancellation.md);metadata.cancelled_parent/metadata.cancelled_stepnaming the cancelled parent, and astate_changeevent on the row's timeline;blocking_reasonKEPT as'join'— the joined-row family marker every fired and terminal join row carries (the map-progress readers exclude the family by it). It denotes an ACTIVE join-wait only whilestatusispending; every block classification in the derivation and the SQL gates on that status, so a cancelled join is never counted as blocked.
The run then converges once its other live work finishes: with no live row
left, the maintenance derivation derives the root cancelled unless an
unabsorbed node failure takes precedence and derives failed — matching what
the rows say. Nested joins follow on later passes (the upstream join is now
the cancelled parent of the next one), and the row leaves
jobs_wf_join_fire_probe_idx immediately, so a batch of unreachable joins
cannot starve newer ones. Terminalizing rather than leaving a stamped
pending row is what makes that possible: a pending row is live to every
liveness read (root maintenance, NodeView.is_blocked_row, the retention
root-guard), so a stamp alone could never let the run finish.
The remedy is a re-run, not a retry. The cancelled parent is not
re-armable, so taskq flows retry cannot reopen the path; if the work is
still needed, start a new run under a new run_key.
The failed-parent propagation¶
A parent's TERMINAL failure — the retry ladder EXHAUSTED, or a
non-retryable class — resolves the joins counting it by the edges' DECLARED
failure policy, recorded on the edge ledger (wf_edge.failure_policy) at
fork/join time. The absorption is on the record; the derivation never
infers it.
fail_closed (the default) — the join fails CLOSED by a flow-scoped
transition set, ONE statement in the failing child's tx2:
- the joined node blocks:
metadata.blocking_reason='failed_parent'+metadata.failed_parent=<the failed node>— its side of the counter is resolved by THIS stamp (the rederive arm locksblocking_reason='join'rows only), so the record never shows a hanging join; - the running peers are PEER-CANCELLED:
status='cancelled'with the cancel-origin markererror_class='CancelledByPeerFailure'(thebyleg — the same outcome reads the same way whichever path produced it) and the structured recordmetadata.peer_cancel = {"by": "peer_failure", "cascade_from": <the failed node>}; - the workflow fails: the flow root flips to
failed(the cascade) — the linearization point every flow-status leg then reads.
The sweep composes: a child whose tx1 committed the terminal failure but
whose tx2 never ran (the crash window) is healed by the rederive arm's
failed_required count — a join whose parent reached ANY failure terminal
(failed, crashed, abandoned) on a non-absorbing edge is
blocked-with-reason by the HEAL, never fired over that parent, and the
parent's id and step key are stamped beside the reason
(metadata.failed_parent / metadata.failed_step).
The terminal-failure trigger: the peer-cascade fires only on TERMINAL failure — a child mid-ladder does not trigger it (a ladder retry emits no terminal, P3 decision 7), so a fail-closed map with a long-ladder child keeps its peers running until exhaustion. BY DESIGN, not an oversight: over-rejecting (murdering peers on an attempt-failure) is the worse asymmetry; the peers' work is real work the flow may still need.
collect — child failures do NOT cascade. Each child runs to its own
terminal; at exhaustion the failure fans in as the typed FailureInfo
item, APPENDED to the join row's metadata.failures array, and the join
FIRES with the typed partial result. FailureInfo EMBEDS the estate's
error envelope — never re-spelled: ErrorInfo(error_class, error_message,
error_traceback) (taskq.backend._protocol, its bound constants carried
as-is), with attempts / node_key / map_index as the workflow-only
extensions. THE TYPE'S IMPORT FACE: from taskq.workflows._types import
FailureInfo (the wire-spec submodule — the documented path, the same
discipline the package root's surface law states; ErrorInfo is
from taskq.backend._protocol import ErrorInfo). attempts carries
the FULL attempt history (one entry per
ladder attempt, every error payload). The fan-in + the fire ride the
terminalizing tx: the fire is strictly AFTER the last ladder attempt
(the ts-ordered pin). A SKIP fans in with ZERO ledger rows — a skip is
not an attempt. The workflow SUCCEEDS with the failure report (the
absorbed-failure clause in the status derivation,
docs/guides/observability.md); the failure detail's home is the
ledger/attempts — the join row's array is the bounded summary (the
JSONB size-cap policy — see The JSONB size cap / compaction policy
below).
The crash class is the collect contract's edge — know it before you rely on the absorption. The fan-in above runs on the child's FAILED
terminal (the ladder exhausted). A child killed MID-ATTEMPT (SIGKILL,
OOM, a lost worker) reaches the FAILED-CLASS terminal crashed through
the fleet's lease-reclaim sweep — and that crash-class terminal
currently contributes NO FailureInfo item to the join's
metadata.failures. What the join then shows, read off the rows: the
crash-class child occupies its slot in the packed list as null (its
slot is on the record — the decode of a typed sum REFUSES the null
loudly, ValidationError … input_value=None, and the run ends failed —
correctness is saved by the loud decode, never silently), with the
failures array EMPTY. The consumer that wants to survive crash-class
children today must type the join's union accordingly or decode
defensively; the crash record's home is the child's own row
(status='crashed', its attempt rows) — docs/guides/runbooks.md's
mid-run crash page has the operator path. (The engine fix — the
crash-class child's failure record riding the same collect fan-in — is
filed against engine.py's failed-parent resolution, which currently
routes outcome == "failed" only.)
The retention coupling¶
The pruner is WORKFLOW-AWARE: the result-expiry sweep may not eat a map's
children before the join fires (a child's result_expires_at is held
while a join-wait node counts it — after the join fires, the subtree ages
together), and retention may not prune a parent row of a
NON-terminal run (the sweep's ledger recount reads parent rows as
truth), nor a finished run's own __flow__ root row while any
non-terminal child or undelivered wf_outbox delivery intent of that run
remains. The intent leg covers terminal effects and loop escalations,
whose consumer materializes on the already-terminal root; archiving first
would make the drain acknowledge a delivery it could not insert. A child
left rootless would likewise have no body to resolve — no claim fence
admits it, and the detector reads it as workflow_root_missing. Terminal
runs whose children are all terminal and whose outbox intents are delivered
prune on the normal schedule. The guards are
WHERE-class conditions on the EXISTING arms — no new sweep process; the
failure mode the guards prevent is Oban-Pro's documented
preserve_workflows lesson (the reduce reading holes — the silent
partial). See docs/guides/maintenance-sweeps.md §7.
The JSONB size cap / compaction policy (this note is the policy's one
home):
the collect's FailureInfo list on the join row is BOUNDED — an append
that would exceed the byte cap (FANIN_FAILURES_BYTE_CAP, 64 KiB)
compacts the row to the bounded summary (the "__truncated__": N marker
counting the items no longer spelled + the ledger pointer); the FULL
detail stays on the ledger/attempts — the record never loses it. The
compacted row stays bounded forever (a later append increments the
marker). The collected result envelope of a map join or gather follows
the same 64 KiB cap: past it the row keeps the prefix that fits,
__truncated__: N and a detail_home pointer, and the full collect
stays on the rows it was collected from (a map join's .item children,
a gather's parents). A map wired directly on the join forks one child per item the join
packed, and every reader of a truncated join — a consumer step's
arguments (_parent_results), FlowRunner.result(), a skip= / guard
predicate's state["results"] (_flow_state), and a child flow's
terminal read (ChildHandle._ok_result) — recursively rebuilds the full
collect off the detail rows (decode_result_with_detail), including
nested joins (such as a gather over truncated map joins or a gather
over gather).
When the detail rows are gone, the read fails closed. A truncated
join's full collect lives only on its parent rows, so retention that
expires or purges them costs more than a stored byte: reading that join
raises WorkflowResultDetailUnavailableError on the FIRST attempt — no
retry, because no retry can restore the rows — and the consuming node
terminal-fails with the class on its row. The same class is raised when
the terminal row's own result was swept, and when a re-pended (retried)
row's result is NULL. skip= predicates are on the same path: their
state["results"] view decodes through the same re-read, so an
unreadable entry fails the gated node deterministically instead of
deciding against a hole. The remedy is to re-run the flow; retrying the
node that raised cannot succeed.
The three cancel legs¶
Cancel = one transaction — the flow flip is the linearization point; every other statement re-checks flow status inside its own statement. THREE legs, all shipped, any two insufficient:
- the fire guard's flow-status leg (finalize tx2 and the sweep's fire);
- the dispatch fence — the claim's candidate WHERE carries the flow-status EXISTS for workflow rows (a pending child of a cancelled flow is unclaimable; it refuses cleanly and the sweep re-derives);
- the finalize fence (the terminal-mark CAS: worker + attempt + claim-epoch — the attempt is the fencing token).
The step ledger + the run-key arbiter¶
The step ledger's claim is ONE round trip
(INSERT … ON CONFLICT (flow_id, step_key, COALESCE(map_index, -1),
attempt, claim_epoch) DO UPDATE … RETURNING) — the ledger row IS the
claim, the arbiter physically blocks double-recording, and map children of
one step key are DIFFERENT claims. ctx.substep("name", fn) is the
user-facing shape: default idempotent ON, idempotent=False opts a step
out.
A substep record belongs to the node execution that made it. The
owner is the calling node's job row and, inside a loop body, the loop
iteration. The same name in two nodes, two map children, two maps or two
iterations is a different record, so each runs its own fn. Within one
execution, calling the same name again replays a succeeded record. A
re-call after a failed one in the same attempt runs fn again and
records THAT run's outcome: the substep claim re-opens the failed row, so
a third call, a retry or a hold resume replays a new succeeded result.
If the re-call fails, its newest error replaces the old one and the next
invocation runs fn again. A call made while one with the same name is
still running (for example, both inside one asyncio.gather) raises
DuplicateSubstepError before it claims anything, and the running call
is left alone. Uncaught, the error fails the node on its first attempt;
in a loop body the loop exhausts as a body failure whose message names
it. Fix the collision instead of retrying the node: because the running
call is not cancelled, a retry can run that effect a second time while
the first call is still inside fn. idempotent=False calls write no
row and are exempt. Give
concurrent substeps distinct names. The
row's step_key is <job id>/<name>, or <job id>.iter<n>/<name> in a
loop body. Upgrading a fleet across this change needs a workflow-executor
cutover: see
the upgrading entry.
The substep holds no connection across the body (the measured tax, stated so nobody re-pays it): the claim and the terminal write are ~1 ms statements, each on its OWN pool acquisition; between them the body runs with NO connection held. Holding ONE connection from the claim to the terminal would collapse a hot map fan-out's concurrent substeps to the execution door's conn count (the dispatcher pool, 4 connections at the shipped default): a 300-child fan-out measured the drop from 32 in-flight to 4 (10.1 s → 27.1 s at the demo profile; 11.1 s → 42.2 s at 0.5 s/call). The exactly-once guarantee never needs the held connection — the claim arbiter linearizes the grant, and the terminal keys the claim's OWN row id. Substep the calls that cannot tolerate a re-run freely: the replay face is throughput-free.
Run-level idempotency claims against
the same composite arbiter with the scope workflow-run:<flow name> — a
conflict returns the EXISTING run's TYPED claim (RunClaim: created /
existing-running / existing-terminal), never a second silent
run, and two different flows sharing a naive key never collide (each
flow's keys namespace its own scope). THE RUN KEY'S SURFACE — ONE
name, both doors: key= (canonical) on FlowRunner.create_flow(key=…)
and the PACKAGED one-call run,
taskq.workflows.run(flow, pool, schema, input=…, key=…) — create +
drive + the decoded result in one call, the typed claim on the returned
WorkflowRunResult (run_key= rides as the alias on both; passing
both and disagreeing is refused). THE TERMINAL CASE IS STATED, NEVER SILENT: a
TERMINAL run's replay answers existing-terminal with the prior run's
id + status — the REFUSED-TO-REUSE verdict (a failed run squatting its
key silently was the founding bug class; the re-run is the caller's
documented choice of a NEW key). On the packaged door the replay is
LOUD at the caller's except: the prior run's error re-raised from
run() carries claim_verdict == "existing-terminal" — the attribute
tells the handler this raise is the replay refusal, not a fresh
failure. The demo endpoint surfaces the
distinction: 202 for created/existing-running, 409 for
existing-terminal. Cron composition: the cron entry
fires the slot key as the run key — same slot twice → ONE run.
THE CREATE IS ATOMIC: the root + the static nodes + the edges + the
root's start are ONE transaction — a kill at any statement window leaves
no ORPHAN ROOT behind (a run row with zero node rows is unrepresentable:
the maintenance derivation develops a run FROM its node rows, and a
nodeless root never derives, never terminalizes, never prunes — and it
would squat the run key forever). The belt for that failure is the
wf_nodeless_root_reap sweep arm: any nodeless root that could ever
exist (a future statement-order regression's debris) is reaped failed
(NodelessRunReaped) once past the reap grace — the re-run is then a
NEW key, the typed claim says existing-terminal.
The cross-run step cache¶
The arbiter's dedups are CONCURRENT and scoped: two callers racing one
run key get one run, and ctx.substep's memo dedups a retry WITHIN a
run. Neither answers the temporal, cross-run question: the re-run (a
new run key, the same input) of an EXPENSIVE body — the OCR's pixels,
the LLM's tokens — executes everything again. The cross-run step cache
is the opt-in that closes it:
import asyncio
import os
import asyncpg
from pydantic import BaseModel
import taskq.migrate
from taskq.workflows import (
Promise,
StepContext,
WorkflowApp,
build,
run,
step,
)
class Doc(BaseModel):
doc_id: str
class Report(BaseModel):
ref: str
calls = {"ocr": 0}
async def ocr(ctx: StepContext, d: Doc) -> Report:
calls["ocr"] += 1
return Report(ref=d.doc_id)
async def consume(ctx: StepContext, r: Report) -> str:
return r.ref
app = WorkflowApp()
@app.workflow("cache_flow")
def cache_flow() -> Promise[object]:
report = step(ocr, Doc(doc_id="d1"), key="ocr", cache=True, cache_ttl=3600.0)
return build(step(consume, report, key="consume"))
async def main() -> None:
dsn = os.environ["TASKQ_PG_DSN"]
schema = os.environ.get("TASKQ_SCHEMA_NAME", "taskq")
await taskq.migrate.apply_pending_locked(dsn, schema=schema, phase="pre")
await taskq.migrate.apply_pending_locked(dsn, schema=schema, phase="post")
pool = await asyncpg.create_pool(dsn)
first = await run(app.get("cache_flow"), pool, schema, input=None, key="cache:demo-1")
second = await run(app.get("cache_flow"), pool, schema, input=None, key="cache:demo-2")
receipt = await pool.fetchval(
f"SELECT metadata->'wf_cache_hit'->>'run_id' FROM \"{schema}\".jobs "
"WHERE metadata->>'flow_id' = $1 AND step_key = 'ocr'",
str(second.flow_id),
)
print(f"first={first.claim.kind} second={second.claim.kind} ocr_calls={calls['ocr']}")
print(f"the hit's receipt names the producing run: {receipt == str(first.flow_id)}")
asyncio.run(main())
THE TWO-CLAIMS LAW — read it before opting in:
- The arbiter dedups CONCURRENT — two runs racing one key are one run. The cache does NOT dedup concurrency: two concurrent misses both run their bodies (that is the arbiter's claim, and the cache never takes it over).
- The cache dedups TEMPORAL — a LATER run over the same body and the same input reads the EARLIER run's result. The address is the Nix-style recursive hash: the body's code-version canon (module, qualname, the body's own source) RECURSED with the resolved input's canonical jsonb. A body's code change IS a new address (the stale-code face is dead by construction); the same body over the same input at any position in any run is the SAME address (position-independent on purpose — the cross-run face's point).
The store is SUCCESS-ONLY: the result fills wf_step_cache on
terminal-succeeded only (ON CONFLICT keeps one winner per address; an
expired row is re-filled by the re-run's success). A failed run writes
NOTHING — the failed-run-squats-the-key bug is closed by construction;
the second run after a failure re-executes the body, never a cached
failure. A cache HIT delivers the cached envelope through the ordinary
fenced finalize: the body never runs, the downstream decodes the SAME
typed shape, and the node row's metadata.wf_cache_hit carries THE
RECEIPT — the address, the producing run's id, the store instant — the
hit is auditable from the row alone.
Verified output (this guide's capture, on a fresh schema — the SECOND run's body never ran):
THE DETERMINISM HAZARD, stated plainly: the cache assumes the body is
DETERMINISTIC for the same input. A non-deterministic body — a
clock-reader, a random walker, a now() sampler — with cache=True
delivers the STALE TRUTH BY CHOICE: the address promises "same body,
same input", never "the world stood still". Opt in only for bodies
whose result is a pure function of the input; the default is OFF (the
cache is a decision, not a surprise), cache_ttl without cache=True
is refused at the wiring site, a non-positive TTL is refused, and a
cache on the multi-parent gather is refused (the v1 surface is the
plain step).
THE ADDRESS'S SCOPE — what "same body, same input" covers, exactly:
- The code half covers the body's OWN source only — module, qualname, the body's source text. A changed HELPER is invisible to the address: a helper's redeploy is a byte-identical address, and the PRE-DEPLOY truth serves until the TTL. That is the documented contract, and the operator's discipline is the remedy: when the closure's truth changes, change the BODY's own source too (even a comment-line change moves the address). A transitive-closure hash (the helpers' sources hashed in) was considered and not built — the cost (a source-read walk over the whole call graph at the claim path, per attempt) and the false-positive face (an unrelated helper edit invalidating every address) are not justified by the hazard the discipline covers.
- The input half covers the WIRED args only. The FLOW input
(
ctx.input) NEVER enters the address. That is whycache=Trueon a body readingctx.inputis REFUSED at the wiring (E18): the cached answer produced under one flow input would serve a later run whose input differs — the cross-tenant leak (tenant A's answer delivered to tenant B, terminal-success, audits clean). For a SOURCE node the flow input is its only run-varying input, so a source body reading the run input has NO sound address either (the 640-row feed served its cached answer to the 60-row feed); the refusal teaches the fix.
The remedy is the same shape for both faces — lift the flow input into the dataflow with an UNcached upstream step and wire its result as the cached body's param (the param enters the address, the value differs per input, the cache caches per value):
import asyncio
import os
import asyncpg
from pydantic import BaseModel
import taskq.migrate
from taskq.workflows import (
Promise,
StepContext,
WorkflowApp,
build,
run,
step,
)
class Tenant(BaseModel):
tenant_id: str
class Report(BaseModel):
ref: str
calls = {"priced": 0}
async def read_tenant(ctx: StepContext) -> Tenant:
"""The UNcached lift: the flow input's value enters the dataflow
here — the flow input still never enters any address."""
return Tenant(tenant_id=ctx.input["tenant_id"])
async def price_for(ctx: StepContext, tenant: Tenant) -> Report:
"""The CACHED body: the tenant is a PARAM — it enters the address,
so each tenant's pricing caches under its own address."""
calls["priced"] += 1
return Report(ref=f"{tenant.tenant_id}:price")
app = WorkflowApp()
@app.workflow("tenant_cache_flow")
def tenant_cache_flow() -> Promise[object]:
tenant = step(read_tenant, key="tenant")
report = step(price_for, tenant, key="price", cache=True, cache_ttl=3600.0)
return build(report)
async def main() -> None:
dsn = os.environ["TASKQ_PG_DSN"]
schema = os.environ.get("TASKQ_SCHEMA_NAME", "taskq")
await taskq.migrate.apply_pending_locked(dsn, schema=schema, phase="pre")
await taskq.migrate.apply_pending_locked(dsn, schema=schema, phase="post")
pool = await asyncpg.create_pool(dsn)
first = await run(
app.get("tenant_cache_flow"), pool, schema, input={"tenant_id": "tenant-A"}, key="tenant:a"
)
second = await run(
app.get("tenant_cache_flow"), pool, schema, input={"tenant_id": "tenant-B"}, key="tenant:b"
)
third = await run(
app.get("tenant_cache_flow"), pool, schema, input={"tenant_id": "tenant-A"}, key="tenant:a2"
)
print(f"priced_calls={calls['priced']} (2: one per tenant — B's run paid, A's re-run hit)")
print(f"A's answer: {await _ref(pool, schema, third.flow_id)} (never B's)")
async def _ref(pool: asyncpg.Pool, schema: str, flow_id: str) -> str:
raw = await pool.fetchval(
f"SELECT result->'value'->>'ref' FROM \"{schema}\".jobs "
"WHERE (metadata->>'flow_id')::uuid = $1 AND step_key = 'price'",
flow_id,
)
return str(raw)
asyncio.run(main())
Verified output (this guide's capture, on a fresh schema — the SECOND run per tenant never re-ran the body):
priced_calls=2 (2: one per tenant — B's run paid, A's re-run hit)
A's answer: tenant-A:price (never B's)
Three more refusals close the remaining sound-address holes, each at the wiring site (and re-proved by the validator's own rules — E17/E19/ E20):
- A typed-route source is refused (E17):
cache=Trueon a source that carriesroute(...)arms wedges the run FOREVER 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 while the source row readssucceededwearing a cache receipt. Cache the route's arms' work, never the fork-spawning source. - An Exit-returning body is refused (E19): the sentinel
terminalizes through the exit finalize, which the success-only store
never sees —
cache=Truewould silently no-op (every run re-executes the body while the cache machinery looks armed). - An unverifiable body source is refused (E20): a builtin, a
partial, or an exec'd fragment cannot be hashed (the address
requires the code-version canon — module + qualname + the body's own
source), and the pre-refusal shape was the SILENTLY uncached step:
the wiring accepted
cache=True, every run re-executed the body, and the only trace was a log line. Define the body as a module-level def, or dropcache=True.
The TTL is the in-DB expiry (expires_at, compared against the DB
clock): an expired row IS a miss — the re-run re-executes and re-fills.
The sweep's retention arm (wf_step_cache_retention, the
TASKQ_WORKFLOW_STEP_CACHE_SWEEP_PERIOD setting, default 1h,
timedelta(0) disables) prunes the expired rows — the freshness
decision is the lookup's; the pruner only deletes the dead weight.
Operating the cache: the eviction face¶
A well-shaped lie at a known address — a body that was deterministic
when it stored and is not anymore, a poisoned payload, a result produced
under a bug since fixed — serves every future run until the TTL with no
way to take it out. The operator's face is the taskq wf surface:
taskq wf cache list [--address-prefix PREFIX] [--limit N]— the cache's rows (the address, fresh/EXPIRED, the producing run, the store and expiry instants) AND the hits'wf_cache_hitreceipts (the hit runs' node rows, naming the address and the producing run each). The receipt already existed on the rows; this is its one surface.taskq wf cache evict [--address-prefix P | --flow RUN_ID | --step STEP_KEY | --all] [--yes]— the poison-pill door. DRY-RUN by default: the command prints the rows that WOULD go and touches nothing;--yesdeletes.--stepresolves the addresses through the step's ownwf_cache_hitreceipts (the only address↔step pairing the rows carry) — for an address no receipt names, use--address-prefix.
Eviction is immediate and one-way: the next run over an evicted address is a MISS — the body re-executes and re-fills on its own success. The lie's service ends when the operator says so, never silently.
The fault classes at the finalize: one fault, one semantics¶
The operator's mental model for a transient blip (a connection storm's
ConnectionError class) landing on a cached step's finalize is the
RECLAIM class, symmetrically on both faces — the HIT's finalize and the
MISS's finalize share one machinery seat, and the classifier reads
WHERE the error escaped, never which face it came from. On either face
the infra-class fault writes the ledger row crashed (never
failed), the retry ladder is untouched, and the node row re-pends:
the run is reclaim-eligible, not dead. The cleared-fault re-drive
completes the step through the ordinary fenced finalize — and on the
hit face the body STILL never runs (that is the cache's whole point);
the wf_cache_hit receipt lands on the reclaimed row with the
re-drive as its producer. A cached step can therefore never
terminal-fail on a transport blip that struck after its body (by
definition) never executed.
The sweep arms (wired)¶
The healing arms register in the leader's maintenance sweep loop
(the _SweepSpec tick table), gated on the backend's workflow capability
marker (workflow_sweeps_capable — the same hasattr seam every
maintenance sweep is admitted through, each capability its own marker; a
backend that implements only the legacy maintenance surface keeps the
arms off):
wf_join_rederive— the lock-first re-derive (FOR UPDATE SKIP LOCKEDthe join-wait children, count the unresolved parent-edges from the edge ledger — an edge resolves only on a succeeded parent, or on a failure terminal its declared policy absorbs — reconcile the cache, stamp orphans, fire the firable) + the set-based fire;wf_signal_sweep— the held rows' clock: the expiry arm (an overduetimeout_shold → the definedabandonedstate, one batch of 100 per tick) and the timer arm (__timer__holds due now → resolveddeliveredwith the wake record, drained to empty per tick);wf_child_join_wake— the child flow's terminal as its join hold's resolver (the held parent node resumes, the pointer-only transport knocks);wf_outbox_drain— the delivery half: consumer rows inserted idempotently on the composite arbiter, the undelivered flag flipped in the insert's transaction;wf_phantom_reap— 'running' ledger rows on terminal flows fenced (the rows-alone reconstruction reconciles). Actx.substeprow's fence is provisional: a call still insidefnwhen it is reaped records its own outcome over the fence when it returns.wf_nodeless_root_reap— the orphan root's belt: a flow root with ZERO node rows (the create-atomicity's debris shape) is reapedfailedpast the grace — the derivation can never develop it.wf_run_reservation_reclaim— therun_reservationsseat's third defence layer: a root-coupled hold whose root is terminal or gone, and whose graph has drained (the cooperative-cancel barrier), is freed so a run that died holding its bucket cannot deny it forever. The transactional release doors and the acquire-time steal are the first two; this arm is what a crash between them leaves behind. Leader-gated onworkflow_sweeps_capable, and its backlog is thetaskq.reservation.run_holds{state="live"|"reclaimable"}split plustaskq.reservation.oldest_reclaimable_run_hold_seconds— a non-zeroreclaimablethat does not fall is this arm not landing.wf_step_cache_retention— the cross-run step cache's expiry arm The cache's own retention: the expired rows pruned (the in-DB TTL's dead weight; the freshness decision is the lookup's — the pruner never touches a fresh row).wf_hold_stamp_reconcile— the hold-stamp reconcile (issue #748): a node parked on ametadata.holdstamp whose hold is no longerheldis unclaimable by the dispatch fence, so this arm clears the dead stamp and re-pends the row (the body's re-execution lands the next named state). The live hold is left standing. It drains within its tick: up tosweep_drain_batchesbatches ofevent_writer_batch_sizerows (800 at the defaults), and each heal emitswf-hold-stamp-reclaimedwith the clearedjob_ids/flow_ids.wf_edge_retention/wf_join_fire_retention/wf_step_ledger_retention/wf_signals_retention/wf_node_progress_retention— THE FIVE FLOW-HISTORY ARMS (below).
The arms' imports stay inside the spec calls (nothing outside the package
may import taskq.workflows at module scope).
The workflow tables' retention arms (the five periods)¶
Beside the two arms the sweep already owned — wf_outbox_retention
(TASKQ_WORKFLOW_OUTBOX_RETENTION_PERIOD, default 24 h) and
wf_step_cache_retention (TASKQ_WORKFLOW_STEP_CACHE_SWEEP_PERIOD,
default 1 h) — the leader's sweep carries FIVE retention arms for the
workflow tables' own rows, one setting per table:
| setting | the rows it retires | the rootless leg's row clock |
|---|---|---|
TASKQ_WORKFLOW_EDGE_RETENTION_PERIOD (wf_edge_retention) |
the wf_edge ledger rows |
the table has NO timestamp column — the rootless class deletes on sight (the pointee's absence IS the age proof) |
TASKQ_WORKFLOW_JOIN_FIRE_RETENTION_PERIOD (wf_join_fire_retention) |
the wf_join_fire rows (the exactly-once ledger's spent fires) |
fired_at |
TASKQ_WORKFLOW_STEP_LEDGER_RETENTION_PERIOD (wf_step_ledger_retention) |
the wf_step_ledger rows (one per attempt — the family's fastest grower) |
created_at |
TASKQ_WORKFLOW_SIGNALS_RETENTION_PERIOD (wf_signals_retention) |
the wf_signals rows (holds and their resolutions) |
created_at |
TASKQ_WORKFLOW_NODE_PROGRESS_RETENTION_PERIOD (wf_node_progress_retention) |
the wf_node_progress rows |
updated_at — a rootless row's flow is reached through the NODE's jobs row (metadata.flow_id; the table has no flow column) |
The direct-only lane's own history shape (the honest limitation):
these retention arms run in the LEADER's sweep registry — a fleet
deployment's own maintenance. A DIRECT-ONLY deployment (no worker
leader) has NO shipped automatic workflow-ledger/capacity retention
driver: inner nonterminal claim history (a ctx.substep's or loop
iteration's own ledger rows beside the fenced outer claim) and
terminal-aged capacity records can persist indefinitely there. They
remain non-authoritative claim history — the current jobs/root rows
decide every status — but nothing collects them until fleet-leader
retention (or a maintenance program explicitly invoking the private
primitives) runs. Terminal status alone invokes no cleanup.
All five default to timedelta(0) = OFF — the deletion-sweep
family's zero-means-off sentinel (negative values refuse at settings
load) — but DELIBERATELY OPPOSITE to the outbox/step-cache precedents,
which default ON: those prune DERIVED data (a delivered outbox row's
narration, an expired cache corpse — deleting them loses nothing
re-derivable), while these five prune THE FLOW HISTORY ITSELF (the
attempt ledger, the fire ledger, the signals). Default-off keeps the
upgrade safe — no surprise deletes on an existing estate; the operator
opts in.
THE DEATH RULE is the FLOW's (a row dies with its flow, never by its own age alone), and each arm runs TWO passes (the flows-side doomed selection — the full-table-walk shape was rejected at production scale and replaced):
- The flows-side pass (every tick): the TERMINAL-AGED ROOTS are
selected FIRST from the JOBS side (
step_key='__flow__'— the root identity, a terminal status, and the root's ownfinished_atpast the period; served byjobs_finished_at_idx), then each selected flow's rows delete through the table's flow_id index, row-LIMITed to the batch. The flow read through its root is the same law the retention coupling enforces one leg earlier (the guards keep the pruner out of a run's way while it lives): a live flow's rows are never touched, and a flow terminalized within the period waits it out. THE AGE CLOCK IS THE ROOT'Sfinished_at— the latest clock any of the flow's rows can carry (the root's age subsumes the row clocks); the comparisons run onstatement_timestamp(), the prune family's selection-bound clock. A NULL-stamped terminal root (the stamp never landed) is SKIPPED — never doomed: no history is removed that has no honest age (a seconds-old flow's history must not vanish under a 30-day period because its stamp never landed) — and the arm's rate-limitedwf-retention-null-finished-atwarning fires when a pass OBSERVES one (an hourly re-warn cadence per table, never keyed to a deletion): fix the stamp or backfill it, the rows stay until they carry an honest age. - The rootless pass (a coarser cadence — every 8th call): the orphan class — a row whose pointee is NOT a flow root at all (the root row absent, or a live NON-root job). It cannot be found from the flows side, so its statement is a PK-ordered walk that visits AT MOST the batch (the LIMIT bounds the SCAN) and probes each visited row's pointee once, deleting the row when the pointee is not a flow root and (where the table has a clock) the row itself is past the period.
Each pass deletes ONE bounded committed batch (prune_batch_size —
NOT a drain, the retention family's one-batch-per-pass discipline). And
the signals arm carries the ABANDONED-HOLD CLEANUP: a terminal flow's
HELD signals delete with the flow — nothing will ever deliver them (the
wait site is terminal) — while a LIVE flow's holds are never touched
(the deliver/resolve/expire arms own those).
The worker execution — the queue is the runtime, in production¶
A workflow row IS a jobs row, and the vanilla claim path dispatches it
— but a claimed row is work only if the claiming worker can RESOLVE the
body. Three fixes ship, one machinery:
1. THE EXECUTION FENCE (the claim's capability leg). A worker that
never imported the flow definitions cannot resolve any body — handing it
a workflow row buys a claim-snooze-claim loop. So the claim statement's
fence admits flow rows ONLY when THIS round's worker registered itself
capable: the workers row's metadata.workflow_execution boolean, stamped
at boot. A non-capable worker NEVER claims a flow row — the row waits for
a capable worker (the defined pre-deployment state; the stranded-jobs
detector surfaces a flow nobody can run). The fence short-circuits on the
step_key probe — a vanilla row's plan cost is one column test, the same
cost class the P3 fence's own comment pins (the zero-tax law: the vanilla
claim path is unchanged; the dispatch band stays green).
2. THE BOOT PROJECTION. A worker whose
process imports at least one WorkflowApp with at least one runnable
workflow boots CAPABLE (the gate counts the projection's actual output —
an imported-but-empty app, or one whose every workflow fails its compile,
projects no cohort and is not capability: the boot refuses and names the
compile failures): the projection
compiles every imported app's declared workflows (which is what populates
the definition registry in the worker's process — the body resolution
answers from these very compiles) and projects the compiled graphs'
(actor, queue) cohorts into actor_config rows — the SAME carrier, the
same sync_actor_config surface, the same drift guards the vanilla
@actor refs ride. The dispatch capacity LATERAL sees the workflow
cohorts; the admin's actors page, the drift machinery and
TASKQ_QUEUES_STRICT see them too — no second, invisible actor
population.
3. THE INTERCEPT (the claimed row's execution door). A claimed row
carrying the flow lineage (metadata.flow_id) executes through the
WORKFLOW machinery, never the actor registry: the body resolves from the
registered definition (the flow root's stamped metadata.workflow
name, the same durable leg the leader's fire arm uses) and runs via the
runner's ledger-claim + finalize machinery — the same two-transaction
finalize, the same fences, the same ladder. NOT a second execution
semantics: the in-process driver and the worker's door differ only in WHO
CLAIMED — both are a real claim sequence (each door's own claim grants
the row's next claim_epoch atomically with its attempt; the ledger
claim and every context/finalize fence carry that granted pair). A row
whose stamped name resolves to nothing (the
definitions not imported anywhere — a deployment defect, or a hand-crafted
row) parks at the snooze cadence budget-free, released_reason=
'workflow-body-unresolvable', the stranded-jobs detector the witness —
LOUD, never a silent wedge. The MISSING RUN ROOT is a different failure
with its own class: when a node's run has lost its own __flow__ root
row (control-plane data corruption — never a body-resolution fault), the
failed-parent seat raises the typed WorkflowRootMissingError BEFORE any
propagation write (the transaction rolls back; the already-committed
child terminal stands), the fleet-claimed executor passes it through
UNWRAPPED, and the worker's own release arm attempts ONE bounded
budget-free 10-second release with released_reason=
'workflow-root-missing' and the dispatch-workflow-root-missing log.
Against the committed tx1 child terminal that release fence reads back
noop — the terminal is preserved byte-identically, never rescheduled.
The stranded detector's workflow_root_missing reason is the witness on
the run's surviving rows; the remedy is the runbook's
restore-or-quarantine recovery, never a worker knob.
The workflow-only worker — how the worker imports definitions¶
The worker imports definitions through --actors, the only registration
mechanism the boot has: the module at module:attr is IMPORTED, and that
import is what mounts every WorkflowApp the module constructs (the boot
projection walks the imported apps). A definitions module whose only
content is the app boots a workflow-only worker:
# myapp/workflows.py — the definitions module
from pydantic import BaseModel
from taskq.workflows import Promise, StepContext, WorkflowApp, build, step
class Ingest(BaseModel):
doc_id: str
class Report(BaseModel):
ref: str
app = WorkflowApp()
@app.actor(max_attempts=7)
async def extract(ctx: StepContext, params: Ingest) -> Report:
return Report(ref=params.doc_id)
@app.workflow("ingest")
def ingest_flow() -> Promise[object]:
return build(step(extract, Ingest(doc_id="d"), key="extract"))
ACTORS = {}
The empty ACTORS mapping is legal exactly when the import mounted at
least one app: the boot gate counts workflow-execution capability from
the same inputs the worker would use, and the worker dispatches workflow
steps only. The refusal (nothing to dispatch … refusing to boot) names
both ingredients — the actor registry and the workflow app — and stays
for a module with genuinely neither.
The split placement — one actor, one queue (the design law)¶
actor_config is keyed by actor name: ONE queue per actor, the estate's
own law. A flow's heterogeneous placement (a source on default,
a chain on gpu) is therefore expressed with distinct actor names per
queue — the chain's gpu step is a gpu-named actor:
CHAIN = Chain(
name="gpu-chain",
start="screen",
steps={...},
actor="wf-gpu",
queue="gpu", # the chain's steps: a gpu-NAMED actor
)
@app.workflow("ingest")
def ingest() -> Promise[object]:
src = chain_source(CHAIN, source_body, key="doc_source") # actor 'wf', queue 'default'
return build(src)
One actor name declared over TWO queues is a cohort conflict — refused loudly (the boot refuses, the drift-guard precedent; the error names the fix). The override-warning path (one queue silently winning) is dead by construction.
The capacity surface — the declared admission terms¶
@app.actor() and wf.step() both accept the vanilla actor surface's
capacity fields — and, beside them, the vanilla enqueue's priority=
face (the rows' claim order) and the vanilla start_to_close= face
(the step deadline; the table's last row) — and the declaration
rides the SAME projection the placement rides:
| the term | what it declares |
|---|---|
max_concurrent |
the per-round admission damper — NOT a hard fleet-wide cap. The dispatch claim's per-actor arithmetic reads actor_config.max_concurrent and admits up to the value per round per producer, so the in-flight count can exceed it under concurrent dispatchers (the over-dispatch bound is (num_producers - 1) * max_concurrent per round — the vanilla field's own law, Actors). A run's root row (step_key = '__flow__'), which stays running for the whole run, never counts toward the value when it is written on wf — every root the engine's own runner writes: only the actor's claimed steps do. These other surfaces still count each live run's root as running on wf, so they can show wf saturated while dispatch is still admitting its steps: Insights running, saturation and unservable_backlog; the taskq.jobs.running gauge; taskq.jobs.by_status{status="running"}; the per-queue running columns on the admin queues overview and taskq queues depth (_QUEUE_OVERVIEW_SQL / _DEPTH_SQL_TEMPLATE); and move_actor_queue's running_jobs_left. The list is not exhaustive — any reader that counts running rows sees roots unless it subtracts them. The strict instrument is reservations — declare one when the bound must hold. |
reservations |
the STRICT slots: a list of ConcurrencyReservation objects (taskq.ratelimit.reservation) — the dispatch-admission gate the vanilla path enforces via the leased reservation_slots rows (the machinery is Rate limiting). The boot collects the nodes' declared instances into the worker's resolved registry and materializes their slot rows in the ensure-slots pass — the same pass the vanilla actors' reservations ride (deliberately NOT gated on the vanilla actor registry, so a pure-workflow worker slots its own). |
result_ttl |
the node result's in-DB TTL in seconds — the vanilla result-expiry sweep's own knob, seeded on the stored row. |
capacity_owner |
who owns the STORED capacity columns once the row exists (accepted on @app.actor(...) and on the route's RouteArm(...); not a step() param). "operator" (the default) is the seed-only law: the literal seeds the row once, the operator owns it thereafter, and a later literal change LOGS a mismatch, never writes. "code" is the opt-out: the boot sync REWRITES max_concurrent and result_ttl from the literal on every boot, so a changed literal deploys by code instead of doing nothing after first boot (the queue and max_pending stay operator-owned under both owners). |
priority |
the rows' claim ORDER (the vanilla enqueue(priority=…) face, carried to the workflow surface): the value stamped into the jobs.priority column, which the dispatch claim's priority DESC orders by — the SAME claim SQL the vanilla rows obey, so a workflow step and a vanilla job compete on one vocabulary. THE PRECEDENCE LAW per row, first non-None wins: the per-call run(..., priority=…)/create_flow(priority=…) override > the step's declaration (step(priority=), RouteArm(priority=) for its arm's children) > the actor's declaration (@app.actor(priority=)) > the column default 0. The per-call face is the load-bearing one — an interactive run jumps a deep sweep backlog without touching its declaration (and the rows materialized AFTER create obey it too: the map/route children a worker forks, and the loop escalation's consumer row the outbox drain enqueues, all resolve the run's stamped override). The domain is the smallint column's (-32768..32767), refused at the declaration site like every other layer that accepts a priority. The map's children and the route's join land at the SOURCE step's resolution; the arms override DOWN from the source — DOWN is graph-DIRECTION, not a value ceiling: an arm's declaration governs its own children BELOW the source in the graph, and the value may raise or lower freely (an arm declaring priority=9 over a source's 2 raises its children's rows to 9; the JOIN stays the source's 2). A handle body carrying priority= (@app.actor(priority=5) wired as the map body or an arm body) resolves as its children's actor level — the same precedence law, read at the fork. A spawned childflow run resolves its OWN declarations: the parent's per-call priority= does not cross the run boundary (the child run is a new create_flow — its rows read the child's own per-call/step/actor law; the parent's stamp governs the parent's rows only). |
start_to_close |
the step's DEADLINE (the vanilla @actor(start_to_close=…) face, carried to the workflow surface — a datetime.timedelta, enforced per ATTEMPT from the body's start): the value is stamped into the row's EXISTING jobs.start_to_close column at the node INSERT (no new column, no migration — the column the vanilla rows always carry), and the runner's body execution wraps in the SAME _enforce_start_to_close the vanilla consumer runs — the #791 TimeoutError split (a body's own TimeoutError stays its own ordinary failure; only the deadline's expiry routes as the timeout), the tx-unwind budget, and the hostile-finally handling inherited. THE RESOLUTION LAW per row, first non-None wins: the step's declaration (step(start_to_close=); a RouteArm(start_to_close=) for its arm's children — the arm overrides DOWN from the source, the JOIN staying the source's own cohort) > the actor's declaration (@app.actor(start_to_close=) — folded into the node at the wiring when the step declares none) > the row's NULL (nothing declared) > the worker's default_start_to_close (the enforcement-time fallback — the worker settings' value the fleet door threads; the dev-loop runner honors the row's stamp only). THE EXPIRY'S DISPOSITION: the attempt BURNS (a real execution — the ledger's failed row records the truthful TimeoutError / start_to_close pair, the vanilla rows' own stamp), the ladder re-pends at its own backoff curve until max_attempts then terminal-fails, and the run stays alive; a START_TO_CLOSE expiry is NEVER a Snooze — but a body raising Snooze WITHIN the window still defers (the deferral wins the race), and a body converting the deadline's cancellation into a Snooze LOSES (the clock's win is final — the vanilla enforcement's own race). THE CANCEL WINS over the deadline: a cancel mark on either carrier (the wf cancel's metadata.cancel_phase or the vanilla cancel's column mark) is fenced in-statement at the deadline's re-pend arm — the node terminalises cancelled, never re-queued under the deadline's backoff. The map's children land at the SOURCE step's resolution; the drain's outbox-materialized consumer rows inherit the downstream node's own declared bound through the fire's bindings. Not an actor_config axis (the deadline is the row's own column value — two steps of one actor may declare different bounds with no conflict law). |
max_pending is deliberately NOT on the workflow surface — it stays a
vanilla-actor parameter. The honest removal (never a dead knob): the
engine's fork/emit inserts bypass the enqueue admission path entirely
(mid-finalize, inside the engine's own transactions), and the claim side
cannot bound a backlog (claiming is the only drain — a claim-side gate
would wedge the backlog forever), so no enforcement point exists that
wouldn't structurally strand rows. Bound a workflow's backlog with
max_concurrent (the damper) or reservations (the strict cap).
THE KEYED FACE (per-tenant caps): rate_limits=/reservations= accept
the vanilla surface's keyed refs (KeyedRateLimitRef /
KeyedReservationRef). The ref's concrete name resolves PER CHILD at
the fork/static-insert — each child's own declared payload runs
key_fn, and the row stamps f"{base_name}:{key}" into its admission
terms beside any static names. THE RATE-LIMIT FACE resolves per record
on the fan-outs (a map_source's children, a route's arms): two
tenants' runs fork under one keyed limit and their child rows carry
distinct concrete buckets. THE RESERVATION FACE is cohort-scoped: a
fan-out source's children RIDE the source row's already-resolved names
(one concrete bucket per RUN), so a keyed reservation on a map/route
source must bind the source step's declared payload face (the
run-scoped inheritance — the wiring door states the rule) and an arm's
keyed reservation is refused (an arm declares no payload of its own). A
static step resolves from the RUN'S OWN INPUT first (a parentless node:
two runs, two inputs, two buckets — one bucket per run), then its
declared data args. At claim the concrete name resolves back through
the boot's collected decls and the per-key bucket materializes on first
acquire — lazy registration, the entry cap (max_keyed_rate_limits /
max_keyed_reservations — a cap hit is the budget-free park at the
gate, never a crash), and the idle-eviction sweep bound registry
growth, the same machinery the vanilla keyed acquires run. One
tenant's saturated bucket snoozes only that tenant's children
(budget-free) while the other tenants' children claim — keyed buckets
never gate the actor's dispatch arithmetic. The registry's keyed-name
space is unambiguous: a base_name that is a :-prefix of another
registered ref's base_name refuses at registration (the longest-match
would silently re-bind a child to the wrong ref's config). A child
whose key cannot resolve (its payload fails the ref's payload_type,
or the key breaks the charset/length law) fails the fork LOUDLY, naming
the child — no row lands half-stamped. A keyed term on a node whose
args resolve from parent results is refused at the wiring (no payload
exists at create).
The runnable demonstration (two tenants, one keyed rate limit, one
round_robin queue, the REAL fleet door) is
examples/tenant_fairness_demo/ — its run prints the per-child bucket
names, the per-key acquire/deny trace, and both tenants' completion.
THE FAIRNESS LAW (the dispatch cohort): every claimable workflow row is
born with its run's flow_id as jobs.fairness_key — on a
round_robin queue each RUN is its own cohort, so a deep run's backlog
cannot occupy whole dispatch rounds against a shallow run's (the
round-robin partition interleaves the runs; the flow root itself stays
unstamped — it is never work). On a strict_fifo queue the stamp is
stored and IGNORED: the claim orders by priority then birth time, a
later-born run waits behind an earlier-born run's rows. The re-pend
paths never touch the column, so a row keeps its cohort across
retries/snoozes. THE STORAGE: the stamp is a 36-char uuid text on every
workflow row (~40 B/row) plus, while the row is pending, the same
value in the common pending probe's key column
(jobs_round_robin_probe_idx) AND a second entry in the population
probes (the unrouted probe for the producer-placed rows, the
assignment-routed probe for the re-pended ones); the upgrade guide
carries the migration faces (the pre-upgrade rows' NULL cohort, the
post-phase backfill, and the jobs_wf_fairness_cohort_check backstop —
the database itself refuses an unstamped workflow row).
THE TERMS FLOW: an @app.actor(max_concurrent=1, max_attempts=7, ...)
handle wired via step() carries its declared terms into the node as
the node's ADMISSION AND RETRY DEFAULTS — the explicit step() params
override, never the reverse. The decorator's own defaults (max_attempts=3,
retry_kind="transient") are not declarations: an actor that does not
state them changes nothing about a step's retry shape (the node keeps
max_attempts=3, retry_kind=None, byte-identical to the unwired form).
(PLACEMENT stays the step's own decision: the handle's NAME is not the
node's actor — the split-placement law above is unchanged.) The
WHICH VERB CARRIES WHICH STEP TERM (the wiring surface's own map — a term absent from a verb's signature is not accepted there, by design):
| term | step |
map_source |
route |
RouteArm |
gather |
loop |
|---|---|---|---|---|---|---|
key= (the node's name) |
✓ | — (the join key is derived: <source-key>.join) |
— (each arm's key derives from the arm type's tag) | — | — | ✓ (the loop's step name) |
actor= / queue= (placement) |
✓ | queue= |
queue= |
✓ (the arm's own placement) | — | — |
on_failure= |
✓ | ✓ | ✓ | — | ✓ | — (the loop exhausts into on_exhausted=) |
max_attempts= / retry_kind= |
✓ | max_attempts= (the items' ladder) |
max_attempts= (the route fork's) |
— | — | — |
rate_limits= |
✓ | ✓ (the items' buckets) | — | ✓ (the arm's children's buckets) | — | — |
max_concurrent= / reservations= |
✓ | — | — | ✓ | — | — |
result_ttl= / priority= / start_to_close= |
✓ | — | — | ✓ | — | — |
skip= / gates= / progress_schema= |
✓ | — | — | — | — | gates= (the loop's HOLD gates) |
cache= / cache_ttl= |
✓ | — | — | — | — | — |
DURATIONS, ONE LAW: every second-denominated term —
timeout_s=, budget_s=, cache_ttl=, result_ttl= — accepts a
datetime.timedelta or a bare number of seconds; the seconds number is
the one stored form (the timedelta normalizes at the wiring face).
start_to_close= is the exception and stays a timedelta-only
declaration (the vanilla @actor's own law: a bare number is refused,
never silently coerced — the pin keeps the refusal honest).
The non-negative-int law is the vanilla one, enforced at the declaration
site: a negative or non-int max_concurrent on
@app.actor is a ValueError before anything registers.
THE PROJECTION IS THE SEED-ONLY CAPACITY LAW — WITH ONE OPT-OUT: the
workflow actors' actor_config rows carry the declared caps — the SAME
law the vanilla @actor literals obey under the default
capacity_owner="operator": the declaration seeds the row; the
operator owns it thereafter — override live via
ActorsClient.set_capacity (or taskq actor-config set), and changing
the @app.actor literal later does NOT update a stored cap (the
capacity fields are omitted from the config-sync's SET clause; a
literal-vs-stored mismatch logs, never writes). The opt-out is
capacity_owner="code": the boot sync REWRITES max_concurrent and
result_ttl from the literal on every boot — a changed literal deploys
by code instead of silently doing nothing after first boot (the queue
and max_pending stay operator-owned under both owners). No new enforcement
machinery exists or is needed: a workflow row IS a jobs row, and the
dispatch claim's per-actor arithmetic reads actor_config for EVERY
actor, wf or not.
THE ONE-CAP-PER-ACTOR LAW: an actor name carrying TWO different capacity
declarations is REFUSED — WorkflowActorCapacityConflictError (the
queue-conflict law's twin on the capacity axes; raised where the boot
projection computes the terms, within one workflow and across
workflows/apps alike). actor_config is keyed by actor — one capacity
per actor, the estate's own law — so the capacity is the ACTOR's, not
the node's: give the differing node its own actor name (the error's
message names the fix).
The queue-default trap — declare the queue your workers run¶
Every wiring verb's queue default is "default" (step's
queue=, the map's map_queue=, the RouteArm's fallback, the chain's
rows, the loop's nodes). A deployment whose workers do not consume
"default" — a fleet of queue specialists — strands every such row
SILENTLY: the fork's INSERT succeeds, the dispatch claim matches only
the claiming worker's own queues, and nothing ever claims the row. THE
DISCIPLINE: declare queue= explicitly per step when your workers don't
run default. A queue named in no worker's consumed set FAILS LOUD,
gated on TASKQ_QUEUES_STRICT (the vanilla queues' own opt-in law):
strict — the boot REFUSES with
WorkflowQueueUnconsumedError; non-strict — the boot proceeds with the
ONE aggregated workflow-cohorts-on-unconsumed-queues warning (the
vanilla warning's own shape, the remedy named), because a per-queue
worker specialization legitimately imports the shared apps module while
a sibling worker consumes the foreign queues. The strictness also has a
SECOND, app-declared face — WorkflowApp(queues_strict=True): the
contract declared in CODE, riding the app every worker child already
imports (the fleet whose children each subscribe to a queue subset
cannot coordinate a fleet-wide env var — it need not: the app's own
definition carries the contract). The faces OR-combine: the boot
refuses when EITHER is set, and the env can only ADD strictness — ops
tightening stays possible, silently disabling a declared contract is
not a thing. THE CROSS-APP TIGHTENING: in a process importing SEVERAL
apps, ONE app's queues_strict=True tightens the gate over the WHOLE
projected cohort set — a co-resident app's sibling-served cohorts
refuse too (the refusal names the queues and the fix). The check fires before
the cohorts' sync writes anything; both arms name the remedies (add the
queue to a worker's consumed set, or route the step elsewhere). The
operator-facing entry is
Upgrading.
The orchestration-only drive¶
drive(flow_id, execute=False) is the fleet-mode driver: the driving
process claims and executes NOTHING — the tick runs only the sweep arms,
and the flow's work executes in the fleet's workers through the
queue-routed dispatch. The execute=True default is the dev-loop driver,
unchanged. Each node on ITS pool: a default-subscribed worker executes
the source, a gpu-subscribed worker the chain — the queue column is
load-bearing end to end. THE DOORS DIVIDE MORE THAN PLACEMENT: the
worker's dispatch claim is also where the declared rate_limits= bind
(the in-process dev-loop door runs no rate-limit acquire — see the
rate-limiting guide's "which door honors the buckets"). Any behavior
that lives at the CLAIM (rate limiting, queue caps, fairness) is a
fleet-door behavior; the dev-loop door is for the wiring's logic.
Run-scoped strict exclusion — run_reservations¶
reservations= on a NODE bounds that node: the bucket is taken when the node is
claimed and given back when it terminalises. A run whose exclusion must hold
across its WHOLE graph — one tenant's import pipeline must never overlap
another run of the same tenant, even while the two runs' nodes are different —
declares the buckets on the workflow instead:
from datetime import timedelta
from taskq.ratelimit.reservation import ConcurrencyReservation
from taskq.workflows import Promise, StepContext, WorkflowApp, build, step
app = WorkflowApp()
tenant_imports = ConcurrencyReservation(name="tenant-import", slots=1, lease=timedelta(minutes=30))
async def fetch(ctx: StepContext) -> str:
return "tenant documents"
async def publish(ctx: StepContext, fetched: str) -> str:
return fetched
@app.workflow("tenant_import", run_reservations=(tenant_imports,))
def tenant_import() -> Promise[object]:
fetched = step(fetch, key="fetch")
return build(step(publish, fetched, key="publish"))
app.get("tenant_import") # Compile and validate the guarded declaration.
The declaration reuses the node surface's own union — a bucket name, a
ConcurrencyReservation, a KeyedReservationRef (resolved from the run's
INPUT, one bucket per run), or a FiniteReservationCohort. create_flow
resolves it ONCE against the run's input, sorts and de-duplicates the concrete
names, and stamps them on the root's metadata.run_reservations, so every later
reader — the admission gate, the release doors, the reclaim sweep, the admin's
reservations page — resolves one set of names from one row. A caller may not
pass run_reservations through root_metadata_extra: a hand-written stamp would
name buckets the declaration never validated.
The hold is the run's, not the worker's. The seat is a
reservation_slots row with job_id = the run's root id, no worker lease and
no expiry (held_by_worker_id IS NULL, lease_expires_at IS NULL), so it is
owed for exactly as long as the root row is live. Nothing that happens to a
WORKER can expire it: a SIGKILL, a SIGTERM drain, a retry backoff, a
multi-day human hold or a timer all leave the seat with the run. Two runs of one
slots=1 bucket therefore never interleave their graphs, and two runs of
different keyed buckets run at the same time.
Where the seat is taken and given back. The admission gate takes the run's
seats for a claimed node (before the body runs, and only for an attempt the gate
will actually execute — a fail-closed park never holds a bucket). It is given
back at every door that terminalises the root, in the same transaction; and the
node whose terminal leaves no live work behind runs the eager release, so a
finished run frees its bucket immediately instead of at the next sweep tick. Two
defence layers back the doors up: an acquisition takes a DEAD run's seat when the
bucket is full, and the maintenance leader's wf_run_reservation_reclaim sweep
frees what both missed. The release and the reclaim require the run's root to be
terminal (or gone) AND no reservation-scoped node of the run to still be running
under a live lease — the COOPERATIVE CANCEL BARRIER, so an operator cancel keeps
the seat while the cancelled body finishes unwinding.
The self-deadlock is refused twice. A run-level bucket that overlaps one a
node, route arm, chain step or terminal effect of the SAME workflow acquires is
E23-run-reservation-overlap at compile: the node would wait on a bucket its own
run holds, which no retry or sweep can break. Nested runs cannot be checked
statically — a child spawned under a live ancestor that already holds the bucket
would do the same thing — so ctx.spawn_flow refuses a child whose own
reservations (run-level, or any node/arm/chain/effect declaration resolvable at
spawn time) intersect the live ancestors' buckets, raising
RunReservationAncestorConflictError BEFORE the child's rows exist. A child
whose bucket only resolves at RUN time — a per-record step, or a chain step
whose key rides the emitted record — cannot be refused there; it is claimed,
denied, and proven: the gate walks the ancestor chain (to FULL depth, cycle-safe)
and, when every link is waiting on the child below through an unbounded
ChildHandle.wait() and the ancestors between them hold every slot of the denied
bucket, the child's node fails deterministically with
RunReservationAncestorConflictError on its first attempt instead of
snooze-looping forever — and the waiting parent's join is woken with
ChildFailed. A waived shape stays ordinary contention: a fire-and-forget spawn,
a bounded wait(timeout_s=…), an expired wait, a terminal ancestor or a
non-ancestor holder all back off and run once capacity frees.
Fleet-only execution. A guarded run stamps required_worker_schema = 3 on its
root (and every descendant inherits the floor through the spawn pointer, without
copying the ancestor's bucket list). The lineage itself is durable: the run's root
carries metadata.wf_run_reservation_lineage, so a descendant's spawn still reads
the schema-3 floor after retention archives the ancestor that declared the
reservation. A pre-upgrade worker — one booted before the
run_reservations machinery existed — never claims such a row at all (the
physical claim trigger refuses it), so a rolling deploy can never let an old
worker run a guarded graph unprotected. The in-process dev-loop door is refused
outright: FlowRunner.drive(execute=True) on a guarded run raises
WorkflowWorkerCapabilityError, naming the fleet as the door that can honour the
declaration. Ordinary runs are unaffected. The rollout order is in
Upgrading.
Honest handoff latency. The seat's release has no cross-worker wake channel:
the run's bucket is handed to the next waiter at the waiter's NEXT claim, and a
denied waiter parks on a capped, jittered ladder keyed on its row's
rate_limit_blocked_count — 1s, 2s, 4s, 8s, 15s, 30s, each rung spread by
±20%, plateauing at 30s. A denial is a CAPACITY denial (the counter climbs, the
row's snooze_count does not move) and never the step-level local retry spin, so
a saturated bucket costs one claim-and-deny cycle per waiter per rung. The
practical consequence for an operator: a finished run's bucket is handed on
within one poll interval if a waiter happens to be claiming then, and otherwise
at its current rung — up to ~30s on a long-contended bucket. There is no
sub-second wake, and nothing in this release claims one.
Bounded active-run admission — max_active_runs¶
A workflow that must bound how many of its runs are in flight at once declares the bound on the workflow, not on a step:
from taskq.workflows import Promise, StepContext, WorkflowApp, build, step
app = WorkflowApp()
async def ingest(ctx: StepContext) -> dict[str, int]:
return {"rows": 0}
@app.workflow("tenant_ingest", max_active_runs=2)
def tenant_ingest() -> Promise[object]:
return build(step(ingest, key="ingest"))
app.get("tenant_ingest") # Compile and validate the declaration.
max_active_runs=N bounds every non-terminal run of that workflow —
pending, scheduled and running, which includes a run parked on a human
hold, a run waiting out a retry backoff, and a run whose nodes are all resting.
That is deliberately not the vanilla max_pending count (which excludes
running): a workflow's "how many of these may be open at once" is a bound on
open runs, and naming it after the pending subset would lie about it. 0
is legal and refuses every fresh run; None (the default) is unbounded.
The refusal is backpressure, not failure. A fresh over-cap create raises
MaxActiveRunsExceededError (a BackpressureError subclass, so an HTTP layer
that already maps BackpressureError to 503 + Retry-After needs no change).
The count is taken under a per-workflow advisory lock, so a burst of concurrent
producers cannot each observe the same free seat; a producer that loses the
lock wait itself raises MaxActiveRunsLockTimeoutError
(max_active_runs_lock_timeout_ms, default 5 s) rather than waiting forever.
Per-call overrides may only tighten. create_flow(..., max_active_runs=1)
on a workflow declared with max_active_runs=5 load-sheds harder for one
create; trying to raise the declared cap raises ValueError — the declaration
exists because the workflow's own admission bound is a property of the graph,
not of a caller's patience, and a caller who could raise it would silently
defeat the invariant for everyone. None means "no override" and inherits the
declaration; it is not a per-call disable.
Where it applies. Every root-creation door: create_flow, the packaged
run, and ctx.spawn_flow targeting a workflow that declares a cap. A
nested spawn that adopts an existing child run (the deterministic child
run_key retry) is NOT a fresh run and bypasses the cap; a genuinely fresh
over-cap child raises MaxActiveRunsExceededError so the parent can
raise Snooze(delay) without burning an attempt. In-run node materialization
(fork, emit_batch) is governed by max_in_flight / EmitBackpressure —
the two bounds answer different questions and neither overrides the other.
The fast path costs no lock. On a capped (or identity-deduped) workflow, a
create carrying an explicit run_key reads that run by its arbiter before taking
any lock: a committed run that is not pending is returned with no advisory lock
at all, so a webhook retry storm on one key never queues behind the cap's lock. A
pending root deliberately does not take that immediate-return path — that is
the interrupted-create signature, and the retry adopts it under the ordered locks
and completes its node rows instead of returning it empty.
Windowed run dedupe — unique_for + identity_key¶
"At most one run per account per hour" is one declaration on the workflow plus the entity key on each create:
from datetime import timedelta
from taskq.workflows import Promise, StepContext, WorkflowApp, build, step
app = WorkflowApp()
async def reconcile(ctx: StepContext) -> dict[str, str]:
return {"account": "acct-7"}
@app.workflow("account_reconcile", unique_for=timedelta(hours=1))
def account_reconcile() -> Promise[object]:
return build(step(reconcile, key="reconcile"))
app.get("account_reconcile")
The producer names the entity on the create —
await runner.create_flow(identity_key="acct-7") — and a replay inside the
window gets the first run back instead of a second one.
The window is per (workflow, identity_key) and is matched against the run
states in unique_states (default pending, scheduled, running,
succeeded). A create that finds a match inside the window returns THAT run —
RunClaim(created=False, dedup_reason="unique_for") — instead of creating a
second one. A deduped create consumes no capacity, so it is never refused by a
full max_active_runs window.
run_key wins. An explicit run_key naming an existing run returns that
run (dedup_reason="run_key") even when another run of the same identity sits
inside the window: the caller asked for one specific run, and replaying a
run_key must never hand back a different run's result. A run_key that names
nothing does not suppress the window — the create still dedupes by identity.
A window without an identity is a no-op that says so. Either the workflow
or the call may declare unique_for; without an identity_key it cannot be
enforced, and the runner warns once (workflow_unique_for_ignored) rather than
silently creating runs under a rule nobody applied — exactly the vanilla
unique_for enqueue's behaviour.
The window is serialized, the states are the filter. Serialisation is one
advisory lock per (workflow, identity_key), taken before the cap's lock, so
concurrent producers of one identity cannot both miss (deadlock-free because
the order is fixed: identity lock, then cap lock). Losing that lock wait raises
UniqueForLockTimeoutError — deliberately not a BackpressureError: nothing is
saturated, the dedup answer was merely not determinable in time, so the caller
retries the same create and dedupes against the winner.
The run-level terminal hook — on_terminal¶
on_exhaustion hangs off a NODE's retry policy and fires when that node's
ladder burns out. When the application wants one callback per RUN — "post the
final report", "release the tenant's slot", "page someone if the import
failed" — the workflow declares on_terminal:
from taskq.workflows import (
ExecutionPolicy,
Promise,
RunTerminalEvent,
StepContext,
TerminalEffect,
WorkflowApp,
build,
step,
)
app = WorkflowApp()
async def report(ctx: StepContext, event: RunTerminalEvent) -> None:
# event.outcome is "succeeded" | "failed" | "cancelled"; event.flow_id,
# event.run_key, event.run_epoch, event.error and the failing/terminal node
# keys are the run's own terminal facts.
print(event.flow_id, event.outcome)
async def import_rows(ctx: StepContext) -> dict[str, int]:
return {"rows": 0}
@app.workflow(
"tenant_import_report",
on_terminal=TerminalEffect(
body=report, policy=ExecutionPolicy(actor="reports", queue="default")
),
)
def tenant_import_report() -> Promise[object]:
return build(step(import_rows, key="import"))
app.get("tenant_import_report")
The hook is an ordinary bounded job, materialized through the same wf_outbox
the fired joins and terminal effects use, addressed at its declaration's own
actor/queue and carrying its rate-limit, reservation, deadline, priority and
retry terms. It receives a frozen RunTerminalEvent (the field-by-field
contract is in the API reference).
The guarantees, plainly.
- Once per
(flow_id, run_epoch)— one durable intent and one queue row per incarnation, enforced by the outbox and jobs idempotency arbiters. A manualretry_workflow_nodeopens a NEW incarnation (run_epochadvances), and the reopened run earns its own intent: epoch 1 and epoch 2 have distinct intents, jobs and events. Each event's callback execution remains at-least-once. - At-least-once execution. A crashed worker, a killed pod or a retried attempt re-runs the BODY. Do not treat the hook as an exactly-once callback.
- Same-database domain closure completes once when the hook writes its own
idempotency marker (keyed by
(flow_id, run_epoch)) and the domain effect in ONE transaction on its own connection. The engine guarantees the intent's and the job's uniqueness; the application's database constraint guarantees the marker's uniqueness. The exactly-once domain write is the application's transaction, and it is the only exactly-once claim this feature makes. The acceptance suite exercises that pattern end to end, including a hook body that crashes after its own transaction commits. - Own-run scope. The hook is settled from the run's own root row and the
run's own node rows (
flow_id); it never reads another run's state, and a spawned child run settles its own hook. - The reclaim/abandon boundary. A run whose body was reclaimed and whose
budget is spent ends
crashed(orabandoned), so its event reportsoutcome="failed"with the engine's own error class onevent.error— the hook is not skipped because nobody was there to finish the run.
When it settles. A run settles when its root is terminal AND no ordinary
member of its graph can still do work. That is stronger than "the root row says
failed": a fail-closed cascade or a loop exhaust terminalises the root while a
real peer body is still mid-execution, and the hook must not report a run as
settled while a body it owns is still running. The withheld settlement is not
lost — the door that finally quiesces the run (the last body's unwind, the
maintenance pass, the operator cancel) settles it in its own transaction, and an
isolated leader arm (wf_terminal_hook_settle) is the backstop for anything a
door missed. Post-terminal obligations — a node's on_exhaustion effect leaf, a
loop's escalation row — run AFTER the run and are excluded from the gate by
construction, so they can neither hold the hook nor poison the next
incarnation.
What it costs and what it refuses. A payload-keyed rate limit or reservation
cannot name a bucket from a declaration with no payload, so it is refused at the
declaration door (WorkflowPolicyError) and re-proved at compile
(E25-run-terminal-effect). A workflow declaring a hook stamps
required_worker_schema = 4 on its runs, so a pre-4 worker never claims a run
whose 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 two-stage rollout is in
Upgrading.
Retention holds a terminal root whose hook has not been settled yet, preserving
the root's identity and binding template until the durable intent exists. It
does not hold the run's node rows: if retention archives them before settlement,
the event's terminal_node_key and failed_node_key can be null.
The build-time validators¶
A malformed graph is a coding error, refused before any row is written:
validate_fork refuses the empty fork that carries NO join (zero
children, nothing to collect — the stranded invisible join's shape);
an empty fork WITH a join is the legitimate shape (the born-zero
fire: the route/map over a legitimately-empty
corpus declares its join, the join is BORN deps_pending=0, fires
immediately, and packs the EMPTY list — result() == [], the run
terminal, SUCCESS truthful: a night with no documents chunked zero
documents, and that is correct); validate_join_spec refuses a join node with zero incoming
edges (the stranded invisible join — before the sweep's LEFT-JOIN
hardening it was not even diagnosable). The runtime backstop: the rederive
arm enumerates edge-less join-wait rows (a LEFT JOIN on the edge ledger)
and stamps them metadata.blocking_reason='orphan_parent' — the record
never looks healthy while the work is wrong.
wf.validate()'s own rule matrix (checker-independent): E1 acyclicity · E2 produced-never-consumed ·
E3 the edge-less join (the compiled graph is public data — the rule
owns the shape injected into it, not just the verb's door) · E4 the
unannotated step · E5 the incompatible consumer — including the
DUCK-TYPED hole (an unannotated/Any param consumes a model producer
unseen) · E6 the fan-in bound · E7 the cross-graph promise (a
promise wired from ANOTHER app's recorder — recorded by the verbs,
rejected here; the colliding-key smuggle builds a silently wrong edge) ·
E8 the loop CARRIER-TYPE (a body refining an unrelated model against
the declared carry_type= (or the model instance passed as initial=) — the recorded declaration is enforced) · E9 the ctx
annotation (must BE StepContext or the declared-unchecked
Any/object) · E10 the arity (the body's params beyond ctx must
match the wired sources' count) · E12 the deps contract (below) ·
W1
the eternal wait (the warning class) · W2 the unknown queue (a queue
no actor declares and TASKQ_QUEUES does not name — the warning class;
the worker-boot fail-fast stays the runtime door).
The deps seam — the body's dependency door (the DI capability)¶
The body's three input channels (one table, one place)¶
A body's parameters arrive through THREE distinct channels — the convention is positional, and every wiring question ("why is my param the run input?") is answered by which channel a param rides:
| the channel | how it arrives | what it holds | declared by |
|---|---|---|---|
| the context | the FIRST parameter, always ctx: StepContext |
the RUN's machinery: ctx.input (the run's input — the SAME dict for every node of the run), ctx.progress(), ctx.substep, the emit batch face |
fixed — never wired |
| the wired payload | the params AFTER ctx, in the wired order |
the node's OWN data: each wired source's DECODED result (a producer's model, the map's item, the join's collected list), then the seed payload's plain args (the body call convention: (ctx, wired_source_1, …, wired_source_n, plain_args…)) |
the wiring verbs' arguments (E10 owns the arity) |
| the deps | the LAST parameter (opt-in) | the app's bound Deps instance — clients, store handles; the SAME instance at every node (per worker, per event loop, under a deps_factory= binding — below) |
deps: MyDeps annotation + WorkflowApp(deps=…) or WorkflowApp(deps_factory=…) (E12 owns the contract) |
The two dict-shaped channels are the common confusion: ctx.input is
the RUN's input (every node sees it — use it for run-wide facts: the
run key's dimension, the feed spec read once); a node's OWN payload is
its wired params (the producer's return, decoded). run(flow, input=…)
seeds ctx.input only — it does NOT seed any body's wired params and
does NOT participate in the cross-run cache's address (the address keys
on the WIRED payload, see the cache section).
Step bodies need dependencies — a client, a store handle, a queue —
WITHOUT reaching through ctx (the context is the RUN's contract, not a
service locator) and without module globals (untestable, unswappable).
The seam: declare a Deps dataclass PER APP and bind ONE instance at
the door; bodies OPT IN by declaring it:
from dataclasses import dataclass
from taskq.workflows import Promise, StepContext, WorkflowApp, build, map_source, step
@dataclass(frozen=True, slots=True)
class EnrichDeps:
marker: str = "enrich-client"
app = WorkflowApp(deps=EnrichDeps()) # ONE instance, bound ONCE at the door
@app.actor(queue="cpu")
async def enrich(ctx: StepContext, doc_id: str, deps: EnrichDeps) -> Summary:
# the THIRD parameter is the deps contract — the runner hands the
# app's bound instance in; the signature is the opt-in.
return Summary(doc_id=doc_id, text=deps.fetch(doc_id))
@app.workflow("doc_ingest")
def doc_ingest() -> Promise[object]:
ingested = step(ingest_body, IngestBatch(doc_ids=["d1"]), key="ingest")
enriched = map_source(ingested, enrich) # the map's children get the SAME instance
return build(step(publish_body, enriched, key="publish"))
The contract, enforced at build by E12-deps-contract (the SAME arity
discipline E10 owns, extended honestly — one param beyond ctx + the
wired sources IS the deps shape):
- a body declaring the deps shape where the app binds no deps is
refused at
app.get(...)— the message names the fix (bind ONE instance at the door:deps=, ordeps_factory=for a resource created lazily on the running loop — below; or drop the parameter: it is never a fourth data source); - a body whose deps annotation the bound instance does not satisfy is refused — both type names in the message;
- a true arity mismatch (two params beyond the wiring) stays E10's.
The bound instance is THE instance — the step bodies, the map's item
children, the loop driver's bodies, and the hold-wake's re-execution all
receive the same object (bound once at the door, never re-minted per
claim — a deps_factory= binding mints it lazily on the running loop
instead, and re-mints it only when its generation rotates: below). The
runner never inspects it (object through the runner); the
TYPING is proven at the decoration — E12's runtime check of the body's
declared type against the binding. Every door binds the same way:
WorkflowApp(deps=…) (the compile carries the binding — the packaged
run(flow, pool, schema) and the worker-hosted execution door read it
from the compiled object), or FlowRunner(…, deps=…) / run(…, deps=…)
(the direct doors — the runner's binding wins, and the validation
re-runs against the effective binding); deps_factory= declares at the
SAME three doors. The InMemoryBackend has NO workflow
execution surface (the named landmine): the seam's test face is
the real FlowRunner against the pg fixtures.
The two faces: static deps= vs the lazy deps_factory=¶
The seam binds ONE deps instance; there are two faces for producing it, and the choice is about WHEN the instance may exist and WHO releases it:
WorkflowApp(deps=…) — the static arm |
WorkflowApp(deps_factory=…) — the lazy arm |
|
|---|---|---|
| when the instance exists | at the declaration site — before any event loop, for the life of the process | lazily, on the RUNNING loop, at the first body execution that declares the deps shape |
| right for | loop-agnostic, cheap, stateless deps (a config object, a pure client wrapper) | loop-bound resources (an asyncpg pool, a loop-bound HTTP client) and anything needing an ASYNC release |
| teardown | none owned by the seam — release it where it was created | exactly ONE owner per instance (the precedence below), released on shutdown, on a generation-changing reload, and on close |
THE MUTUAL EXCLUSION: deps= and deps_factory= are refused TOGETHER at
every declaration door (WorkflowApp, FlowRunner, run(...)) — the
ValueError names the law ("the deps seam binds ONE instance"). The same
construction-time check refuses deps_teardown= or deps_generation=
beside a static deps=: a teardown callback and a generation source release
and rotate a FACTORY-created instance — a static one is released where it
was created, not by the seam.
An explicit deps= / deps_factory= on a direct door (FlowRunner(…),
run(…)) OVERRIDES the compile's binding without tripping the refusal —
the validation re-runs against the EFFECTIVE binding, so E12 reads what the
bodies will actually receive.
The factory shapes and the ONE teardown owner¶
The factory declaration has no resource side effects — the factory is never invoked at declaration, compile, or validation time (E12 reads its return ANNOTATION only). The accepted shapes, each shape's ONE teardown owner named; every resolved instance has EXACTLY ONE teardown owner and undergoes at most one teardown attempt:
from contextlib import asynccontextmanager
from taskq.workflows import WorkflowApp
class Deps:
def __init__(self) -> None:
self.pool = None
async def aclose(self) -> None: ...
def sync_factory() -> Deps: # shape 3: the product's aclose() is the teardown
return Deps()
async def async_factory() -> Deps: # shape 3, awaited on the running loop
return Deps()
@asynccontextmanager
async def managed_deps(): # shape 1: the exit below IS the teardown —
resource = Deps() # pairing this shape with deps_teardown= is REFUSED
yield resource
await resource.aclose()
async def generator_deps(): # a bare async generator function: the same
resource = Deps() # shape — its finalisation is the sole owner
yield resource
app = WorkflowApp(deps_factory=managed_deps) # ONE declaration, lazy arm
The precedence, in order:
- The context-manager factory — an
@asynccontextmanagerwrapper, a bare async generator function, or a plain factory whose product IS an async context manager: its__aexit__/ finalisation closes what it yielded. Pairing this shape withdeps_teardown=is REFUSED — dual ownership is the bug the precedence exists to prevent (caught at the declaration when the factory is statically an async generator function; at resolve time when a plain factory produces a context manager). - The explicit callback — a plain sync/async factory plus
deps_teardown=callback(the callback receives the instance; sync or async). The callback is the sole owner EVEN WHEN the produced object also exposesaclose()— explicit beats implicit. - The product's
aclose()— a plain factory with no callback releases through the produced object'saclose()when it has one, and owns nothing otherwise.
A factory that raises resolves nothing: the exception propagates to that body unchanged, NOTHING is cached, and the next claim retries the factory — no half-state survives a failed initialization. An owner-initiated teardown attempt is BOUNDED (the worker's close budget per binding). On the worker, a failing release is logged with its cause and never skips the remaining owners.
E12 with a factory — the product-type contract¶
E12 never invokes the factory. The PRODUCT TYPE is read from the factory's
return annotation, unwrapping every shipped shape: () -> T, an async
callable's () -> Awaitable[T], -> AsyncContextManager[T],
-> AsyncIterator[T] / -> AsyncGenerator[T, None], a class factory (the
class itself), and a concrete async-CM class (its __aenter__ result names
the product). A body whose declared deps type the product does not satisfy
is refused at app.get(...) / compile with BOTH type names. The
zero-false-positive doctrine is unchanged: an absent annotation, Any,
object, a union, or a non-runtime-checkable protocol SKIPS the check — a
guess is never rejected. The arity law is unchanged (E10 owns a true
two-params-beyond-the-wiring mismatch).
The scope — one instance per worker, per event loop¶
The worker-hosted door resolves the app's factory ONCE PER (declared
binding, worker identity, event loop): the first deps-declaring body on that
loop mints the instance under an asyncio.Lock — concurrent first claims
serialize, so the factory runs exactly once however many bodies, runs and
workflows of the app execute — and every later body of the app on that
worker receives THE SAME object. A second worker, a workgroup child (its own
loop, its own pool), or a second loop in the same process resolves its OWN
distinct instance: instances never cross a loop boundary, a child starting
later never inherits an earlier child's instance, and one worker's shutdown
never releases a co-resident worker's entry. The direct door is per-runner:
one resolution per FlowRunner, and each child runner a drive creates owns
its own.
The lifecycle order — exactly where the release runs¶
SETUP: after the worker's event loop and PG pools exist (that is the factory's reason to exist), at the first deps-declaring body's execution — never at boot, never at import.
TEARDOWN — on the graceful-shutdown unwind AND the sibling-crash unwind (wherever the worker's exit stack still runs), in exact order:
- the worker's TaskGroup DRAINS — in-flight claims finish;
- every already-resolved factory-created deps instance releases, exactly once, each with its own bounded attempt;
- THEN the worker's PG role pools close (the deps release is pushed onto
the bootstrap's exit stack before
open_worker_deps' own unwinds).
The ordering keeps an already-resolved instance's release ahead of pool
close; a release that outlives its bound is cancelled and reported rather
than holding pool teardown open indefinitely. THE SHUTDOWN-BUDGET MODEL:
each distinct WorkflowApp(deps_factory=…) binding adds one sequential
bounded release to the tail before the pools close; when the modelled tail
exceeds TASKQ_TERMINATION_GRACE_PERIOD, startup warns
workflow-deps-shutdown-budget-exceeds-termination-grace naming the binding
count and the required grace (the configuration guide's termination-grace
row carries the arithmetic). One or more cancelled rotations can leave
superseded generations pending beside the current one, adding one bounded
release per pending generation per affected binding beyond that startup
model. A HARD-KILLED worker
(SIGKILL, OOM) runs no teardown — its loop is never unwound and the process
exit is the release, the same bound every other worker-scoped resource has.
Reload and generation invalidation¶
A factory bound to changing configuration (a settings reload, a rotated
downstream client) declares a generation source — deps_generation=, a
callable answering an int or str that CHANGES when the factory's inputs
do. Any other answered type is reported as a TypeError at reload; the
current instance keeps serving. The binding starts at generation 0;
without a source it never rotates, and its instance lives for the owner's
lifetime.
On the worker, EVERY reload (SIGHUP, request_reload(), the scheduled
reload) runs the deps hand-off at the top — BEFORE any pool is swapped:
- each app binding's current generation is re-read (a source that raises is reported and the binding keeps serving its current instance — a broken settings read must not wedge the reload or the worker);
- the superseded generation's in-flight bodies DRAIN, bounded: a body already running keeps its own resource while it finishes within the drain bound, while a claim arriving mid-rotation gets the NEW instance — the swap happens FIRST, then the drain;
- the superseded instance releases EXACTLY ONCE, and — when the generation advanced — the worker's cached runners are evicted, so the next claim rebuilds one over the new generation.
The bound is an escape hatch, not an unlimited clean-completion promise:
clean-completion protection ends at the drain bound. A changed generation's
superseded instance is then released anyway, exactly once; on an unchanged
generation the live instance stays, but the old-pool close still proceeds
after its own bounded claim drain. A body or finalize still running after
that point can fail against released deps or a closed pool and follows
ordinary durable job-failure recovery; its later unwind runs no second
teardown. The worker reports the expiry as workflow-deps-drain-timeout.
A reload whose generation did not change still drains the live generation —
it is the settle point before the caller swaps whatever those claims were
admitted with. The direct door rotates explicitly:
await runner.reload_deps(drain_timeout=…). It applies the same force-
proceed law, returning drained=False after it releases a superseded
instance whose body outlived the bound; that body's later failure 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. run(…)'s factory lives
for the one call, so that door takes no deps_generation= — there is
nothing to rotate.
The direct door's disposal¶
FlowRunner is an async context manager: async with FlowRunner(…) as
runner: or an explicit await runner.aclose() — the runner releases the
deps resolution it minted (one teardown attempt, a no-op when nothing
resolved) plus every child runner its drive created, each owner attempted
even when an earlier one fails; a failure propagates after every owner has
been attempted. The packaged run(...) does this for the caller: the
factory-created instance releases on the success AND the failure
path of the call. A resolution the runner does NOT own (the worker's shared,
worker-scoped one) is never closed by a runner — its owner releases it at
worker shutdown.
Observability — proving one-instance-per-worker¶
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 is an identity, never a metric dimension (the metric cardinality
contract), so per-worker attribution is the log line's job.
The flow API: the concept¶
taskq.workflows now ships the authoring surface: plain types for
data, Promise[T] for wiring. A workflow is a build function — SYNC
and PURE — that SPELLS the graph by dataflow:
- a promise consumed downstream is an EDGE (the consumer dispatches strictly after the producer terminalizes);
- a call with SEVERAL promise arguments is the FAN-IN join — and its user body IS that node's body, run inside the join's finalize transaction with the DECODED parent results (the reducer is in the wiring, not engine code; its result cascades downstream as NORMAL steps);
map_source(source, body)is the map: the source's finalize forks N children (fresh jobs — per-item ledger identity), the join collects, and the promise is the FLATPromise[list[R]](neverPromise[list[Promise[R]]]— the checker rejected the nested shape);route(source, arms)is THE TYPED ROUTE: the arms are a dict keyed by the source's union MEMBERS' TYPES —route(docs, {TextDoc: RouteArm(body=extract_text, queue="cpu"), ImageDoc: RouteArm(body=ocr_text, queue="gpu")})— each element runs ITS type's arm as a fresh job, the arm'sRouteArmstamps its children's queue/actor (the per-arm placement), the arm body's declared param type is the decode's target (the element arrives AS the declared model — never a dict), and the derived<source>.joinpacks the arms' returns (the typed sum — the flatPromise[list[R]], R the union of the arms' returns). THE ARM CONTRACT IS EXACT (E15's exact-member law atvalidate()): the declared model must BE the union member — a SUPERCLASS builds clean past the old issubclass fence and the runtime decode then drops the subclass's own fields (pydantic'sextra='ignore'default, the silent data loss the sum's reader cannot see), and an UNRELATED model is the wiring promising data the arm cannot accept; both are the build-time refusal. The children's rows are graph nodes whose step keys NAME their arm (<source>.item:<module.qualname>), and the join feeds the downstream wiring like any node's — FORK, FAN BACK IN at the next step (the barrier section below).map_source(source, {A: fn_a, B: fn_b})is the same verb's dict form — one machinery, two spellings; The route attaches to a wired source node (the constraint stated where the verb is taught, not only in the error): a route's source must be a node with a BODY — the route dispatches the source's own return. A map's derived join (<source>.join) declares no body (it is the default identity packer), soroute(enriched, arms)over a map's collect is REFUSED at build. The natural enrich-then-branch pipeline spells the identity pass-through step between the map and the route — the honest one-liner:enriched = step(branch_seam, mapped, key="branch"),route(enriched, arms)(the pass-through's body returns its argument; the route's source is then the enriched collect, named).
The single-value disposition:
route(source, arms) is a MAP face — its source produces the
ELEMENTS' list, and a SINGLE-VALUE (non-list) Promise[A|B] is refused
at build (route's source 'x' does not declare a list[...] return —
the route is a MAP face: the source produces the elements' list, the
arms key its members). At runtime the same shape lies fail closed: a
source body that returns None (the forgotten return) or any other
non-list value fails the source deterministically on attempt 1 with
error_class='RouterNotTotal' — nothing routes, and [] remains the
honest empty-corpus return. There is no per-value arm dispatch on a plain
step: routing ONE union value is the chain step's in-body Route
(see the router section below — Route({EnrichOutcome.OK: "score", …}), the
total-over-the-outcome-enum fence at declaration time); inside a graph
body, match the union yourself and return the arm's product.
- sink(...) is the explicit fire-and-forget (RECORDED in the compiled
metadata — never silent); build(result, *residuals) is the terminal
completeness point (the Promise[Never] residuals are the static
side of E2's produced-never-consumed rule).
Nothing about the tree is STORED: the graph is spelled by the wiring and compiled fresh — same module → same compile, byte-stable (the Mermaid golden's law). Sequencing, hence a depth-N DAG, is dataflow — the migration's depth-3 graph fits ONE flow.
The dispatch-time predicates: step(..., skip=pred) —
pred: Callable[[state], bool] — is evaluated WHEN THE NODE
DISPATCHES against the flow's state ({"input": …, "results": {…}}), a
sibling's COMPLETED result decides it. A skipped child SUCCEEDS WITH
THE RECORD (the result names the skip — the envelope never lies about
what ran) and fans into its absorbing joins (collect) as a
typed item — a skip is not an attempt (zero ledger rows).
A skip= PREDICATE IS REFUSED ON A FAN-OUT SOURCE. Wiring the
step(..., skip=…) as the source of map_source(...) or route(...)
is refused at the attachment (WorkflowBuildError) and re-proved by the
validator (E22-skip-fan-out-source): the skip path finalizes the
source with the skip record and never spawns the fork, so the derived
<source>.join row would never exist — the downstream consumer would
wait on it forever (the run standing running with no error row
anywhere) and a terminal map would read succeeded over a result() of
None. When there is nothing to fan out, return [] from the source
body: the empty join fires immediately with the honest [].
DEPRECATED FOR DISPATCH — teach the typed route. The predicate's
face is STRINGLY: the state it reads is decoded JSON dicts, and a
predicate keyed by a tag (item["mime"] == "video") can skip EVERY
downstream arm and still let the run terminalize SUCCEEDED having
routed NOTHING — the exact silent drop the totality fence exists to
refuse. For
"dispatch each element by what it IS", the typed route is the taught
face: the union's members key the arms, a non-total route is a BUILD
refusal (E15), and an element of a type with no arm dies LOUDLY
(RouterNotTotal) — never succeeds-having-routed-nothing. The
predicate stays for the sibling-conditional shapes it is honest for
(an "only if X succeeded" dispatch), and its docstring names the
recorded finding.
The sync barrier — fork, fan back in at the join¶
The typed route's arms each emit per-element results; the next step
consuming the route's promise is the FAN-IN — the worked shape (the
document sync pipeline, examples/doc_mime_route.py, verbatim):
docs = step(sync_source, key="docs")
routed = route(
docs,
{
TextDoc: RouteArm(body=extract_text, queue="cpu"),
ImageDoc: RouteArm(body=ocr_text, queue="gpu"),
UnsupportedDoc: RouteArm(body=dead_letter),
},
)
chunks = step(chunk, routed, key="chunk") # the chunk consumes the join's collected list
return build(step(enrich, chunks, key="enrich"))
The barrier's semantics, stated exactly:
- The all-members join — the chunk fires ONCE, only when ALL the
routed children have terminalized (the join's
deps_pendingcount = the elements). The staggered arms (the text fast, the OCR slow) cannot make the chunk fire early or twice: the fire ledger (wf_join_fire,UNIQUE(join_job_id)) carries at most one fire per joined node, ever, and the chunk's claim starts strictly after the LAST child's terminal. THE EMPTY CORPUS IS TRUTHFUL (the born-zero fire — the build-time validators): a source whose body returns[]forks zero children, the join fires immediately with the EMPTY list, and the run terminalizes SUCCEEDED —result() == []is the typed sum's honest value, never a wedge and never a lyingNone. - The decode at the barrier — the chunk body's list param is the
decode's target: the collected list re-validates into the DECLARED
models (the typed sum —
list[ExtractedText | DeadLettered]here); the body sees models with attribute access, never dicts. A foreign item in the sum dies LOUDLY in the decode. - The failure faces — the route's
on_failure=declares the join's incoming edges' policy (the propagation duality, at the route's fan-in): fail_closed(the default): a child's terminal failure → the join blocks withblocking_reason='failed_parent'NAMING the failed parent on the row, the chunk never fires, and the flow fails (the cascade) — the partial result never masquerades as the whole.collect: the child's failure fans in as a typedFailureInfoitem on the join'smetadata.failures(the policy that ran is ON the item — the envelope must not lie) + the decrement; the join fires when the last child terminalizes, with the SURVIVORS ONLY packed (the absorbed parent contributes NO result item to the sum — its absence is on the record, never a junk slot the decode cannot honor), and the flow lives (the derivation reads the absorption record, never a heuristic).
The typed boundary: the body's param annotations are
the payload codec — the runner re-validates the jsonb round-trip into
the DECLARED model; a body sees the type it declared, never a raw
dict. wf.validate() refuses an unannotated body (E4 — the annotation
IS the wiring).
The union consumer's discriminator law: a body
param decoded as a UNION of models (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. When two members' required fields stand in the
subset relation, the richer member's payload satisfies the thinner
contract and the decode picks the first-annotated member — the richer
member's own fields silently never surface (the mispick).
validate() walks every body the runner injects into (the steps, the
map's item children, the route's arms, the loop bodies) and names the
risk by the members' declared fields — the only evidence the compile
has: FIELD-IDENTICAL required faces are the hard refusal (the mispick
is GUARANTEED — every payload decodes as the first member); the
one-directional subset is the warning naming it; distinct members
(each requires a field the other lacks) are clean — the thinner
validation fails on the missing field, the union falls through to the
true member. The fix either way: a Literal discriminator field on
each member (kind: Literal["image"] / Literal["audio"]) — the
discriminated union decodes by the tag, never by field-count luck.
The typed early exit — Exit[DoneT] (the None-end's
sanctioned escape): a body returns Exit(payload) to TERMINAL-SUCCEED
the node with a typed result NOW — the runner unwraps the sentinel, the
node's ledger terminal records the exit, and every non-terminal
DOWNSTREAM node is marked SKIPPED-WITH-THE-RECORD
({"skipped": true, "exit_from": …} — the record never lies about the
nodes that didn't get to run; zero ledger rows, a skip is not an
attempt). All rows terminal → the derivation reports the workflow
COMPLETE. A plain T return is the DATA result — sentinels appear only
where the body's control flow says so; a body annotated -> Exit[Report]
returning a bare value (or a bare return) is the checkers' MUST_ERROR.
The manual resume — FlowRunner.retry_node(run_id, node_key) (the
redispatch escalation — "the ladder then manual"): the operator's
audited, CAS-guarded re-arm of a TERMINAL-FAILED node. The attempt
ordinal CONTINUES (never resets — the ladder's own 'failed' count is
the budget, so each manual retry buys exactly ONE more attempt); the
re-run is safe by the step ledger (ctx.substep returns recorded
results); the node's TRANSITIVE blocked closure re-opens — the barrier's
key-based wait relation is part of that closure, so retrying a chain
source reaches its barrier and every consumer behind it even though no
wf_edge links them (the stamps return to join-wait — the sweep's
re-derive re-derives them, a stamp is the cache — except a chain
barrier's, which returns to its own armed chain_barrier wait: that
dependency is reserved and edgeless, so join-wait would strand it
forever); a terminal-FAILED flow root returns to running (a CANCELLED
root stays closed — the cancel was deliberate). "Who retried this" is a
ROW (workflow.retry_node). Surfaced as the taskq flows retry verb.
The retry knob: step(..., retry_kind=..., max_attempts=...)
— retry_kind="permanent" takes NO ladder; a transient failure's
attempts re-pend with backoff and emit NO terminal until exhaustion
(P3 rule 7), then the failed-parent propagation takes over.
A worker crash does not spend this ladder: on a transient step the crash
reclaim gates on the row's claim counter (attempt < max_attempts) while
the ladder counts the step's failed ledger rows, so the two budgets
stack and, counting crashes and body failures alone, a step that never
holds or defers can run up to 2 * max_attempts - 1 times (a permanent
step runs once: its first crash or body failure is terminal). An
infrastructure fault in the runner's own bookkeeping after the body
returned re-pends with no claim ceiling and never spends the ladder,
though the re-run's claim still spends crash headroom — see
retries.md §12.
The control-flow signals (the same typed signals the vanilla bodies raise)¶
A workflow body raising taskq.exceptions.Snooze or RetryAfter does
NOT ladder — the signals are the body's control flow, never a failure —
and the runner resolves each to a NAMED disposition, the wf face of the
vanilla consumer's own catch (the row dispositions mark_snoozed /
mark_retry_after_consume_{true,false}, mirrored onto the finalize's
fences):
| signal | the disposition's row law |
|---|---|
Snooze(delay) |
the node re-schedules at clock_timestamp() + delay (floored at MIN_DEFERRAL_INTERVAL — a zero/now snooze must not park at the head of the dispatch order); the claim's attempt increment is REFUNDED, so max_attempts is never exhausted by snoozes alone and the ledger re-claims the SAME attempt arbiter row; snooze_count increments; no terminal, no decrement — the join's accounting is unchanged and the run stays live. |
RetryAfter(delay, consume_budget=False) |
the same snooze semantics (the vanilla's own vocabulary) — the refund, the floor, the counter. |
RetryAfter(delay, consume_budget=True) |
the claim's increment STANDS (the burn — the next claim mints the next attempt), the raw delay is kept, and the budget gates it: past max_attempts the step terminal-fails MaxAttemptsExceeded ("retry budget exhausted") through the wf terminal door — the failed-parent propagation takes over. |
In every case the step's result capture stays empty (nothing succeeded),
the claim's ledger row rests awaited (the hold's own
resume-not-retry status — never a failed row the ladder would count),
and the node's metadata carries the deferral stamp — the run page's
deferral line renders
the signal, the next fire time, and the snooze count while the step
sits. The signals' full vanilla contract (the construction-time
ValueErrors, the schedule_to_close interaction, the
Retry-After-header example) is Control-flow
signals. A deferral refused by an
operator cancel in flight (the cancel mark wins, the vanilla's own law —
on EITHER carrier: the workflow cancel's metadata stamp AND the vanilla
cancel's own column mark, the admin job-page cancel's arm)
terminalises the node cancelled, and a zombie's deferral (the claim
fenced) records the attempt fenced — the run is never wedged by a
refused deferral. The extension seam is named, with its honest bound:
the next deferral DISPOSITION (a new signal, a non-terminal row law)
adds a DeferralDisposition member, one statement arm, one resolver
entry — and nothing else; a new TERMINAL verdict (a death the doors
own) additionally needs a per-door route in BOTH the step's and the
loop's disposition routes (the doors' semantics differ by law — the
step's exhaustion finalizes through the wf terminal door, the loop's
through the loop's own named state — so the route is per-door, never a
shared special case). The disposition's seat is the
runner's step-body seam (the step, the chain, the map's item children,
the route's arms); a LOOP body raising a signal routes through the SAME
disposition — the loop's iteration machinery already resumes a
mid-iteration hold, and the deferral is the same resume, later by the
delay: the loop node row re-schedules, the iteration counters are
untouched (the advance never ran), and the loop resumes at THAT
iteration with the ladder unburned. The bound holds there too: a loop
body exhausting the budget via RetryAfter(consume_budget=True) past
max_attempts takes the loop's own body-failure face (the named state +
the flow terminalized, MaxAttemptsExceeded on the record) — the ladder
still bounds loops.
THE DEADLINE INTEROP (the step's own start_to_close — the resolution
law in the capacity surface
table): a Snooze/RetryAfter raised WITHIN the window defers (the
deferral wins the enforcement's race — the deadline never fires); a
START_TO_CLOSE expiry is a REAL attempt burn, never a deferral, so a
body catching the deadline's cancellation and converting it to a
Snooze LOSES — the clock's win is final (the vanilla enforcement's
own race, mirrored verbatim); and an operator cancel in flight outranks
the deadline (the cancel-fenced law — the node terminalises
cancelled, the cancel's vocabulary).
The reads (FlowRunner.result(flow_id) — the
terminal's result, DECODED ONCE through the estate's JSON seam; on a
FAILED run the read is the FAILURE's face — the typed
WorkflowRunError carrying the UNABSORBED failing node's error
class + message (the failure that failed the run: a branch failure
the join's collect policy absorbed never names the verdict — WHAT
failed, and why, answered AT the read; failed and
running are never indistinguishable). A CANCELLED run's read is the
CANCEL's face: the typed WorkflowRunCancelledError — a
WorkflowRunError subclass, so existing except WorkflowRunError
clauses catch it — carrying the terminal status and the cancel reason
the cancel verb recorded (cancelled, failed, and running are never
indistinguishable). The driver
drive(flow_id, until="held" | "terminal") (the loop's own driver —
loop; the bound max_ticks is the hang's fence).
The drive's return is the verdict — check it. drive returns one
of three strings: "terminal" (the flow row reached
succeeded/failed/cancelled), "held" (only under
until="held" — a node waits on a human/deadline), or "max_ticks"
(the tick budget was SPENT without reaching until — a bounded
give-up, NOT a status). A "max_ticks" return is the driver saying "I
stopped trying"; the operator's next act is to read the ROWS
(taskq flows status, the flow root's status) to learn why — never to
assume the run advanced. RESUME SEMANTICS — the crashed in-process
run is the one door that does not reopen in-process: the in-process
drive runs no lock-reclaim sweep (that is the worker maintenance
leader's job), so a run whose executing process died keeps its
running rows leased by a dead worker, and re-driving
drive(execute=True) on a fresh runner ticks to max_ticks (~110 s
at the defaults) changing nothing. The working resume is the FLEET
door: drive(flow_id, execute=False) (or just the worker fleet) — the
leader's lease-reclaim sweep waits out the dead claim's lock lease
(~2 min at the defaults; see the runbooks' mid-run crash page), re-pends
the killed child, and the fleet executes the rest. The cancel +
re-issue runbook (a fresh run_key) is the alternative when the
re-drive is not wanted — the idempotent absorbs make the re-issue's
re-execution safe.
The type contract¶
The wiring's typing story has TWO faces, and both are load-bearing:
- The checker face (static): the plain-function bodies are
checker-typed end to end; the negative probes live in
tests/typeprobe/(pyright 1.1.414 + ty 0.0.85, the CItype-probesgate). The checker is ABSENT at runtime — which is exactly why the second face exists. - The validator face (runtime, checker-independent):
wf.validate()re-proves the wiring's totality from the compiled graph (the rules table in the API reference). A graph that typechecks AND validates is pinned clean by BOTH; a mutation of either face fails its own pin.
The two faces — what each one owns (the honest boundary)¶
The mechanism shipped in the verbs is probe-proven (the type-mechanism
corpus, wf_generic_step_negative_types.py, on both pinned checkers):
Promise is COVARIANT; step[R] infers R from the body's declared
return (step(fetch, params) wires a Promise[Report] when fetch
returns Report); gather[R] preserves the element type
(Promise[list[R]], never an erase to Promise[Any]); build's
residual slot is Promise[Never] — covariant, so every REAL data
handle in the slot fails. But the two faces own different questions,
and neither covers the other's:
| the edge's question | WHO catches it | WHERE |
|---|---|---|
the handle flow: an unconsumed data handle passed to build as a residual (Promise[Report] in the Promise[Never] slot) |
The checker, at typing | build(...) call — an error in the IDE and in CI (reportArgumentType / invalid-argument-type) |
the handle flow: a consumer that DECLARES the handle type (Promise[Config]) handed the wrong handle (Promise[Report]) — the contravariant-consumer rejection |
The checker, at typing (live because Promise is covariant) |
the handle-passing call site |
the handle flow: gather's element type threaded to a typed join consumer (Promise[list[Report]] where Promise[list[Config]] is declared) |
The checker, at typing | the join-consumer call site |
| the promise-as-data mistake (a promise passed where the DECODED model / list is wanted — the direct unit-call form) | The checker, at typing (the corpus's wf_api_negative_types.py) |
the unit-call site |
the DECODED-payload compat: a producer's body returns Report, a consumer's body declares Config |
validate(), at build — E5-incompatible-consumer |
compiled.validate() / worker boot |
the DECODED-payload hole: the consumer's param carries NO model annotation (Any / a plain dict — the duck-shaped hole) |
validate(), at build — E5-incompatible-consumer |
compiled.validate() / worker boot |
a promise nobody consumes, nobody sunk, nobody named terminal (not passed to build at all) |
validate(), at build — E2-produced-never-consumed |
compiled.validate() / worker boot |
The boundary has a REASON, not just a history: the bodies take DECODED
payloads, not handles (decoded once — the fan-in's args are the
parents' decoded results). The wiring verbs' *args are therefore
ERASED (object) — statically they are either promise handles (the
handle flow, the checker's face) or plain data, and the checker cannot
see a decoded model inside an erased argument list. That is why the
canonical wrong graph "producer Report → consumer wanting Config"
caught at the WIRING SITE (step(consume, produced_promise)) is NOT a
checker error — the wiring call is erased — and IS a validate() refusal
(E5) the moment the graph compiles. The corpus asserts this boundary
as its own probe (probe_wiring_site_decoded_payload_is_the_validators_face):
the line must stay CLEAN under both checkers, and the gate's
unmarked-error rule fails the corpus if it ever fails. What the IDE
catches at typing is the HANDLE flow; what validate() catches at build
is the DECODED-payload compat. Read the gate's error as the handle-flow
law; read validate()'s refusal as the payload law; neither report
subsumes the other.
Fan-out & reduce: the one-flow shape¶
The common pipeline — fan-out N independent steps, reduce into a join, cascade downstream — is spelled (never glued):
from pydantic import BaseModel
from taskq.workflows import Promise, StepContext, WorkflowApp, build, step
app = WorkflowApp()
class Ingest(BaseModel):
doc_id: str
class Stats(BaseModel):
n: int
@app.actor(queue="cpu")
async def stage_a(ctx: StepContext, params: Ingest) -> Stats:
return Stats(n=1)
@app.actor(queue="cpu")
async def stage_b(ctx: StepContext, params: Ingest) -> Stats:
return Stats(n=2)
@app.actor(queue="cpu")
async def reduce(
ctx: StepContext, a: Stats, b: Stats
) -> Stats: # the join's user body — the DECODED parents
return Stats(n=a.n + b.n)
@app.actor(queue="cpu")
async def tail(ctx: StepContext, total: Stats) -> Stats:
return total
@app.workflow("doc_ingest")
def doc_ingest() -> Promise[object]:
a = step(stage_a, Ingest(doc_id="d1"), key="a")
b = step(stage_b, Ingest(doc_id="d1"), key="b")
reducer = step(reduce, a, b, key="reducer") # the fan-in: TWO parents
return build(step(tail, reducer, key="tail")) # the cascade: a NORMAL step
compiled = app.get("doc_ingest")
compiled.validate() # the zero-false-positive bar: this graph is clean
The fan-in's failure policy is declared ON the join
(on_failure="fail_closed" — the duality: a failed
parent either fails the join closed (the cascade, the peers
peer-cancelled) or fans in as a typed FailureInfo item and the join
FIRES with the typed partial). The ABSORBING policy is
"collect" — the failures fan in AS PART of the typed FailureInfo
items and the join FIRES with the typed partial (the engine also
accepts the spelling "maybe" — the same absorption, one meaning). The fan-in bound is 1000 declared
parents (MAX_FAN_IN_PER_JOIN) — past it, partition the map.
For a RUNTIME-determined N: map_source(source, item_body) — the
source's body returns the list, the fork spawns one fresh job per item
(map_index = the item's ledger identity), and the join packs the
decoded item results for the downstream body. The map takes NO key=:
the join's key is DERIVED (<source-key>.join — the engine's fork
addresses it), so naming the node means naming the SOURCE. (A key=
parameter on the map does not exist and no value of one would be
honored — the derived key is the only form.)
The item ladder honors the stamped max_attempts (the knob is the
operator's, the record keeps it): a
transient-failing item ladders to the max_attempts wired on the
map_source — the SAME knob a plain step honors, stamped on every
child row by the fork: a plain step wired 7 ladders 7, and a map item
wired 7 does the same. The deterministic-failure and
permanent routes are unchanged (they never ride the ladder).
The ladder's backoff curve (the plan-ahead
numbers): a laddered attempt's re-pend waits
0.05 × 2^(failed_count) seconds — 50 ms after the first failure, then
100 ms, 200 ms, 400 ms, 800 ms, 1.6 s, 3.2 s… doubling with no cap
inside the ladder (the vanilla actors' retry curve has its own
documented jitter and caps — docs/guides/retries.md; the workflow
node's ladder is this plain doubling). A rehearsal's worst-case wall
budget for max_attempts=N is therefore the sum of the first N−1
doublings plus each attempt's own run time.
Child flows: a step spawns a sub-flow and joins its result¶
The map's fork fans out inside ONE flow. When the sub-work is another
WHOLE flow — the agent spawning sub-investigations, each a real run the
run explorer sees, the admin operates, the CLI lists — the step calls
ctx.spawn_flow and JOINS the child's terminal. The child is a REAL
flow: its own root row, its own node rows, its own run-key claim — the
spawn is the child's create_flow in the create seam's own ONE
transaction. The join is the HITL hold's own shape: the wait registers
a hold on the spawning node, the slot releases (never a failed
attempt), and the child's terminal is the hold's RESOLVER — the wake
arm delivers, the body resumes, the closed union's member returns.
timeout_s=0.0 would never wait; the example passes None (the
default — wait as long as the child lives; a cancelled parent cancels
its children, so no join outlives its flow):
import asyncio
import os
import asyncpg
from pydantic import BaseModel
import taskq.migrate
from taskq.workflows import (
ChildCancelled,
ChildFailed,
ChildOk,
Expired,
Promise,
StepContext,
WorkflowApp,
build,
step,
)
class Probe(BaseModel):
topic: str
class SubReport(BaseModel):
findings: list[str] = []
class Digest(BaseModel):
verdict: str
findings: list[str] = []
child_app = WorkflowApp()
@child_app.actor(queue="default", max_attempts=1)
async def sub_investigate(ctx: StepContext) -> SubReport:
# The FLOW INPUT's face: the spawn's `input=` rides the child
# root's payload; the body re-hydrates it through the declared
# model's own validator (the jsonb value, decoded once).
probe = Probe.model_validate(ctx.input)
return SubReport(findings=[f"looked at {probe.topic}"])
@child_app.workflow("docs_childflow_child")
def docs_childflow_child() -> Promise[object]:
return build(step(sub_investigate, key="probe"))
parent_app = WorkflowApp()
@parent_app.actor(queue="default", max_attempts=3)
async def investigate(ctx: StepContext, params: Probe) -> Digest:
# THE SPAWN: the child is a REAL flow. The run key
# (`childflow:{parent_flow}:{node}:{slot}`) is the TWO-CLAIMS LAW
# at the flow level: the retry ADOPTS the same child, never
# duplicates it (a terminal child adopted as-is is the
# deterministic replay; `key=` overrides the slot).
handle = await ctx.spawn_flow(
"docs_childflow_child",
input=Probe(topic=params.topic),
result=SubReport,
)
# THE JOIN (the wait IS the hold): the CLOSED union — the checker
# forces the fail-close arms (a body matching only ChildOk falls
# through and fails against this Digest return).
outcome = await handle.wait()
match outcome:
case ChildOk(result=report):
return Digest(verdict="ok", findings=report.findings)
case ChildFailed():
# THE CHILD FAILED — never a silent swallow: the body
# DECIDES (finish with what it has here).
return Digest(verdict="child-failed")
case ChildCancelled():
return Digest(verdict="child-cancelled")
case Expired():
# THE JOIN'S OWN PATIENCE EXPIRED (`timeout_s=` arms the
# hold's deadline — the DB clock; the face fires ONCE per
# abandoned hold per EXECUTION — one replay slot per node
# row and attempt, shared by that execution's children).
return Digest(verdict="expired")
@parent_app.workflow("docs_childflow_parent")
def docs_childflow_parent() -> Promise[object]:
return build(step(investigate, Probe(topic="the-estate"), key="spawn_join"))
async def main() -> None:
dsn = os.environ["TASKQ_PG_DSN"]
schema = os.environ.get("TASKQ_SCHEMA_NAME", "taskq")
await taskq.migrate.apply_pending_locked(dsn, schema=schema, phase="pre")
await taskq.migrate.apply_pending_locked(dsn, schema=schema, phase="post")
pool = await asyncpg.create_pool(dsn)
from taskq.workflows import FlowRunner
# The registration door — the spawn resolves the child's compiled
# graph from the registry (the definitions must be imported in the
# driver's process).
child_app.get("docs_childflow_child") # noqa: B018 (registers the child)
runner = FlowRunner(parent_app.get("docs_childflow_parent"), pool, schema)
claim = await runner.create_flow(input=Probe(topic="the-estate"))
outcome = await runner.drive(claim.flow_id, until="terminal")
assert outcome == "terminal", outcome
result = Digest.model_validate(await runner.result(claim.flow_id))
assert result.verdict == "ok", result
assert result.findings == ["looked at the-estate"], result
await pool.close()
asyncio.run(main())
The child actor's declared retry terms are its steps' defaults: the
max_attempts=1 on sub_investigate ladders the probe node's attempts
at 1 — a declared term folds into every step that does not state its
own, and an actor that states none changes nothing.
The identity runs BOTH directions: the parent's node row carries the
child's flow id (metadata.child_flows — the receipt), the child's
root row carries the parent's (parent_flow_id / parent_node_id /
parent_step_key — the provenance). The cancel cascade: cancelling the
parent's run walks the family from the rows' parent links (the
receipts the accelerator) and cancels each child's rows — the worklist
walk below. The fan-out is the body's own loop: spawn K handles (each
slot a distinct, retry-stable key) and join each — the fork's
all-members semantics at the flow level.
The spawn's atomicity face. The default
slot is CLAIMED in one atomic statement (the increment of the attempt's
cursor, which restarts at slot 0 under each new claim (claim_epoch) and
counts up within it, and the returned slot are one row-CAS), so K CONCURRENT
spawns — asyncio.gather(*[ctx.spawn_flow(...) for t in tenants]), the
natural fan-out spelling — take K DISTINCT slots and mint K DISTINCT
children, each carrying its own input. A cursor read/write race would
adopt the same slot for all K spawns, mint ONE
child, and hand every caller tenant-0's verdict wearing K labels —
silent fabricated results, zero errors, green pins. A SAME-key
concurrent spawn ADOPTS the same child (the arbiter's run-key CAS) and
every caller receives THAT child's handle — the shared face.
A deferral's re-run (Snooze, RetryAfter(consume_budget=False)) keeps
the attempt number but is a new claim, so it re-derives slot 0 and
adopts the child it already minted provided no other execution has
advanced the same key since that child was minted. The slot indexes
the key's ARRIVAL order across every writer, not one execution's
logical spawn ordinal: a stale body that interleaves a spawn (its lease
lapsed, sharing the attempt number), or a concurrent unkeyed fan-out
whose CAS order permutes, shifts the order a later claim walks, so its
k-th spawn can adopt a child another execution minted for a different
input. A deferral or hold-resume of a serial body re-derives its own
slots in order; a fan-out that must join STABLY across resumes passes
key= (the slot's allocation order is the scheduler's; the author's
identity is the caller's — a resumed body re-executes the gather and
the adoption follows the KEYS).
In a loop body the default spawn is
per iteration: the cursor is spawn_slot_<attempt>.iter<i> and the run
key's node segment is <key>.iter<i> (the ledger's iteration key), so a
resume or a deferral that re-runs iteration k adopts k's own children.
A map item is its own job row, so its cursor is already per-sibling
(spawn_slot_<attempt>) — but every map item of one node shares a
step_key, so the run key's node segment carries the item:
<key>.item<m>. Two items of one map never adopt each other's child.
An explicit key= is the author's identity and is never scoped to an
iteration: a constant key in a loop body names ONE child, which every
iteration adopts, so a body that wants a child per iteration puts the
iteration in its key. key= may not be a bare decimal string ("0",
"12"): that spelling is the default key's slot segment, so the spawn
refuses it with the typed SpawnKeyReservedError (a ValueError; a
deterministic authoring failure, so an uncaught one terminal-fails the node
on attempt 1) rather than let a numeric key alias the node's first unkeyed
spawn. Upgrading from a release whose loop iterations
shared the cursor: an iteration that spawned unkeyed under the old
release and runs again after the upgrade (a deferral, a hold or join
resume, a reclaim; iteration 0 too) derives the new key and mints its
unkeyed children once more, and a join resumed that way waits on the new
child while the first one's result goes unread. During a rolling deploy
old and new workers derive different keys, so it can happen in either
direction. Upgrading from a release whose map items shared one run key
(the release before this one): every map item's unkeyed spawn now
derives <key>.item<m>, so an in-flight map item re-run after the
upgrade mints its child once more and adopts the item-keyed child from
then on — with the same rolling-deploy ambiguity, in either direction.
Keyed spawns (whose keys are not bare decimals) keep their keys.
The depth bound. A self-spawning flow (a workflow that spawns
itself, directly or through a cycle of children) cannot mint a
generation per sweep tick forever: the spawn walks the ancestor chain
from the ROWS' parent_flow_id links — capped at the declared max
depth, DEFAULT_SPAWN_MAX_DEPTH (32) — and past the bound the typed
SpawnDepthExceededError (FanInBoundExceededError's sibling)
terminal-fails the node, the retry ladder unburned (re-running cannot
shrink the ancestor chain). The same walk detects a CYCLE in the parent
links (a corrupted/operator-written link cannot run the walk forever —
the same bound fires, the message names it). A fan-out that genuinely
needs more depth declares max_depth= at the spawn site.
The result contract. result= must be a pydantic model class that
pydantic can render a JSON schema for. Any other value, including a plain
type such as int, bare BaseModel, or a duck-typed class that supplied
the three members the old doors read (and so worked by shape before this
check), is refused with SpawnResultModelError (a TypeError) — as is a
model class whose own JSON schema pydantic cannot build (an unresolved
forward reference, or an arbitrary_types_allowed field). The join
decodes the child's terminal result into the declared model; a child
result that model cannot validate raises ChildResultContractError (a
ValueError) at the join — also a deterministic authoring failure,
because the terminal row is the truth and every attempt would decode it
identically. The check is the spawn's first act: it runs before the child
is created and ahead of the spawn's other refusals, and it fires even
when the handle is never waited on. The refusal terminal-fails the node
without spending the retry ladder, and a declared on_exhaustion effect
does not fire (a deterministic refusal is not an exhaustion). Inside a
loop body the loop exhausts with LoopBodyFailure, and the class name is
in the message.
The spawn target. The child workflow is resolved from the compile
registry in THIS process, so the spawn's two target refusals are
ChildWorkflowUnknownError when the named workflow is not registered
(the definitions must be imported here) and ChildWorkflowNoTerminalError
when it IS registered but its compiled graph declares no terminal node (a
workflow whose step promises are explicitly sunk with sink(...), so the
join could never read a result). The terminal-less refusal is a
DETERMINISTIC authoring failure: within a process, re-running cannot give
the compiled graph a terminal; its class subclasses
ChildWorkflowUnknownError, so except ChildWorkflowUnknownError: catches
both. In Python, catching the base still catches it; a row-level alert,
dashboard, or saved query matches the error_class string, though, and
these rows record ChildWorkflowNoTerminalError — matching only the base
matches zero of them, so match both names. The refusal fires before any
child flow row, spawn cursor, or receipt is written: it spends no retry
budget and writes exactly one failed ledger row (jobs.attempt reads the
claim ordinal, which a prior hold's resume increments, so it is not always
1), and a declared on_exhaustion effect does not fire. During a
mixed-version rolling deploy that adds a terminal to a previously
terminal-less child, an in-flight parent landing on an older worker fails
deterministically without retrying onto a newer worker. Its remedy is to
give the child a terminal by returning its step promise (or build(...)
it) instead of sinking it. Inside a loop body the loop exhausts with
LoopBodyFailure, and the class name is in the message.
The retention interplay (the operator's rule). The cancel cascade
cancels the family; the retention purge must WALK THE PARENT LINKS the
same way — purging a child's rows while its parent still runs leaves a
DANGLING child pointer on the parent's row. The parent's resume
FAILS CLOSE on it: the dangling pointer raises the typed
ChildFlowLostError and the run terminal-fails with the class on the
record. It is NEVER a silent respawn: a respawn would run
the child's side effects twice while the parent reads SUCCEEDED.
The cascade walks the rows. The cancel cascade collects children
from the ROWS' crash-safe parent_flow_id direction first — the
receipts (metadata.child_flows) are the accelerator, the rows the
law. A child created but never receipted (the crash between
child-create and receipt-write) is STILL collected: the orphan window
— the crash-then-cancel that let a child escape the cascade forever —
is unrepresentable. The cascade itself is a WORKLIST WALK, never
Python recursion: a 1200-deep family cancels clean (the recursive walk
raised RecursionError at the operator and left hundreds of runs
running).
The dev-drives parity. The dev-loop driver's tick runs the expiry
arm, so a timeout_s wait — including a child join's — fires the
Expired member in a dev drive exactly as it does under the leader's
sweep belt: the dev loop is the same engine as the fleet's.
The admin sees the family. The run explorer renders the parent↔child links the rows carry: the parent's page links each child flow's run page, a child's page links its parent — the identity faces the child line landed, surfaced.
Loops & back-edges¶
wf.loop(name, body, *, initial, carry_type, until, max_iterations,
budget_s, on_exhausted, escalates_to, gates) — the loop is v1; the
signature is the SHIPPED verb's own, every parameter spelled: initial seeds the
carry at iteration 0, carry_type declares the carry's model (every
committed carry is revalidated at each boundary — the advance, a
resume, the memo replay; the type-only declaration's initial carry is
the empty None, and a committed None against a declared model or
dict is the loud LoopCarryContractError — a JSON-native declared type
keeps the untyped None), until is awaited per iteration,
budget_s bounds the loop's wall clock, and the exhaustion takes
on_exhausted ("fail" | "escalate" — the escalation step via
escalates_to=, with gates='s HOLD gates). Each iteration is FRESH jobs: the iteration-scoped
step keys (workflow, loop_key, iteration, step) keep the idempotency
ledger per-iteration (the contract unchanged). The body returns the
CONTROL UNION:
Done(payload)— the loop stops; the payload is the loop's result.Refine(feedback)— the carry threads into the next iteration.
The carry is frozen at spawn and advanced EXACTLY ONCE per iteration — in the ADVANCE STATEMENT, one atomic write shared with THE CAP GUARD (a refused advance IS the exhaustion). A carry advanced at hold/retry time is the optimistic-apply defect (double-apply / lost-apply) — the pin keeps the safe shape honest. Crash recovery: a resume reads the iteration's LEDGER row (the memo) — the body is not re-consulted mid-iteration without the at-least-once boundary being stated.
The two walls are different:
- the iteration cap (
max_iterations) bounds TOTAL SPAWNS regardless of time — the only wall left when the budget is paused; - the budget (
budget_s) is the TIME wall — and it is BLIND while the loop holds on a human (budget_paused): a held loop is invisible to the budget sweep even when its deadline is forced into the past. THE CONSUME-BUDGET DEFECT (the consume alternative — the arm reads the budget instead of pausing) killed a held loop mid-hold and refused the operator's later approval: work silently lost. The mutation pin keeps the pausing shape honest (removing the pause arm makes the pin fail). (The operator's OWN latency between two holds, though — that time the budget DOES consume once the pause lifts: the wall measures the loop's working time including the gaps, never the holds themselves.)
EXHAUSTION IS NAMED, NEVER SILENT: the cap or the budget wall
terminates the loop into the iteration_cap_exhausted /
budget_exhausted state — and THE FLOW TERMINALIZES IN THE SAME
TRANSACTION (STRANDED-FLOW: an exhausted loop that never
terminalized left the flow running forever — the worker ticks
forever, the admin shows a live run; the pin exercises it).
The exhaustion policy is read by the driver and the sweep:
on_exhausted="escalate" enqueues the escalation
through the SAME outbox the fired joins use — addressed to the
workflow's REGISTERED escalation step (loop.escalation; the body is
your escalates_to=fn, or the framework default, registered at compile
by the definition registry), and the escalation consumer job RUNS:
the drained job resolves the registered body and terminal-succeeds
carrying the exhaustion record — no dead letter, on EITHER path (the
live driver's cap check AND the sweep's orphaned-loop arm). (The
payload door — the escalation's payload — is matched to the registered
escalation step's declared shape, never to the loop's argument order:
the wiring's SHAPE decides, the declaration order decides nothing.)
on_exhausted="fail" terminal-fails the flow and enqueues NOTHING.
The cap lets the final iteration run: the advance guard admits the advance TO the cap, so the
metadata's counter REACHES max_iterations — the live driver exhausts
at its top-of-loop cap check, and the crash window (a worker death
after the final advance) leaves exactly that state on the running row
for the SWEEP's cap arm to own. The sweep's
iteration >= max_iterations predicate is REACHABLE in production —
never a hand-crafted state.
The semantics decision, by escape point: infra fault
≠ body failure, and the classifier reads WHERE the error escaped, never
merely its type. An exception the BODY raised is a BODY failure even
when it wears a ConnectionError face — the loop's typed failure
(LoopBodyFailure, the flow terminalized); a body cannot forge an
infra fault (the poison-body wedge — 20 crashed rows, a running flow
forever — is the rejected variant, kept failing by the attack probe). An
infra fault raised by the DRIVER'S OWN machinery reclaims: the ledger
says crashed, the ladder does NOT burn, the lease machinery re-claims
from the ledger, the loop completes on the re-claim.
until= is AWAITED (Callable[[], Awaitable[bool]]): a bare sync
closure returning a coroutine object is TRUTHY — a verification that
never awaits it proves nothing. The predicate is awaited by the
driver, per iteration.
NAIVE-MEMO IS AUTHOR GUIDANCE, PINNED: the durable memo — one model invocation per iteration, never one per resume — is the ONE-TX shape (read + write inside one transaction; the ledger's claim statements ARE that shape). The engine gives you the carry + the TX boundary; the memo shape is author work — the negative example (a read-modify-write across transactions: a crash between "model ran" and "proposal committed" strands the counter, the re-run UniqueViolations, the ladder then fails the loop) is the shape to never write.
The driver (drive(flow_id, until="held" | "terminal")) is bounded —
max_ticks fences the hang.
The streaming source & the chain¶
A "source sync" — a paged upstream whose run executes a body that is a
paged generator: fetch page → ctx.emit_batch(children, cursor=…)
→ checkpoint the page cursor → fetch the next page. Pages stream: each
page's records are chain-start rows that claim and terminalize WHILE
the source is still mid-stream (the measured shape: 236 chain claims +
165 chain terminals before the last page's emit) — nothing waits for
the pager to exhaust.
The emit tx — the one new primitive¶
ctx.emit_batch(children, cursor=…) is ONE transaction:
- the children INSERT — the certified fork-children shape (parallel-array, app-side uuid7 ids), parent = the source row;
- the edge rows — child → source,
fail_closed(a mid-stream source death is the honest fail-closed parent; the edges reconcile emit debt exactly as the fork's reconcile fork debt); - the cursor checkpoint — the source row's OWN metadata (the
emit_cursorkey; no new table, no new column), guarded by the FULL dispatch fence (status='running' AND locked_by_worker AND attempt AND claim_epoch).
Why one tx (the fork-atomicity law at page granularity): a kill at
ANY statement window — including after the cursor write but before
the commit — rolls the whole batch back; the REAL reclaim
(sweep_expired_locks) + the promotion sweep re-pend the source (it
never finalized), and the re-claim re-emits exactly the lost page. The
cursor is never advanced outside the emit tx. The pins kill the emit at
every window with a real pg_terminate_backend and count: zero
re-emitted children, zero lost children, the cursor == the last
committed page.
The terminal-crash class is terminal-for-real (the no-zombie
promise's crashed-terminal wedge fix): a node row in crashed
(budget-exhausted — the reclaim's crashed branch wrote it because
nothing would ever revive it) or abandoned derives the FAILED-class
terminal, never liveness. The runbook asymmetry: a corpse that reports
running forever is the wedge (the operator must notice forever); an
honest failed terminal is resumable-by-rerun. The wedged root heals on
ONE maintenance pass — the pin family
tests/test_wf_crashed_terminal_wedge.py holds the semantics, the
mutation pin (the assertion fails on a corpse), and the zombie audit's
spellings. The LEDGER's crashed rows are the ATTEMPT-level reclaim
receipt (the row re-pends — the real crash recovery), never a terminal.
The fence needs nothing new: with no fan-in there is no join to
fire early — the successor hazard is the PREMATURE TERMINAL (the run
finalizing while work is live), and the fence for it is the shipped
rows-only derivation itself: the root finalizes only when every row is
terminal (or resolved-blocked). A derivation cannot fire early because
it is not a fire at all. The 30-sweep probe (a mid-stream death, then
30 hard sweep passes with NO worker) holds: nothing terminalizes,
firable=0, zero join-wait rows — the join machinery is inert in this
design.
The durable importer: the caller's transaction joins the page¶
By default, ctx.emit_batch commits on TaskQ's own connection — separate from
any database writes your source body makes. A crash between those two commits
leaves application rows without their chain records, or vice versa. Passing an
open asyncpg connection via ctx.cursor(conn=conn) and
ctx.emit_batch(..., conn=conn) puts your application writes, the page's
children and edges, and the cursor checkpoint in one commit.
from taskq.workflows import StepContext, chain_start
async def import_pages(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,
)
Requirements and preflight. conn must be an asyncpg.Connection or
asyncpg.pool.PoolConnectionProxy (unwrap ORM wrappers such as SQLAlchemy's
AsyncConnection via .driver_connection, or use an asyncpg pool directly).
In one pg_catalog-qualified round trip, both emit_batch and ctx.cursor
verify that conn holds an asyncpg-owned, open, READ COMMITTED, read-write
transaction (never read_only) on the pool's own database (current_database())
and PostgreSQL cluster (system_identifier). Any mismatch — including raw-SQL
BEGIN (refused by the managed savepoint), or a restricted
pg_control_system role — raises deterministic
taskq.workflows.EmitTransactionError (never retried or parked). The pool's
identity is cached per pool and primed before a chain_source body runs, so a
page acquires nothing from the pool it is holding; if the pool cannot be read,
the prime is a logged best-effort miss. A page that then passes conn= sees
the prime's cause: a restricted pg_control_system role is refused
deterministically, while a saturated pool raises the builtin TimeoutError
after the bounded (1 s) checkout and is retried by the runner's ladder. A
writable physical clone (pg_basebackup / PITR) carries the same
system_identifier, so this check cannot tell it from the primary.
What to design for:
- One task per connection. Never share a caller connection across concurrent
tasks:
asyncpghas one top-level transaction per connection, so a nestedconn.transaction()silently turns into a savepoint. TaskQ refuses an overlapping in-flightconn=call on the same connection (EmitTransactionError). - Savepoint-scoped writes. Each
conn=page runs inside aSAVEPOINTin your open transaction. CatchingEmitFencedError,PageDivergedError, orMapIndexExhaustedErrorrolls back the savepoint cleanly so committing your own work leaks no children, edges, or cursor updates. Underconn=, a poisoned page (map_indexpast ceiling) raisesMapIndexExhaustedErrorwhole before any write. - Admission lock and capacity. Every statement runs on
conn(zero TaskQ-pool acquires during the page). Once a page fits, TaskQ takes the flow's transaction-scoped advisory lock before updating the source row; a rejected recheck rolls back the savepoint and releases the lock immediately, while an admitted page holds it until your commit or rollback. Capacity bounds still apply: a page that does not fit raisesEmitBackpressurewith nothing written and leaves your transaction usable — and it must ESCAPE your body, because that signal is what parks and resumes the source from the last committed checkpoint. - Codecs,
search_path, and GUCs. JSONB parameters are bound text-first (::text::jsonb) and emit statements arepg_catalog-qualified; keeppg_catalogreachable and unshadowed on your sessionsearch_pathso the invoker-rightsnotify_job_inserttrigger succeeds (shadowing it fails deterministically withEmitTransactionErrorand rolls the savepoint back). TaskQ never runsSET LOCALonconn. - Keep transactions short — and fleet-only. Committing a
conn=page refreshes the source row's lease and grants a one-lease reclaim deferral, but heartbeats cannot renew the source row while your transaction locks it (they useSKIP LOCKEDso sibling jobs stay unaffected). Keep commits to one page: long holds delay sibling emitters and, pastlock_lease, pageTaskQRunningLeaseExpired(seerunbooks.md). Because lease refresh needs a real lease,conn=is refused underworkflows.run(); run under a fleet worker orFlowRunner(..., lock_lease=...).
See the workflows API reference for the full preflight and lock-ordering specification.
The refuted-claim discipline: map_index is load-bearing¶
The per-record identity rides map_index, stamped at emit (with the
record's trace_id). The certified fork's idempotency key
(wf:{flow}:emit:{map_index}:{step}) and the step-ledger's claim
arbiter ((flow, step_key, COALESCE(map_index,-1), attempt,
claim_epoch)) BOTH discriminate siblings by it — the pre-stamp shape
emitted 200 applications without it and observed 198
UniqueViolations: every record's enrich child collided onto one row.
EmitChild therefore REQUIRES both stamps (a child without them is
refused before any row exists), and chain_start carries them forward.
Every row of one record's chain shares its trace_id — the operator's
drill-down is one query.
The identity's upper bound is resolved from the schema, never a
compile-time constant. MAP_INDEX_CEILING (32767) is only the threshold
that triggers one catalog read of the five carriers (jobs,
jobs_archive, wf_step_ledger, wf_outbox, wf_signals); once the
atomic POST migration widens all five to bigint, the resolved bound is
BIGINT_MAX (9223372036854775807) and records past 32767 stream without
restart. Only the EXPLICIT unbounded declaration (max_in_flight=None)
keeps the no-catalog-read fast path for an ordinary 0..32767 page, so only
it fails to detect a broken carrier shape there. Bounded emit is the DEFAULT
(max_in_flight is EMIT_MAX_IN_FLIGHT_DEFAULT, 1000, unless a workflow
declares None), and its capability preflight revalidates the five-carrier
width on every call — at flow creation, at each runner drive's adoption, and
at every emit, terminal/park, drain-chunk and marker-sweep seat (both bounded
emit paths, unreserved admission and reserved replay, preflight before any
write): one catalog
read per call, two on the composite park-adopt and marker-sweep paths that
invoke two preflighted entry points. It refuses a mixed, malformed, or botched
schema with WorkflowWorkerCapabilityError before any body, child, cursor, or
park write — a mixed or malformed carrier set preserves the resolver's
MapIndexSchemaError as its __cause__, the deployment class the runner's
deterministic leg reads — and the object-set checks themselves stay cached per
schema and width. A candidate above 32767 makes the
authoring doors — emit_batch, the map fork, insert_fork, and
insert_node — consult that resolved bound, and they fail closed with
MapIndexSchemaError (the admin panel answers HTTP 503) when the five
carriers are missing, mixed, NOT NULL, or of an unsupported type. The
hold door enforces the identity's type and non-negative lower bound; its
identity is either absent or a row-derived value the authoring doors
already checked, so it does not re-resolve the upper bound. A record
past the resolved bound raises the named MapIndexExhaustedError; its
valid page-mates still commit. The join counter jobs.deps_pending stays a smallint and is a
separate bound: widening the identity does not make one join over more
than 32767 children legal. That counter — not the identity — limits a
join-bearing fork, alongside the declared MAX_FAN_IN_PER_JOIN (1,000
unless child_driven=True); definitions.validate_fork enforces both
only when fork.join is not None, so a joinless engine
ForkSpec(join=None) and streaming chain_source/emit_batch have no
join counter to exceed (only the resolved map_index domain applies). A
typed route (FlowRunner._route_fork) validates its join-bearing fork
on the body path, before the finalize, and an oversized route fails
deterministically with FanInBoundExceededError before any row is
written. A map_source (FlowRunner._map_fork) runs inside
_finalize_success after the identity-domain check: more than
ceiling + 1 items fails first with MapIndexExhaustedError, and
insert_fork then enforces validate_fork's join bounds with
FanInBoundExceededError before the children are written. On a
pre-created-join adoption, insert_fork additionally refuses
existing_deps + len(children) > 32767 inside the finalize transaction
before the counter UPDATE; the raise unwinds the transaction's child
inserts. definitions.validate_join_spec is an exported standalone
build-time helper (the same MAX_FAN_IN_PER_JOIN bound, raising
FanInBoundExceededError) that no shipped authoring path (insert_node,
insert_fork, WorkflowCompiled.validate) invokes automatically.
The router: conditional edges, total or refused¶
CHAIN = Chain(
name="application-enrichment",
start="screen",
steps={
"screen": Step(
body=screen_app,
outcomes=ScreenOutcome,
route=Route({ScreenOutcome.CLEAN: "enrich", ScreenOutcome.FLAGGED: "manual_review"}),
),
"enrich": Step(
body=enrich_app,
outcomes=EnrichOutcome,
route=Route({EnrichOutcome.OK: "score", EnrichOutcome.SPARSE: DONE}),
),
"score": Step(body=score_app, outcomes=ScoreOutcome, route=Route({ScoreOutcome.OK: DONE})),
"manual_review": Step(
body=manual_review,
outcomes=ReviewOutcome,
route=Route({ReviewOutcome.APPROVE: DONE, ReviewOutcome.REJECT: DONE}),
),
},
)
# the SOURCE is the paged generator — each yield = ONE emit tx:
@app.workflow("application_sync")
def application_sync() -> Promise[object]:
return build(chain_source(CHAIN, source_body, key="source"))
The bodies are ordinary typed-outcome coroutines
(async def screen_app(ctx: StepContext, item) -> ScreenOutcome); the router's
decision is the body's return. Totality is the fence, at two doors:
- Declaration time —
Chainrefuses a route that is not total over its step's outcome enum:chain step 'screen': route is not total over ScreenOutcome — missing ['flagged'] … the outcome it drops would silently strand a record's chain.A route to a non-step key, and a non-step start, are the same door's refusals. - Run time —
RouterNotTotal: an outcome with no arm fails the step LOUDLY witherror_class='RouterNotTotal'— the record names the defect; the record's chain visibly dies, never silently drops, and the run's derivation cannot claim success over it.
The chain is declared ONCE and instantiates per record through the
certified fork-at-finalize machinery: each chain step's finalize forks
AT MOST ONE child (the route's arm — no fan-in, no join), the record's
payload, map_index and trace riding forward.
The typed route at the GRAPH level¶
The chain's route is the per-record stream's router. The GRAPH DSL has
its own face of the same machinery — route(promise, arms) (the flow API's
typed route): the union MEMBERS key the arms, the per-arm placement
rides RouteArm, the arm bodies receive the DECODED typed models, and
the children's rows ARE graph nodes feeding the derived join (the
fan-back-in the chain cannot spell). The arm contract is EXACT: each
arm body declares ITS OWN member on the item param — a superclass (or
an unrelated model) is the build refusal (E15's exact-member law).
The totality fence is the same
vocabulary at both levels, at THREE doors: the wiring verb's refusal
(missing/unknown members, NAMED), the validator's
E15-route-totality (the checker-independent re-proof from the
compiled graph), and the runtime RouterNotTotal — the element of a
type with no arm, or a source return that is not the declared
list[...] at all (the body that lied about its union) — fails the
source LOUDLY, nothing routes, the run FAILS. A skip= predicate on
a route source is refused at the wiring: the dispatch-time skip gate
would finalize the source succeeded without its fork, stranding the
join and the downstream consumer. The skip-silent shape is dead at
both levels.
Chain or DAG? (the one-paragraph decision guide)¶
The chain is the per-record stream — a route arm per outcome, at
most one child per step, no fan-in, no join; pick it when every record
flows ALONG ONE PATH and the arms are the branching. The DAG is the
shared shape — step/gather/map_source wiring with real
fan-in joins: pick it when independent results CONVERGE (a reducer
consuming two parents, a gather's all-upstream join, a map's
collected join). The typed route (route) is the
converge-and-dispatch shape — a map whose per-element arms DIFFER
(the mime-type router: text to the chunker, images to the OCR) with
the arms fanning back in at the next step; it is a MAP attachment (one
fork per source), not a chain, and not a bare gather. The wrong guess
costs a restructuring, not a
migration: a fan-in spelled as a chain has NOWHERE to put the second
parent (the chain's finalize forks at most one child — the convergence
is unwritable), and a route spelled as a DAG arm drags the whole graph
into the per-record stream where the shared joins never fire. The two
compose — the chain's records fan OUT of a chain_source (the emit
tx) into any downstream DAG node, and a chain step's body can be the
consumer of an upstream gather: the stream is the row source, the
graph is the convergence.
The all-emitted barrier: chain_barrier(src)¶
A streaming source finishes emitting before its emitted records finish running.
chain_barrier(src) wires a derived <src.key>.barrier node over a
chain_source that resolves only after the source has succeeded and every
emitted record's branch has terminalized, handing a ChainBarrierSummary to
any downstream step.
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 conservation. ChainBarrierSummary carries source_key,
emitted_records, succeeded_records, failed_records, cancelled_records,
and cursor (the source's final committed checkpoint). The barrier checks
emitted == succeeded + failed + cancelled (plus zero live records and one
group per emitted record) before returning, failing the barrier rather than
reporting an inconsistent count.
Placement and capacity. actor=None and queue=None inherit the source's
resolved placement; explicit non-empty values override individually. The
barrier is armed at create (deps_pending=1, blocking_reason='chain_barrier')
with no wf_edge from the source, and neither the barrier nor static nodes
downstream of it count against max_in_flight while pending — so a barrier
behind a full-capacity 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 (no peer-cancel storm), the barrier is fenced
failed_parent, the run fails with UnabsorbedNodeFailure on the root, and
downstream steps do not run. To tolerate degraded records, route them to a
fallback step inside the chain or read the per-record rollup from the rows.
Wait scope. The barrier waits for every chain step to terminalize —
including steps parked in ctx.wait_signal(...), ctx.wait_until(...), or an
awaited ctx.spawn_flow(...).wait() child flow — but deliberately does not
wait for detached fire-and-forget spawn_flow children or asynchronous
terminal effects (RetrySpec(on_exhaustion=...)).
Runtime shape. The engine releases the barrier reactively in the transaction that finishes the last branch (or the source's own terminal for a zero-record source), and the workflow sweep heals any missed release; operator retry re-arms a fenced barrier, and run cancellation fences it like any waiting row. See the workflows API reference for the field schema and build-time refusals.
The partial-success run (the envelope must not lie)¶
With no fan-in there is no absorbing edge, so the honest run vocabulary
stays the shipped one: the run failed when any chain failed
(UnabsorbedNodeFailure on the root — the alert hook), succeeded
when none did. The run's REPORT is the read-side rollup over the rows
(per-trace bool_or(status='failed') — {failed_chains: 7, total: 200}
is one query), never a new engine state. A "partial" derived status
would be a new primitive (a new terminal class, a new render rule across
the explorer/admin/API surface) rejected: the report reads the same
truth from the rows without it. Partial success as an AUTHORED ROUTE is
the ergonomic answer: route the degraded outcome to a fallback step and
the run succeeds with the degraded records visibly on their own route.
The migration path: from the actor's ad-hoc children to the chain¶
The TaskQ-native pattern this replaces — an actor body dispatching its own child jobs ad hoc (the hand-rolled "spawn a follow-up job per record, then a counter row to know when they're done") — maps onto the chain surface:
| the ad-hoc actor pattern | the flow's shape | what it buys |
|---|---|---|
ctx/client child dispatch mid-body |
the source's ctx.emit_batch per page (the children + edges + cursor, ONE tx) |
the fork-atomicity law at page granularity: a crash rolls the page back WHOLE and the resume re-emits exactly the lost page — the ad-hoc pattern's window (children enqueued, cursor lost, or the inverse) is structurally gone |
| the hand-rolled "done counter" row / the polling parent | nothing — the run root derives from the ROWS (the maintenance leg) | no counter to corrupt, no polling job, no wedged "waiting on children" state: the root's terminal IS the derivation |
| ad-hoc retry/backoff per child | the certified retry ladder (the row's own curve) | the ledger carries the full per-attempt history; the reclaim owns crashes |
| the follow-up job's invisible dependency | the chain's declared route (the fork's edge row) | the lineage is QUERYABLE: trace_id per record, map_index per record, parent_id per row — the ad-hoc pattern's children have no lineage and no completion semantics |
| the payload re-marshalled into each child | the record rides the row's payload verbatim (the fork carries it) | the drill-down reads one record's whole chain by its trace |
The lineage law: every row a source/chain writes carries
flow_id (the run), trace_id (the record), map_index (the record's
index — the discriminator) and parent_id (the emitting row). The
migration BUYS the lineage and the completion semantics and PAYS the
declared-edges discipline: the children are the fork's (an edge row
each, the ledger's truth), the completions are the derivation's — there
is no ad-hoc escape hatch, and a child dispatched outside the fork is a
foreign row no derivation counts. The honest boundary: an actor's
ad-hoc children that must remain in the NATIVE queue (no flow) keep
their no-lineage semantics — the migration is opt-in per workload, not
a fleet conversion.
The emit transaction's p50 stays single-digit ms per page, and a chain-shaped dispatch backlog costs the same ms-class as plain jobs at 200 chains — the streaming source adds one bounded transaction per page, not per record.
HITL: humans are rows¶
ctx.wait_signal((Approval, Escalate), timeout_s=…, tool=…, args=…,
reason=…) — THE TYPED WAIT. The tuple form is the typed wait (PEP 604
unions in value position carry no static payload information — the
return type is the union and narrows with isinstance); the
single-payload form is the one-member overload.
The resume contract:
the body re-executes FROM THE TOP on resume — there is NO
determinism requirement on the body; pre-wait side effects are
ctx.substep-ledgered and replay cheap. The delivered holds are the
node's ANSWER QUEUE: each execution's wait sequence consumes them in
epoch order (the per-call cursor, scoped to the executing claim: a
resume or a retry re-executes from the top and replays the answers in
order, while a step that waits twice in one execution takes the next
answer) — a RETRY replays the answers (the
operator never re-answers); a wait past the queue's end registers a NEW
hold (a NEW epoch — the multi-hold: the same signal name can hold
again, the chained gate works because the waits are sequential).
The payload rides the row: the human's answer IS
the row's payload; ctx.signal(name) reads it on resume (the read
before delivery is the typed SignalUnavailableError — never a silent
None).
The reply handle: every hold's id (uuid7, time-ordered) is THE
reference — HitlClient.resolve(id, decision) addresses ONE hold; the
(node, signal, epoch) identity disambiguates MULTIPLE holds. The
resolve is IDEMPOTENT (an already-resolved hold is the DEFINED no-op)
and AUDITED ("who resolved this" is a ROW, not a log line).
MAP SIBLINGS HOLD CONCURRENTLY, AS DISTINCT ROWS (the LedgerWatch
F2 fix — the per-item approval is the machinery's OWN shape): the hold
identity is
(workflow_id, node_key, signal_name, COALESCE(map_index, -1),
hold_epoch) — the map index rides the identity, so two items of one
map_source holding on the same signal name are TWO hold rows
(HitlClient.list(run=…) lists BOTH; each HoldContext carries its
map_index — the UI renders the item it addresses). Each resolve wakes
exactly the hold it names: the resume addresses the hold's OWN node by
the hold id stamped into that node's metadata — one hold, one node,
one answer consumed by its own sibling. A single shared
identity per node key would collide the siblings — the second sibling
wedged running forever in-process, or its hold INSERT died of the
unique arbiter into the ladder and its retry STOLE the first sibling's
delivered answer. A per-item review workflow (one hold per item, all
concurrent) is spelled directly on the map — no per-item run keys, no
side table.
The hold row's status vocabulary (the four spellings the ROWS carry, in one table):
status |
how a hold gets there | what the wait site does on resume |
|---|---|---|
held |
the wait site registered it (the live hold) | the wait site re-reads it (the idempotent re-hold) |
delivered |
a resolve/deliver won the CAS | the answer queue replays its payload |
abandoned |
one state, two doors: the expiry sweep fired past expires_at (the timeout door), or the operator abandoned it (taskq flows abandon <hold_id> / the admin run page's Abandon — the operator door; the row's payload carries abandoned_by='operator') |
the wait returns the Expired member (the fail-close), carrying abandoned_by — "timeout" for the sweep's rows, "operator" for the operator door's |
cancelled |
the run's cancel cascade swept it | the flow is terminal — the body does not resume |
All four live on wf_signals.status (partial-unique over the
UNRESOLVED holds only — resolved_at IS NULL); resolved_at is set
by every non-held transition.
The context contract: the hold carries the payload-model
schema (what a UI renders from), the author-supplied
reason/tool/args, the provenance (run id, node key, gate name, epoch,
created_at, the deadline). The redact law extends before persist:
the context passes the chain-then-hook redact
pipeline (the vetted masks + the hold surface's token-head pass + the
workflow's own redact= hook, wired from the registered definition) IN
THE SAME TRANSACTION as the hold's insert — the row never carries a
canary, so the default HitlClient (no hook handed, none wired) cannot
leak it at list/get; the read-side chain pass is the belt over the
persist-time law.
The knob, never the truth: a hold's appearance is
NOTIFIABLE (pg_notify on the taskq_wf_holds channel — the estate's
notify discipline); the notification carries THE POINTER (hold id + run
id + event) — a lost knock costs latency, never correctness: the
consumer converges by polling HitlClient.list(run=…).
The broadcast, typed: the knob's legs are now three
TRANSACTIONAL broadcast channels — taskq_wf_hold_created (the hold
CREATED, inside the insert's own tx), taskq_wf_hold_resolved (inside
the CAS-winning resolve/deliver tx, carrying verdict_kind: the
payload model the typed door validated against), and
taskq_wf_hold_expired (the defined abandoned state — the sweep's
deadline pass or the operator's abandon; the payload carries
abandoned_by: "timeout" from the sweep, "operator" from the
abandon door). The channels are
GLOBAL and the payload carries the SCHEMA (pg_notify is
per-database; the schema-per-module estate shares one database across
many schemas — the listener filters by payload, never by channel
arithmetic; that filter IS the isolation between the estate's
schemas). A rolled-back hold-create is SILENT by construction: PG
delivers a NOTIFY only when its transaction commits — and a
rolled-back RESOLVE is the same silence (the CAS + the audit + the
broadcast ride one tx). The typed consumer is
taskq.workflows.HitlListener — DIRECTLY ASYNC-ITERABLE, the events a
CLOSED union — and it BACKFILLS FROM THE ROWS at start (LISTEN first,
then the open-hold snapshot): a hold created before the listener
existed is still delivered, and its own late NOTIFY is deduped by
hold_id — the missed-event window is ZERO by construction. EVERY
(re)backfill ends with the Backfilled(open_hold_ids=…) reconcile
snapshot (the union's fourth member): a hold resolved or expired while
the listener was DOWN never announces its own death, so the consumer
drops any open card the snapshot disowns — and any stale event replayed
from before the outage dies the same death. Every subscriber gets its
own queue and its own end sentinel (the fan-out: N watching users, each
seeing every event — never a partition). The admin's /sse/{topic}
surface gained the holds topic: the same typed events (backfilled at
subscribe) streamed to the browser over the same session re-check
every other topic keeps. The resolve door is unchanged.
The listener's operational landmines (each one real; the listener's docstring carries the same four):
- PgBouncer: transaction-pooling (the default
pool_mode = transaction) SILENTLY breaks LISTEN — a LISTEN is session-scoped and a transaction pooler hands the session away after every tx, so notifications stop arriving with no error anywhere. The listener OWNS its dedicated connection for the stream's life precisely for this: it must be a DIRECT connection (bypass the pooler, or run a session-pooling port). This is the #1 real-world NOTIFY failure. - The capacity tax: that dedicated connection is ONE POOL SLOT FOR THE STREAM'S LIFE. Size the pool for the listeners you run; an SSE face holding a listener per browser tab spends one slot per tab.
- Fork safety: the dedicated connection is an asyncio transport
bound to the loop and process that opened it (asyncpg is documented
fork-unsafe —
_forkguard). An app that forks after the listener starts (uvicorn/gunicorn multi-worker,--preload) must start the listener IN EACH WORKER after the fork — never inherit a parent's live listener. - Expiry precision is AT-LEAST: the deadline fires on the DB clock
at the first leader-sweep pass at-or-after it — worst case
timeout_s+ the sweep interval + a leader failover's gap. Never promise a precise 120 s: the expiry is a floor; the fail-close is the guarantee.
The expiry is a value, not an exception: the
wait's outcome is the CLOSED UNION of the declared models joined with
Expired — the CHECKER FORCES the fail-close arm. From the REAL
example (examples/deep_research.py):
outcome = await ctx.wait_signal(
(ContinueApproval,),
timeout_s=APPROVAL_TIMEOUT_S, # the REAL default: 120.0
reason="the research loop wants to continue past the free passes",
)
match outcome:
case ContinueApproval() as approval:
if not approval.approved:
return Done(carry.finish_with_what_you_have(note=approval.note))
carry = carry.model_copy(update={"approved": True})
case Expired():
# THE FAIL-CLOSE: nobody watching — finish with what you have.
return Done(carry.finish_with_what_you_have())
The REAL file is examples/deep_research.py (the demo's fake corpus + the
loop wiring live there).
The typed expiry is a RESULT the body matches: the run SUCCEEDS
carrying the finish-with-what-you-have state — the user not watching
is a RESULT, typed and named, never a hang and never a failure. A body
that ignores the arm fails the checker (the fall-through against the
body's declared return; the bare unwrap against the missing attribute —
the type-probe corpus holds both markers). SignalTimeoutError stays
in the vocabulary for the body that WANTS the failure — the escalation
ladder's own use: raise it yourself off the Expired member. (The
example honors the loop's shape law — ONE wait per iteration; the
scenario's "three loops" are three research passes inside the first
iteration, because the answer queue's cursor IS the iteration counter.
The law has TEETH now — the W5-loop-wait-shape rule: a loop-kind body whose wait is
CONDITIONAL (some iterations wait, others don't) leaves the iteration
cursor past the answer queue — stranded answers, retries replaying the
wrong slot — and the wait site REFUSES the mis-aligned state with the
named LoopWaitShapeError. A plain step's cursor is
consumption-ordered; conditional waits are legal there.)
The operator door: a hold may also be abandoned by a human —
taskq flows abandon <hold_id> [--reason …], HitlClient.abandon(...),
or the admin run page's Abandon button. The row lands in the same
defined abandoned state (with abandoned_by='operator' on the
row's payload, and the operator's --reason beside it under
abandon_reason — the wait's declared context keys, its own
reason/tool/args among them, survive the merge) and the resumed
wait returns the same Expired member —
now carrying abandoned_by="operator" (the sweep's rows read
"timeout"). The value-not-machinery law is the operator door's own:
a body that wants the operator abandon to be a failure raises
SignalAbandonedError itself off that arm (the machinery never raises
it). An abandon is a stop-wait, not a verdict — no payload, no gate:
the parent fail-closes while a child flow keeps running. Timer holds
refuse the door (the clock is their only resolver), and a second
abandon of an operator-abandoned hold is the defined no-op.
The timers: the deadline is DB-CLOCK compared (the signal sweep's
expiry arm is the only live timer on a held row); the expired hold →
the defined abandoned state (the resume's wait site returns the
union's Expired member — the typed face, never a silent orphan;
abandoned_by names the door that wrote it);
timeout=None must be EXPLICIT (the W1 validate warning).
The timeout face is the union's second arm: after the sweep marks the hold abandoned, the
resume's wait site RETURNS the Expired member — the fail-close arm
the CHECKER forces — and NEVER mints an automatic new epoch (hold →
expire → re-hold → ∞ is the shape the face refuses). A body that WANTS
the failure raises SignalTimeoutError
ITSELF off the member (the escalation ladder's own use — the machinery
never raises): a step ladders and terminal-fails (the fail policy's
shape); a loop's failure-class rules route it as the BODY failure it
is. The operator door's failure is the same shape one door over —
SignalAbandonedError raised by the body off the Expired member
whose abandoned_by reads "operator". A deliberate re-wait — the
body matched the expiry member and
waits again within the same execution — is a NEW body decision: it
registers a NEW hold with a NEW epoch. The one exception is the child
join, which keeps one replay slot per node row and attempt rather than
one per child: an execution that has already observed two expired
children replays Expired for a re-wait on the first instead of minting
a new hold. The other timer policies
(resume_with_default / the escalation arm on the TIMER) are recorded
LATER for v1 (the don't-pay law): the body-level escape — match the
Expired member, return the default / enqueue the escalation
yourself — is the sanctioned composition until then, and it is exactly
what the value-based face enables.
The deliver boundary is real: a resolve
validates the payload against the hold's DECLARED models — BY SHAPE,
never by declaration order — BEFORE the CAS: a payload that fits NO
model, or fits MORE than one without the gate's discriminator=, is
the typed refused (the hold SURVIVES, nothing is consumed, the
refusal is AUDITED and the operator sees WHY). The union wait narrows
to the model the payload's shape fits — a lenient first member cannot
swallow a strict second member's delivery.
The audit is exactly-once: the resolve's
audit row + the knock ride the CAS-WINNING transaction — two concurrent
resolves → exactly ONE hitl.resolve audit row, ONE knock, ONE
resolution; the loser writes nothing.
The cancel cascade: FlowRunner.cancel_workflow(run_id,
reason=…) — ONE transaction (the flip is the linearization point), the
held signals → cancelled in the same snapshot, a LATE operator
deliver returns the typed refused (no zombie wake, no resume event),
terminal rows untouched, IDEMPOTENT (cancel twice = one cancel), the
audit row rides the same tx.
RESUME-NOT-RETRY : a hold's resume consumes NO
ladder attempts — the ledger distinguishes awaited from failed;
the ladder counts failed only. The shared-counter variant (2 holds +
max_attempts=3 = terminal failure with zero retries) is the defective
shape, named for the operator.
The durable timer: the clock is a resolver¶
"Remind them tomorrow" is a hold whose RESOLVER IS THE CLOCK:
ctx.wait_until(when, key=…) — the body sleeps, the run survives, the
wake resumes the body. THE TIMER'S FACE INVERTS THE EXPIRY'S: the
human gate's deadline-pass (wait_signal's timeout_s) is the
Expired member — the fail-close the checker forces. The timer's
deadline-pass is THE WAKE — the sweep resolves the hold
'held' → 'delivered' with the clock's own receipt and the body
RESUMES. The timer's point is the continuation, never the fail-close.
import asyncio
import os
import asyncpg
from pydantic import BaseModel
import taskq.migrate
from taskq.workflows import (
Promise,
StepContext,
TimerWake,
WorkflowApp,
build,
run,
step,
)
app = WorkflowApp()
class FollowUp(BaseModel):
ticket: str
@app.workflow("reminder_flow")
def reminder_flow() -> Promise[object]:
return build(step(remind_body, FollowUp(ticket="T-1"), key="remind"))
async def remind_body(ctx: StepContext, params: FollowUp) -> str:
# THE ONE-DAY SHAPE: `ctx.wait_until(when, key="remind")` with
# `when = datetime.now(timezone.utc) + timedelta(days=1)` — here a
# 1-second float so the verified run finishes fast. The pre-timer
# side effect is SUBSTEP-ledgered: the resume re-executes the body
# from the top and the substep replays (never re-runs).
wake = await ctx.wait_until(1.0, key="remind")
return (
f"ticket={params.ticket} wake={wake.key} by={wake.fired_by} late={wake.lateness_s >= 0.0}"
)
async def main() -> None:
dsn = os.environ["TASKQ_PG_DSN"]
schema = os.environ.get("TASKQ_SCHEMA_NAME", "taskq")
await taskq.migrate.apply_pending_locked(dsn, schema=schema, phase="pre")
await taskq.migrate.apply_pending_locked(dsn, schema=schema, phase="post")
pool = await asyncpg.create_pool(dsn)
outcome = await run(app.get("reminder_flow"), pool, schema)
print(f"claim={outcome.claim.kind} outcome={outcome.outcome} result={outcome.result}")
asyncio.run(main())
Verified output (this guide's capture, on a fresh schema):
The machinery, and the laws each piece carries:
- The row is the truth (the hold's law, unmodified): the timer IS
a
wf_signalshold row under the reserved__timer__signal prefix. The held representation releases the worker's SLOT (no lease, no claim, no attempt burned while sleeping); a LOOP node's budget pauses while the timer stands — the wall is blind while the body waits on the clock, exactly as while it waits on a human. - The sweep's timer arm (the expiry arm's inverted twin, wired
beside it in the leader's signal sweep and in the dev-loop
tick): every due timer hold resolves'delivered'— never'abandoned'— with the WAKE as the payload (fired_by='timer', the timer'skey, thescheduledandfired_atinstants). The'held' → 'delivered'CAS is the fence: a twice-fired timer is unrepresentable, and a cancelled flow's timer never wakes. The sweep is the wake's only owner: the fleet never claims a held row, so a due timer resumes on the next leader sweep tick (sweep_interval, default 30 s) plus a dispatch poll. The two arms that resolve a held row have different per-tick bounds:wait_until's timer arm drains its whole due set within one tick (sweep_due_timers(..., drain=True)), whereas await_signal(timeout_s=...)expiry is resolved by the one-batchwf_signal_sweeparm (sweep_expired_signals,drain=False: oneLIMIT 100pass per tick), so a burst of N expired human holds resumes overceil(N/100)ticks — 30 s per 100 after the deadline. - The durability is the design: a worker DEATH mid-wait changes
nothing — the hold row's expiry arms the reclaim, the successor's
sweep fires the wake, the body resumes from the top (the
re-execution doctrine: pre-timer side effects are
ctx.substep-ledgered and replay). The pin drops the arming driver and lets a fresh runner's sweep complete the flow. - The at-least face (the expiry's own precision law, restated):
the fire lands at the FIRST sweep pass at-or-after the deadline —
never early, never at a precise wall time.
TimerWake.lateness_s(thefired_at−scheduleddelta) is that honesty, on every wake. Pass afloat(seconds; the DB clock owns the base) or adatetime(the absolute instant; naive means UTC — the DB never re-bases it). - The timer is not a human hold:
HitlClient.list()never enumerates it (the reserved prefix is the split's mark — the display surfaces show it AS a timer), and the resolve boundary REFUSES any hand-delivered payload — a well-formed forgery of the wake's schema included. The clock is the only resolver this hold takes. - The interplay: the cancel cascade kills the timer with the flow
(it is an ordinary hold row — the same one-tx cascade);
ExpiredandTimerWakeare orthogonal in one flow (a human gate's fail-close beside a clock's wake fan in as two named outcomes); a mid-wait REDEPLOY re-enters the NEW body on the wake's resume (the versioning contract). In a LOOP the timer shares the answer queue's cursor — the ONE-wait-per-iteration shape law (W5) reads a conditional timer exactly as a conditionalwait_signal.
The naive-datetime law (the silent coercion, stated at the API
face): a naive datetime — no tzinfo — passed to wait_until is
interpreted as UTC. The coercion is silent (when.replace(tzinfo=UTC)):
no error, no local-zone reading — 17:00 naive means 17:00 UTC, not
your server's 17:00. The DB never re-bases the instant: the hold row's
expires_at is exactly the coerced value, the wake fires at that UTC
instant, and the wake's scheduled stamp reads it back unchanged. Pass
a tz-aware datetime (datetime.now(timezone.utc) + timedelta(...))
to mean what you said; a naive one is accepted for continuity and reads
as UTC. (A float of seconds keeps the relative face — the DB clock's
own now is its base.)
Progress: the nodes report¶
A workflow body reports its own progress: await ctx.progress(75, "page
3/4", {"page": 3}) — pct (int 0..100 or None), message (chars-capped
at 1024), data (jsonb, capped at 8 KiB). All optional; call it as often
as you like.
The emission is best-effort, and that is the design (the
law: observability degrades FIRST, never correctness). The call updates
an in-memory buffer latest-wins and arms a cadence flush (~20 writes/s at
the 50 ms cadence — a 1000-emissions/s body coalesces to the same write
rate); it NEVER awaits the network and NEVER touches the finalize path.
The coalescing is HONEST: the node's occurrences counter counts every
emission that coalesced into the row, so the record shows both the
delivered state and the emission rate. A flush that fails is counted and
warned once (progress-flush-lost); a node whose every flush fails still
terminalizes normally. A lost emission costs freshness; a blocked node
costs correctness.
The two channels (both bounded by construction):
| channel | table | shape | bound |
|---|---|---|---|
| the STATE channel | wf_node_progress |
one row per (node_id, channel), upserted latest-wins + the occurrence counter + the dropped counter |
nodes × channels — CONSTANT under any emission rate |
| the STREAM channel | wf_node_stream |
append rows in a per-node ring, drop-oldest with the dropped count ON THE RECORD | the ring bound (64/node; the retention sweep's prune arm is the backstop) |
The state channel answers "where is this node NOW" (a gauge). The stream channel answers "what did it report along the way" (a replay). The state channel keeps NO history: "what did the body report at 14:32" is answerable only where the author streamed it (the stream) — the honest boundary, stated in the progress guide.
The declared schema: step(body, ...,
progress_schema=Page) declares the shape of the node's data
emissions — a wrong-shaped emission is refused with
ProgressRefusedError (raised INTO the body: an authoring error is the
body's problem). The declaration is what makes a separate UI render the
emission — the context-contract law applied to progress. On a MAP SOURCE
the declaration reaches the children (<source>.item).
AUTO-PROGRESS IS A PROJECTION, NOT A SECOND STREAM (decision b): the
engine's node-start/terminal events project into the SAME stream with
class='auto' (the body's emissions are class='user'); the kind
vocabulary is CLOSED (progress, wf.node.started, wf.node.terminal —
validated at emit AND by the storage CHECK), and ONE seq generator backs
the table. ONE stream, ONE cursor serves both classes — a second
seq-cursor space would re-create the fleet's SSE-vocabulary
fragmentation. The projection is additive best-effort writes at the
claim/finalize seams: the finalize's own transactions are untouched (the
zero-finalize-changes probe is a shipped pin).
The progress-lie fence (the display law): the node's STATUS derives from the LEDGER; the progress renders INSIDE the terminal state, never over it. A body that reports 99% "almost done" and then FAILS shows failed with pct=99 inside — never 99%-running. A crash window (the worker died mid-emission) leaves the display STALE — freshness only — and the terminal heals it. The progress row is ADVISORY, always.
The aggregation is derived at read: a map's progress is
its children's grouped read ("120/200 · 0 running · avg pct 62" — one
query, LEFT JOINed to the state channel); a fan-in's is the edge ledger.
The user's aggregate of intermediate results WITHOUT a join node: declare
map_source(source, item, aggregate=fn) — a PURE, read-side fn evaluated
AT READ TIME over the children's decoded result rows (mid-flight,
unblocked, writing nothing). The join node is for DATAFLOW; progress
aggregation is OBSERVABILITY — a join whose only reader is the display
is the W2 validate warning (the join-for-progress anti-pattern: the DAG
would block on a display question).
The faces (every face a view over the same rows):
- the SSE stream:
GET /api/flow/{flow_id}/progress/streamon the admin router — adisplayframe first (ledger + state),progressframes in seq order (id:the seq — the browser EventSource reconnect contract), and — when the ring pruned past a reconnecting cursor — a NAMEDresyncframe (the partial mode + the state payload): the display converges, never a silent empty-success. - the run display:
run_display(pool, wsql, flow_id)— the ledger-derived states with the progress inside (the explorer's data contract);keyed_display(display)renders it name-first. Both are public API of the workflows package:from taskq.workflows import keyed_display, run_display. Thewsqlis the runner's own statement bag (runner.wsql— theFlowRunnerbuilds it from the schema). Seedocs/guides/progress.md's executable fence. - the gauge: workflow-dimensioned ONLY (the
_other_collapse) — per-child progress is NEVER a metric label series; it lives in the rows (the map line / the display), read on demand.
The vocabulary shims: the fleet's two live SSE vocabularies are MAPPED, not converted — each is a pure function over the one stream's rows:
| fleet vocabulary A | the stream | fleet vocabulary B |
|---|---|---|
{"type": "progress", "job": <node>, "pct": <pct>, "note": <message>} |
class='user', kind='progress' |
{"event": "update", "id": <node>, "percent": <pct>, "detail": <message>} |
| — | class='auto', kind='wf.node.started' |
{"event": "lifecycle", "id": <node>, "phase": "started"} |
| — | class='auto', kind='wf.node.terminal' |
{"event": "lifecycle", "id": <node>, "phase": "done"} |
A consumer of either old vocabulary is served by the ONE stream through its shim unchanged — the consolidation is the migration win (the third vocabulary cannot sprout: the kind set is closed at the emit path and by the storage CHECK).
The in-flight versioning contract¶
The decision — the registry-is-truth contract: a REDEPLOYED definition is adopted by the in-flight runs at their NEXT NODE CLAIM. The compile's STRUCTURE is the create-time snapshot (the nodes, the edges, the wiring — a run's graph never morphs mid-flight); every BODY resolves from the CURRENT registry at the claim seam (the resolution is per-claim, never per-run — the registry answers first, the compiled node's own body is the fallback when the registry lacks the key). A redeploy keeps the same node KEYS, so the registry hit is the norm: the new code runs the old run's remaining nodes.
TODAY'S HONEST PREDECESSOR: before this section existed, the same adoption happened SILENTLY — a mid-flow deploy changed in-flight behavior with no contract text and no taught read. The contract names the behavior; the STAMPS record it.
The stamps are the operator's read: every
node claim writes jobs.code_version — the body's canonical content
hash (the tors content hash over the named payload: module, qualname,
source, and the decorator's explicit pin when given). WHICH code ran
each row is a ROW fact, per node, per attempt:
SELECT step_key, attempt, code_version
FROM taskq.jobs
WHERE (metadata->>'flow_id')::uuid = $1
ORDER BY id;
A run whose rows carry TWO different hashes for one node = the deploy drift happened mid-run, and the rows say which side of it each attempt ran. The hash is a RECORD, never a gate: a body the hash cannot read (a builtin, a partial) records as NULL — the loss is logged, the claim never fails on its own audit.
The remediation (the operator's tool when the adoption is NOT what
a run should continue with): the cancel-then-restart path —
FlowRunner.cancel_workflow(run_id) (or the admin's cancel door),
then re-run on the current code under a NEW run key (the run-key
arbiter's own law: the re-run is a NEW key, never a replay of the
cancelled run's). There is no per-run code pin in v1: a run mid-flight
cannot be HELD on old code — the adoption is the contract, the
cancel-restart is the escape.
The edge cases (each re-enters the NEW body through the same claim-time resolution — the pin covers the second):
- A run mid-LOOP: the iteration's body re-resolves at the resume —
the next iteration (and the resumed one) runs the NEW code. If the body
SPAWNS, the iteration's (or map item's) unkeyed child run keys are derived
by whichever release executes it — the loop body's
<key>.iter<i>and the map item's<key>.item<m>(the per-iteration/per-item key, and the spawn-key upgrade note in Upgrading). An iteration or item that re-runs across the redeploy can mint its unkeyed children once more. Drain the run, or cancel-and-restart it, when a duplicated child side effect is unacceptable — this section's two escape hatches are the same rule. - A run mid-WAIT: the timer's wake or the human delivery's resume re-enters the NEW body — a wake is a resume like any other, and the claim-time resolution is the only body source. The answer queue's replay law holds ACROSS the deploy: the new body's wait site consumes the already-delivered answer (the operator's re-run never re-sleeps, the operator never re-answers).
- A cached step: the cache's address INCLUDES the
code_version— a redeploy is a NEW address, so the new code's results land on the new code's cache line and an old line is never served to a new body (the cache design's own law — the stale-truth hazard's structural kill).
The snapshot-per-run design: pinning each run's code AT CREATE (the create stamps the definition snapshot, the run reads its own snapshot forever) is not shipped yet — it would re-derive the compile-time registry discipline. Until it lands, the registry-is-truth contract above is THE behavior — rely on the stamps to see it, and on cancel-restart to escape it.
The versioning wedge (know it before you
rename): because the CURRENT registry is the only body source, a
redeploy that RENAMES or REMOVES a node wedges every in-flight run
sitting at it: the run's node row still exists (the create-time
structure snapshot), but the current graph no longer declares the key,
so the node can never claim a body again — the run is a ZOMBIE: never
terminal, nothing fails it, and nothing else in the CLI or the admin
surface said so. The drift is now VISIBLE: taskq flows status <run_id>
--app yourapp.workflows:app compares the run's node inventory against
the current registry's compiled graph and names the stranded nodes (a
node the current registry does not declare), the zombie law, and the
remedy (cancel + re-run). Related, and equally entailed by the
contract: a mid-map redeploy provably MIXES v1+v2 results in one run —
the fan-out's children claim the body one at a time, and the code
changed between claims (the registry-is-truth contract IS the mixing;
this is not a defect to fix but a fact to see). The per-node stamps
(jobs.code_version) are the read that says which side of the drift
each attempt ran; the map's summary row can carry mixed versions by
design. Escape hatches, both: the cancel-then-restart path above, or
re-deploy the old definition to let the run finish before re-deploying
the new one.
The context contract (what a body asserts on)¶
The body's ctx is the observability primitive: every field the contract names is on the LIVE surface (a body asserting on ctx is a pin, not a mock):
| Field | What it is |
|---|---|
ctx.flow_id |
the run's id (the address every surface takes) |
ctx.job_id |
this node attempt's job row |
ctx.node_key |
the node's key — the map's children run under <source>.item (the per-item ledger identity) |
ctx.attempt |
the attempt ordinal: a crash's re-run and a hold's resume each advance it, so it is not the ladder's count (the ladder counts the step's failed ledger rows: retries.md §12) |
ctx.input |
the FLOW input (create_flow(input=...)) |
ctx.flow_name |
the workflow's registered name |
ctx.queue |
the queue this node rides (the wiring's placement) |
ctx.claimed_at |
the attempt's claim timestamp |
ctx.map_index |
the map item's index (None off a map) |
ctx.budget_remaining_ms |
the loop's budget wall's remaining read (loop runs; None off a loop) |
ctx.hold_epoch |
the last consumed hold's epoch (a resumed body's answer identity) |
The two doors' contracts differ (stated, not hidden): the STEP door coerces — a body handing a pydantic model to step(...) has it re-validated at the boundary (the dict round-trips as the model). The EMIT door refuses — ctx.progress(...)'s payloads are dicts/bytes (the wire's own vocabulary); a pydantic model handed to emit is the LOUD ProgressRefusedError (an authoring error is the body's problem). Pass model.model_dump() at emit. (The emit door's model acceptance is not part of the contract; the refusal stands until the door learns models.)
The cancellation surface (what a body observes when a run is stopped)¶
An operator's cancel_workflow_run (the api-reference's ID-addressed cancel) and a deploy's drain (SIGTERM, the drain monitor, an isolate, a sibling-crash teardown) both reach a running body through the SAME cooperative channel: the attempt's live cancel carrier, read through ctx. The full body-visible surface:
| Member | What it is |
|---|---|
ctx.cancellation_requested |
True the moment a cancel reaches this attempt — a live, non-blocking bool (cancel_event.is_set()); safe to check inside tight loops |
ctx.cancel_event |
the live asyncio.Event — await ctx.cancel_event.wait() wakes the instant the signal lands |
await ctx.wait_cancelled() |
suspend until this attempt is cancelled, then return the origin at wake time. Every writer stamps the origin and then sets the event in the same step, so the waiter is woken once, by the transition itself: a body parked here is never re-woken by a later escalation, and a wake that follows an operator's cancel over an earlier shutdown signal reports OPERATOR |
ctx.cancel_origin |
who asked — CancelOrigin.NONE / OPERATOR / SHUTDOWN, the LIVE read (a body re-reading after a NONE → SHUTDOWN → OPERATOR transition sees the current asker, never a construction-time snapshot) |
ctx.cancel_reason |
the operator's stated reason — None unless operator-cancel metadata is present (a shutdown invents none). UNTRUSTED INPUT: operator free text from outside the system. The fleet record is shape-bounded only (control characters escaped, length capped at 500 by bound_reason); a direct-door CancelState carries its embedder's values as supplied. Neither path output-encodes — escape it for whatever sink renders it |
ctx.cancel_principal |
who asked for the operator cancel — None on the same rule, and UNTRUSTED on the same terms (fleet-bounded or embedder-supplied, never output-encoded) |
Every member is a LIVE read through the attempt's carrier — the worker's own JobContext on the fleet path, an injected CancelState on the direct door (run(...) / FlowRunner, which default to an unset event and CancelOrigin.NONE) — never a snapshot: a mid-body origin transition is observed the instant it lands. Import the vocabulary from the package root:
The reason and the principal also land durably, outside any body. An
operator's cancel_workflow_run writes the bounded record under
jobs.metadata.wf_cancel ({"reason": ..., "principal": ...}, both already
normalized and shape-bounded) on the run's root row and on every targeted
non-terminal row, including one left running for cooperative cancellation. That
is the record the run-level audit trail and the
admin job page's metadata display read, and it is why the values outlive the
process with no column and no migration. Nothing polls it in-process: the
root leaves running in the same statement that writes it. The strings in it
carry exactly the trust ctx.cancel_reason / ctx.cancel_principal carry —
untrusted operator free text, bounded but never output-encoded.
Drain vs operator cancel: the disposition table¶
On the fleet path, the two channels share one event but route to OPPOSITE verdicts — the origin decides, never the exception type (a deploy and an operator cancel both surface as asyncio.CancelledError). A direct door's injected CancelState is an observation seam only: it neither flips the run root nor invokes the worker's shutdown release, so this table's durable dispositions belong to cancel_workflow_run and worker shutdown:
CancelOrigin.SHUTDOWN — a deploy's drain |
CancelOrigin.OPERATOR — an operator cancel |
|
|---|---|---|
| The attempt's end | Released, never terminalized: a claim-epoch-scoped shutdown release (mark_interrupted) hands the row back to the fleet — pending, or scheduled behind the release hold while a detached body task has not provably unwound — interrupt_count bumps, the lease clears, no cancel verdict is written |
Terminalized cancelled: the workflow-aware operator finalization writes the verdict (idempotent — cancel twice is one cancel); the run is over |
| Retry budget | Preserved — the release writes ZERO failed wf_step_ledger rows, so the body-failure ladder is untouched. The spent attempt stands: the increment is not refunded (it started executing), the same law the vanilla rows keep |
The recorded attempt rows stand; the cancelled run is not resumed, so no budget question arises |
| Resume contract on re-claim | All three: the step ledger's memoization (every succeeded ctx.substep record replays its result — completed work never re-runs), the durable chain_source cursor (the source row's emit_cursor metadata, fenced by the full dispatch fence — the re-claim re-emits exactly the lost page, never a committed one), and the loop iteration ledger (the node row's iteration counter + carry, advanced once per iteration under the claim fence — the resumed loop continues at the recorded iteration) |
None — the body does not resume |
| Who wins a race | An operator cancel that lands mid-drain WINS: the release's cancel_phase = 0 fence answers noop and the row routes through the operator's terminalization |
Final — a later shutdown signal never downgrades an operator's verdict |
Two body-level corollaries the table implies: a body that observes SHUTDOWN and returns normally (ignoring the interruption) commits succeeded cleanly if its claim fence still holds — a completed result is never discarded by a deploy; and the cancel-that-races pattern is the cancellation guide's reconcile law carried to the workflow rows.
If the worker dies mid-cancel, the node belongs to the workflow estate's
own recovery owner, never to the vanilla crash sweep. Sweep 1
(reclaim_expired_locks) and isolate_self both exclude cancel-flagged
workflow node rows — a node's terminal owns its step ledger, its reservation
and its completion wake-ups, which a generic job-row write would settle around.
The leader's wf_cancelled_claims arm is the owner: leader-gated and gated on
the backend implementing the workflow sweep surface (workflow_sweeps_capable,
a class-level constant on PostgresBackend), it runs every sweep_interval, and once the
cancel request has outlived the whole ladder (lock_lease +
cancellation_grace_period + cleanup_grace_period + 60 s) it settles the
node through the same fenced operator-cancel door the cancel ladder uses. See
architecture.md for both
deadlines it covers and maintenance-sweeps.md for its
cadence and batch bound.
The two-channel body pattern¶
A body that holds something expensive reads the origin and picks its exit:
import asyncio
from taskq.workflows import CancelOrigin, StepContext
async def close_or_checkpoint(ctx: StepContext) -> None:
if not ctx.cancellation_requested:
return
if ctx.cancel_origin is CancelOrigin.OPERATOR:
# The run is over for good: close/clean up the domain record and
# exit. The row terminalizes `cancelled` — the cancel is the run's
# final word, and a result a cancelled run's body returns is never
# published (anything that must survive the cancel belongs in the
# domain record you just closed out). The one exemption is a
# materialized after-terminal effect — its committed intent is a
# durable obligation the cancel does not revoke (see "Authored
# terminal effects" below).
await archive_domain_record(ctx.job_id)
return
# CancelOrigin.SHUTDOWN: this attempt is released back to the fleet and
# re-run on a surviving worker from the durable checkpoints. Record the
# checkpoint through the memoized ledger and raise — returning a partial
# result the fleet cannot use as-is would record `succeeded` for half the
# work. ctx.progress is best-effort observability, not resume state.
await ctx.substep("shutdown-checkpoint", checkpoint_domain_record, ctx.job_id)
raise asyncio.CancelledError
Fleet path only. The two dispositions above are the worker's: on the fleet
path the attempt that observes the origin is the one whose row the worker
releases or terminalises. A direct door — run(..., cancel_state=...) or a
FlowRunner handed a CancelState — has no worker behind it: injecting a
carrier there flips nothing durable and raises nothing for you, so a body that
sees OPERATOR on a direct door must still return or raise on its own (and the
run's own CancelledError propagation aborts run()). Use the carrier on the
direct door to observe and to test a body's cancellation branch, not to expect
the durable dispositions.
How fast a body sees it (the observation latency guarantee)¶
Cancellation is COOPERATIVE and BEST-EFFORT by contract: nothing pre-empts a body's code at the signal itself. A body that never reads the surface is interrupted by the operator ladder after cancellation_grace_period, or by the shutdown orchestration's forcing phase after its own grace. The per-attempt start_to_close deadline is independent machinery, not the cancel escalation setting. For an operator cancel, the wake chain is: the cancel commits and posts pg_notify → the worker's notify listener wakes the heartbeat loop ahead of its next tick → the cancel-poll tick stamps the live carrier → ctx.cancel_event sets. SHUTDOWN is stamped locally by the worker's shutdown orchestration. In the normal fleet both channels are SUB-SECOND from the request to the body's wake (the suite's bound is <= 1.0 s, measured over the real production paths). A lost operator NOTIFY degrades to the heartbeat poll backstop (the loop reads the cancel flags on every tick — heartbeat_interval, default 10 s): the observation is delayed, never lost. The DATABASE FENCES stay authoritative either way — the dispatch fence (a pending child of a cancelled flow is unclaimable), the finalize CAS, and the release's claim-epoch fence are checked in-statement regardless of what any body observed — so a body that misses the signal cannot commit a competing node verdict or fork new database work past the fence: the rows decide.
The observability contract (the workflow spans)¶
The vanilla lifecycle emits spans at every messaging point (enqueue
{actor}, process {actor}, attempt.{N}, dispatch, cron fire —
see the observability guide's span hierarchy).
A workflow's rows never ride that path — the fleet intercept bypasses
consume_one_job and the dev drive never enters it — so the workflows
package emits its own spans at the wf lifecycle's points, with the SAME
machinery and the SAME laws (no new otel machinery, no new metrics):
- The RUN span —
run {workflow}(INTERNAL): one pertaskq.workflows.runcall. It is a root (new_root=True, the producer-link pattern): linked, never parented, to the ambient trace — a caller's own span is not held open for the run's lifetime, the link is the correlation. Created at the flow's first claim (the run-key claim) and ended at the drive's stop. Child flows carry no run span of their own — their steps ride the tree below their parent's. - The STEP span —
step {step_key}(INTERNAL): ONE attempt of one node through the claim tail — the one shared tail the dev drive and the worker-hosted fleet door both land in, so both faces emit it. When the run drives in-process (execute=True), the step span is the run span's child (otel's in-process context propagation). On a fleet worker there is no run span in that process, so the step span is a per-process root: the vanilla's cross-process law is producer-stamped ids on the job row plus a consumer-side link, and wf rows have no producer span to stamp otel ids from (the row'strace_idcolumn carries the wf per-record lineage id — a different concept). The cross-process correlation is therefore thetaskq.flow_idattribute; no traceparent crosses processes.
The attribute contract (the vanilla taskq.* namespace):
| span | attribute | value |
|---|---|---|
| run | taskq.workflow |
the registered workflow name |
| run | taskq.flow_id |
the run's root-row id (set the moment the claim returns) |
| run | taskq.queue |
the root row's queue (a constant by construction — the steps carry their own) |
| run | taskq.run_key |
only when the caller declared a key= — UNREDACTED caller-controlled text (the observability guide's own caveat for taskq.identity_key: attribute cardinality is free but the value rides whole; declare keys accordingly — a slot timestamp, never an email + token) |
| run | taskq.priority |
only when the caller declared a priority= |
| run | taskq.outcome |
the drive's label: terminal / held / max_ticks |
| step | taskq.flow_id, taskq.workflow, taskq.step |
the flow link, the name, the step key |
| step | taskq.attempt |
the attempt ordinal |
| step | taskq.queue |
the node's queue, when the node's decl carries one (the fork-spawned map children have no decl) |
| step | taskq.map_index |
the map item's index, when the row has one |
| step | taskq.outcome |
the claim tail's own label: succeeded / skipped / loop / held / deferred / fenced / laddered / cancelled, and crashed for the machinery boundary's re-raise |
Status and events follow the vanilla consumer span's laws. Status:
OK on the succeeded class, ERROR on the failed class, the mid-states
(held, deferred, fenced, cancelled) UNSET. The lifecycle events reuse
the vanilla grammar (lifecycle.running, then
lifecycle.succeeded/lifecycle.failed/lifecycle.cancelled with
from_state/to_state). The fan-out's shape is EVENTS on the spans,
never separate spans — wf.forked (the map source's children count),
wf.join_fired (the join keys that fired in the finalizing tx),
wf.held (the hold id + the signals), wf.deferred (the signal + the
delay), and wf.laddered (the error class + whether the ladder
re-pended) beside the SCRUBBED exception event.
The redaction law holds unchanged: a failing step's error is
rendered through the obs layer's scrub pass once — the Postgres DETAIL
row values are dropped and every credential family (URI userinfo and
query credentials, libpq parameters, auth headers, OAuth/JWT tokens,
presigned-URL signatures, vendor secrets) is masked, so none of it
reaches the exporter. The
no-op law holds unchanged: with telemetry off (TASKQ_OTEL_ENABLED=false)
the attribute documents are never built, no span is created, and the run
is byte-identical (a run under spans and a run without them produce the
same rows). Metrics: none are added — the vanilla's one wf-relevant
instrument is the maintenance leader's fleet gauge
(taskq.wf_progress_nodes_total); no per-run wf metric exists to
mirror, and the per-node truth lives in the rows and the run page.
Visualizing workflows: the admin's run explorer¶
The admin UI's Workflows tab is the run explorer: the runs list (the inventory question — newest first, capped at 200), and the run page (/taskq/workflows/{run_id}):
Setup: the admin router mounts with the auth posture configured
(TASKQ_ENVIRONMENT=dev for local, or an auth_dependency — the
fail-closed check refuses an unauthenticated mount otherwise). The run
explorer's RESOLVE/DELIVER/CANCEL actions need
TASKQ_ADMIN_ACTIONS_ENABLED=true (the default false answers 403 on
those actions); the actions answer 501 when the admin's process mounts
no WorkflowApp — the resolve/deliver doors need the definitions
imported in THAT process to validate and drive the hold's payload.
- The graph — the run's Mermaid, emitted FROM THE ROWS (the live graph is a row fact; the admin never imports the workflow's module): the collapsed map renders as ONE hexagon with a
done/totalcounter — zero child boxes (the counter reads the children's TRUE parent — the map source the fork parented them at — and the run header carries the SUM across sources); the render does not scale with the fan-out (a 10k map renders one hexagon, never 10k lines). The child detail lives in the node panel. Rendered ONCE by the vendored mermaid (no bundler, no React, no CDN — the air-gapped-ops argument); every later update is a classList patch ondata-node-key— zero re-renders (the node keys and statuses are sanitized/escaped against the legend's closed vocabulary — a poisoned row key cannot blind the live updates). The state colors: green succeeded, blue running, red failed, amber HELD (a human is waiting). - The node panel — click a node (or Tab to it and press Enter): the status header, the attempts + the retry kind, the trace id, the captured error (errors-only by default; the panel's read is DISPLAY-CAPPED with the dropped-count named — the full detail stays in the rows), one upstream hop (the causal chain via parent_id), and the attempt ledger.
- The deferral line — a step sitting on a body-raised
Snooze/RetryAfterrenders the line beside its status chip: the signal that deferred it, the NEXT FIRE TIME, and the node's snooze count — the operator's "why is this step sitting here" answer without leaving the page. The line is the ROW's truth (the deferral stamp's own discriminator): it appears when the node arrives at the snoozed state and clears when the step re-claims or a later ladder repend lands (never a stale decoration), in the server snapshot and on the live SSE frames alike. - The runs list's deferral badge — the same state at the RUN level: a run with a node sitting on a live deferral renders the badge on its runs-list row (the sitting nodes' count, the earliest next fire, the deferral depth) — a pathologically deferring run is visible from the INVENTORY, never only after opening the run. A run with no sitting deferral renders no badge.
- The holds & decisions — the held row's waiting-on state: the gate, the node, the epoch, the deadline, the author's reason/tool/args, the DECLARED payload schema, and a prefilled valid example. The Resolve form delivers through the typed door (the wrong payload answers the named pydantic error inline; the hold survives — and the REFUSAL ITSELF is audited: the trail records the refused attempt with its reason, so probing the door is as visible as using it). Resolved holds render as decisions (the rows-alone audit).
- The audit trail — every operator action on the run (resolve/deliver/cancel) is a ROW here: the principal, the action, the reason. This includes the REFUSED actions — a shape-refused resolve or deliver writes its
refusedrow (the refusal is the action). Reads are never audited. - The live transport — SSE (
/taskq/api/runs/{id}/stream): every frame is a revisioned FULL snapshot; the seq-cursor drops stale frames;Last-Event-ID(EventSource supplies it for free on reconnect) continues the cursor and the next frame carries the whole state — the reconnect never loses state. The stream re-checks the admin session every poll — a session revoked MID-STREAM ends the stream at the next tick (the same law/sse/{topic}keeps; a verifier error or a hung verifier fails closed). An UNKNOWN run id is a404at subscribe (the same subscribe-time refusal/sse/{topic}gives an unknown topic) — a run that exists but has no node rows yet still streams. The page setssuppress_refresh=True(the meta refresh would destroy the live SVG). - The no-JS story, stated honestly: the no-JS surface is the SERVER-RENDERED INITIAL SNAPSHOT (the state at page load, from the same grouped query the boot JSON carries). No interactive no-JS mode is invented; without JS the page is a snapshot, and says so where the live badge would be.
The diagnosis runbook¶
A workflow is stuck. The order of questions:
- What is the run's state?
taskq flows status <run_id>— the derivation over the node rows; every stuck node names its waiting-on state + its remedy. The root row's own status is a CACHE (the rows are the truth — the page says so beside the derived status). - Is it waiting on a human?
taskq flows holds <run_id>— the pending holds with their deadlines. A hold with NO deadline is the W1 warning's subject (a workflow that waits forever on a human is a support ticket — the deadline istimeout_s=, explicit). The operator's reply:taskq flows resolve <hold_id> '<json>' --app myapp.workflows:app(the payload validates through the hold's declared models before anything moves; a wrong shape is refused and the hold survives). - Is a node failed? The status names it + its claim headroom (
attemptvsmax_attempts; the CLI labels it "ladder headroom", but on a workflow step it is the crash reclaim's budget, and the body-failure ladder countsfailedledger rows: retries.md §12). The manual resume:taskq flows retry <run_id> <node>— the ledger is KEPT (the spent attempts stay recorded), neither count resets (a transient node whose ladder ran out gets one more body attempt, and its first crash is terminal), the blocked closure re-opens. - Is it a join that can never fire? The status renders the join-wait rows with the deps counter. A join blocked
failed_parentre-opens when the failed parent's retry lands (a parent that endedcrashed/abandonedis not re-armable — re-run instead); a join blockedorphan_parent/flow_deadis the fence's record — see the failure-propagation section. A join over a CANCELLED parent is not left waiting at all: the sweep terminalizes itcancelledwitherror_class='CancelledByCancelledParent', so the run converges andtaskq flows statusnames the cancelled parent. - Still stuck? The admin's run page renders the SAME derivation + the node panel's attempt ledger + the audit trail. The rows-alone law: if the CLI and the page disagree, the ROWS decide — file it as a defect with both outputs.
- Is the work slow or is the holder dead? (the stuck-vs-slow triage.) A body that hangs inside its own code (a long wait, a dead dependency) is never a stuck finding — its row is
running, which no why-stuck arm names.flows statusgives running rows their own face: each running row older than a minute prints its running AGE (sincestarted_at) and the lease check. The lease check is the verdict: taskq job show <job_id>on arunningrow prints the lease face (locked_by_worker,last_heartbeat_at,lock_expires_at). A FRESH lease is work in progress — slow is slow. A LAPSED lease is a dead holder — the row says so (lease: LAPSED ... the holder is presumed DEAD).- The reclaim sweep repends a lapsed row (or crashes it past the attempt budget) within
TASKQ_SWEEP_INTERVAL(default 30 s) — but only while a leader is up. A lapsed lease with no live worker staysrunninguntil one returns: if the whole fleet died, the rows wait, and the FIRST 3am fix is to bring a worker back. Confirm the death from the record:taskq job events <job_id>carries onestate_changerow withreason: lock_expiredand the dead worker's id per reclaim. - The timers' face: a node waiting on a typed signal (a hold) is NOT running —
taskq flows holds <run_id>names the hold with its DEADLINE (the wake time: when the timeout fires, the body'sExpiredarm runs). A hold with no deadline is the W1 warning's subject (step 2).
The operator's rows: the wf_* tables and the closed vocabularies¶
Every workflow fact is a row in the same database; the CLI and the explorer are conveniences over these tables, and at 3am the raw query is always reachable. The tables (all in your schema, default taskq):
| Table | One row per | The columns that matter |
|---|---|---|
jobs (the workflow rows) |
a run's root (step_key='__flow__'), every node, every map child |
step_key (the positional node key — never changes across holds/retries/reclaims), deps_pending (the join counter — a CACHE; the edge ledger is truth), map_index (the fan-out slot), parent_id (the graph's parent pointer — the fork's source node), code_version (the per-attempt code hash), metadata (flow_id, workflow, blocking_reason, failed_parent, wf_cache_hit), plus the vanilla columns (status, attempt, max_attempts, the lease columns, the error columns) |
wf_edge |
dependency edge (child_id, parent_id, failure_policy) |
the join counter's ONLY truth source; the failure policy the edge was wired with (collect/fail_closed) |
wf_join_fire |
exactly-once join fire (join_job_id UNIQUE) |
the fire guard's record: at most one fire per joined node, ever |
wf_outbox |
a fired join's consumer delivery | delivered false = the drain still owes the consumer rows |
wf_step_ledger |
one attempt of one step (flow_id, step_key, map_index, attempt, claim_epoch) |
the attempt record: status (the attempt's outcome), result, error_class, error_message, capture (the failure IO-capture, per the workflow's policy) |
wf_signals |
one hold/delivery (workflow_id, node_key, signal_name, hold_epoch) |
status='held' = a pending human wait; expires_at = the deadline; payload_schema = the declared payload shape |
wf_node_progress / wf_node_stream |
per-node progress/state-channel rows | the progress faces |
wf_step_cache |
one cached step result (content_address) |
run_id (the producing run), result, expires_at (the TTL) |
The closed vocabularies (the values the surfaces render, and what each means):
- The run's identity, one id per surface: the prose says "run id";
the Python kwarg is
flow_id=(the claim's ownJobId);HitlClient.listacceptsrun=(canonical) andflow_id=; the CLI spells itrun_id(taskq flows holds <run_id>); the admin URL is/taskq/workflows/{run_id}. One id — thejobsroot row — spelled per surface. -
"Hold" is the user-facing concept: a node waiting on a human, a deadline, or a typed signal. The implementation names it in places (
GateDecl,wf_signals, the gates= parameter) — the surfaces the operator reads (the run explorer, the CLI, this guide) say "hold". -
A node row's
statusis the vanilla jobs vocabulary:pending,scheduled,running,succeeded,failed,cancelled,crashed,abandoned. Two derived pending SHAPES exist — join-wait (pending+deps_pending > 0) and held (pending+ the unresolvedwf_signalsrow).crashed/abandonedare TERMINALS (zero outbound transitions; the derivation folds them into the failed class). - The run status is DERIVED from the node rows:
running(any node live or a cancel in flight) →failed(any unabsorbed failure) →blocked(any hold, join-wait, or blocked row) →complete→cancelled→pending. The root row's ownstatusis a CACHE of this derivation. metadata.blocking_reason(why a pending row cannot be claimed):join— a HEALTHY join-wait (fires when its parents finalize);failed_parent— a parent reached a failure terminal (failed,crashed,abandoned), either on a non-absorbing (fail-closed) edge or as the terminal-flow fence's attribution on an absorbing edge (the parent's id and step key are stamped beside it inmetadata.failed_parent/metadata.failed_step);orphan_parent— the rederive arm found join-wait rows with no edges (the belt-and-suspenders stamp);flow_dead— the fence's record: the flow died and the join can never fire;body_unavailable— a fired join whose body never resolved in any worker's process (the delivery CONTINUED; the warning is the record). The markers describe apendingrow's reason; a join that reached a terminal status keeps'join'as the joined-row family marker (a swept unreachable join iscancelled+error_class='CancelledByCancelledParent').
The audit recipe: "what did this run actually do?"¶
Reconstructing a run's story from the surfaces (no app source, no logs):
- The shape:
taskq flows status <run_id>— the nodes, the derived status, every stuck row's why + remedy. - The attempts: each node's
attemptvsmax_attemptsis the claim count the crash reclaim gates on, while the body-failure ladder counts the node'sfailedledger rows (retries.md §12); the LEDGER is the per-attempt record. The CLI's node read (and the explorer's node panel) renders the attempt ledger per node; in SQL:SELECT step_key, attempt, status, error_class, created_at FROM taskq.wf_step_ledger WHERE flow_id = '<run_id>' ORDER BY created_at— every attempt's outcome, in order, with the class of every death the runner recorded (the crash reclaim never writes the ledger: a lease-reclaimed crash is itscrashedrow intaskq.job_attempts). The same query returnsctx.substeprecords beside the node attempts. Actx.substeprow is the LATEST outcome of its (attempt,claim_epoch), not an immutable per-call record: a caught failure that the body re-called had itserror_class/error_messagecleared on the re-open (the claim re-opens the row in place, and the retired error is logged asworkflow-substep-failure-retiredrather than kept as a second row), sostatus='succeeded'with NULL error columns can mean a recovered re-call, not only a first-try success. A row whosestep_keybegins with its ownjob_id(<job id>/<name>, or<job id>.iter<n>/<name>in a loop body) is a substep record of that node job; jointaskq.jobsonjob_idfor the node's key. (A/alone does not mark one: a loop's own key may contain/.) - The vanilla events:
taskq job events <job_id>— the state changes (lock_expiredreclaims carry the dead worker's id). - The cache hits: a node row with
metadata.wf_cache_hit(rendered bytaskq job show <job_id>ascache_hit:and by the explorer's node panel) NEVER executed — the body ran in the receipt'srun_id, andwf_step_cacheholds the delivered result (SELECT content_address, run_id, created_at FROM taskq.wf_step_cache WHERE content_address = '<address>'). A bad cached result is evicted by deleting the address's row; the next run re-executes and re-fills it:DELETE FROM taskq.wf_step_cache WHERE content_address = '<address>'; - The graph:
jobs.parent_idis the fork's source pointer (every map child points at the source node; node rows point at their wired parents);wf_edgeis the complete edge list with each edge's failure policy. The parent↔child walk is a two-column query:SELECT child.step_key, child.map_index, parent.step_key AS via FROM taskq.wf_edge e JOIN taskq.jobs child ON child.id = e.child_id JOIN taskq.jobs parent ON parent.id = e.parent_id WHERE e.flow_id = '<run_id>'; - The operator's actions: the explorer's audit-trail section (and
admin_auditrows) record every resolve/deliver/cancel — including the REFUSED ones.
Chain execution policy — one target resolver¶
Step(body=..., policy=ExecutionPolicy(...)), Chain(default_policy=...), and
chain_source(..., policy=...) share the converted target terms; they are not a
second reservation, retry, or actor-capacity implementation. Every source/leaf
field supports omission/None = inherit. Use the explicit CLEAR_POLICY
sentinel to clear one inherited option. Frozen ExecutionPolicy carries
actor, queue, existing rate-limit/reservation declarations,
max_concurrent, result_ttl, capacity_owner, priority, start_to_close,
and an optional workflow RetrySpec.
Precedence is target policy → target actor-handle defaults → chain default →
compatibility placement/defaults. A run's explicit priority= still outranks
all of those, including rows emitted or forked later. Compatibility
actor/queue/max_attempts lower into this same representation;
contradictory co-declarations fail early with E21-execution-policy, while an
equivalent redeclaration is accepted. Handle names/queues do not replace the
chain target's placement. Two different cohort capacities/owners require
different actor names, exactly as above.
The source is not a record leaf. chain_source's policy comes from its own
arguments and handle, never silently from Chain.default_policy. The same
resolved target governs chain starts, routed forks, row stamps, boot cohort
projection and ladder lookup. Bounded strict slots, actor capacity, result TTL,
priority, and per-attempt start_to_close therefore ride the ordinary jobs
rows/actor registry instead of needing an application-side scheduler.
RetrySpec wraps the existing validated RetryPolicy; its exceptions map
accepts exception classes mapped to canonical kinds, RetryOverride, or the
workflow-specific WorkflowRetryOverride. The most specific exception class
wins. A mapped None explicitly selects the default policy instead of falling
through. A custom classifier uses the existing safe-hook fallback if it raises
or returns a malformed value. Only body-raised ordinary exceptions enter it:
engine authoring faults, Snooze/RetryAfter, deadline enforcement,
cancellation/shutdown and infrastructure persistence faults stay in their own
domains.
Declared exponential, linear, and fixed curves share compute_backoff's
base/cap/jitter arithmetic with the live ladder and durable row curve. New
workflow declarations reject time_budget (use per-attempt start_to_close)
and reject indefinite as a budget bypass; already-persisted legacy rows retain
their existing vocabulary. Legacy retry_kind="permanent" normalizes to the
persistent non_retryable, which also outranks consuming RetryAfter.
An explicitly advertised workflow-only
WorkflowRetryOverride(delay=..., consume_budget=False) does not consume
max_attempts, advance a source's logical failure ordinal, or increment the
legacy snooze_count. Such a spec must declare positive finite
non_consuming_limit. The deferral's own claim-fenced row law increments and
reads the durable jobs.metadata.wf_retry.non_consuming_count in the same
transaction as the deferral. At the exact bound it terminates as
RetryDeferralBudgetExceeded; an advertised wait itself has no failed-ledger
outcome and interruption does not consume an ordinary failure. A malformed
counter/bound fails closed with no counter reset or ledger mutation.
This new bound is deliberately not applied retroactively to generic
body-raised Snooze or RetryAfter(consume_budget=False) without such a retry
declaration; that pre-existing public unbounded seam is a named compatibility
limitation, not a newly bounded guarantee. Ordinary backpressure also never
moves this provider counter.
A chain keyed reservation whose concrete name depends on a record must use
FiniteReservationCohort(ref=existing_keyed_ref, keys=(...)). Boot materializes
exactly those concrete slots; emit/fork verifies the payload-derived name is in
that finite set. Arbitrary new per-record slots are refused rather than
silently created. This restriction does not turn per-attempt reservations into
run-scoped exclusion.
Authored terminal effects — durable intent, not external exactly-once¶
RetrySpec(on_exhaustion=TerminalEffect(body=..., policy=...)) declares one typed
terminal effect for that resolved target. Its independent ExecutionPolicy must
name non-empty actor and queue; its own bounded retry, priority,
start_to_close, reservations and dependencies execute through the ordinary
worker path. The body receives (ctx, event: ExhaustionEvent) with the flow,
node/record identity, attempt, durable run_epoch, current record,
ErrorInfo, and the exact terminal reason.
On a winning ordinary retry/non-retryable/deadline/non-consuming-limit terminal,
the node terminal, claim-owned failed ledger, and one stable wf_outbox
intent commit atomically. The physical key contains flow + run incarnation +
node/record + effect identity. Outbox replay/idempotency materializes exactly one
ordinary effect job; a later operator cancel cannot erase an already committed
intent. Cancel before the winning disposition writes no intent. A failed parent
still suppresses ordinary children; only this explicit marked effect runs after
its own node's failed terminal. The effect 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. A missing registered body remains visibly unclaimed, never a
successful no-op.
The body can be invoked again after a worker/process crash. External calls and
arbitrary Python side effects are therefore at-least-once, not
exactly-once. Same-database domain closure completes once only when the effect
writes its idempotency marker (derived from the event key) and domain effects in
one application DB transaction. There is no generic exactly_once=True flag.
Direct in-process execution refuses this guarded feature; apply the capability,
run-epoch and intent PRE migrations and run the declaring cohorts with capable
fleet workers. The effect's own settlement fact is its job's terminal write
plus the application's idempotent domain closure — no root status, failed or
cancelled, proves that an effect exited.
Slot-free emit backpressure: saturation is a park, not a failure¶
When a whole page does not fit under the workflow's declared
max_in_flight, the emit raises taskq.workflows.EmitBackpressure — a
control signal, deliberately not an error and never a RuntimeError:
- it escapes BEFORE any child, edge, cursor, or application row is written (the whole page is written or none of it is);
- catch it only to add context and re-raise. It MUST escape the caller body:
swallowing it returns the body normally, the source finalizes
succeededwith its previous cursor, and the refused page is silently omitted from the run — no park, no retry, no error. It is deliberately outsideSnoozeandRetryAfterand never enters the failure ladder; backpressure_timeout_sat the emit boundary is diagnostic-only input — raw wait time, park counts, and non-consuming counts never fail healthy saturation.
The park transaction releases the claim and heartbeat, refunds the physical
attempt while preserving the durable logical ordinal, records the current
ledger claim as nonterminal awaited, and rests the source as a
non-claimable scheduled row whose scheduled_at holds the PARK INSTANT.
The marker (metadata.blocking_reason='backpressure' plus the typed
deferral and version-1 record) — never the timestamp — is the park's
identity: scheduled_at is not a due date, is never an admin next_fire,
and ordinary timers/holds/retries keep their own meaning.
Capacity is DERIVED, never counted: there is no persisted total, waiter
count, cached head, or cached minimum width to drift. Every fit decision
reads the run's real jobs rows at the moment it runs (the running
source's own row excluded), so vanilla reclaim, cancel, deadline, and
re-arm writers need no capacity bookkeeping. The run's max_in_flight
bounds the outstanding materialized rows plus whole admitted pages.
Wake is a threshold-created durable intent and an event-driven drain:
- each terminal/park event runs one indexed exact-marker probe; only when a parked waiter exists is capacity derived, and only when the oldest FITTING waiter newly fits is a durable promotion intent created (with its accelerator notification) in the same transaction;
- the drain promotes the oldest fitting real waiter under the run's
advisory lock and attaches a durable page-width RESERVATION, so a woken
source cannot be barged into another no-fit re-park. A replay may present
fewer records than its reservation; it may not present more — the excess
raises the public
taskq.workflows.EmitReservationExceededError: nothing is written, and the source terminalizes on the first violation (the deterministic grant-violation route — no retry budget spent) with its reservation removed in the same winning terminal statement. This is distinct from a genuinePageDivergedError— the idempotency arbiter's collision names a cursor re-sync remedy; a width mismatch never does; - the maintenance leader drains durable intents from committed capacity notifications, leadership assumption, LISTEN reconnect backfill, and a bounded pending-intent fallback at its maintenance interval. Durable rows, not notifications, are the authority — a lost or duplicate notification costs latency, never correctness;
- healthy source/promotion work is O(pages) with the event-side evaluation
law
E = T + X + K ≤ 2T + K; each observation is Θ(live + parked) — independent of accumulated terminal history — and candidate fit selection is Θ(parked) ≤ Θ(S) (one exact park is a state of one declared chain-source row). The parked-heavy tradeoff is real and disclosed: at very large parked populations the per-observation scan is not parked-constant time. Bounded notification-loss reconciliation (the maintenance-interval pending-intent selection and the exact-marker sweep) is an explicit amendment — crash/loss recovery is NOT claimed as pure O(pages).
Cancellation and failure while parked. A parked source has NO owner,
lease, heartbeat, or worker slot (a capacity reservation is not an execution
reservation). An operator run cancel terminalizes the parked row
cancelled and fences its exact ledger claim. A root that terminal-fails
after a genuine child failure exhausted its declared retry policy — while
an exact parked source still holds un-emitted work — is the one durable
proof that the run is provably not draining; the exact park represents
un-emitted resumable source work whether or not an emit_cursor key is
present (a first-page park with no committed cursor is the same resumable
obligation — the absent key means zero pages have committed, not that the
park is empty). The same failure transaction fences the parked source with
durable error_class='WorkflowNotDrainingError' (a string value, not an
importable class), the causal child/root ids on the record, and no
logical-attempt or ladder spend. Healthy saturation, elapsed time, and
nonterminal retries are never such proof.
Reading the surfaces. has_live prevents premature success before the
parked suffix; has_unresolved permits failed-root completion. The admin
surface shows a parked source as a scheduled row whose deferral line reads
the signal and deferred (backpressure) with the park time displayed as the
parked-at time — never as a next fire — and counts parks on the exact
marker, distinct from failure.