Repository navigation
fix(workflows): a map on a join no longer gets a second join row from the outbox (#745) - #751
Conversation
… the outbox (#745) When a map_source sat directly on another map's or route's join, the outer fork listed the nested map's join as one of its join's consumers. The outer join's fire then put that binding on the outbox, and the drain inserted a row for the nested join under wf:<step_key>, while the nested fork inserted its own row under its parent-scoped key. The keys differ, so nothing deduplicated them. If the fork landed first, the drain's row sat pending on a finished run (flows list read "pending root=succeeded") or ran the join a second time. If the drain landed first, its row was claimable with no deps before the fork existed; claimed early, it succeeded empty and the run either wedged running or computed its result from an empty join. The fix skips map_join nodes when _map_fork and _route_fork build the join's consumer bindings, the same condition the static insert already uses. A nested map's join now has one writer, its own source's fork. Static consumers keep their bindings, so the fork's consumer edges and the drain belt are unchanged. The adoption branch in insert_fork stays for runs whose outer fork ran on the old code; its comment now says what it can still find and that it has no status guard. Tests: test_wf_map_on_join_pins.py pins the three drain orderings over map, route, mixed (the outer join also feeds a static step) and depth-3 shapes, plus the invariant itself (no join row's consumers and no outbox row name a map_join node). The keyed admission pin test_an_adopted_join_carries_the_stamp_and_feeds_depth_3 reached adoption only because the drain pre-created the nested join, so it is reconciled to the new contract: it now writes the old-code binding on src.join itself, and asserts the adoption positively (one row, keyed wf:src.join.join). It is the in-flight compatibility pin. Docs: a seam-audit-matrix row for the fork/drain consumer-binding seam, and an upgrading.md entry with two read-only queries that find the rows in-flight runs can still leave behind, with their remedies. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
upgrading.md: the closing sentence of the #745 note said a second <join>.join row that ran while the nested fork's children were live always ends with the right result and needs no repair. That holds only when the nested map is the last fan-out. With a map on the nested map's join (three levels), the second row forks that map again with no items, the step after it runs on the empty join (result 0 of 10 in the probe), and the real nested join's fork then fails on a duplicate wf_edge row, so the run stays running. Neither query listed it. The note now scopes the sentence, adds a third read-only query for these runs, explains why an adopted row reads succeeded with deps_pending > 0, and says what a failed or cancelled root means for the second query (a run stopped with taskq flows cancel stays listed). All three queries were run against the red state, the depth-2 control, a healthy depth-3 run, the after-terminal stray (before and after taskq job cancel) and both face-2 shapes. _runner.py: the _map_fork docstring still said the join's consumers are all of the wiring's downstream nodes; a nested map's join is excluded. test_wf_map_on_join_pins.py: the late-drain arms now assert tick() called the muted drain, so a hoisted drain_outbox import cannot turn the mute into a no-op and silently run the in-process order. An inert mute turns all six late-drain cases red on this guard. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
) The third query added in b0d22a2 also listed a healthy run: when the drain's row was adopted while still pending (the in-process order), the nested join has one row, keyed wf:<step_key>, succeeded with deps_pending 0, and its own map join exists, so every predicate matched and the note told the operator to re-run a run with the right result. The query now requires a second row for the same step in the run (the fork's own), which is what the three-level face leaves behind. The deps_pending filter is dropped; an adopted row never has a sibling. Re-checked on the edited SQL: the three-level red state is listed (and stays listed after taskq flows cancel); a normally adopted run at two and three levels, the two-level while-live run, a healthy three-level run, the after-terminal stray (before and after taskq job cancel) and both early-claim shapes are not. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
The review is done. The issues it confirmed are fixed on this branch, CI is green, and it's ready to merge. |
clinzy
left a comment
There was a problem hiding this comment.
Multi-model review (9 of 9 reviewers returned). No Critical or Important findings. Everything below is Minor (not blocking).
The fix looks right to me. I checked that _map_fork always builds its JoinSpec, even when the body returns no list, so dropping the outbox binding leaves the nested fork as the one writer in every case. That matches how _insert_static_nodes already treats top-level map joins. Lint and pyright are clean, and the whole tests/test_wf_*.py family plus the probe and attack files ran 1398 passed against real Postgres.
Minor, all inline:
- The
map_joinfilter is copied into 3 places (worth a shared helper). - The
_map_forkdocstring still says it returnsNone. - The adoption probe has no status guard. This is pre-existing; a follow-up.
- Uneven test coverage across the drain orderings and shapes.
- The second adoption order has no test.
- Cost, coverage and scope notes on the
upgrading.mdrecovery queries.
| for downstream in sorted(self.compiled.nodes) | ||
| if join_key in self.compiled.nodes[downstream].parents | ||
| # a map on this join: its join is the nested fork's own row (#745) | ||
| and self.compiled.nodes[downstream].kind != "map_join" |
There was a problem hiding this comment.
Minor (nice to have, not blocking): The kind != "map_join" rule now lives in three places: _insert_static_nodes (L621), here, and _route_fork (L2741). The roughly 30-line binding generator around it is duplicated between the two forks too. A future fork kind that misses the filter brings back the double writer, and test_no_binding_names_a_nested_join only guards the two forks that exist today. A small shared helper such as _join_consumer_bindings(join_key) would keep the rule in one place. Five of the nine reviewers raised this independently.
Related: _map_fork's docstring got the "except a nested map's join (#745)" note, but _route_fork's docstring didn't.
There was a problem hiding this comment.
Closed in 5574dabe4: centralized all four sites onto NodeDecl.is_fork_spawned_join and mirrored _map_fork's consumer-exclusion sentence onto _route_fork's docstring.
| outbox carries the consumer bindings — the cascade | ||
| fix). ``None`` when the body returned no list (the map over | ||
| fix), except a nested map's join, which its own fork writes | ||
| (#745). ``None`` when the body returned no list (the map over |
There was a problem hiding this comment.
Minor (nice to have, not blocking): This docstring still says "None when the body returned no list", but _map_fork has no early return. A non-list value becomes items = [], and the ForkSpec with its JoinSpec is built unconditionally, so the result is a zero-child join that fires empty. That behavior is also what makes this fix safe: the nested fork always writes its own join, even for an empty map. Worth saying that instead of None, which is _route_fork's shape.
| # in-flight run), or one an engine-level caller inserted itself | ||
| # through insert_node. The fork adopts it: add the items' weight to | ||
| # the counter + stamp the consumers, never a second insert. The probe | ||
| # has no status guard: adopting a row that already ran leaves the |
There was a problem hiding this comment.
Minor (nice to have, not blocking): (follow-up, pre-existing) The new comment is accurate and honest about the problem, but the silent failure it describes is still reachable. An in-flight run with an old binding can adopt a row that has already run, and the only detection is the manual queries in upgrading.md. Selecting status in the probe and logging a structured warning, or raising a typed error, when the adopted row isn't pending would make that case fail loudly instead of finishing with an empty join. This doesn't need to block this PR.
There was a problem hiding this comment.
Closed in 44c23f8c7 + b86e09e14: insert_fork's probe now orders pending rows first, guards the adoption UPDATE with AND status = 'pending' RETURNING id, logs wf-fork-join-adoption-skipped at warning when a non-pending row is skipped, and falls through to the fork's insert path.
| _assert_one_writer(await _flow_rows(wf_conn, wf_schema, flow_id), nested) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("shape", ["map", "route"]) |
There was a problem hiding this comment.
Minor (nice to have, not blocking): The ordering arms are covered unevenly:
- The early-drain arm here, and the
while_livearm of the late-drain test, are parametrized overmap/routeonly. mixed, where the join also feeds a static step, so the filtered binding list isn't empty, anddepth3, the caseupgrading.mdcalls out as producing wrong results, only run in the terminal and in-process orderings.- No shape covers an empty outer fan-out. The born-zero fire is a separate path that reads the same
consumers, and it's the path most likely to drain before the fork in production.
Extending the parametrize lists to SHAPES, plus an empty shape, would cover all of these.
| @@ -918,11 +929,48 @@ def w() -> Promise[object]: | |||
| runner = FlowRunner(app.get("wf_keyed_adopted_join"), wf_pool, wf_schema) | |||
There was a problem hiding this comment.
Minor (nice to have, not blocking): This compat pin covers one adoption order: the row the drain created is adopted while it's still pending. The more harmful in-flight order is the one the new _fork.py comment and query 2 describe: the drained row is claimed and finishes before the nested fork adopts it. That order has no pin. One case that lets the drained join run first, then asserts succeeded with deps_pending > 0 (the shape query 2 looks for), would keep the docs' SQL tied to real behavior.
There was a problem hiding this comment.
Closed in 44c23f8c7: pinned the already-run drained join order in tests/test_wf_join_adoption_pins.py::test_insert_fork_skips_an_already_run_nested_join_row_instead_of_adopting_it (asserting the fork writes its own join row, the run completes with the true result, and wf-fork-join-adoption-skipped is logged).
| adopted by it: | ||
|
|
||
| ```sql | ||
| SELECT n.id, n.metadata->>'flow_id' AS run_id, n.step_key, n.deps_pending, |
There was a problem hiding this comment.
Minor (nice to have, not blocking): A few notes on the recovery queries. They're read-only, so this is about operators getting the right answer.
- Cost: all three scan
jobson a leading-wildcardLIKE. Query 3'sEXISTSlegs comparemetadata->>'flow_id'as text, so they can't usejobs_wf_flow_nodes_idx, which is on the::uuidcast. Casting both sides to uuid and adding a line saying to run these on a replica or off-peak would help on a large table. - Coverage: an empty outer map that drains, gets claimed early and is then adopted with
+ 0stayssucceededwithdeps_pending = 0, so this query misses it. I reached that by reading the code; I didn't run it. Also, query 3 can't see an adopted stray because only one row exists. Query 2 is what catches that, and one sentence saying so would help readers. - Scope: "runs whose outer fork ran on an earlier release" undersells the risk at depth 3 and deeper. An intermediate fork that runs on an old worker brings the old binding back at that level.
clinzy
left a comment
There was a problem hiding this comment.
Final call: Ready to merge.
Reviewer verdicts: 9 Ready to merge, 0 With fixes, 0 Blocked (9 of 9 returned a review).
No Critical or Important findings, and 1398 workflow tests passed. The Minor items in my review are optional follow-ups: the duplicated map_join filter, the stale _map_fork docstring, a status guard on the adoption probe, test-shape coverage, and notes on the recovery queries.
clinzy
left a comment
There was a problem hiding this comment.
Approved. 9 of 9 reviewers voted Ready to merge, and 1398 workflow tests passed. The Minor items in my review are optional follow-ups.
There was a problem hiding this comment.
Reviewed and exercised this against real Postgres (both driver doors including dispatch_batch + execute_flow_job, single-predicate and both-predicate mutations in a scratch checkout, all three upgrading.md detectors + remedies, and failure/empty-corpus topologies).
The two-line fix itself is sound: and self.compiled.nodes[downstream].kind != "map_join" in _map_fork and _route_fork is the exact discriminator matching _insert_static_nodes, both lines are essential (reverting _route_fork alone reds 5 tests), and a zero-consumer join executes cleanly through both the in-process driver and the fleet claim seat.
Inline comments below cover 1 Critical + 7 Warnings around the runbook remedy, the retained adoption branch, nested-map re-derive precedence, and pins/contracts:
- Critical — Detector-1 remedy permanently marks a successful run
cancelled(C1):taskq job cancel <id>on the surplus row flips every rows-derived surface (taskq flows list,taskq flows status, admin run page) tocancelledpermanently while the root stayssucceeded(and fails the always-on G7 status-truth invariant), with no verb to reconcile a terminal root. Because the surplus row is a pure orphan (0wf_edge, 0wf_step_ledger), we should state that cost explicitly and offer the guarded orphan-row removal SQL that restorescomplete+ G7. - Unguarded adoption probe in
insert_fork(W1): the probe right under the rewritten comment has noAND status = 'pending'guard, so during a rolling deploy a drain-minted row that already ran gets adopted,DECREMENT_SQLrefuses every child's decrement, and the run wedgesrunningforever (confirmed red live). AddingAND status = 'pending' ORDER BY id LIMIT 1+ a warning log on skipped non-pending rows preserves pending adoption byte-for-byte while closing the wedge. - Pre-existing
REDERIVE_SWEEP_SQLprecedence stampsorphan_parenton nested-map consumers (W2): on nested maps the post-map consumer sitspending, deps_pending=1, blocking_reason='join'with 0wf_edgerows while the outer map runs, soblockedoverwritesblocking_reasontoorphan_parenton both clean runs (surviving onsucceededrows!) and dead runs (blockingflow_fencedfrom stampingflow_dead). Confirmed pre-existing onorigin/main, made deterministic by nested maps. - In-process pin survives full revert of the fix (W3):
test_the_in_process_drive_keeps_one_nested_join_rowpasses 4/4 with both predicates deleted because adoption collapses the surplus row; asserting the fork'sidempotency_key(wf:{flow}:{parent}:...) makes it deletion-sensitive. - Missing pin for the 3
upgrading.mddetectors & remedy (W4): no test currently pins the three SQL queries against drift. NodeDecl.kinddomain drift,_route_forkdocstring, and_consumer_bindingcontract (W5, W6, W7):NodeDecl.kindcomment lists fictionalmap_sourceand omitschain_source/loopwhile 4 sites duplicatekind != 'map_join'(W5);_route_forkdocstring lacks the exclusion sentence added to_map_fork(W6); and_types.py::_consumer_bindingclaims malformed entries degrade toNonewith a suppression citing non-existent asserts while actually raisingKeyError/ValueError(W7).
I'll follow up with fixes on the branch (merging origin/main cleanly) to close C1 and W1–W7.
| AND (r.id IS NULL OR r.status NOT IN ('pending', 'scheduled', 'running')); | ||
| ``` | ||
|
|
||
| Cancel each one with `taskq job cancel <id>`. The row goes straight to |
There was a problem hiding this comment.
C1 (Critical) & W4 — taskq job cancel <id> permanently misreports a successful run as cancelled (and no test pins the 3 detectors).
derive_workflow_status falls to rule 5 (any cancelled -> cancelled) as soon as the surplus row is cancelled, and WORKFLOW_ROOT_MAINTAIN_SQL never re-derives a succeeded root. Every rows-derived surface (taskq flows list, taskq flows status, admin run page) permanently reports a successful run as cancelled and the estate's G7 status-truth check fails (assert 'cancelled' == 'complete').
State that permanent status cost explicitly here, offer the guarded orphan-row DELETE (requiring zero wf_edge rows as parent/child and zero wf_step_ledger rows, which restores complete and G7), and pin all three detectors + remedy in a docs-contract test (W4).
There was a problem hiding this comment.
Fixed in 4d4cd47b5 + b86e09e14:
- C1:
docs/guides/upgrading.mdnow states the permanentcancelledstatus cost oftaskq job cancel <id>, provides the guarded orphan-rowDELETE(includingn.metadata ? 'flow_id', finished/pruned root guard,wf_edgechild/parent check, andwf_step_ledgercheck), and documents thewf-fork-join-adoption-skippedlog event. - W4:
tests/test_upgrading_guide_map_on_join_docs_contract.pyextracts all 4 SQL fences verbatim fromupgrading.mdand pins Detector 1–3, the guardedDELETErestoringcomplete+ G7, healthy runs returning[]/DELETE 0, and liverunningflows' pending drain rows staying untouched (DELETE 0) and completingcomplete.
| # in-flight run), or one an engine-level caller inserted itself | ||
| # through insert_node. The fork adopts it: add the items' weight to | ||
| # the counter + stamp the consumers, never a second insert. The probe | ||
| # has no status guard: adopting a row that already ran leaves the |
There was a problem hiding this comment.
W1 — Add AND status = 'pending' ORDER BY id LIMIT 1 (plus logging) to the retained adoption probe.
Right under this comment, SELECT id, deps_pending FROM ... WHERE step_key = $1 AND (metadata->>'flow_id')::uuid = $2 adopts a drain-minted nested join even if it already ran (succeeded/running), causing DECREMENT_SQL to refuse every child's decrement and wedging the run running forever (confirmed red live: drive_verdict='max_ticks', adopted_nested_join=[{'status': 'succeeded', 'deps_pending': 4}]).
Guarding with AND status = 'pending' ORDER BY id LIMIT 1 preserves pending adoption byte-for-byte, lets the fork take the insert path if a stale row already ran, and emitting a warning log when a non-pending row is skipped makes the residue observable.
There was a problem hiding this comment.
Fixed in 44c23f8c7 + b86e09e14: insert_fork's adoption probe orders ORDER BY (status = 'pending') DESC, id LIMIT 1, adopts only when status == 'pending' with a guarded UPDATE ... WHERE id = $4 AND status = 'pending' RETURNING id (closing the concurrent-claim TOCTOU), logs wf-fork-join-adoption-skipped at warning (and wf-fork-join-adopted at debug only after landing), and falls through to the fork's insert path on skipped rows. Pinned in tests/test_wf_join_adoption_pins.py.
| for downstream in sorted(self.compiled.nodes) | ||
| if join_key in self.compiled.nodes[downstream].parents | ||
| # a map on this join: its join is the nested fork's own row (#745) | ||
| and self.compiled.nodes[downstream].kind != "map_join" |
There was a problem hiding this comment.
W2, W5 & W7 — Three surrounding mechanism contracts now relied on here:
- W2 (
_sql_sweep.py::REDERIVE_SWEEP_SQL): pre-existing precedence bug made deterministic by nested maps — a post-map consumer sitspending, deps_pending=1, blocking_reason='join'with 0wf_edgerows while the outer map runs, soblockedstamps itorphan_parenton both clean runs (surviving onsucceededrows!) and dead runs (blockingflow_fencedfrom stampingflow_dead). - W5 (
_graph.py::NodeDecl.kind): the comment lists fictionalmap_sourceand omitschain_source/loop, while_insert_static_nodes,_map_fork, and_route_forkeach spellkind ==/!= 'map_join'independently — fix the declared domain and centralize on one predicate onNodeDecl. - W7 (
_types.py::_consumer_binding/_consumer_bindings): the docstring claims malformed entries degrade toNoneand line 806's# Why:cites non-existent asserts, while missing required keys / malformed sub-docs actually raiseKeyError/ValueError.
There was a problem hiding this comment.
Fixed in af73808f0, 44c23f8c7, 5574dabe4, and b86e09e14:
- W2:
REDERIVE_SWEEP_SQLinsrc/taskq/workflows/_sql_sweep.pynow yields terminal-flow rows fromblockedtoflow_fenced(stamping truthfulflow_dead/failed_parent) and defersedge_count = 0on live flows while another live non-root row exists, keeping one-resolution-per-row mutual exclusion intact. Pinned intests/test_wf_map_on_join_failure_pins.py(all 5 tests + 1,400 wf tests green). - W5: corrected
NodeDecl.kindcomment to the true 5 values (step,gather,map_join,chain_source,loop) and centralized all 4 static-skip/consumer-exclusion sites ontoNodeDecl.is_fork_spawned_join(pinned intests/test_wf_consumer_binding_scope_pins.py). - W7: updated
src/taskq/workflows/_types.pywith_required_str(removing 3 pyright ignores), accurate validation-vs-degradation docstring, and an honest# Why:comment (pinned intests/test_wf_join_adoption_pins.py).
| for downstream in sorted(self.compiled.nodes) | ||
| if join_key in self.compiled.nodes[downstream].parents | ||
| # a map on this join: its join is the nested fork's own row (#745) | ||
| and self.compiled.nodes[downstream].kind != "map_join" |
There was a problem hiding this comment.
W6 — Mirror _map_fork's docstring update on _route_fork.
This line is required (reverting only :2741 reds 5 tests including media.join binding ['media.join.join', 'sib']), yet _route_fork's docstring still says nothing about excluding nested map_join consumers.
There was a problem hiding this comment.
Fixed in 5574dabe4: _route_fork's docstring now mirrors _map_fork's consumer-exclusion contract.
|
|
||
|
|
||
| @pytest.mark.parametrize("shape", SHAPES) | ||
| async def test_the_in_process_drive_keeps_one_nested_join_row( |
There was a problem hiding this comment.
W3 — This pin survives deleting both fix lines.
In the in-process ordering, the drain mints wf:<nested> and the next tick's fork adopts it, so _assert_one_writer still sees 1 succeeded row (4 passed with both predicates reverted). Asserting the persisted writer discriminator (idempotency_key starts with wf:{flow}:{parent}:) makes all 4 arms go red when the fix is reverted.
There was a problem hiding this comment.
Fixed in 5574dabe4: _assert_one_writer now asserts the exact fork idempotency_key (wf:{flow}:{parent}:{join}) across every arm (mutation-verified: reverting both predicates fails all 4 arms of test_the_in_process_drive_keeps_one_nested_join_row). Also adopted the fleet claim-seat pin in tests/test_wf_map_on_join_fleet_door.py.
…truth (#745) The re-derive sweep's blocked arm stamped `orphan_parent` on two states that are not wiring faults, and the stamp then locked the truthful arm out (the flow_fenced arm keys on the `join` sentinel the stamp overwrote): * a DEAD flow's reserved consumer (pending, counter reserved, zero edges) whose nested fork never ran — the root reaches `failed` and the consumer is stamped `orphan_parent`, sending an operator after a misnamed child that does not exist. `orphan_parent` is now a live-flow diagnosis: a terminal flow's rows belong to `flow_fenced` (`flow_dead` / `failed_parent`). * a LIVE flow's static consumer of a fork-spawned join, which is born `pending, deps_pending = 1, edge_count = 0` while the nested fork that writes its edge has not run yet. The edge-less leg now DEFERS while any other live non-root row exists in the flow (that row can still fork and write the edge), and stamps only once the candidate is the flow's last live row — nothing is left to release it. One resolution per row per pass is preserved: `blocked` is flow-live-only and `flow_fenced` keeps its exclusions, so no row is written by two arms of one statement snapshot. Pins: `tests/test_wf_map_on_join_failure_pins.py` (a clean nested map leaves no wiring-fault record; a dead flow's consumer carries a truthful reason; plus the empty-corpus composition, the route-on-join refusal and the flat gather scope guard).
The fork's adoption probe read a nested join row whatever its state. Since #745 no binding names a `map_join`, so the only row it can still find was minted by an outbox drain from a pre-#745 stamp (an in-flight run) — and a worker can claim and finish that row before the outer join's own fork probes. Adopting a finished row leaves its children's decrements refused (they are gated on `jobs.status = 'pending'`), so the counter never drains, the nested join never fires, and the run rests `running` with every child succeeded. - The probe now reads only a PENDING row, ordered `(status = 'pending') DESC, id LIMIT 1` so a pre-fix multi-row residue resolves to the lowest pending row deterministically. - A non-pending row is left untouched: the fork takes its normal insert path and completes with the true children. The refusal is logged as `wf-fork-join-adoption-skipped` — a never-adopted residue keeps `deps_pending = 0`, so it is invisible to all three upgrade detectors on a two-level shape and the log is the only record. - The supported pending adoption logs `wf-fork-join-adopted`. - The comment above the probe describes the guarded behaviour. Also make the cross-release `consumers` parser's stated contract true: the three required keys are read directly (`KeyError` when missing, `ValueError` when wrong-typed) and the structured sub-docs validate; only `start_to_close_s` degrades to `None`. The docstring and the `# Why:` suppression claimed a malformed entry degrades — there were no asserts, and the leader's re-derive arm calls this parse inside the sweep. Pins: tests/test_wf_join_adoption_pins.py
#745) `taskq job cancel <id>` on a detector-1 row is not a repair: the cancelled row defeats `derive_workflow_status`'s all-terminal rule forever, and the maintenance leg only re-derives a `running` root, so every rows-derived surface (`taskq flows list`, the headline of `taskq flows status`, the admin run page) reports a successful run as `cancelled` permanently, and the status-truth check keeps flagging it. Say that beside the remedy, and give the guarded removal that actually restores `complete`: the row must be `pending`, keyed with the drain's bare `wf:<step>`, end in `.join.join`, and have no `wf_edge` row as child or parent and no `wf_step_ledger` row — so a real join row, which has its source's edge and a claim history, can never match. Pin the section as an executable contract: the three detectors are extracted from the document (not retyped) and driven against the real pre-fix state — detector 1 selects exactly the surplus row and 2 and 3 do not also claim it — then the documented removal deletes exactly that row and the run's rows derive `complete` under its `succeeded` root (the always-on G7 truth). The second pin drives a healthy post-fix run: no detector selects it and the removal has nothing to delete. Also record the fourth shape the fork's new status guard creates: a skipped already-run row is debris, not a wrong answer, and only the `wf-fork-join-adoption-skipped` log names it.
`NodeDecl.kind` declared a domain that does not exist in production: `"map_source"` is never assigned (`map_item is not None` is the map-source marker), and two values the compile does assign (`chain_source`, `loop`) were missing. Correct the comment to the five real values and give the static-insert-versus-fork-spawned question a single named predicate, `NodeDecl.is_fork_spawned_join`, used by both static node loops and both fork builders — so the static skip and the consumer exclusion cannot drift apart. Document `_route_fork`'s consumer exclusion as `_map_fork` already does: the two comprehensions are twins, and reverting only the route side reds five pins. Sharpen `test_the_in_process_drive_keeps_one_nested_join_row` with the writer identity: the row's `idempotency_key` is the fork's parent-scoped shape, never the drain's bare one. That ordering was green under the defect because the fork adopted the drain's row, and now all four shape arms die when the exclusion is reverted. Pins: tests/test_wf_consumer_binding_scope_pins.py — the fan-in shapes the exclusion must keep (a route join's static sibling, a gather over a map's join, a gather that is also a map source), the five-value kind domain, and the `.join`-suffix naming law the operator-facing upgrade detectors read.
#745) The in-process pins control the drain's placement inside one event loop; this pin drives the same shape through the production claim seat (`dispatch_batch` + `execute_flow_job`) with the leader's belt (`sweep_join_rederive` + `drain_outbox`). It proves the claim leg the fix leans on: a zero-consumer join row still passes the dispatch fence (neither claim fence reads `blocking_reason`), the run terminalises with the right result, and both join rows carry their own source's fork key — never the drain's bare one.
…live runs (#745) Review follow-up on the upgrade guide's remedy and the fork's adoption write: - The guarded `DELETE` now also requires the flow link and the absence of a LIVE root (`pending`/`scheduled`/`running`): a pending drain-minted row on a running flow — the row a worker may be about to claim and a nested fork may still adopt — is never repair material. Only a finished or pruned run's row is. The prose names the guard, and a pin drives the real live-run state (a drain row minted while the outer join has fired and the root is still running): the extracted statement returns `DELETE 0`, the row survives, and the run then finishes on it through the supported adoption path. - The adoption `UPDATE` repeats the probe's status leg inside the write (`AND status = 'pending' RETURNING id`). A worker that claims the pending row between the SELECT and the UPDATE now loses the adoption instead of wedging the run: the fork logs `wf-fork-join-adoption-skipped` with the re-read status and falls through to its own insert path. - The failure pins' docstrings no longer claim `_route_fork`'s consumer filter is unreachable: a join cannot be a route's SOURCE, while a `map_source` on a route's join is exactly the shape that exercises that filter — which the success pins' `route` arm drives. The stale `parent_node.kind == "map_join"` reference now names `is_fork_spawned_join`. - Docs-contract test cleanups: drop an unused model, an unused fixture and two redundant `search_path` resets; the "invisible to the detectors" sentence now states the real reason (a never-adopted row keeps `deps_pending = 0`).
What changed
When a
map_sourcesat directly on another map's or route's join, the outer fork listed the nested map's join (<outer>.join.join, compiled kindmap_join) as one of its join's consumers. The outer join's fire put that binding on the outbox, anddrain_outboxinserted a row for the nested join underwf:<step_key>. The nested fork inserts its own row under the parent-scoped keywf:{flow}:<outer>.join:<outer>.join.join(_fork.py#L191), so the drain'sON CONFLICTnever matched and the step got two rows.Which writer landed first decided what went wrong. If the fork won, the drain's row sat
pendingon a finished run (taskq flows listshowedpending root=succeeded, the run in issue 745), or a worker claimed it while the nested children were still running and the join work ran twice under one step-ledger identity. If the drain won, its row was claimable withdeps_pending = 0before the fork existed. Claimed early, it succeeded empty, the fork then adopted the terminal row, and the run either wedgedrunningforever or the step after the nested map ran on an empty join and the run succeeded with a wrong result.The fix is one predicate in the binding generators of
_map_forkand_route_fork: skip a downstream node whose kind ismap_join._insert_static_nodesalready skips the same nodes. A nested map's join now has one writer, its own source's fork. Static consumers keep their bindings, so the fork's consumer edges and the drain's insert for static rows stay as they were. There's no SQL change and no migration.The adoption branch in
insert_forkstays, because in-flight runs whose outer fork ran on old code still carry the old binding. Only its comment changed. The old one saidcreate_flowpre-inserts the join, which is stale sincecreate_flowskips map joins. The new one says what the probe can still find (a row the drain minted from a binding stamped before this fix, or one an engine-level caller inserted throughinsert_node) and that the probe has no status guard.Docs: a row in
seam-audit-matrix.mdfor the fork/drain consumer-binding seam, and an entry under silent behaviour changes inupgrading.md. It has three read-only queries for what in-flight runs can still leave behind. The first finds straypendingrows on finished or pruned runs (remedytaskq job cancel). The second finds adopted rows that ran early,succeededwithdeps_pending > 0(remedytaskq flows cancelif the root isrunning, re-run if it issucceeded). The third covers three or more levels of nesting, where a second row ran while the nested children were live (stop the run if it's stillrunning, then re-run it).Closes #745
Blast-radius audit (required for src changes)
_map_forkand_route_forkpass toJoinSpec(consumers=...)(L2532, L2758). They become the join row'smetadata.consumers, which the fire turns into outbox rows fordrain_outbox.insert_forkgot a comment edit only._map_forkis called only from_finalize_success, which both the in-process_run_nodeand the worker doorrun_fleet_claimed_stepreach._route_forkis called only from the route body path and handed to_finalize_successasprebuilt_route_fork. Those two are the onlyJoinSpec(sites in src, andinsert_fork(has one caller,engine.py#L418. The otherConsumerBinding(producers are terminal effects (_effects.py#L128, ownwf_effect:key) and the decoder (_types.py#L681), and neither builds amap_joinbinding. The join rederive reads the samemetadata.consumers, so it picks up the fix. A route's join is alsokind="map_join"(_graph.py#L1769), andNodeDecl.kindhas no other join kind (_graph.py#L711). A route can't sit on a join, since the build refuses a source with no body (_graph.py#L1714-L1717), so the nested fan-out is always a map.tests/test_wf_map_on_join_pins.pyruns four shapes:map,route,mixed(the outer join also feeds a static stepsib) anddepth3(a map on a map on a map's join).test_a_late_drain_never_mints_a_second_nested_join_rowmutes the drain until the run is terminal (all shapes) or until the nested fork has landed (map,route).test_an_early_drain_never_creates_the_nested_join_before_its_forkchecks that no nested row exists between the outer join's fire and its fork.test_no_binding_names_a_nested_joinpins the invariant directly, whatever the drain timing: no join row's consumers and no outbox row name amap_joinnode, and formixedthe outer join still bindssib, which keeps its onewf:sibrow.test_the_in_process_drive_keeps_one_nested_join_rowis the plain-drive control. The adoption branch is covered by the reconciled keyed admission pin described below, and the suite's G7 status check runs at teardown for every wf test.Proof
12 failed, 4 passed, 4 errors. The 4 passes are the plain-drive controls, and the 4 errors are G7 teardown failures where the root reportssucceededwhile the rows reconstructpending. With the fix, the pins file plustests/test_wf_keyed_admission_pins.py:35 passed._map_forkpredicate:8 failed, 8 passed, 3 errors. Everymap,mixedanddepth3case of the drain and invariant tests goes red (the plain-drive control is green on the base tree too). Removing only the_route_forkpredicate:4 failed, 12 passed, 2 errors, and everyroutecase of those tests goes red. One of the 2 errors was a docker read timeout at session teardown. Writing[]in place of the old binding in the reconciled keyed pin:1 failed, on its adoption assertion (L1002). After restoring all three:35 passed.test_an_adopted_join_carries_the_stamp_and_feeds_depth_3. Its old contract relied on the outer fork's binding forsrc.join.join, so the drain pre-created that row and the depth-2 fork adopted it. The test checked that the adopted row existed and carried the join-wait marker and the run's cohort. After the fix that binding is gone, and the test would have passed through the insert path without ever reaching adoption. It now writes the old-code binding onsrc.joinitself, built with_consumer_binding_docfrom the compiled decl, after the depth-1 fork and while bothsrc.itemchildren are still pending (asserted). It then asserts exactly onesrc.join.joinrow keyedwf:src.join.join, the drain's key, where the old check was onlyis not None. The marker, cohort and depth-3 assertions are unchanged. It now serves as the in-flight compatibility pin.ruff check .givesAll checks passed!,ruff format --check .gives1958 files already formatted, and barepyrightgives0 errors, 0 warnings, 0 informations.Main picked up #737 for issue 717 while this was open. It changed the same probe in
insert_fork, so I merged main in with 5d7e28c. The conflict covered the probe's comment and the query line under it, and the merge keeps main'sfetchrowand its smallint check on adoption with this PR's comment. On the merge commit,tests/test_wf_*.pyplus the docs contract files with-n 4 -m 'not load_sensitive'gave1 failed, 1425 passed, the same local-only failure described below.Other suites that ran on the fixed tree:
tests/test_wf_*.py -n 4 -m 'not load_sensitive':1 failed, 1260 passed. The failure istest_wf_emit_capacity_controls.py::test_docs_surface_scan_rejects_missing_and_finds_qualified_error, which parses every Python fence underdocs/and tripped on a gitignored local design note in my checkout that isn't part of this PR. With that file moved aside the module gives4 passed.301 passed.test_wftest files that referencemap_source,FlowRunner,workflows._fork,ConsumerBindingorJoinSpec, plustest_backend_wf_emit_capacity_subscribe.pyandtest_atk_upgrade_mixed_fleet.py:178 passed, 1 skipped(the skip needs a restartable cluster).101 passed, and a docs examples run:5 passed.I also ran the two
upgrading.mdqueries, copied from the doc's SQL fences, against runs made with both predicates reverted (the old behaviour). The stray-row query returned exactly the drain-keyed pending rows for all four shapes.taskq job canceltook each one tocancelled, the root stayedsucceededand the result didn't change,taskq flows listwent frompending root=succeededtocancelled root=succeeded, and the query came back empty afterwards. The adopted-row query matched both early-claim end states (root_statusrunningwith the run wedged, andsucceededwith result 0 of 10), each withdeps_pending10, and cancelling the wedged run throughcancel_workflow_run, the call behindtaskq flows cancel, moved its root tocancelled. Neither query matched a normally adopted join (deps_pending0) or a run where the stray ran while the nested children were live (twosucceededrows, right result).That last case only holds when the nested map is the last fan-out. If another map sits on the nested map's join, a stray that runs while the children are live forks that third map with no items.
finalthen runs on the empty join (0 instead of 10), and the real nested join's fork fails on a duplicatewf_edgerow, so the run staysrunning. Neither query listed it. b0d22a2 and e516688 scope that sentence in the doc and add a third query for these runs. I ran all three queries against that state, the two-level case, a healthy three-level run, the after-terminal stray before and aftertaskq job cancel, both early-claim shapes, and runs where the drain's row was adopted while still pending, at two and three levels. Each one listed only its own rows.Not covered: a worker-subprocess reproduction of the drain-first race on a fleet. The pins drive the in-process runner and mute
drain_outboxto pin the ordering.test_no_binding_names_a_nested_joinshows the outer join no longer names the nested join, so the fire writes no outbox row for it and a fleet drain has nothing to race.🤖 Generated with Claude Code