diff --git a/docs/design/seam-audit-matrix.md b/docs/design/seam-audit-matrix.md index de459f39e..b6a097d12 100644 --- a/docs/design/seam-audit-matrix.md +++ b/docs/design/seam-audit-matrix.md @@ -102,6 +102,7 @@ separate phases). | deadline sweep (heartbeat arm) | a slow-but-live worker near the deadline | the phantom-cancel window: a failed tick retries promptly so the recovery beat lands inside the 2x floor | `test_heartbeat.py::test_one_fast_transient_failure_is_one_miss_retried_promptly` | | archive / retention sweeps | retention bounds vs live readers | bounded batches, event TTL carve-out for reclaim events | `test_attack_rt_retention_integration.py`, `test_sweepaudit_bounded_writes.py` | | sweep liveness under long batches | a sweep batch outlasts the staleness budget | `_drain_bounded` renews the detector stamp mid-sweep | `test_drain_liveness.py`, `test_rt_worker_sweep_telemetry.py` | +| the fork/drain consumer-binding seam (the fork's join `consumers` → the fire's outbox → `drain_outbox`), callers: `_map_fork`, `_route_fork` | the outbox drain lands before or after a nested map's fork on the outer join (#745) | a join row has one writer, its own source's fork: no binding names a `map_join` node, so the drain never mints a join row | `test_wf_map_on_join_pins.py` | ## 6. State machines diff --git a/docs/guides/upgrading.md b/docs/guides/upgrading.md index 6ed8ec7ea..ea273df6c 100644 --- a/docs/guides/upgrading.md +++ b/docs/guides/upgrading.md @@ -2047,6 +2047,155 @@ is still emitted, so dashboards and any rules you wrote against it keep working, but if you overrode the bundled alert's threshold, re-express the override in seconds of oldest-pending age. +### A map on another fan-out's join: the nested join has one row + +> **Unreleased.** Silent; runs whose outer fork ran on an earlier release +> can still show the old behaviour. + +A `map_source` placed on another map's or route's join used to get two +`.join` rows: the nested fork's own, and a second one the outbox +drain inserted under `idempotency_key = 'wf:'`. Depending on +which landed first, the second row stayed `pending` on a finished run +(`taskq flows list` showed `pending root=succeeded`), ran the join work a +second time, or ran before the nested fork existed. In that last case the +run either wedged `running` forever, or the step after the nested map ran +on an empty join and the run succeeded with a wrong result. The outer +fork no longer lists the nested join as a consumer, so the nested fork +writes the only row. + +The fix covers runs whose outer fork runs on the new release. A run whose +outer fork ran on an earlier release, including on an old worker during a +rolling deploy, keeps the old binding and can still show any of the +behaviours above. Nothing repairs those rows automatically. Three read-only +queries find them. The first finds second rows left `pending` on a +finished or pruned run: + +```sql +SELECT n.id, n.metadata->>'flow_id' AS run_id, n.step_key, r.status AS root_status +FROM jobs n +LEFT JOIN jobs r + ON r.id = (n.metadata->>'flow_id')::uuid AND r.step_key = '__flow__' +WHERE n.metadata ? 'flow_id' + AND n.step_key LIKE '%.join.join' + AND n.idempotency_key = 'wf:' || n.step_key + AND n.status = 'pending' + AND (r.id IS NULL OR r.status NOT IN ('pending', 'scheduled', 'running')); +``` + +`taskq job cancel ` is the record-only repair, and its cost has to be +stated plainly: the row goes to `cancelled`, the root keeps its status and +the run's result does not change, but every surface that derives the run's +status from its rows — `taskq flows list`, the headline of `taskq flows +status`, the admin run page — then reports the successful run as +`cancelled`, permanently. The maintenance leg only re-derives a root that +is still `running`, so nothing ever reconciles a terminal root from its +rows again, and the estate's status-truth check (a `succeeded` root must +derive `complete`) keeps flagging the run. + +Remove the row instead. A second row is a pure orphan: no edge row names +it as child or parent, no step-ledger row records a claim for it, and no +consumer belongs to it. The statement below deletes one only when every +one of those facts holds, the row is still `pending` under the drain's own +key, and the run it belongs to is finished or pruned — never a live run's +fresh drain row. A real join row has its source's edge and a claim +history, so it can never match: + +```sql +DELETE FROM jobs n +WHERE n.metadata ? 'flow_id' + AND n.step_key LIKE '%.join.join' + AND n.idempotency_key = 'wf:' || n.step_key + AND n.status = 'pending' + AND NOT EXISTS ( + SELECT 1 FROM jobs r + WHERE r.id = (n.metadata->>'flow_id')::uuid + AND r.step_key = '__flow__' + AND r.status IN ('pending', 'scheduled', 'running') + ) + AND NOT EXISTS ( + SELECT 1 FROM wf_edge e + WHERE e.child_id = n.id OR e.parent_id = n.id + ) + AND NOT EXISTS ( + SELECT 1 FROM wf_step_ledger l + WHERE l.job_id = n.id + ); +``` + +The run's rows then derive `complete` under its `succeeded` root, so the +root's status, the run's result and every rows-derived surface agree. +Re-run the first query to confirm it no longer selects the run. + +The second finds second rows that ran before the nested fork and were then +adopted by it: + +```sql +SELECT n.id, n.metadata->>'flow_id' AS run_id, n.step_key, n.deps_pending, + r.status AS root_status +FROM jobs n +LEFT JOIN jobs r + ON r.id = (n.metadata->>'flow_id')::uuid AND r.step_key = '__flow__' +WHERE n.metadata ? 'flow_id' + AND n.step_key LIKE '%.join.join' + AND n.idempotency_key = 'wf:' || n.step_key + AND n.status = 'succeeded' + AND n.deps_pending > 0; +``` + +The row is `succeeded` with `deps_pending > 0` because the nested fork +adopted it after it had already run, so its children's count never drains. +If `root_status` is `running`, the run is wedged: stop it with +`taskq flows cancel `. If it is `succeeded`, the step after the +nested map ran on an empty join, so treat that run's result as suspect and +re-run it. If it is `failed` or `cancelled` (a run you stopped with +`taskq flows cancel` stays on the list), the run ended without a result; +re-run it if you still need one. + +A second row that ran while the nested fork's children were still running +is harmless when the nested map is the last fan-out: the run ends with two +`succeeded` rows and the right result, and nothing needs repair. It is not +harmless when another map sits on the nested map's join (three levels or +more). The second row forks that map again with no items, so the step after +it can run on an empty join, and the real nested join's own fork then fails +on a duplicate `wf_edge` row. The third query finds these runs: + +```sql +SELECT n.id, n.metadata->>'flow_id' AS run_id, n.step_key, n.status, + r.status AS root_status +FROM jobs n +LEFT JOIN jobs r + ON r.id = (n.metadata->>'flow_id')::uuid AND r.step_key = '__flow__' +WHERE n.metadata ? 'flow_id' + AND n.step_key LIKE '%.join.join' + AND n.idempotency_key = 'wf:' || n.step_key + AND n.status NOT IN ('pending', 'cancelled') + AND EXISTS ( + SELECT 1 FROM jobs f + WHERE f.metadata->>'flow_id' = n.metadata->>'flow_id' + AND f.step_key = n.step_key + AND f.id <> n.id + ) + AND EXISTS ( + SELECT 1 FROM jobs m + WHERE m.metadata->>'flow_id' = n.metadata->>'flow_id' + AND m.step_key = n.step_key || '.join' + ); +``` + +If `root_status` is `running`, stop the run with +`taskq flows cancel ` (it stays on the list). Whatever its status, +treat the run's result as suspect and re-run it. + +A fourth shape is not a repair case, so none of the queries selects it. If +the drain's second row had already run (or was still running) when the +nested fork reached it, the fork now refuses to adopt it and writes its own +row: the run completes with the right result, and the leftover row sits +`succeeded` with `deps_pending = 0` — debris, not a wrong answer, and +invisible to the three queries above because a never-adopted row keeps +`deps_pending = 0`. The refusal is recorded as a +`wf-fork-join-adoption-skipped` log event naming the run, the step key and +the leftover row. + --- ## Bounded inputs diff --git a/src/taskq/workflows/_fork.py b/src/taskq/workflows/_fork.py index d1c7681a1..c0f4f4b8b 100644 --- a/src/taskq/workflows/_fork.py +++ b/src/taskq/workflows/_fork.py @@ -14,11 +14,12 @@ from __future__ import annotations -from typing import TYPE_CHECKING +import structlog from taskq._ids import new_uuid from taskq.backend._protocol import ConnLike, JobId from taskq.constants import SMALLINT_MAX +from taskq.obs import get_logger from taskq.workflows._policy import canonical_retry_kind, row_retry_curve from taskq.workflows._sql import WorkflowSql from taskq.workflows._types import ( @@ -32,8 +33,7 @@ ) from taskq.workflows.definitions import FanInBoundExceededError, validate_fork -if TYPE_CHECKING: - pass +logger: structlog.stdlib.BoundLogger = get_logger(__name__) __all__ = ["FORK_CHUNK", "insert_fork"] @@ -160,20 +160,28 @@ async def insert_fork( join_id: JobId | None = None if fork.join is not None: - # the API's create_flow pre-inserted every node — the join included - # (deps 1: its source edge). When the row exists, the fork adopts it: - # add the items' weight to the counter + stamp the consumers — never a - # second insert (the plain insert's idempotency collision killed the - # second demo run's fork). The engine's raw shapes (no static row) keep - # the insert path. + # The DSL never pre-inserts a join (create_flow skips map joins), and + # since #745 no binding names one. The probe can still find a row + # minted by an outbox drain from a binding stamped before #745 (an + # in-flight run), or one an engine-level caller inserted itself + # through insert_node. The fork ADOPTS a PENDING one: add the items' + # weight to the counter + stamp the consumers, never a second insert. + # The status leg is load-bearing: adopting a row that already ran + # leaves the consumers' reserved deps unreleased (the run wedges or + # reads an empty join), so any other state is left untouched — the + # fork takes the insert path and its own row runs with the true + # children. The read is ordered so a pre-fix residue (several rows + # for the key) resolves deterministically: the lowest PENDING row + # wins, and a non-pending row is read only to report it. join_row = await conn.fetchrow( - f"SELECT id, deps_pending FROM {wsql.schema}.jobs WHERE step_key = $1 " # noqa: S608 # Why: the schema is the bundle's validated identifier; every value is $-bound. - "AND (metadata->>'flow_id')::uuid = $2", + f"SELECT id, status, deps_pending FROM {wsql.schema}.jobs WHERE step_key = $1 " # noqa: S608 # Why: the schema is the bundle's validated identifier; every value is $-bound. + "AND (metadata->>'flow_id')::uuid = $2 " + "ORDER BY (status = 'pending') DESC, id LIMIT 1", fork.join.step_key, flow_id, ) - if join_row is not None: - join_id = JobId(join_row["id"]) + if join_row is not None and join_row["status"] == "pending": + candidate = JobId(join_row["id"]) # The counter is a COUNT of unterminal parents (a smallint, never # the widened record identity), and the pre-created join already # carries its own source edge's weight: the adoption adds the @@ -202,11 +210,17 @@ async def insert_fork( reservations=fork.join.reservations, ) join_doc.pop("flow_id", None) - await conn.execute( + # The status leg repeats the probe's guard INSIDE the write: a + # worker can claim the pending row between the SELECT and this + # UPDATE, and adopting it after the claim would leave the + # consumers' reserved deps unreleased exactly as adopting a + # finished row would. Zero rows RETURNING = lost that race. + adopted = await conn.fetchval( f"UPDATE {wsql.schema}.jobs " # noqa: S608 # Why: the schema is the bundle's validated identifier; every value is a bound parameter. "SET deps_pending = deps_pending + $1, " "metadata = jsonb_set(metadata || $2::jsonb, '{consumers}', $3::jsonb, true) " - "WHERE id = $4", + "WHERE id = $4 AND status = 'pending' " + "RETURNING id", len(children), _jsonb(join_doc), _jsonb( @@ -215,9 +229,45 @@ async def insert_fork( ).get("consumers") or [] ), - join_id, + candidate, + ) + if adopted is not None: + join_id = JobId(adopted) + logger.debug( + "wf-fork-join-adopted", + flow_id=str(flow_id), + step_key=fork.join.step_key, + existing_job_id=str(join_id), + ) + else: + concurrent_status = await conn.fetchval( + f"SELECT status FROM {wsql.schema}.jobs WHERE id = $1", # noqa: S608 # Why: the schema is the bundle's validated identifier; the id is a bound parameter. + candidate, + ) + logger.warning( + "wf-fork-join-adoption-skipped", + flow_id=str(flow_id), + step_key=fork.join.step_key, + existing_job_id=str(candidate), + existing_status=( + str(concurrent_status) if concurrent_status is not None else "missing" + ), + ) + elif join_row is not None: + # The row exists and has already run (or is running): adopting + # it would leave every consumer's reserved dep unreleased — + # the wedge the old status-less probe caused. The residue is + # otherwise invisible to the upgrade detectors (a + # never-adopted row has deps_pending = 0), so this is the one + # place it is reported from the system's own records. + logger.warning( + "wf-fork-join-adoption-skipped", + flow_id=str(flow_id), + step_key=fork.join.step_key, + existing_job_id=str(join_row["id"]), + existing_status=str(join_row["status"]), ) - else: + if join_id is None: join_id = JobId(new_uuid()) await conn.execute( wsql.fork_join_node, diff --git a/src/taskq/workflows/_sql_sweep.py b/src/taskq/workflows/_sql_sweep.py index ea104dd93..567a3d1dc 100644 --- a/src/taskq/workflows/_sql_sweep.py +++ b/src/taskq/workflows/_sql_sweep.py @@ -24,7 +24,13 @@ # Missing parents (a misnamed-child edge) never fire silently: the blocked # arm stamps metadata.blocking_reason='orphan_parent' (the blocked-with- # reason state, §17.2's chains render from it) and the firable arm excludes -# them — the record must never look healthy while the work is wrong. +# them — the record must never look healthy while the work is wrong. The +# stamp is a LIVE-FLOW diagnosis: a flow-terminal row is flow_fenced's +# (its 'flow_dead'/'failed_parent' resolution is the truthful one, and +# the blocked stamp would destroy the 'join' sentinel that arm keys on), +# and an edge-less live row defers while another live row can still +# write its edge (a static consumer of a fork-spawned join is born that +# way — the nested fork's edge is the only thing that releases it). REDERIVE_SWEEP_SQL = """\ WITH locked AS ( SELECT c.id, c.step_key, c.metadata->>'flow_id' AS flow_id, c.deps_pending @@ -43,6 +49,9 @@ ), counts AS ( SELECT l.id AS child_id, + -- the flow link, for the blocked arm's two liveness legs (the + -- terminal-flow hand-off and the reserved-consumer deferral). + l.flow_id AS flow_id, count(*) FILTER (WHERE e.child_id IS NOT NULL) AS edge_count, count(*) FILTER (WHERE e.child_id IS NOT NULL AND p.id IS NULL) AS missing_parents, count(*) FILTER ( @@ -68,12 +77,14 @@ -- path that never wrote its edges) must be ENUMERATED — the inner -- join made it invisible (never reconciled, never fired, never -- stamped blocked-with-reason): silently stranded in join-wait - -- forever with a healthy-looking record. The edge-less row blocks - -- below (edge_count = 0 → orphan_parent), the 'record healthy, work - -- wrong' class rejected with a reason. + -- forever with a healthy-looking record. The edge-less row is + -- DIAGNOSED by the blocked arm's guarded legs (the misnamed-child + -- case, or — once nothing live is left to write the edge — the + -- reserved-consumer case), the 'record healthy, work wrong' class + -- rejected with a reason. LEFT JOIN {schema}.wf_edge e ON e.child_id = l.id LEFT JOIN {schema}.jobs p ON p.id = e.parent_id - GROUP BY l.id + GROUP BY l.id, l.flow_id ), blocked AS ( UPDATE {schema}.jobs j @@ -85,7 +96,42 @@ ) FROM counts c WHERE j.id = c.child_id - AND (c.missing_parents > 0 OR c.edge_count = 0) + AND ( + -- The misnamed-child edge: a written edge whose parent row does + -- not exist can never resolve, whatever else the flow is doing. + c.missing_parents > 0 + -- The edge-less join-wait row: a wiring fault only once nothing + -- is left that could still write its edge. A static consumer of + -- a fork-spawned join is born exactly this shape — pending, the + -- counter reserved, ZERO edges — while the nested fork that + -- writes ``FORK_CONSUMER_EDGES_SQL`` has not run yet (its source + -- join is still live in the flow). While ANY other live non-root + -- row exists in the flow it can still fork and write that edge, + -- so this pass DEFERS; when the candidate is the flow's only + -- live row, nothing can release it and the stamp is truthful. + OR ( + c.edge_count = 0 + AND NOT EXISTS ( + SELECT 1 FROM {schema}.jobs live + WHERE (live.metadata->>'flow_id')::uuid = (c.flow_id)::uuid + AND live.id <> c.child_id + AND live.step_key <> '__flow__' + AND live.status IN ('pending', 'scheduled', 'running') + ) + ) + ) + -- A terminal flow's resolution is the fence's, never this arm's: the + -- flow_fenced arm below stamps 'flow_dead'/'failed_parent', and it + -- keys on the 'join' sentinel this stamp would overwrite — stamping + -- here first made the truthful reason unreachable for the reserved + -- consumer of a nested join whose fork never ran (the flow died + -- first). 'orphan_parent' is a live-flow diagnosis only. + AND NOT EXISTS ( + SELECT 1 FROM {schema}.jobs f + WHERE f.id = (c.flow_id)::uuid + AND f.step_key = '__flow__' + AND f.status IN {terminal} + ) AND NOT j.metadata @> '{{"blocking_reason": "orphan_parent"}}'::jsonb RETURNING j.id ), @@ -155,7 +201,10 @@ ) -- One resolution per row per pass: the arms all see the same -- statement snapshot, so the exclusion (not the write order) - -- keeps the double-update undefined-result class out. + -- keeps the double-update undefined-result class out. The + -- blocked arm is flow-live-only (it yields a terminal flow's + -- rows to THIS arm), so its exclusion here is a belt; the + -- blocked_required exclusion is the load-bearing one. AND NOT EXISTS (SELECT 1 FROM blocked b WHERE b.id = jj.id) AND NOT EXISTS (SELECT 1 FROM blocked_required br WHERE br.id = jj.id) ) cand diff --git a/src/taskq/workflows/_types.py b/src/taskq/workflows/_types.py index 285cf60e2..e405f4848 100644 --- a/src/taskq/workflows/_types.py +++ b/src/taskq/workflows/_types.py @@ -803,7 +803,7 @@ def _consumer_bindings(raw: object) -> tuple[ConsumerBinding, ...]: # asyncpg returns jsonb as ``str`` on un-coded connections — parse # before indexing (the estate's _json seam, never the stdlib import). decoded: Any = _json_loads(raw) if isinstance(raw, str) else raw - return tuple(_consumer_binding(c) for c in decoded) # pyright: ignore[reportUnknownArgumentType] # Why: the Any-contract walk — decoded's members are Unknown; _consumer_binding's asserts guard the runtime shape. + return tuple(_consumer_binding(c) for c in decoded) # pyright: ignore[reportUnknownArgumentType] # Why: the Any-contract walk — decoded's members are Unknown; _consumer_binding validates the required keys and the structured sub-docs (KeyError/ValueError on a malformed stamp) rather than asserting the shape away. def _seconds_or_none(raw: object) -> timedelta | None: @@ -862,16 +862,39 @@ def _retry_from_doc(raw: object) -> RetrySpec | None: ) +def _required_str(raw: dict[str, Any], key: str) -> str: + """One REQUIRED binding field: a stamp that lacks the key raises + ``KeyError``, and a present-but-wrong-typed value raises ``ValueError`` + — the persisted shape is validated at this boundary, never degraded.""" + value = raw[key] + if not isinstance(value, str): + raise ValueError(f"workflow consumer binding {key!r} must be a string") + return value + + def _consumer_binding(raw: dict[str, Any]) -> ConsumerBinding: """one metadata ``consumers`` entry → the typed binding (the walk's - own arm): the declared deadline parses back from the binding's - SECONDS (the jsonb wire form — :func:`_consumer_binding_doc`'s own - serialization); a malformed value degrades to None (the binding is - a declaration, never a correctness input worth a sweep death).""" + own arm). + + The three REQUIRED keys — ``step_key``, ``actor``, ``queue`` — are read + directly (:func:`_required_str`): a stamp missing one raises + ``KeyError`` and a wrong-typed one raises ``ValueError``. The + structured sub-docs validate through their own readers + (``rate_limits``/``reservations`` via :func:`_string_tuple`, ``retry`` + via :func:`_retry_from_doc`), so a malformed entry raises there too. + ONLY the declared deadline degrades: ``start_to_close_s`` is a duration + hint parsed back from the jsonb wire form + (:func:`_consumer_binding_doc`'s serialization), so a malformed value + becomes ``None`` (:func:`_seconds_or_none`) rather than a raise. + + This is a CROSS-RELEASE parse — since #745 a ``map_join``-naming + ``consumers`` stamp can only be written by an older release into the + same database — so the raise is a loud refusal at a real boundary, not + a sweep death the reader is promised cannot happen.""" return ConsumerBinding( - step_key=raw["step_key"], # pyright: ignore[reportUnknownArgumentType,reportIndexType] # Why: the Any-contract walk (the ledger wrote the shape). - actor=raw["actor"], # pyright: ignore[reportUnknownArgumentType,reportIndexType] - queue=raw["queue"], # pyright: ignore[reportUnknownArgumentType,reportIndexType] + step_key=_required_str(raw, "step_key"), + actor=_required_str(raw, "actor"), + queue=_required_str(raw, "queue"), payload=raw.get("payload"), map_index=raw.get("map_index"), start_to_close=_seconds_or_none(raw.get("start_to_close_s")), diff --git a/src/taskq/workflows/api/_graph.py b/src/taskq/workflows/api/_graph.py index 150c1200d..e874276cf 100644 --- a/src/taskq/workflows/api/_graph.py +++ b/src/taskq/workflows/api/_graph.py @@ -708,7 +708,14 @@ class NodeDecl: #: projected literal on every boot. The projection carries it into the #: cohort's ``ActorConfig``. capacity_owner: str = "operator" - kind: str = "step" # "step" | "map_source" | "gather" | "map_join" + #: The compile's node discriminator. Exactly five values are assigned: + #: ``"step"`` (the default), ``"gather"``, ``"map_join"``, + #: ``"chain_source"`` and ``"loop"``. ``"map_source"`` is NOT one of + #: them: ``map_item is not None`` is the map-source marker (the + #: runner's fork decision reads it). ``is_fork_spawned_join`` below is + #: the single predicate for the ``"map_join"`` row the static insert + #: skips and the fork builders refuse to name as a consumer. + kind: str = "step" # a pydantic model the node's ``ctx.progress`` data emissions must satisfy. # On a map source the declaration reaches the children (the ``.item`` # keys resolve it through their source). @@ -765,6 +772,20 @@ class NodeDecl: cache: bool = False cache_ttl: float | None = None + @property + def is_fork_spawned_join(self) -> bool: + """True when this node's row is written by its SOURCE's fork, not by + the static insert: the one spelling of the question the static node + pass (both loops) and both fork builders ask. + + The static pass must not pre-insert such a node (its source's fork + writes the row) and the fork's consumer list must not name it (its + own fork writes the nested one) — two behaviours, one fact. Today + exactly ``kind == "map_join"``; a future derived-join kind decides + here, once, instead of drifting across four call sites. + """ + return self.kind == "map_join" + class Promise[T_co]: """The wiring handle to one node's future result. diff --git a/src/taskq/workflows/api/_runner.py b/src/taskq/workflows/api/_runner.py index 5bf5a21bd..605c65a3c 100644 --- a/src/taskq/workflows/api/_runner.py +++ b/src/taskq/workflows/api/_runner.py @@ -618,7 +618,7 @@ async def _insert_static_nodes( ) -> None: for key in sorted(self.compiled.nodes): node = self.compiled.nodes[key] - if node.kind == "map_join": + if node.is_fork_spawned_join: continue # spawned by the source's fork # The map-join's downstream is a static row: every # non-join node is inserted upfront — a node whose parent is @@ -720,7 +720,7 @@ async def _insert_static_nodes( # The edges in a second pass (both endpoints exist). for key in sorted(self.compiled.nodes): node = self.compiled.nodes[key] - if node.kind == "map_join": + if node.is_fork_spawned_join: continue for parent_key in node.parents: parent_node = self.compiled.nodes.get(parent_key) @@ -733,7 +733,7 @@ async def _insert_static_nodes( if child_row is None: continue # the fork's outbox writes these edges at fire if parent_row is None: - if parent_node is not None and parent_node.kind == "map_join": + if parent_node is not None and parent_node.is_fork_spawned_join: # the map JOIN'S edge — the fork writes the edge row at # the source's finalize . The counter is reserved now: # the consumer can never dispatch before the join's @@ -2474,7 +2474,8 @@ def _map_fork( one per list element — fresh jobs, per-item ledger identity) + the join whose consumers are the wiring's downstream nodes (the 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 nothing — the join fires empty, the collect states it). ``run_priority`` is the RUN's per-call override (the wf-priority @@ -2564,6 +2565,8 @@ def _map_fork( ) 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 not self.compiled.nodes[downstream].is_fork_spawned_join ) return ForkSpec( children=tuple( @@ -2644,6 +2647,13 @@ def _route_fork( actor/queue), and the element's jsonb under the item key (the arm body's declared param type is the decode's target — R3). + The join's consumers are the wiring's downstream nodes (the outbox + carries the consumer bindings — the cascade fix), EXCEPT a nested + map's join, which its own fork writes (#745): naming it here would + put a binding for the nested join on the outer join's fire, and the + drain would mint a second row for one step key. ``_map_fork``'s + comprehension carries the same exclusion — change both or neither. + LOUD DOOR (R1 — the skip-silent shape is DEAD): an element whose type has no arm raises :class:`RouterNotTotal` before any row is written — the caller converts it to the source's @@ -2744,6 +2754,8 @@ def _route_fork( ) 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 not self.compiled.nodes[downstream].is_fork_spawned_join ) children: list[ChildSpec] = [] for i, element in enumerate(items): diff --git a/tests/test_upgrading_guide_map_on_join_docs_contract.py b/tests/test_upgrading_guide_map_on_join_docs_contract.py new file mode 100644 index 000000000..dd5348e8d --- /dev/null +++ b/tests/test_upgrading_guide_map_on_join_docs_contract.py @@ -0,0 +1,388 @@ +# ruff: noqa: S608 # Why: the schema is a fixture-derived test identifier; every value is $-bound. +"""The #745 section of ``docs/guides/upgrading.md`` as an executable contract. + +The section "A map on another fan-out's join: the nested join has one row" +is the change's only instrument for finding — and its only instruction for +repairing — pre-fix persisted state: three read-only queries plus one +guarded removal. Nothing else in the suite executes those statements, so a +key-shape change (the drain's bare ``wf:`` vs the fork's +``wf:::``), a status leg added to the adoption, or a +relaxed dotted-key refusal would silently turn a detector into a false +all-clear, or the removal into a row-eater. + +So the statements are extracted from the document (not retyped) and driven +against a state the real runner can leave behind: an in-flight run whose +outer fork ran before #745 (the old binding stamped onto the outer join, the +same forge the keyed-admission pin uses) with the leader's outbox drain +landing after the run terminalised. Pinned: + +* detector 1 selects exactly the surplus row, and detectors 2 and 3 do not + also claim it; +* the documented removal deletes exactly that one row and the run's rows + then derive ``complete`` under its ``succeeded`` root — the estate's + status-truth invariant (G7), which the alternative ``taskq job cancel`` + cannot restore (a ``cancelled`` row forever defeats rule 4 of + ``derive_workflow_status``, and the maintenance leg never re-derives a + terminal root); +* no detector and no removal touches a healthy post-fix run. +""" + +from __future__ import annotations + +import json +import re +from pathlib import Path +from typing import Any + +import asyncpg +import pytest + +import taskq.workflows._sweep as sweep_module +from taskq.workflows import ( + FlowRunner, + Promise, + StepContext, + WorkflowApp, + build, + map_source, + step, +) +from taskq.workflows._cli import ( + FLOW_ROOT_STEP_KEY, + FlowListRow, + FlowNodeRow, + derive_flow_status, + format_flow_list, +) +from taskq.workflows._status import reconstruct_workflow_status + +pytestmark = pytest.mark.integration + +GUIDE = Path(__file__).resolve().parents[1] / "docs" / "guides" / "upgrading.md" +SECTION = "### A map on another fan-out's join: the nested join has one row" + + +async def seeds(ctx: StepContext) -> list[dict[str, int]]: + return [{"seed": s} for s in range(10)] + + +async def expand(ctx: StepContext, seed: dict[str, int]) -> list[str]: + return [f"s{seed['seed']}-{k}" for k in range(5)] + + +async def ident(ctx: StepContext, x: object) -> object: + return x + + +async def count(ctx: StepContext, xs: list[object]) -> int: + return len(xs) + + +def _wire(app: WorkflowApp) -> str: + """The issue's shape: a map on a map's join, consumed by ``final``.""" + + @app.workflow("upgrading_map_on_map_join") + def upgrading_map_on_map_join() -> Promise[object]: + first = map_source(step(seeds, key="seeds"), expand) + return build(step(count, map_source(first, ident), key="final")) + + return "upgrading_map_on_map_join" + + +def _statements() -> tuple[list[str], str]: + """The section's SQL fences, verbatim: the three detectors and the guarded + removal, in document order.""" + text = GUIDE.read_text(encoding="utf-8") + start = text.index(SECTION) + rest = text[start + len(SECTION) :] + nxt = re.search(r"^#{2,3} ", rest, flags=re.MULTILINE) + body = rest[: nxt.start()] if nxt else rest + fences = [f.strip() for f in re.findall(r"```sql\n(.*?)```", body, flags=re.DOTALL)] + detectors = [fence for fence in fences if fence.startswith("SELECT")] + removals = [fence for fence in fences if fence.startswith("DELETE")] + assert len(fences) == 4, f"the section carries three detectors and one removal; got {fences}" + assert len(detectors) == 3, detectors + assert len(removals) == 1, removals + return detectors, removals[0] + + +async def _rows(conn: asyncpg.Connection, schema: str, flow_id: Any) -> list[asyncpg.Record]: + return await conn.fetch( + f"SELECT id, step_key, status, idempotency_key, deps_pending, " + f"metadata->>'blocking_reason' AS blocking_reason " + f"FROM \"{schema}\".jobs WHERE (metadata->>'flow_id')::uuid = $1 AND id <> $1 " + "ORDER BY id", + flow_id, + ) + + +def _listed(rows: list[asyncpg.Record], root_status: str) -> str: + """The ``flows list`` line for this run, through the CLI's own render.""" + nodes = [ + FlowNodeRow( + step_key=r["step_key"], + status=r["status"], + deps_pending=r["deps_pending"], + blocking_reason=r["blocking_reason"], + ) + for r in rows + ] + line = format_flow_list( + [ + FlowListRow( + run_id="00000000-0000-0000-0000-000000000000", + workflow="upgrading_map_on_map_join", + root_status=root_status, + derived=derive_flow_status(nodes), + nodes_total=len(nodes), + created_at=None, + ) + ] + ) + return line[1].replace("00000000-0000-0000-0000-000000000000", "") + + +async def _step_rows( + conn: asyncpg.Connection, schema: str, flow_id: Any, step_key: str +) -> list[dict[str, Any]]: + return [ + dict(r) + for r in await conn.fetch( + f'SELECT id, status, deps_pending, idempotency_key FROM "{schema}".jobs ' + "WHERE (metadata->>'flow_id')::uuid = $1 AND step_key = $2 ORDER BY id", + flow_id, + step_key, + ) + ] + + +async def _live_drain_state( + wf_pool: asyncpg.Pool, + wf_conn: asyncpg.Connection, + wf_schema: str, + monkeypatch: pytest.MonkeyPatch, +) -> tuple[FlowRunner, Any, dict[str, Any]]: + """A LIVE run holding a pending drain-minted nested-join row — the state + the removal must never touch. Returns (runner, flow_id, drain row).""" + app = WorkflowApp() + runner = FlowRunner(app.get(_wire(app)), wf_pool, wf_schema) + flow_id = (await runner.create_flow()).flow_id + + real_drain = sweep_module.drain_outbox + + async def _muted_drain(*_a: object, **_k: object) -> int: + return 0 + + # the source runs; stamp the pre-#745 binding before the outer join fires. + await runner.tick(flow_id) + await _forge_old_binding(runner, wf_conn, wf_schema, flow_id) + + # hold the leader's drain back until the outer join has fired, so the + # nested join row can only come from the drain itself. + monkeypatch.setattr(sweep_module, "drain_outbox", _muted_drain) + for _ in range(50): + outer = await _step_rows(wf_conn, wf_schema, flow_id, "seeds.join") + if [r["status"] for r in outer] == ["pending"] and outer[0]["deps_pending"] == 0: + break + await runner.tick(flow_id) + else: + raise AssertionError("the outer join never fired") + assert await _root_status(wf_conn, wf_schema, flow_id) == "running" + + monkeypatch.setattr(sweep_module, "drain_outbox", real_drain) + await real_drain(wf_pool, runner.wsql) + drained = await _step_rows(wf_conn, wf_schema, flow_id, "seeds.join.join") + assert [r["idempotency_key"] for r in drained] == ["wf:seeds.join.join"], drained + assert drained[0]["status"] == "pending", drained + assert await _root_status(wf_conn, wf_schema, flow_id) == "running" + return runner, flow_id, drained[0] + + +async def _root_status(conn: asyncpg.Connection, schema: str, flow_id: Any) -> str: + return str( + await conn.fetchval( + f'SELECT status FROM "{schema}".jobs WHERE id = $1 AND step_key = $2', + flow_id, + FLOW_ROOT_STEP_KEY, + ) + ) + + +async def _forge_old_binding( + runner: FlowRunner, conn: asyncpg.Connection, schema: str, flow_id: Any +) -> None: + """Stamp the nested map's join onto the outer join's consumers — the + binding a fork that ran before #745 wrote.""" + from taskq.workflows._types import ConsumerBinding, _consumer_binding_doc + from taskq.workflows.api._graph import rate_limit_names, reservation_names + from taskq.workflows.api._runner import _node_retry_spec + + decl = runner.compiled.nodes["seeds.join.join"] + old_binding = _consumer_binding_doc( + ConsumerBinding( + step_key="seeds.join.join", + actor=decl.actor, + queue=decl.queue, + payload={}, + failure_policy=decl.on_failure, + start_to_close=decl.start_to_close, + rate_limits=rate_limit_names(decl.rate_limits, what="the old binding"), + reservations=reservation_names(decl.reservations, what="the old binding"), + priority=decl.priority, + retry=_node_retry_spec(decl), + ) + ) + stamped = await conn.execute( + f"UPDATE \"{schema}\".jobs SET metadata = jsonb_set(metadata, '{{consumers}}', $2::jsonb, true) " + "WHERE (metadata->>'flow_id')::uuid = $1 AND step_key = 'seeds.join'", + flow_id, + json.dumps([old_binding]), + ) + assert stamped == "UPDATE 1", stamped + + +async def _late_drain_state( + wf_pool: asyncpg.Pool, + wf_conn: asyncpg.Connection, + wf_schema: str, + monkeypatch: pytest.MonkeyPatch, +) -> tuple[FlowRunner, Any, dict[str, Any]]: + """A terminal run in the guide's query-1 state: an in-flight run whose + outer fork carried the pre-#745 binding, with the leader's outbox drain + landing after the run finished. Returns (runner, flow_id, surplus row).""" + app = WorkflowApp() + runner = FlowRunner(app.get(_wire(app)), wf_pool, wf_schema) + flow_id = (await runner.create_flow()).flow_id + + # tick once (the source runs), then stamp the pre-#745 binding before the + # outer join fires: the fire copies metadata->'consumers' into the outbox. + await runner.tick(flow_id) + await _forge_old_binding(runner, wf_conn, wf_schema, flow_id) + + # the leader's drain lags the dispatch (the sweep cadence): muted through + # the run, so the outbox row is still undelivered when the run terminalises. + real_drain = sweep_module.drain_outbox + muted_calls = 0 + + async def _muted_drain(*_a: object, **_k: object) -> int: + nonlocal muted_calls + muted_calls += 1 + return 0 + + monkeypatch.setattr(sweep_module, "drain_outbox", _muted_drain) + assert await runner.drive(flow_id) == "terminal" + monkeypatch.setattr(sweep_module, "drain_outbox", real_drain) + assert muted_calls > 0, "tick() never called the muted drain" + assert await runner.result(flow_id) == 10 + + # the leader's late tick: the drain mints the surplus nested-join row. + await real_drain(wf_pool, runner.wsql) + rows = await _rows(wf_conn, wf_schema, flow_id) + surplus = [dict(r) for r in rows if r["step_key"] == "seeds.join.join"] + assert len(surplus) == 2, surplus + drain_row = next(r for r in surplus if r["idempotency_key"] == "wf:seeds.join.join") + assert drain_row["status"] == "pending", drain_row + return runner, flow_id, drain_row + + +async def test_the_detector_selects_the_surplus_row_and_the_guarded_removal_restores_truth( + wf_pool: asyncpg.Pool, + wf_conn: asyncpg.Connection, + wf_schema: str, + monkeypatch: pytest.MonkeyPatch, +) -> None: + await wf_conn.execute(f'SET search_path TO "{wf_schema}"') + detectors, removal = _statements() + + runner, flow_id, drain_row = await _late_drain_state(wf_pool, wf_conn, wf_schema, monkeypatch) + + before = await _rows(wf_conn, wf_schema, flow_id) + root_before = await _root_status(wf_conn, wf_schema, flow_id) + assert root_before == "succeeded", root_before + + # ── detector 1 selects exactly the surplus row; 2 and 3 do not ──────── + found = await wf_conn.fetch(detectors[0]) + assert [(str(r["id"]), r["step_key"], r["root_status"]) for r in found] == [ + (str(drain_row["id"]), "seeds.join.join", "succeeded") + ], [dict(r) for r in found] + assert [dict(r) for r in await wf_conn.fetch(detectors[1])] == [] + assert [dict(r) for r in await wf_conn.fetch(detectors[2])] == [] + + # the guide's before-line: the run reads pending under a succeeded root. + assert "pending" in _listed(before, root_before), _listed(before, root_before) + assert "root=succeeded" in _listed(before, root_before) + + # ── the removal is a pure-orphan delete: exactly one row ────────────── + deleted = await wf_conn.execute(removal) + assert deleted == "DELETE 1", deleted + + after = await _rows(wf_conn, wf_schema, flow_id) + assert [r["id"] for r in after if str(r["id"]) == str(drain_row["id"])] == [], ( + f"the guard refused the surplus row or deleted more than it: {[dict(r) for r in after]}" + ) + root_after = await _root_status(wf_conn, wf_schema, flow_id) + assert root_after == "succeeded", root_after + # the load-bearing promise: the root keeps its status, the result intact. + assert await runner.result(flow_id) == 10 + + # ── the estate's status truth, which the cancel remedy cannot restore ─ + assert await reconstruct_workflow_status(wf_conn, runner.wsql, flow_id) == "complete" + after_line = _listed(after, root_after) + assert "complete" in after_line, after_line + assert "root=succeeded" in after_line, after_line + # detector 1 no longer selects the run (the guide's confirmation step). + assert [dict(r) for r in await wf_conn.fetch(detectors[0])] == [] + + +async def test_the_removal_never_deletes_a_live_runs_pending_drain_row( + wf_pool: asyncpg.Pool, + wf_conn: asyncpg.Connection, + wf_schema: str, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The removal's root guard, in the direction that matters most: a + ``pending`` drain-minted row on a LIVE run — the row a worker may be + about to claim, and the row a nested fork may still adopt — is never + deleted. Only a finished or pruned run's row is repair material.""" + await wf_conn.execute(f'SET search_path TO "{wf_schema}"') + detectors, removal = _statements() + + runner, flow_id, drained = await _live_drain_state(wf_pool, wf_conn, wf_schema, monkeypatch) + assert await _root_status(wf_conn, wf_schema, flow_id) == "running" + # detector 1 already excludes a live run; the removal must agree with it. + assert [dict(r) for r in await wf_conn.fetch(detectors[0])] == [] + + assert await wf_conn.execute(removal) == "DELETE 0" + still = await _step_rows(wf_conn, wf_schema, flow_id, "seeds.join.join") + assert [(r["id"], r["status"]) for r in still] == [(drained["id"], "pending")], still + + # and the run is left to finish: its nested fork adopts that pending row + # (the supported compatibility path), so refusing the delete lost nothing. + assert await runner.drive(flow_id) == "terminal" + assert await runner.result(flow_id) == 10 + nested = await _step_rows(wf_conn, wf_schema, flow_id, "seeds.join.join") + assert [(r["id"], r["status"]) for r in nested] == [(drained["id"], "succeeded")], nested + assert await reconstruct_workflow_status(wf_conn, runner.wsql, flow_id) == "complete" + + +async def test_the_detectors_and_the_removal_select_nothing_on_a_healthy_run( + wf_pool: asyncpg.Pool, wf_conn: asyncpg.Connection, wf_schema: str +) -> None: + """The converse every remedy depends on: no healthy post-fix run matches a + detector, and the removal has nothing to delete (an operator must never be + sent after one).""" + await wf_conn.execute(f'SET search_path TO "{wf_schema}"') + detectors, removal = _statements() + + app = WorkflowApp() + runner = FlowRunner(app.get(_wire(app)), wf_pool, wf_schema) + flow_id = (await runner.create_flow()).flow_id + assert await runner.drive(flow_id) == "terminal" + assert await runner.result(flow_id) == 10 + await sweep_module.drain_outbox(wf_pool, runner.wsql) + + for i, statement in enumerate(detectors, start=1): + rows = await wf_conn.fetch(statement) + assert [dict(r) for r in rows] == [], f"detector {i} selected a healthy run: {rows}" + assert await wf_conn.execute(removal) == "DELETE 0" + assert await reconstruct_workflow_status(wf_conn, runner.wsql, flow_id) == "complete" diff --git a/tests/test_wf_consumer_binding_scope_pins.py b/tests/test_wf_consumer_binding_scope_pins.py new file mode 100644 index 000000000..ca49ef277 --- /dev/null +++ b/tests/test_wf_consumer_binding_scope_pins.py @@ -0,0 +1,284 @@ +# ruff: noqa: S608 # Why: the schema is a fixture-derived test identifier; every value is $-bound. +"""The *other* fan-in shapes the fork's ``is_fork_spawned_join`` exclusion decides. + +``tests/test_wf_map_on_join_pins.py`` pins the exclusion (a nested map's join +is not a consumer) and one retained consumer of a MAP join (``mixed``: ``sib``). +These pins walk the shapes that file never combines, because the predicate's +correctness is a two-sided claim: it must exclude the fork-spawned join row and +keep every statically inserted child — the child whose ``deps_pending`` +``_insert_static_nodes`` reserved against the join and whose only release is the +consumer binding the fork stamps. + +* a static sibling of a ROUTE's join (the ``mixed`` shape, route side); +* a ``gather`` over a map's join (``kind="gather"`` — a static row); +* a ``gather`` that is *also* a map source (``kind="gather"`` on both ends of + the predicate: a reserved consumer of one join and the source of another); +* the compile's kind domain itself, and the naming law the operator-facing + upgrade detectors rely on (every fork-spawned join key ends in ``.join``). +""" + +from __future__ import annotations + +import enum +from typing import Any + +import asyncpg +import pytest +from pydantic import BaseModel + +from taskq.workflows import ( + Chain, + FlowRunner, + Promise, + RouteArm, + Step, + StepContext, + WorkflowApp, + build, + chain_source, + gather, + loop, + map_source, + route, + step, +) +from taskq.workflows.chain import DONE, Route + +pytestmark = pytest.mark.integration + + +class Img(BaseModel): + n: int + + +class Aud(BaseModel): + n: int + + +class Outcome(enum.Enum): + OK = "ok" + + +async def seeds(ctx: StepContext) -> list[dict[str, int]]: + return [{"seed": s} for s in range(10)] + + +async def expand(ctx: StepContext, seed: dict[str, int]) -> list[str]: + return [f"s{seed['seed']}-{k}" for k in range(5)] + + +async def media(ctx: StepContext) -> list[Img | Aud]: + return [Img(n=i) if i % 2 else Aud(n=i) for i in range(6)] + + +async def on_img(ctx: StepContext, x: Img) -> str: + return f"img{x.n}" + + +async def on_aud(ctx: StepContext, x: Aud) -> str: + return f"aud{x.n}" + + +async def ident(ctx: StepContext, x: object) -> object: + return x + + +async def count(ctx: StepContext, xs: list[object]) -> int: + return len(xs) + + +async def add(ctx: StepContext, xs: list[object], n: int) -> int: + return len(xs) + n + + +async def one(ctx: StepContext) -> int: + return 1 + + +async def _flow_rows(conn: asyncpg.Connection, schema: str, flow_id: Any) -> list[asyncpg.Record]: + return await conn.fetch( + f'SELECT step_key, status, idempotency_key, deps_pending FROM "{schema}".jobs ' + "WHERE (metadata->>'flow_id')::uuid = $1 AND id <> $1 ORDER BY id", + flow_id, + ) + + +async def _rows_for( + conn: asyncpg.Connection, schema: str, flow_id: Any, step_key: str +) -> list[dict[str, Any]]: + return [dict(r) for r in await _flow_rows(conn, schema, flow_id) if r["step_key"] == step_key] + + +async def _consumers_of( + conn: asyncpg.Connection, schema: str, flow_id: Any, join_key: str +) -> list[str]: + rows = await conn.fetch( + f"SELECT c->>'step_key' AS consumer FROM \"{schema}\".jobs j, " + "jsonb_array_elements(j.metadata->'consumers') c " + "WHERE (j.metadata->>'flow_id')::uuid = $1 AND j.step_key = $2 ORDER BY 1", + flow_id, + join_key, + ) + return [r["consumer"] for r in rows] + + +def _assert_no_pending(rows: list[asyncpg.Record]) -> None: + pending = [dict(r) for r in rows if r["status"] == "pending"] + assert pending == [], f"a terminal run holds no pending row; got {pending}" + + +async def test_a_route_join_keeps_its_static_sibling( + wf_pool: asyncpg.Pool, wf_schema: str, wf_conn: asyncpg.Connection +) -> None: + """The ``mixed`` shape on the ROUTE side. + + ``media.join``'s consumers are exactly ``["sib"]``: the map on the join is + excluded, the static sibling is not (its reserved dep is released only by + the binding the route's fork stamps).""" + app = WorkflowApp() + + @app.workflow("route_join_static_sibling") + def route_join_static_sibling() -> Promise[object]: + routed = route(step(media, key="media"), {Img: RouteArm(body=on_img), Aud: on_aud}) + sib = step(count, routed, key="sib") + return build(step(add, map_source(routed, ident), sib, key="final")) + + runner = FlowRunner(app.get("route_join_static_sibling"), wf_pool, wf_schema) + flow_id = (await runner.create_flow()).flow_id + assert await runner.drive(flow_id) == "terminal" + # the outer value is the 6 arm returns; sib counts the same 6. + assert await runner.result(flow_id) == 12 + + rows = await _flow_rows(wf_conn, wf_schema, flow_id) + _assert_no_pending(rows) + nested = await _rows_for(wf_conn, wf_schema, flow_id, "media.join.join") + assert len(nested) == 1, nested + assert nested[0]["status"] == "succeeded", nested + sib = await _rows_for(wf_conn, wf_schema, flow_id, "sib") + assert [r["idempotency_key"] for r in sib] == ["wf:sib"], sib + assert await _consumers_of(wf_conn, wf_schema, flow_id, "media.join") == ["sib"] + + +async def test_a_gather_over_a_map_join_stays_a_consumer( + wf_pool: asyncpg.Pool, wf_schema: str, wf_conn: asyncpg.Connection +) -> None: + """``kind="gather"`` must stay a consumer: the gather is a static row whose + dep ``_insert_static_nodes`` reserves against the join.""" + app = WorkflowApp() + + @app.workflow("gather_over_map_join") + def gather_over_map_join() -> Promise[object]: + first = map_source(step(seeds, key="seeds"), expand) + other = step(one, key="other") + joined = gather([first, other]) + return build(step(count, joined, key="final")) + + compiled = app.get("gather_over_map_join") + gather_keys = [k for k, n in compiled.nodes.items() if n.kind == "gather"] + assert len(gather_keys) == 1, compiled.nodes + gather_key = gather_keys[0] + + runner = FlowRunner(compiled, wf_pool, wf_schema) + flow_id = (await runner.create_flow()).flow_id + assert await runner.drive(flow_id) == "terminal" + # the gather packs its two parents: the map's 10-item list and `one`'s 1. + assert await runner.result(flow_id) == 2 + + rows = await _flow_rows(wf_conn, wf_schema, flow_id) + _assert_no_pending(rows) + gathered = await _rows_for(wf_conn, wf_schema, flow_id, gather_key) + assert len(gathered) == 1, gathered + assert gathered[0]["status"] == "succeeded", gathered + assert await _consumers_of(wf_conn, wf_schema, flow_id, "seeds.join") == [gather_key] + + +async def test_a_map_on_a_gather_keeps_the_gather_a_consumer( + wf_pool: asyncpg.Pool, wf_schema: str, wf_conn: asyncpg.Connection +) -> None: + """The same node is a reserved consumer of one join and the source of + another (``kind="gather"`` on both ends of the predicate).""" + app = WorkflowApp() + + @app.workflow("map_on_gather") + def map_on_gather() -> Promise[object]: + first = map_source(step(seeds, key="seeds"), expand) + other = step(one, key="other") + joined = gather([first, other]) + return build(step(count, map_source(joined, ident), key="final")) + + compiled = app.get("map_on_gather") + gather_key = next(k for k, n in compiled.nodes.items() if n.kind == "gather") + + runner = FlowRunner(compiled, wf_pool, wf_schema) + flow_id = (await runner.create_flow()).flow_id + assert await runner.drive(flow_id) == "terminal" + assert await runner.result(flow_id) == 2 + + rows = await _flow_rows(wf_conn, wf_schema, flow_id) + _assert_no_pending(rows) + nested = await _rows_for(wf_conn, wf_schema, flow_id, f"{gather_key}.join") + assert len(nested) == 1, nested + assert nested[0]["status"] == "succeeded", nested + assert await _consumers_of(wf_conn, wf_schema, flow_id, "seeds.join") == [gather_key] + + +async def _source_body(ctx: StepContext, upstream: object) -> None: + del ctx, upstream + + +async def _screen(ctx: StepContext, item: object) -> Outcome: + del ctx, item + return Outcome.OK + + +def _chain() -> Chain: + return Chain( + name="kind-domain-chain", + start="screen", + queue="default", + steps={ + "screen": Step( + body=_screen, + outcomes=Outcome, + route=Route({Outcome.OK: DONE}), + ) + }, + ) + + +async def _loop_body(ctx: StepContext, carry: object) -> object: + del ctx + return carry + + +def test_the_compiled_kind_domain_is_enumerated() -> None: + """The domain the fork predicate keys on has no ``Literal``/enum; this + canary names it, so a new ``kind`` cannot reach production without a + decision about ``_insert_static_nodes``' skip and the fork builders' + consumer filters. + + ``NodeDecl.kind`` declares five values and the compile assigns all five + here. The second half is the naming law the operator-facing upgrade + detectors read instead of a ``kind`` column: every fork-spawned join's + step key ends in ``.join`` (and every ``.join`` node is fork-spawned), so + ``n.step_key LIKE '%.join.join'`` selects exactly the nested joins.""" + app = WorkflowApp() + + @app.workflow("kind_domain") + def kind_domain() -> Promise[object]: + first = map_source(step(seeds, key="seeds"), expand) + other = step(one, key="other") + joined = gather([first, other]) + routed = route(step(media, key="media"), {Img: RouteArm(body=on_img), Aud: on_aud}) + chained = chain_source(_chain(), _source_body, other, key="source") + counted = loop("counter", _loop_body, max_iterations=2) + return build(chained, joined, routed, first, counted) + + compiled = app.get("kind_domain") + observed = {n.kind for n in compiled.nodes.values()} + assert observed == {"step", "gather", "map_join", "chain_source", "loop"}, observed + + fork_spawned = {k for k, n in compiled.nodes.items() if n.is_fork_spawned_join} + dotted = {k for k in compiled.nodes if k.endswith(".join")} + assert fork_spawned == dotted, (fork_spawned, dotted) + assert fork_spawned == {"seeds.join", "media.join"}, fork_spawned diff --git a/tests/test_wf_join_adoption_pins.py b/tests/test_wf_join_adoption_pins.py new file mode 100644 index 000000000..3fa393ce4 --- /dev/null +++ b/tests/test_wf_join_adoption_pins.py @@ -0,0 +1,295 @@ +# ruff: noqa: S608 # Why: the schema is a fixture-derived test identifier; every value is $-bound. +"""The fork's retained join-adoption path (the cross-release compatibility +surface), and the parser that reads the stamp it exists for. + +Before #745 the outer fork listed a nested map's derived join among its own +join's consumers, so an older release's fire put a binding for that join on +the outbox and the drain pre-created the row under ``wf:``. After #745 +no binding names a ``map_join``, so a persisted stamp that still does is the +only remaining producer — an in-flight run's row, written by a release that +predates the fix. + +``insert_fork`` therefore keeps an adoption branch, and it is the whole +in-flight compatibility path. Two pinned laws: + +``test_insert_fork_skips_an_already_run_nested_join_row_instead_of_adopting_it`` + The probe reads only a PENDING row. A row a worker already finished (or + is running) must never be adopted: the adopted children's decrements are + gated on ``jobs.status = 'pending'``, so the counter never drains, the + nested join never fires, the post-nested-map consumer keeps its reserved + dep and the run rests ``running`` with every child succeeded. With the + guard the fork takes its normal insert path and the run completes with + the TRUE children. The skipped residue is reported + (``wf-fork-join-adoption-skipped``) — after the guard it is invisible to + all three ``docs/guides/upgrading.md`` detectors on a two-level shape, + because a never-adopted row keeps ``deps_pending = 0``. + +``test_the_persisted_consumer_parser_raises_on_a_malformed_entry`` + The parser that reads that stamp fails loudly on a malformed entry — + the three required keys raise ``KeyError``, the structured sub-docs + raise ``ValueError`` — and degrades ONLY the declared deadline. It is a + cross-release parse: the docstring says what the code does, and the + raise is the leader sweep's loud refusal, not a promised silent + degrade. +""" + +from __future__ import annotations + +import json +from typing import Any + +import asyncpg +import pytest +import structlog +from pydantic import BaseModel + +import taskq.workflows._sweep as sweep_module +from taskq.workflows import ( + FlowRunner, + Promise, + StepContext, + WorkflowApp, + build, + map_source, + step, +) +from taskq.workflows._types import ConsumerBinding, _consumer_binding_doc, _consumer_bindings + +pytestmark = pytest.mark.integration + + +class Seed(BaseModel): + n: int + + +async def seeds(ctx: StepContext) -> list[Seed]: + return [Seed(n=i) for i in range(4)] + + +async def expand(ctx: StepContext, seed: Seed) -> list[str]: + return [f"s{seed.n}-{k}" for k in range(3)] + + +async def ident(ctx: StepContext, x: object) -> object: + return x + + +async def count(ctx: StepContext, xs: list[object]) -> int: + return len(xs) + + +def _app() -> WorkflowApp: + app = WorkflowApp() + + @app.workflow("adoption_of_a_finished_row") + def adoption_of_a_finished_row() -> Promise[object]: + first = map_source(step(seeds, key="seeds"), expand) + return build(step(count, map_source(first, ident), key="final")) + + return app + + +async def _one_row(conn: asyncpg.Connection, schema: str, flow_id: Any, key: str) -> dict[str, Any]: + found = await conn.fetch( + f'SELECT id, step_key, status, deps_pending, idempotency_key FROM "{schema}".jobs ' + "WHERE (metadata->>'flow_id')::uuid = $1 AND step_key = $2", + flow_id, + key, + ) + assert len(found) == 1, f"expected one {key!r} row; got {[dict(r) for r in found]}" + return dict(found[0]) + + +async def test_insert_fork_skips_an_already_run_nested_join_row_instead_of_adopting_it( + wf_pool: asyncpg.Pool, + wf_schema: str, + wf_conn: asyncpg.Connection, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The interleaving a rolling deploy can produce: the drain pre-creates + the nested join from a pre-#745 binding and a worker claims and finishes + it before the outer join's own fork probes. + + The drain row is marked ``succeeded`` directly rather than driven through + a second worker: one process cannot race itself — the in-process driver + claims a run's claimable rows in id order, and the outer join's id is + always minted before the drained row's. The row state written here is the + state the fleet produces. + + The law: the post-nested-map step must still get its result. A fork that + adopted the finished row would keep ``deps_pending = 4`` on it (its own + children's decrements are gated on ``jobs.status = 'pending'``, which the + finished row is not), so the nested join would never fire and ``final`` + would keep the dep the static insert reserved for it. The guarded probe + refuses the row, the fork inserts its own, and the run completes with the + true children. + """ + app = _app() + runner = FlowRunner(app.get("adoption_of_a_finished_row"), wf_pool, wf_schema) + flow_id = (await runner.create_flow()).flow_id + + real_drain = sweep_module.drain_outbox + + async def _muted_drain(*_a: object, **_k: object) -> int: + return 0 + + # The leader's drain lags the dispatch (sweep_interval): hold it back so + # the ordering below is the test's, not the tick's. + monkeypatch.setattr(sweep_module, "drain_outbox", _muted_drain) + + # One tick: ``seeds`` finalizes and its fork writes ``seeds.item`` plus + # ``seeds.join`` — whose consumers are empty (the #745 fix). + await runner.tick(flow_id) + + # Re-stamp the outer join with the binding an OLD release's fork wrote, so + # the fire puts the nested join on the outbox. Since #745 this is the only + # way a ``map_join`` binding exists at all. + decl = runner.compiled.nodes["seeds.join.join"] + old_binding = _consumer_binding_doc( + ConsumerBinding( + step_key="seeds.join.join", + actor=decl.actor, + queue=decl.queue, + payload={}, + failure_policy=decl.on_failure, + start_to_close=decl.start_to_close, + ) + ) + stamped = await wf_conn.execute( + f"""UPDATE "{wf_schema}".jobs + SET metadata = jsonb_set(metadata, '{{consumers}}', $2::jsonb, true) + WHERE (metadata->>'flow_id')::uuid = $1 AND step_key = 'seeds.join'""", + flow_id, + json.dumps([old_binding]), + ) + assert stamped == "UPDATE 1", stamped + + # Drive the outer map's children to terminal so the join fires, and stop + # at the instant it is claimable but not yet forked. + for _ in range(20): + outer = await _one_row(wf_conn, wf_schema, flow_id, "seeds.join") + if outer["status"] == "pending" and outer["deps_pending"] == 0: + break + await runner.tick(flow_id) + outer = await _one_row(wf_conn, wf_schema, flow_id, "seeds.join") + assert outer["status"] == "pending" and outer["deps_pending"] == 0, outer + assert ( + await wf_conn.fetchval( + f'SELECT count(*) FROM "{wf_schema}".jobs ' + "WHERE (metadata->>'flow_id')::uuid = $1 AND step_key = 'seeds.join.join'", + flow_id, + ) + == 0 + ), "the nested join must not exist before its own source forks" + + # The leader's drain lands: the pre-fix binding pre-creates the nested join + # (deps 0, no join-wait marker — claimable by anyone). + await real_drain(wf_pool, runner.wsql) + drained = await _one_row(wf_conn, wf_schema, flow_id, "seeds.join.join") + assert drained["idempotency_key"] == "wf:seeds.join.join", drained + assert drained["deps_pending"] == 0 and drained["status"] == "pending", drained + + # A worker claims it and finishes it before the outer join's fork probes: + # the join body is the default packer over no parents, so it succeeds with + # the empty collect — the pre-fix "ran on an empty join". + finished = await wf_conn.execute( + f"""UPDATE "{wf_schema}".jobs + SET status = 'succeeded', attempt = 1, result = '{{"value": []}}'::jsonb + WHERE id = $1 AND status = 'pending'""", + drained["id"], + ) + assert finished == "UPDATE 1", finished + + monkeypatch.setattr(sweep_module, "drain_outbox", real_drain) + with structlog.testing.capture_logs() as logs: + verdict = await runner.drive(flow_id, max_ticks=120) + + observed = { + "nested_join_rows": [ + dict(r) + for r in await wf_conn.fetch( + f'SELECT id, status, deps_pending, idempotency_key FROM "{wf_schema}".jobs ' + "WHERE (metadata->>'flow_id')::uuid = $1 AND step_key = 'seeds.join.join' " + "ORDER BY id", + flow_id, + ) + ], + "post_nested_map_step": [ + dict(r) + for r in await wf_conn.fetch( + f'SELECT status, deps_pending FROM "{wf_schema}".jobs ' + "WHERE (metadata->>'flow_id')::uuid = $1 AND step_key = 'final'", + flow_id, + ) + ], + } + assert verdict == "terminal", ( + "the fork adopted a nested join row that had already run, so the nested join " + "never fired, the post-nested-map step kept its reserved dep, and the run never " + "terminalised — observed " + json.dumps(observed) + ) + result = await runner.result(flow_id) + assert result == 4, (result, observed) + + # The fork wrote its OWN row (parent-scoped key) with the true children… + fork_row = next( + (r for r in observed["nested_join_rows"] if str(r["id"]) != str(drained["id"])), None + ) + assert fork_row is not None, observed + assert fork_row["idempotency_key"] == f"wf:{flow_id}:seeds.join:seeds.join.join", fork_row + assert fork_row["status"] == "succeeded" and fork_row["deps_pending"] == 0, fork_row + # …and left the already-run row untouched: skipped, never adopted. + residue = next( + (r for r in observed["nested_join_rows"] if str(r["id"]) == str(drained["id"])), None + ) + assert residue == { + "id": drained["id"], + "status": "succeeded", + "deps_pending": 0, + "idempotency_key": "wf:seeds.join.join", + }, observed + assert observed["post_nested_map_step"] == [{"status": "succeeded", "deps_pending": 0}], ( + observed + ) + + # The refusal is reported: the residue is invisible to the upgrade + # detectors once it is never adopted, so the system's own records are the + # only place an operator can find it. + skipped = [entry for entry in logs if entry.get("event") == "wf-fork-join-adoption-skipped"] + assert len(skipped) == 1, logs + assert skipped[0]["flow_id"] == str(flow_id) + assert skipped[0]["step_key"] == "seeds.join.join" + assert skipped[0]["existing_job_id"] == str(drained["id"]) + assert skipped[0]["existing_status"] == "succeeded" + assert skipped[0]["log_level"] == "warning" + + +def test_the_persisted_consumer_parser_raises_on_a_malformed_entry() -> None: + """The persisted ``consumers`` stamp's parser validates rather than + degrading — except the declared deadline. + + The three required keys are read directly: a stamp that lacks one raises + ``KeyError``. ``rate_limits``/``reservations`` and ``retry`` are + structured sub-docs whose own readers raise ``ValueError``. Only + ``start_to_close_s`` degrades to ``None`` (it is a duration hint, not a + correctness input). The parser is a cross-release boundary — an older + release can be the only writer of a ``map_join``-naming stamp — so this + is the contract the docstring must state, and it is pinned here because + the leader's re-derive arm calls it inside the sweep.""" + # One missing required key — the shape a partially written / hand-edited + # stamp produces. + with pytest.raises(KeyError): + _consumer_bindings([{"actor": "a", "queue": "q"}]) + # A wrong-typed required key raises too (never a silent coercion). + with pytest.raises(ValueError): + _consumer_bindings([{"step_key": 1, "actor": "a", "queue": "q"}]) + # A present-but-malformed structured field raises (both readers). + with pytest.raises(ValueError): + _consumer_bindings([{"step_key": "k", "actor": "a", "queue": "q", "rate_limits": "x"}]) + with pytest.raises(ValueError): + _consumer_bindings([{"step_key": "k", "actor": "a", "queue": "q", "retry": "x"}]) + # Only the declared deadline actually degrades to None. + (binding,) = _consumer_bindings( + [{"step_key": "k", "actor": "a", "queue": "q", "start_to_close_s": "nope"}] + ) + assert binding.start_to_close is None diff --git a/tests/test_wf_keyed_admission_pins.py b/tests/test_wf_keyed_admission_pins.py index d3f8040de..0c6f0d734 100644 --- a/tests/test_wf_keyed_admission_pins.py +++ b/tests/test_wf_keyed_admission_pins.py @@ -880,8 +880,19 @@ async def test_an_adopted_join_carries_the_stamp_and_feeds_depth_3( marker) must leave the adoption UPDATE shaped EXACTLY like the non-adopted join: the join-wait marker ON, the run's cohort ON. A THIRD map over that join then reads the stamp and its children ride - the run's cap — the depth-3 face.""" + the run's cap — the depth-3 face. + + The in-flight compatibility pin (#745). New code never names a + nested map's join among the outer join's consumers, so only a run + whose outer fork ran under the old code reaches adoption: its join + row carries the old binding, the fire puts it on the outbox, and the + drain pre-creates the nested join before the nested fork. The test + writes that old stamp on ``src.join`` itself; it models the + drain-first, unclaimed order (adoption of a pending row) only.""" from taskq.ratelimit.refs import KeyedReservationRef + from taskq.workflows._types import ConsumerBinding, _consumer_binding_doc + from taskq.workflows.api._graph import rate_limit_names, reservation_names + from taskq.workflows.api._runner import _node_retry_spec class Nested(BaseModel): tenant_id: str @@ -918,11 +929,48 @@ def w() -> Promise[object]: runner = FlowRunner(app.get("wf_keyed_adopted_join"), wf_pool, wf_schema) flow_id = (await runner.create_flow()).flow_id - # the nested map's join node ('src.join.join', kind map_join) is skipped by - # the static insert, so the fired depth-1 join's outbox drain pre-creates - # it (the consumer row: the flow link + the cohort stamp, no join-wait - # marker, the static-shape idempotency key). The depth-2 fork's adoption - # probe finds that row and adopts it. + # the first tick runs 'src' (the depth-1 fork). Before any 'src.item' + # child finalizes (the last one's fire reads the join's consumers), + # stamp the binding the old fork wrote for the nested map's join + # ('src.join.join', kind map_join — skipped by the static insert). The + # fired join's outbox drain then pre-creates it (the consumer row: the + # flow link + the cohort stamp, no join-wait marker, the static-shape + # idempotency key), and the depth-2 fork's adoption probe adopts it. + await runner.tick(flow_id) + children = await wf_pool.fetch( + f"""SELECT status FROM "{wf_schema}".jobs + WHERE (metadata->>'flow_id')::uuid = $1::uuid + AND metadata ? 'flow_id' AND step_key = 'src.item'""", # Why: the schema is the module fixture's validated identifier; every value is $-bound. + flow_id, + ) + assert [r["status"] for r in children] == ["pending", "pending"], ( + f"the stamp lands before any depth-1 child runs; got {children}" + ) + decl = runner.compiled.nodes["src.join.join"] + old_binding = _consumer_binding_doc( + ConsumerBinding( + step_key="src.join.join", + actor=decl.actor, + queue=decl.queue, + payload={}, + failure_policy=decl.on_failure, + start_to_close=decl.start_to_close, + rate_limits=rate_limit_names(decl.rate_limits, what="the old binding"), + reservations=reservation_names(decl.reservations, what="the old binding"), + priority=decl.priority, + retry=_node_retry_spec(decl), + ) + ) + stamped = await wf_pool.execute( + f"""UPDATE "{wf_schema}".jobs + SET metadata = jsonb_set(metadata, '{{consumers}}', $2::jsonb, true) + WHERE (metadata->>'flow_id')::uuid = $1::uuid + AND metadata ? 'flow_id' AND step_key = 'src.join'""", # Why: the schema is the module fixture's validated identifier; every value is $-bound. + flow_id, + json.dumps([old_binding]), + ) + assert stamped == "UPDATE 1", stamped + level3 = 0 for _ in range(12): await runner.tick(flow_id) @@ -941,14 +989,20 @@ def w() -> Promise[object]: # exactly the non-adopted join's — the join-wait marker and the run's # cohort, on the adopted row. - adopted = await wf_pool.fetchrow( - f"""SELECT metadata->'reservations' AS res, metadata->>'blocking_reason' AS reason + nested_rows = await wf_pool.fetch( + f"""SELECT metadata->'reservations' AS res, metadata->>'blocking_reason' AS reason, + idempotency_key FROM "{wf_schema}".jobs WHERE (metadata->>'flow_id')::uuid = $1::uuid AND metadata ? 'flow_id' AND step_key = 'src.join.join'""", # Why: the schema is the module fixture's validated identifier; every value is $-bound. flow_id, ) - assert adopted is not None + # adopted, not inserted: one row, under the drain's key (the fork's own + # insert would key it wf:{flow}:src.join:src.join.join). + assert [r["idempotency_key"] for r in nested_rows] == ["wf:src.join.join"], ( + f"the depth-2 fork adopts the drain-precreated row; got {[dict(r) for r in nested_rows]}" + ) + adopted = nested_rows[0] names = _loads(adopted["res"]) if adopted["res"] is not None else None assert names == ["run-guard:deep-9"], ( f"the ADOPTED join row carries the run's cohort; got {names}" diff --git a/tests/test_wf_map_on_join_failure_pins.py b/tests/test_wf_map_on_join_failure_pins.py new file mode 100644 index 000000000..fe8cd1fe3 --- /dev/null +++ b/tests/test_wf_map_on_join_failure_pins.py @@ -0,0 +1,319 @@ +# ruff: noqa: S608 # Why: the schema is a fixture-derived test identifier; every value is $-bound. +"""The map-on-another-fan-out's-join family's FAILURE face. + +``tests/test_wf_map_on_join_pins.py`` pins the success path of the #745 fix +(one writer per nested join, nothing pending). Nothing there makes a step +fail, and the failure path is where the topology's one novel row shape +lives: the post-map step (``final``) is a STATIC row whose dep is *reserved* +without an edge (``_runner.py::_insert_static_nodes``'s +``parent_node.is_fork_spawned_join`` branch), and the edge that releases it +is written only when the NESTED fork runs +(``_fork.py::insert_fork``'s ``wsql.fork_consumer_edges``). + +So between the consumer's birth and the nested fork's claim, ``final`` is +``pending`` with ``deps_pending = 1``, the bare ``join`` marker and ZERO edge +rows — which is also the exact shape the re-derive sweep's ``blocked`` arm +reads (``_sql_sweep.py::REDERIVE_SWEEP_SQL``: ``c.missing_parents > 0 OR +c.edge_count = 0``). Before the repair, that arm stamped it +``orphan_parent``, its ``jsonb_set`` OVERWROTE ``blocking_reason``, and both +the ``blocked`` guard (``NOT metadata @> '{"blocking_reason": +"orphan_parent"}'``) and the ``flow_fenced`` arm's own predicate +(``metadata @> '{"blocking_reason": "join"}'``) then locked the row out of +every later pass — so the truthful ``flow_dead``/``failed_parent`` +resolution, which the same statement has an arm for, was never reachable +again. + +The pinned law, in both directions: + +* a run that SUCCEEDS must leave no ``orphan_parent`` record on the consumer + that ran (the pass defers an edge-less row while another live row can + still fork and write its edge); +* a DEAD flow's consumer must carry the fence's record (``flow_dead``) or + the named dead parent (``failed_parent``), never the wiring-fault stamp + (a terminal flow's resolution belongs to the ``flow_fenced`` arm). + +The stamps are not interchangeable. ``docs/guides/runbooks.md`` documents +``'orphan_parent'`` as "an edge points at a parent row that does not exist (a +misnamed child): the join can never fire; fix the definition and re-run" — +a wiring fault with a wiring remedy — while ``'flow_dead'`` is "the fence's +record: the flow died and this join can never fire" with the retry-or-cancel +remedy ``_cli.py::stuck_lines`` derives from it. + +``test_a_route_cannot_sit_on_a_join`` pins the build refusal: a join node +declares no body, so ``route()`` refuses to attach to one — a join can +never be a ROUTE's source. The reverse placement is the one that exercises +``_route_fork``: a ``map_source`` on a ROUTE's join makes that route's fork +compute ``.join``'s consumers, and the nested map's join must not be +among them. ``tests/test_wf_map_on_join_pins.py``'s ``route`` arm drives +exactly that shape. +""" + +from __future__ import annotations + +import json +from typing import Any + +import asyncpg +import pytest +from pydantic import BaseModel + +from taskq.workflows import ( + FlowRunner, + Promise, + RouteArm, + StepContext, + WorkflowApp, + WorkflowBuildError, + build, + gather, + map_source, + route, + step, +) +from taskq.workflows._status import reconstruct_workflow_status + +#: the reasons a consumer row on a DEAD flow may honestly carry: the fence's +#: record (``'flow_dead'``) or the named dead parent (``'failed_parent'``). +TRUTHFUL_DEAD_REASONS = ("failed_parent", "flow_dead") + + +class Img(BaseModel): + n: int + + +async def seeds(ctx: StepContext) -> list[dict[str, int]]: + return [{"seed": s} for s in range(3)] + + +async def expand(ctx: StepContext, seed: dict[str, int]) -> list[str]: + if seed["seed"] == 1: + raise RuntimeError("the corpus reader failed") + return [f"s{seed['seed']}-{k}" for k in range(2)] + + +async def expand_clean(ctx: StepContext, seed: dict[str, int]) -> list[str]: + return [f"s{seed['seed']}-{k}" for k in range(2)] + + +async def on_img(ctx: StepContext, item: Img) -> str: + return f"img{item.n}" + + +async def ident(ctx: StepContext, x: object) -> object: + return x + + +async def count(ctx: StepContext, xs: list[object]) -> int: + return len(xs) + + +def _map_on_join(app: WorkflowApp, name: str, item_body: Any) -> None: + """Register the issue's topology: a map, then a map placed on that map's + join, then the static step that consumes the NESTED join.""" + body = item_body + + @app.workflow(name) + def wired() -> Promise[object]: + first = map_source(step(seeds, key="seeds"), body) + return build(step(count, map_source(first, ident), key="final")) + + +async def _final_row(conn: asyncpg.Connection, schema: str, flow_id: Any) -> asyncpg.Record | None: + return await conn.fetchrow( + f'SELECT step_key, status, deps_pending, metadata FROM "{schema}".jobs ' + "WHERE (metadata->>'flow_id')::uuid = $1 AND step_key = 'final'", + flow_id, + ) + + +def _reason(row: asyncpg.Record | None) -> str | None: + assert row is not None + # jsonb comes back as a str on the fixture's codec; tolerate both. + meta = row["metadata"] + if isinstance(meta, str): + meta = json.loads(meta) + return meta.get("blocking_reason") if isinstance(meta, dict) else None + + +@pytest.mark.integration +async def test_a_dead_flow_resolves_the_post_map_consumer_with_a_truthful_reason( + wf_pool: asyncpg.Pool, + wf_schema: str, + wf_conn: asyncpg.Connection, +) -> None: + """One outer item fails (``fail_closed``): the outer join can never fire, + so the nested fork never runs and ``final``'s reserved dep is never + released. The run itself reaches a truthful terminal (``failed``); the + ROW must say why it can never run. ``orphan_parent`` says the child edge + is misnamed and sends the operator to fix a definition (runbooks.md) — + on a run whose real remedy is the failed step's retry.""" + app = WorkflowApp() + _map_on_join(app, "map_on_join_item_failure", expand) + runner = FlowRunner(app.get("map_on_join_item_failure"), wf_pool, wf_schema) + flow_id = (await runner.create_flow()).flow_id + + assert await runner.drive(flow_id) == "terminal" + # the run's own verdict is legible: the failed child fails the root. + assert await reconstruct_workflow_status(wf_conn, runner.wsql, flow_id) == "failed" + + final = await _final_row(wf_conn, wf_schema, flow_id) + assert final is not None, "the post-map consumer is a static row — it always exists" + assert final["status"] == "pending", f"the nested fork never ran; got {dict(final)}" + reason = _reason(final) + assert reason != "orphan_parent", ( + f"THE FALSE-WIRING RECORD: the post-map consumer of a nested join rests " + f"{dict(final)} — the re-derive sweep stamped 'orphan_parent' (its blocked " + "arm's c.edge_count = 0 leg) on a row whose edge was never written because " + "the nested fork never ran, not because the edge is misnamed. The stamp " + "overwrote 'join', so the sweep's flow_fenced arm can never re-stamp it and " + "no later pass touches the row again. runbooks.md reads 'orphan_parent' as " + "'a misnamed child: fix the definition and re-run' — the operator is sent " + "after a wiring bug that does not exist." + ) + assert reason in TRUTHFUL_DEAD_REASONS, ( + f"the consumer of a nested join on a dead flow must carry the fence's record " + f"('flow_dead') or the named dead parent ('failed_parent'); got {reason!r} " + f"({dict(final)})" + ) + + +@pytest.mark.integration +async def test_a_successful_nested_map_leaves_no_orphan_parent_stamp( + wf_pool: asyncpg.Pool, + wf_schema: str, + wf_conn: asyncpg.Connection, +) -> None: + """The same stamp lands on a run that SUCCEEDS: the window between the + consumer's birth and the nested fork's consumer-edge write spans the whole + outer map, so the in-process drive's first sweep tick stamps it before any + child has finished. A completed run must not carry the misnamed-child + record on a node that ran.""" + app = WorkflowApp() + _map_on_join(app, "map_on_join_clean", expand_clean) + runner = FlowRunner(app.get("map_on_join_clean"), wf_pool, wf_schema) + flow_id = (await runner.create_flow()).flow_id + + assert await runner.drive(flow_id) == "terminal" + assert await reconstruct_workflow_status(wf_conn, runner.wsql, flow_id) == "complete" + assert await runner.result(flow_id) == 3 + + final = await _final_row(wf_conn, wf_schema, flow_id) + assert final is not None + assert final["status"] == "succeeded", dict(final) + assert _reason(final) != "orphan_parent", ( + f"A CLEAN RUN CARRIES THE WIRING-FAULT RECORD: {dict(final)} — the consumer " + "ran and the run completed, yet the row still says its child edge is " + "misnamed. Any detector keyed on metadata.blocking_reason = " + "'orphan_parent' reads this healthy run as a broken definition." + ) + + +def test_a_route_cannot_sit_on_a_join() -> None: + """A join node declares no body, so ``route()`` refuses to attach to it: + a fan-out's join can never be a ROUTE's source. The reverse placement — + a ``map_source`` on a route's join — is the shape that exercises + ``_route_fork``'s consumer filter: that route's fork builds the join's + consumers and must not name the nested map's join.""" + app = WorkflowApp() + + @app.workflow("route_on_join_refused") + def wired() -> Promise[object]: + first = map_source(step(seeds, key="seeds"), expand_clean) + return build(route(first, {Img: RouteArm(body=on_img)})) + + with pytest.raises(WorkflowBuildError, match="declares no body"): + app.get("route_on_join_refused") + + +@pytest.mark.integration +async def test_an_empty_corpus_under_a_nested_map_still_terminalises( + wf_pool: asyncpg.Pool, + wf_schema: str, + wf_conn: asyncpg.Connection, +) -> None: + """The composition this topology newly creates: a ZERO-consumer join over + a ZERO-item corpus. The outer map's body returns ``[]``, so the outer join + is born ``deps_pending = 0``, fires at birth, and (as a map source itself) + forks the nested map over the empty list — whose join is again born + ``deps_pending = 0`` but now HAS the static consumer. ``insert_fork`` + writes the consumer edge before the born-zero fire, so the born-zero nested + join is claimable, runs, and releases the consumer's reserved dep. The run + must terminalise SUCCESS with ``result() == 0``, never wedge ``running`` + with an unreleasable reserved dep.""" + + async def nothing(ctx: StepContext) -> list[dict[str, int]]: + return [] + + app = WorkflowApp() + + @app.workflow("map_on_join_empty") + def wired() -> Promise[object]: + first = map_source(step(nothing, key="seeds"), expand_clean) + return build(step(count, map_source(first, ident), key="final")) + + runner = FlowRunner(app.get("map_on_join_empty"), wf_pool, wf_schema) + flow_id = (await runner.create_flow()).flow_id + + assert await runner.drive(flow_id) == "terminal" + assert await reconstruct_workflow_status(wf_conn, runner.wsql, flow_id) == "complete" + assert await runner.result(flow_id) == 0 + + nested = await wf_conn.fetch( + f'SELECT step_key, status, deps_pending FROM "{wf_schema}".jobs ' + "WHERE (metadata->>'flow_id')::uuid = $1 AND step_key LIKE 'seeds.join%' " + "ORDER BY step_key", + flow_id, + ) + assert [(r["step_key"], r["status"], r["deps_pending"]) for r in nested] == [ + ("seeds.join", "succeeded", 0), + ("seeds.join.join", "succeeded", 0), + ], [dict(r) for r in nested] + + +@pytest.mark.integration +async def test_a_gather_on_a_map_join_is_not_stamped_in_the_in_process_drive( + wf_pool: asyncpg.Pool, + wf_schema: str, + wf_conn: asyncpg.Connection, +) -> None: + """The SCOPE of the mis-stamp above, pinned so the repair does not + overshoot: the in-process gate holds for a consumer whose producer join + already exists when the pass runs. ``FlowRunner.tick`` claims and runs + BEFORE it sweeps, so a ``gather`` reserved on a map's join gets its edge + in the same tick the map source forks, and the sweep never sees the gap. + Only a consumer of a *fork-spawned* join (``.join.join`` — created a + whole map-phase later) stays edge-less across passes. + + This is why the finding names the nested topology rather than the whole + reserved-dep path; if this test ever goes red, the stamp is general and + the repair's blast radius is wider than stated.""" + + async def expand_fan(ctx: StepContext, seed: dict[str, int]) -> list[str]: + return [f"s{seed['seed']}-{k}" for k in range(2)] + + async def total(ctx: StepContext, xs: list[object]) -> int: + return sum(len(x) if isinstance(x, list) else 1 for x in xs) + + app = WorkflowApp() + + @app.workflow("gather_on_map_join") + def wired() -> Promise[object]: + first = map_source(step(seeds, key="seeds"), expand_fan) + return build(step(total, gather([first]), key="final")) + + runner = FlowRunner(app.get("gather_on_map_join"), wf_pool, wf_schema) + flow_id = (await runner.create_flow()).flow_id + + assert await runner.drive(flow_id) == "terminal" + assert await reconstruct_workflow_status(wf_conn, runner.wsql, flow_id) == "complete" + + rows = await wf_conn.fetch( + f'SELECT step_key, status, metadata FROM "{wf_schema}".jobs ' + "WHERE (metadata->>'flow_id')::uuid = $1 AND step_key = 'gather'", + flow_id, + ) + assert len(rows) == 1, [dict(r) for r in rows] + assert _reason(rows[0]) != "orphan_parent", ( + f"the reserved-dep window is no longer closed inside a tick — the " + f"mis-stamp is not specific to a fork-spawned join: {dict(rows[0])}" + ) diff --git a/tests/test_wf_map_on_join_fleet_door.py b/tests/test_wf_map_on_join_fleet_door.py new file mode 100644 index 000000000..bc13a33db --- /dev/null +++ b/tests/test_wf_map_on_join_fleet_door.py @@ -0,0 +1,185 @@ +"""The map-on-a-join shape through the fleet's own claim seat: does the +run converge when the claim comes from ``backend.dispatch_batch`` and the +attempt from ``execute_flow_job``, instead of from ``FlowRunner.tick()``? + +The pins in ``tests/test_wf_map_on_join_pins.py`` control the drain's +placement inside one event loop. The two legs they never touch are the two +the fleet owns: the CLAIM (a workflow row must pass the dispatch fence, and +the outer join this fix leaves with ``consumers = []`` must still be +claimable by a real dispatch round) and the ATTEMPT (a fork-spawned join +row's body resolves through the fleet's execution door, not the driver's +loop). Both doors share ``_finalize_success`` — the fork/fire/drain chain +is one code path — so what this file adds is the claim seat and the +leader's belt around it, and the assertion that each join row is written +by its own source's fork (the parent-scoped key), never by the drain. + +Everything else is the production composition: the cohort's +``actor_config`` rows, ``register_worker(workflow_execution=True)``, the +leader belt's two arms (``sweep_join_rederive`` + ``drain_outbox``) — the +rig the fleet-face pins in ``test_wf_start_to_close_pins.py`` and +``test_wf_policy_fleet.py`` build. The actor rows are seeded per round from +the rows about to be dispatched rather than from the boot projection's +compilations (a harness affordance: the claim bound is the round's +population, and the placement columns are the compile's own). + +A zero-consumer join row is claimable because neither claim fence reads +``blocking_reason`` (``CLAIMABLE_NODES_SQL_TEMPLATE`` and the dispatch +fence do not name it): the join-wait marker is diagnostic, not a fence. +This file proves that from the production seat rather than by reading the +fences. + +``clean_jobs_app`` truncates the module schema per test, so this file stays +its own module: it must not be merged beside a module-scoped seed. +""" + +from __future__ import annotations + +from datetime import timedelta +from typing import TYPE_CHECKING + +import pytest + +from taskq.worker.run import register_worker +from taskq.workflows import ( + FlowRunner, + Promise, + StepContext, + WorkflowApp, + build, + map_source, + step, +) +from taskq.workflows._sweep import drain_outbox, sweep_join_rederive +from taskq.workflows._worker_execution import execute_flow_job + +if TYPE_CHECKING: + import asyncpg + + from taskq.testing.fixtures import JobsApp, ModulePgSchema + from taskq.workflows._sql import WorkflowSql + +pytestmark = pytest.mark.integration + +WORKFLOW = "fleet_door_map_on_join" + + +async def seeds(ctx: StepContext) -> list[dict[str, int]]: + return [{"seed": s} for s in range(10)] + + +async def expand(ctx: StepContext, seed: dict[str, int]) -> list[str]: + return [f"s{seed['seed']}-{k}" for k in range(5)] + + +async def ident(ctx: StepContext, x: object) -> object: + return x + + +async def count(ctx: StepContext, xs: list[object]) -> int: + return len(xs) + + +def _build(app: WorkflowApp) -> None: + @app.workflow(WORKFLOW) + def fleet_door_map_on_join() -> Promise[object]: + first = map_source(step(seeds, key="seeds"), expand) + return build(step(count, map_source(first, ident), key="final")) + + +async def _seed_actor_configs(pool: asyncpg.Pool, schema: str, flow_id: object) -> None: + # the boot projection writes these from the compile; a claim round needs + # the row for every actor it dispatches, and the fork-spawned rows share + # their source node's cohort. + await pool.execute( + f'INSERT INTO "{schema}".actor_config (actor, queue) ' # noqa: S608 # Why: fixture-derived schema identifier; every value is $-bound. + f'SELECT DISTINCT actor, queue FROM "{schema}".jobs ' + "WHERE (metadata->>'flow_id')::uuid = $1 AND status = 'pending' " + "AND deps_pending = 0 AND assignment_routed = false " + "ON CONFLICT (actor) DO NOTHING", + flow_id, + ) + + +async def _due_queues(pool: asyncpg.Pool, schema: str, flow_id: object) -> list[str]: + rows = await pool.fetch( + f'SELECT DISTINCT queue FROM "{schema}".jobs ' # noqa: S608 # Why: fixture-derived schema identifier; every value is $-bound. + "WHERE (metadata->>'flow_id')::uuid = $1 AND status = 'pending' " + "AND deps_pending = 0 AND assignment_routed = false", + flow_id, + ) + return sorted({str(r["queue"]) for r in rows}) or ["default"] + + +async def test_the_nested_join_seam_converges_through_the_fleet_claim_seat( + clean_jobs_app: JobsApp, + module_pg_schema: ModulePgSchema, + wf_sql: WorkflowSql, +) -> None: + schema = module_pg_schema.schema_name + deps = clean_jobs_app.deps + pool = deps.dispatcher_pool + + app = WorkflowApp() + _build(app) + runner = FlowRunner(app.get(WORKFLOW), pool, schema) + flow_id = (await runner.create_flow()).flow_id + + # the boot's two production registrations: the workers row (capability + # is DATA — the dispatch fence reads it) and the cohort's actor rows. + worker_id = await register_worker(pool, deps.settings, workflow_execution=True) + + rounds = 0 + claims = 0 + for _ in range(80): + rounds += 1 + await _seed_actor_configs(pool, schema, flow_id) + queues = await _due_queues(pool, schema, flow_id) + claimed = await clean_jobs_app.backend.dispatch_batch( + worker_id, queues, 10, timedelta(seconds=30) + ) + claims += len(claimed) + for job in claimed: + await execute_flow_job(pool=pool, schema=schema, worker_id=worker_id, job=job) + await sweep_join_rederive(pool, wf_sql) + await drain_outbox(pool, wf_sql) + status = await pool.fetchval( + f'SELECT status FROM "{schema}".jobs WHERE id = $1', # noqa: S608 # Why: fixture-derived schema identifier. + flow_id, + ) + if status in ("succeeded", "failed", "cancelled"): + break + + rows = await pool.fetch( + f'SELECT step_key, status, idempotency_key, metadata FROM "{schema}".jobs ' # noqa: S608 # Why: fixture-derived schema identifier. + "WHERE (metadata->>'flow_id')::uuid = $1 AND id <> $1 ORDER BY id", + flow_id, + ) + snapshot = [ + { + "step_key": r["step_key"], + "status": r["status"], + "idempotency_key": r["idempotency_key"], + } + for r in rows + ] + root_status = await pool.fetchval( + f'SELECT status FROM "{schema}".jobs WHERE id = $1', # noqa: S608 # Why: fixture-derived schema identifier. + flow_id, + ) + result = await runner.result(flow_id) + + assert root_status == "succeeded", ( + f"the fleet door did not terminalize the run after {rounds} rounds " + f"(root={root_status}); rows={snapshot}" + ) + for key in ("seeds.join", "seeds.join.join"): + found = [r for r in snapshot if r["step_key"] == key] + assert len(found) == 1, f"the join {key!r} has one row; got {found}" + assert [r for r in snapshot if r["status"] == "pending"] == [], snapshot + assert claims > 0, "the dispatch round never claimed a row — the door was never exercised" + assert result == 10, result + # the nested join's writer was the FORK, not the drain: the fork's key is + # parent-scoped, the drain's is not (the two shapes the defect hinges on). + nested_keys = {r["step_key"]: r["idempotency_key"] for r in snapshot} + assert nested_keys["seeds.join"] == f"wf:{flow_id}:seeds:seeds.join", nested_keys + assert nested_keys["seeds.join.join"] == f"wf:{flow_id}:seeds.join:seeds.join.join", nested_keys diff --git a/tests/test_wf_map_on_join_pins.py b/tests/test_wf_map_on_join_pins.py new file mode 100644 index 000000000..537ab9075 --- /dev/null +++ b/tests/test_wf_map_on_join_pins.py @@ -0,0 +1,352 @@ +# ruff: noqa: S608 # Why: the schema is a fixture-derived test identifier; every value is $-bound. +"""A map placed directly on another fan-out's join (a map's or a route's): +the nested join row ``.join.join`` has exactly ONE writer — its own +source's fork — so a run ends with exactly one such row and nothing pending. +(A route cannot sit on a join: a join declares no body, so the build refuses +it.) + +The defect (#745): the outer fork listed the nested map's derived join as +one of its join's consumers, so the outer join's fire put a binding for it +on the outbox. On the fleet the leader's drain runs on the sweep cadence +(``sweep_interval``, 30 s by default) while the dispatch claims the outer +join and forks the second map at once: the fork inserts the nested join +under ``wf:{flow}:.join:.join.join``, then the drain inserts a +second row for the same step under ``wf:.join.join``. The keys differ, +the arbiter never fires, and the second row sits ``pending`` forever beside +the real one (the run reads ``pending root=succeeded``). + +The pins place the drain the way the fleet's cadence can: muted until the +run is terminal (the issue's run), muted until the nested fork landed (the +drain arrives while the nested children run), or at the end of every tick +(it lands before the outer join is claimed — no nested row may exist yet). +The last pin states the invariant itself, whatever the drain's timing: no +join row's consumers name a ``map_join`` node, so the outbox never carries +one. +""" + +from __future__ import annotations + +from typing import Any + +import asyncpg +import pytest +from pydantic import BaseModel + +import taskq.workflows._sweep as sweep_module +from taskq.workflows import ( + FlowRunner, + Promise, + RouteArm, + StepContext, + WorkflowApp, + build, + map_source, + route, + step, +) + +pytestmark = pytest.mark.integration + +# map: a map on a map's join (the issue's run); route: a map on a route's +# join; mixed: the outer join also feeds a static step; depth3: a map on a +# map on a map's join (two nested joins). +SHAPES = ("map", "route", "mixed", "depth3") + + +class Img(BaseModel): + n: int + + +class Aud(BaseModel): + n: int + + +async def seeds(ctx: StepContext) -> list[dict[str, int]]: + return [{"seed": s} for s in range(10)] + + +async def expand(ctx: StepContext, seed: dict[str, int]) -> list[str]: + return [f"s{seed['seed']}-{k}" for k in range(5)] + + +async def media(ctx: StepContext) -> list[Img | Aud]: + return [Img(n=i) if i % 2 else Aud(n=i) for i in range(6)] + + +async def on_img(ctx: StepContext, x: Img) -> str: + return f"img{x.n}" + + +async def on_aud(ctx: StepContext, x: Aud) -> str: + return f"aud{x.n}" + + +async def ident(ctx: StepContext, x: object) -> object: + return x + + +async def count(ctx: StepContext, xs: list[object]) -> int: + return len(xs) + + +async def add(ctx: StepContext, xs: list[object], n: int) -> int: + return len(xs) + n + + +def _wire(app: WorkflowApp, shape: str) -> tuple[list[str], int]: + """Register ``map_on_{shape}_join``; returns the nested join step keys + (outermost first) and the expected final value.""" + if shape == "map": + + @app.workflow("map_on_map_join") + def map_on_map_join() -> Promise[object]: + first = map_source(step(seeds, key="seeds"), expand) + return build(step(count, map_source(first, ident), key="final")) + + return ["seeds.join.join"], 10 + + if shape == "route": + + @app.workflow("map_on_route_join") + def map_on_route_join() -> Promise[object]: + routed = route(step(media, key="media"), {Img: RouteArm(body=on_img), Aud: on_aud}) + return build(step(count, map_source(routed, ident), key="final")) + + return ["media.join.join"], 6 + + if shape == "mixed": + + @app.workflow("map_on_mixed_join") + def map_on_mixed_join() -> Promise[object]: + first = map_source(step(seeds, key="seeds"), expand) + sib = step(count, first, key="sib") + return build(step(add, map_source(first, ident), sib, key="final")) + + return ["seeds.join.join"], 20 + + @app.workflow("map_on_depth3_join") + def map_on_depth3_join() -> Promise[object]: + first = map_source(step(seeds, key="seeds"), expand) + return build(step(count, map_source(map_source(first, ident), ident), key="final")) + + return ["seeds.join.join", "seeds.join.join.join"], 10 + + +async def _flow_rows(conn: asyncpg.Connection, schema: str, flow_id: Any) -> list[asyncpg.Record]: + return await conn.fetch( + f'SELECT step_key, status, idempotency_key FROM "{schema}".jobs ' + "WHERE (metadata->>'flow_id')::uuid = $1 AND id <> $1 ORDER BY id", + flow_id, + ) + + +async def _nested_count( + conn: asyncpg.Connection, schema: str, flow_id: Any, step_key: str, *, waiting: bool = False +) -> int: + return int( + await conn.fetchval( + f'SELECT count(*) FROM "{schema}".jobs ' + "WHERE (metadata->>'flow_id')::uuid = $1 AND step_key = $2" + + (" AND status = 'pending' AND deps_pending > 0" if waiting else ""), + flow_id, + step_key, + ) + or 0 + ) + + +def _assert_one_writer(rows: list[asyncpg.Record], nested: list[str], flow_id: Any) -> None: + for key in nested: + found = [dict(r) for r in rows if r["step_key"] == key] + assert len(found) == 1, f"the nested join {key!r} has one writer; got rows {found}" + assert found[0]["status"] == "succeeded", found + # WHO wrote it: the fork keys parent-scoped + # (``wf:{flow}:{parent}:{join}``), the outbox drain keys bare + # (``wf:{join}``). Without this leg the in-process ordering is green + # under the defect too — the drain mints the row, the nested fork + # ADOPTS it, and the surplus collapses back to one. + parent = key.removesuffix(".join") + expected = f"wf:{flow_id}:{parent}:{key}" + assert found[0]["idempotency_key"] == expected, ( + f"the nested join {key!r} must be written by its own source's fork " + f"(key {expected!r}); got {found[0]['idempotency_key']!r} — the " + f"unparented 'wf:{key}' is the outbox drain's key" + ) + pending = [dict(r) for r in rows if r["status"] == "pending"] + assert pending == [], f"a terminal run holds no pending row; got {pending}" + + +@pytest.mark.parametrize( + ("shape", "drain_lands"), + [(s, "after_terminal") for s in SHAPES] + [(s, "while_live") for s in ("map", "route")], +) +async def test_a_late_drain_never_mints_a_second_nested_join_row( + shape: str, + drain_lands: str, + wf_pool: asyncpg.Pool, + wf_schema: str, + wf_conn: asyncpg.Connection, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The fleet's usual ordering: the second fork lands before the + leader's drain. The drain lands either after the run is terminal (the + issue's run) or while the nested children still run (children that + outlive the sweep interval). Either way each nested join has exactly + one row and the terminal run has no pending row.""" + app = WorkflowApp() + nested, expected = _wire(app, shape) + runner = FlowRunner(app.get(f"map_on_{shape}_join"), wf_pool, wf_schema) + flow_id = (await runner.create_flow()).flow_id + + real_drain = sweep_module.drain_outbox + muted_calls = 0 + + async def _muted_drain(*_a: object, **_k: object) -> int: + nonlocal muted_calls + muted_calls += 1 + return 0 + + # the leader's drain lags the dispatch (the sweep cadence): mute it — the + # run completes without it (the consumers' deps are released by the fork's + # edges; the drain is the belt). + monkeypatch.setattr(sweep_module, "drain_outbox", _muted_drain) + if drain_lands == "while_live": + for _ in range(50): + await runner.tick(flow_id) + if await _nested_count(wf_conn, wf_schema, flow_id, nested[0], waiting=True): + break + assert await _nested_count(wf_conn, wf_schema, flow_id, nested[0], waiting=True) == 1 + # the leader's tick lands while the nested children run; every + # later tick drains too. + monkeypatch.setattr(sweep_module, "drain_outbox", real_drain) + assert await runner.drive(flow_id) == "terminal" + monkeypatch.setattr(sweep_module, "drain_outbox", real_drain) + # the mute works only while tick() reads drain_outbox off the module at + # call time; a hoisted import would leave it inert and these arms would + # silently run the in-process order. + assert muted_calls > 0, "tick() never called the muted drain" + assert await runner.result(flow_id) == expected + await real_drain(wf_pool, runner.wsql) # the leader's late tick + + _assert_one_writer(await _flow_rows(wf_conn, wf_schema, flow_id), nested, flow_id) + + +@pytest.mark.parametrize("shape", SHAPES) +async def test_the_in_process_drive_keeps_one_nested_join_row( + shape: str, wf_pool: asyncpg.Pool, wf_schema: str, wf_conn: asyncpg.Connection +) -> None: + """The in-process ordering (the drain runs at the end of every tick, + before the outer join is claimed): one row per nested join, nothing + pending, the right answer — and the row is the FORK'S (the parent-scoped + idempotency key), never the drain's bare one. + + That last leg is what makes the arm deletion-sensitive: under the #745 + defect this ordering is green on every other assertion, because the drain + mints the nested join first and the nested fork ADOPTS it, collapsing the + surplus back to one row.""" + app = WorkflowApp() + nested, expected = _wire(app, shape) + runner = FlowRunner(app.get(f"map_on_{shape}_join"), wf_pool, wf_schema) + flow_id = (await runner.create_flow()).flow_id + assert await runner.drive(flow_id) == "terminal" + assert await runner.result(flow_id) == expected + await sweep_module.drain_outbox(wf_pool, runner.wsql) + + _assert_one_writer(await _flow_rows(wf_conn, wf_schema, flow_id), nested, flow_id) + + +@pytest.mark.parametrize("shape", ["map", "route"]) +async def test_an_early_drain_never_creates_the_nested_join_before_its_fork( + shape: str, wf_pool: asyncpg.Pool, wf_schema: str, wf_conn: asyncpg.Connection +) -> None: + """The other ordering: the drain lands between the outer join's fire + and its claim. No row for the nested join may exist yet — its source + (the outer join) has not forked. A drain-made one is pending with + deps_pending 0 and no join-wait marker, so any worker can claim it + before the fork; it then succeeds empty, the fork adopts the terminal + row, and ``final``'s reserved dep is never released (the run wedges + ``running``, or ``final`` runs on the empty join).""" + app = WorkflowApp() + nested, expected = _wire(app, shape) + outer_join = nested[0].removesuffix(".join") + runner = FlowRunner(app.get(f"map_on_{shape}_join"), wf_pool, wf_schema) + flow_id = (await runner.create_flow()).flow_id + + fired = False + for _ in range(50): + await runner.tick(flow_id) # the tick ends with the drain + fired = bool( + await wf_conn.fetchval( + f'SELECT count(*) FROM "{wf_schema}".jobs ' + "WHERE (metadata->>'flow_id')::uuid = $1 AND step_key = $2 " + "AND status = 'pending' AND deps_pending = 0", + flow_id, + outer_join, + ) + ) + if fired: + break + assert fired, f"the outer join {outer_join!r} never fired" + premature = await _flow_rows(wf_conn, wf_schema, flow_id) + assert [dict(r) for r in premature if r["step_key"] == nested[0]] == [], ( + f"the nested join {nested[0]!r} exists before its source {outer_join!r} forked" + ) + + assert await runner.drive(flow_id) == "terminal" + assert await runner.result(flow_id) == expected + _assert_one_writer(await _flow_rows(wf_conn, wf_schema, flow_id), nested, flow_id) + + +@pytest.mark.parametrize("shape", SHAPES) +async def test_no_binding_names_a_nested_join( + shape: str, wf_pool: asyncpg.Pool, wf_schema: str, wf_conn: asyncpg.Connection +) -> None: + """The invariant, not its symptoms: a join row's only writer is its + own source's fork, so no join row's consumers name a ``map_join`` + node and the outbox never carries one — with no outbox row there is + no drained row to race the fork, in any order. The outbox carries + exactly the static consumers of the joins (``mixed``: the outer + join still feeds ``sib``, through its one static row).""" + app = WorkflowApp() + _nested, expected = _wire(app, shape) + runner = FlowRunner(app.get(f"map_on_{shape}_join"), wf_pool, wf_schema) + flow_id = (await runner.create_flow()).flow_id + assert await runner.drive(flow_id) == "terminal" + assert await runner.result(flow_id) == expected + + nodes = runner.compiled.nodes + map_joins = {k for k, n in nodes.items() if n.kind == "map_join"} + static_consumers = sorted( + k for k, n in nodes.items() if n.kind != "map_join" and set(n.parents) & map_joins + ) + # the binding doc carries no kind: key the check on step keys. + named = await wf_conn.fetch( + f"SELECT j.step_key AS join_key, c->>'step_key' AS consumer " + f"FROM \"{wf_schema}\".jobs j, jsonb_array_elements(j.metadata->'consumers') c " + "WHERE (j.metadata->>'flow_id')::uuid = $1 AND j.metadata ? 'consumers' " + "ORDER BY 1, 2", + flow_id, + ) + bindings = [(r["join_key"], r["consumer"]) for r in named] + assert [b for b in bindings if b[1] in map_joins] == [], ( + f"a join row's consumers name a map_join node: {bindings}" + ) + outbox = [ + r["consumer_step_key"] + for r in await wf_conn.fetch( + f'SELECT consumer_step_key FROM "{wf_schema}".wf_outbox ' + "WHERE flow_id = $1 ORDER BY consumer_step_key", + flow_id, + ) + ] + assert outbox == static_consumers, ( + f"the outbox carries exactly the joins' static consumers; got {outbox}" + ) + if shape == "mixed": + assert [c for j, c in bindings if j == "seeds.join"] == ["sib"], bindings + sib = await wf_conn.fetch( + f'SELECT idempotency_key FROM "{wf_schema}".jobs ' + "WHERE (metadata->>'flow_id')::uuid = $1 AND step_key = 'sib'", + flow_id, + ) + assert [r["idempotency_key"] for r in sib] == ["wf:sib"], sib