Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/design/seam-audit-matrix.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
149 changes: 149 additions & 0 deletions docs/guides/upgrading.md
Original file line number Diff line number Diff line change
Expand Up @@ -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>.join` rows: the nested fork's own, and a second one the outbox
drain inserted under `idempotency_key = 'wf:<step_key>'`. 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 <id>` 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,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor (nice to have, not blocking): A few notes on the recovery queries. They're read-only, so this is about operators getting the right answer.

  • Cost: all three scan jobs on a leading-wildcard LIKE. Query 3's EXISTS legs compare metadata->>'flow_id' as text, so they can't use jobs_wf_flow_nodes_idx, which is on the ::uuid cast. Casting both sides to uuid and adding a line saying to run these on a replica or off-peak would help on a large table.
  • Coverage: an empty outer map that drains, gets claimed early and is then adopted with + 0 stays succeeded with deps_pending = 0, so this query misses it. I reached that by reading the code; I didn't run it. Also, query 3 can't see an adopted stray because only one row exists. Query 2 is what catches that, and one sentence saying so would help readers.
  • Scope: "runs whose outer fork ran on an earlier release" undersells the risk at depth 3 and deeper. An intermediate fork that runs on an old worker brings the old binding back at that level.

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 <run_id>`. 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 <run_id>` (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
Expand Down
84 changes: 67 additions & 17 deletions src/taskq/workflows/_fork.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand All @@ -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"]

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand All @@ -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,
Expand Down
63 changes: 56 additions & 7 deletions src/taskq/workflows/_sql_sweep.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 (
Expand All @@ -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
Expand All @@ -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
),
Expand Down Expand Up @@ -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
Expand Down
Loading