Repository navigation
Description
Problem
The deps seam hands every workflow body one static instance bound at declaration time — not a resolver that runs per worker/loop.
WorkflowApp(deps=...) binds an object once. The compile carries it. The worker-hosted execution door passes compiled.deps to every body invocation, for the life of the process, and nothing disposes it. The guide states the contract plainly: "The bound instance is THE instance … bound once at the door, never re-minted per claim. The runner never inspects it."
That is fine for a stateless client handle. It does not work for any dependency that must bind to the running event loop, which is the normal case for a downstream consumer's worker:
- an
asyncpgpool / connection factory (one pool per loop, and the loop does not exist at import/declaration time), - an HTTP client holding loop-local connection state,
- a session factory scoped to the loop's pool,
- anything with an
aclose()that must run during drain.
The vanilla actor path already has this: the worker builds a ProviderRegistry, and bodies resolve settings and resources at the claim boundary, scoped to the runtime loop, with teardown on shutdown. Workflow bodies get the opposite face — one object shared by every body, created before the loop, never released. The engine's own comment acknowledges the shape: "the compiled carries the app's bound instance (bound once at WorkflowApp(deps=…)) — the worker-hosted runner hands the same instance to every body invocation the vanilla door does."
So a consumer cannot migrate real bodies. Its options are:
- Make every dependency loop-agnostic. Impossible for a DB pool or a loop-bound client without wrapping them in another proxy.
- Build a process-global lazy proxy that re-binds per loop on first use. That is exactly the lifecycle hazard the vanilla DI seam was built to avoid: a global that mutates on first touch, whose teardown order is undefined, which is shared by co-resident workgroup children with separate loops, and which no test covers. Shipping that into production is "hope it works once".
- Do not migrate. Which is not a defect in the consumer.
The engine also forecloses the test escape hatch: InMemoryBackend has no workflow execution surface, so the only way to exercise a body in tests is a real FlowRunner against a real pool — the same object that a fleet worker holds. Any deps design must therefore be provable in both doors.
Evidence
src/taskq/workflows/_worker_execution.py:937-969—_runner_for(...)caches one runner per(schema, workflow, worker id, default_start_to_close)and constructs it withdeps=compiled.deps if isinstance(compiled, CompiledWorkflow) else None. The instance is read from the compiled definition, not resolved per invocation, and the cache is keyed on process-stable values (pool identity, worker id) so it survives for the worker's life. There is no teardown path fordeps.docs/guides/workflows.md:1210-1290§ "THE DEPS SEAM — the body's dependency door (the DI capability)":- the three input channels table, with deps as "the app's bound
Depsinstance — clients, store handles; the SAME instance at every node"; WorkflowApp(deps=EnrichDeps()) # ONE instance, bound ONCE at the door;- "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). The runner never inspects it.";
- the E12 contract: the binding is validated once against the body's annotation, at build.
- the three input channels table, with deps as "the app's bound
docs/guides/workflows.md:1290-1295— "The InMemoryBackend has NO workflow execution surface (the named landmine): the seam's test face is the realFlowRunneragainst the pg fixtures."- No lifecycle hook exists anywhere in the signature: the binding is a plain object, and
FlowRunner(..., deps=...)is described as "the direct doors — the runner's binding wins", i.e. still a value, never a factory.
The asymmetry is the point: the same engine that resolves vanilla actor dependencies per claim, per loop, with disposal, offers workflow bodies a single compile-time constant.
Required
A worker-scoped deps factory / provider bridge, additive to the existing static contract.
- A factory face.
WorkflowApp(deps_factory=...)(or an equivalent provider protocol — a callable returning a deps instance, optionally async) that is invoked lazily, after the runtime loop exists, rather than at declaration/compile time. - Worker-and-loop scope. One instance per worker process per loop, created on first use, reused within that worker's lifetime, and never shared across loops. Each workgroup child (separate process, separate loop, separate pool) must resolve its own instance independently.
- Lifecycle. An async
setup/teardown(or an async-context-manager product) with a documented call order relative to the worker's pool creation and its drain: setup before the first body, teardown exactly once on graceful shutdown, on reload, and on a crash-recovery path where it can run at all. - Preserve the static contract.
deps=keeps working unchanged for stateless bindings. A body declaring a deps type is satisfied by either face, and the E12 arity/typing check runs against the factory's product type at build time (so the error still surfaces atapp.get(...), not at the first claim). - Make it observable. Expose the resolution (a counter/timer or a debug log naming the worker and the generation) so an operator can prove "one instance per worker" rather than infer it.
- Invalidate on reload. The worker-hosted runner cache must rebuild when the factory's generation changes (a settings reload, a credential rotation), not silently keep the old product.
Acceptance criteria
Fleet-level, with real workers and a real pool.
- Binds to the running loop. A body declaring a deps type whose factory opens a loop-bound resource asserts
resource.loop is asyncio.get_running_loop():- in a fleet-claimed worker (the real execution door), and
- in an in-process
FlowRunner.drive(...)against the pg fixtures.
Both must pass. A single passing door is not acceptance.
- One per worker, reused. For N bodies × M runs on one worker, the factory is invoked exactly once and the same instance is handed to every body — counted, asserted to 1. Across two workers, exactly two invocations and two distinct instances.
- Disposed on shutdown. On graceful shutdown and on a rolling reload, teardown runs exactly once per worker and the resource is closed before the pool closes. A test drives a drain and asserts zero
RuntimeError: Event loop is closed/attached to a different loop/pool is closederrors, and asserts the teardown counter. - Workgroup children are independent. Two children in one process (separate loops, separate pools) each get their own instance; a test asserts the instances differ and that no object identity crosses. A child that starts later must not inherit the earlier child's instance.
- No cross-loop leakage under concurrency. With
max_concurrency > 1on a sync/workflow cohort, an instance is never used from a thread/loop it was not created on; stress test with two concurrent body families and assert no loop-mismatch errors. - Static contract unchanged. A
deps=instance still reaches every body unchanged; a factory whose product fails the body's annotation is still refused at build with both type names; a true arity mismatch stays the existing error. - Reload invalidates. Change the factory's generation (a settings mutation the test controls), trigger the reload path, and assert the next body sees a new instance and the old one's teardown ran.
- Docs. The deps seam section states the two faces, which one to choose, the exact lifecycle order, and the scope guarantee (per worker, per loop) — replacing the current single-instance claim for the factory case.
Impact
Every consumer whose bodies need a pool, an HTTP client, or any loop-scoped resource — which is essentially every consumer migrating real work rather than a demo — must either rewrite its dependency construction as loop-agnostic (often impossible) or build a process-global mutable proxy with undefined teardown beside the engine's DI. The second option is the precise failure mode the engine's own worker DI avoids: a per-loop pool behind a global, re-bound on first touch, shared by co-resident children, and covered by no test.
It also blocks the development story: because InMemoryBackend has no execution surface, a body must be exercised through the real runner, so the deps resolution must be correct in both the dev door and the worker door. Today it is correct in neither for a loop-bound resource — it is a value, and the value was created before the loop existed.
Related: #716 (gating execution-policy surface); #720 (cancellation state/origin) — the same body-boundary gap, a different fact.
Environment
- taskq-py @
99e9a7d0(feat(workflows): adoption hardening, feat(workflows): adoption hardening #715) - Python 3.12+, PostgreSQL 18
- A workgroup with several child processes (the common deployment shape) is what makes the per-loop scope load-bearing
Activity
feat(workflows): add worker-scoped deps_factory for loop-bound depend…