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
7 changes: 6 additions & 1 deletion docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -1654,12 +1654,17 @@ the placeholder in SQL files and `_IDENT_RE`-validated interpolation in Python.
### `jobs` vs `job_attempts` vs `job_events`

- `jobs` is the hot table. Columns hold the current snapshot: `status`,
`attempt`, `locked_by_worker`, `error_class`, `result`, etc.
`attempt`, `claim_epoch`, `locked_by_worker`, `error_class`, `result`, etc.
- `job_attempts` records every execution attempt with outcome, duration, and
error. Pruned via `ON DELETE CASCADE`.
- `job_events` records every state transition and cancel request as an immutable
audit log. Also pruned via `ON DELETE CASCADE`.

`attempt` is the displayed, saturating retry counter; `claim_epoch` is its
non-saturating fencing twin, a `bigint` bumped by exactly 1 per claim and
fenced on by every terminal/ownership write. See
`01.00.18_02_pre_claim_epoch.sql` for the invariant.

This separation keeps the `jobs` hot path narrow (fewer columns updated per
transaction) while providing full per-attempt forensics in `job_attempts` and
a queryable audit trail in `job_events`.
Expand Down
2 changes: 1 addition & 1 deletion docs/guides/cancellation.md
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ One shape carries no marker, deliberately: a worker can crash after a cancel was

Cancellation does not consume retry budget. Once a job transitions to `cancelled` or `abandoned`, it is immediately terminal and will not be retried, regardless of `max_attempts` or `retry_kind`.

An interruption by shutdown spends the interrupted attempt: the claim's increment is **not** refunded (the attempt started executing, so it counts against `max_attempts`; `interrupt_count` on the row counts the release). A job interrupted on every deploy therefore walks toward `max_attempts` one attempt per deploy; give such jobs `schedule_to_close` (the release never parks a row past it) or checkpoint via progress state. This keeps the attempt epoch monotonic, which is what fences a delayed (zombie) handler's terminal write out of a re-dispatched attempt.
An interruption by shutdown spends the interrupted attempt: the claim's increment is **not** refunded (the attempt started executing, so it counts against `max_attempts`; `interrupt_count` on the row counts the release). A job interrupted on every deploy therefore walks toward `max_attempts` one attempt per deploy; give such jobs `schedule_to_close` (the release never parks a row past it) or checkpoint via progress state. This keeps the attempt epoch monotonic, which is what fences a delayed (zombie) handler's terminal write out of a re-dispatched attempt; the fence itself is the row's `claim_epoch` beside the attempt number (see `01.00.18_02_pre_claim_epoch.sql` for the invariant).

This is distinct from a `TimeoutError` or unhandled exception, both of which go through the normal retry decision logic (`decide_after_failure`) and may reschedule the job if budget remains.

Expand Down
2 changes: 2 additions & 0 deletions docs/guides/retries.md
Original file line number Diff line number Diff line change
Expand Up @@ -577,6 +577,8 @@ A crash is indistinguishable from the worker simply vanishing, so the fleet lear

A graceful shutdown is different in mechanism but not in cost: the worker announces it is leaving, in-flight actors observe the cancel event, and any job still running when the grace periods expire is *released* back to the fleet. The interrupted attempt is spent, not refunded: it did start executing, and refunding it would let the re-run share the attempt epoch with the process that is still shutting down. The re-run claims the next attempt number, and `interrupt_count` on the job row carries the aggregate. A deploy therefore trades one attempt of budget for the guarantee that no attempt epoch is ever shared between a dying process and its replacement.

The guarantee has a second leg: the row's `claim_epoch`, a non-saturating internal claim identity bumped by exactly 1 per claim, which every terminal write fences on beside the attempt number, so two executions can never hold the same fence, even once the displayed `attempt` counter parks at the smallint ceiling. See `01.00.18_02_pre_claim_epoch.sql` for the invariant.

The operator controls for how quickly a crash is *detected* are the heartbeat knobs: `heartbeat_interval` (how often a worker proves it is alive), `lock_lease` (how long a claim survives without one: the startup-validated invariant `lock_lease >= 4 × heartbeat_interval` keeps a slow-but-live worker from being reclaimed), and the per-actor `heartbeat_timeout`. Tightening them reclaims crashed work sooner at the cost of reclaiming slow-but-alive workers. See [workers.md](workers.md) for the settings and [ops.md](ops.md) for the `crashed` and `abandoned` state definitions.

---
Expand Down
38 changes: 38 additions & 0 deletions docs/guides/upgrading.md
Original file line number Diff line number Diff line change
Expand Up @@ -2209,3 +2209,41 @@ and `ConcurrencyReservation.acquire` grew an optional `timeout=` forward to
`asyncpg.Pool.acquire` for callers with a budget in hand (default `None`
keeps the previous unbounded-acquire behaviour for callers that wrap their
own).

### The terminal-write fence survives the attempt ceiling

> **Unreleased.** Correctness fix with one additive pre migration
> (`01.00.18_02_pre_claim_epoch.sql`; apply it before rolling the code, as
> with every `pre` file).

At the attempt ceiling the terminal writes could record the wrong outcome.
The displayed `attempt` counter is stamped by the claim with a saturating
increment (`LEAST(attempt + 1, 32767)`), so a row parked at the smallint
ceiling (`retry_kind='indefinite'` climbs there after enough retries) claims
at 32767 again and again. A reclaim plus a redispatch to the same worker
then gave the stale execution and the live one the same
`(status, locked_by_worker, attempt)` fence: the stale execution's
`mark_succeeded` won, the job recorded the stale result, and the live
execution's write read `WorkerOwnershipMismatch`. The displayed counter
keeps its saturating semantics on purpose (the clamped row must still run,
and its budget arms must still land), so the fix adds a second, non-saturating
fence column instead of touching it.

Every row now carries `claim_epoch bigint NOT NULL DEFAULT 0`
(`jobs` and `jobs_archive`; `ADD COLUMN` with a constant default, metadata
only, no table rewrite). The dispatch claim bumps it by exactly 1 per claim,
and every terminal/ownership write that already fenced on `attempt` gained
the conjunct `claim_epoch = <the writer's own claim view>`:
`mark_succeeded`, `mark_failed`, `mark_cancelled`, `mark_retry`,
`mark_snoozed`, both `mark_retry_after` variants, and `mark_interrupted`,
every arm of the multi-arm arbiters included.

The invariant itself lives in the migration file. The operational shape: the
value the writer presents is the `claim_epoch` of the `JobRow` its own
dispatch returned (and of the actor context, `ctx.claim_epoch`, which the
shutdown release reads); a caller that cannot present one (a `None` bind)
no-ops through the same machinery the attempt fence uses, the same
cannot-prove-it doctrine both fences apply. The in-memory testing backend
mirrors the semantics exactly. No operator action is needed beyond applying
the migration first; the column is never read by user-facing surfaces and
the displayed `attempt` counter is unchanged.
7 changes: 6 additions & 1 deletion src/taskq/backend/_dispatch_sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -999,7 +999,12 @@
-- is absorbed by the ON CONFLICT guard every job_attempts insert
-- carries, so the audit trail keeps the first record of the number
-- and no terminal path raises.
attempt = LEAST(j.attempt + 1, 32767)
-- The displayed counter saturates on purpose; the FENCE must not:
-- the +1 epoch stamp below is what keeps two executions of one row
-- from ever sharing a fence. See 01.00.18_02_pre_claim_epoch.sql
-- for the invariant.
attempt = LEAST(j.attempt + 1, 32767),
claim_epoch = j.claim_epoch + 1
-- The UPDATE finds its rows through a one-shot id array, not a
-- FROM-clause join against eligible: a join's strategy is the
-- planner's choice, and at shallow depths the whole-backlog seq scan
Expand Down
37 changes: 34 additions & 3 deletions src/taskq/backend/_protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -980,6 +980,16 @@ class JobRow:
``taskq/backend/_dispatch_sql.py``. Trailing default: rows
materialised before the marker existed read producer-placed.
"""
claim_epoch: int = 0
"""The row's non-saturating claim-epoch fence: bumped by exactly 1 on
every successful dispatch claim, left untouched by the reclaim sweeps
that clear locks, and fenced on by equality (against the writer's own
claim view) by every terminal/ownership write that fences on
``attempt``. Trailing default: rows materialised before the column
existed read 0, the one epoch no claim can ever stamp (the first
claim of any row stamps 1). The invariant lives in
01.00.18_02_pre_claim_epoch.sql.
"""


@dataclass(frozen=True, slots=True)
Expand Down Expand Up @@ -1868,6 +1878,7 @@ async def mark_succeeded(
*,
result_bytes: bytes | None = None,
attempt: int | None = None,
claim_epoch: int | None = None,
) -> bool:
"""Mark a job succeeded, computing ``result_expires_at`` at completion.

Expand All @@ -1881,6 +1892,15 @@ async def mark_succeeded(
present the epoch, also no-ops: a terminal write that cannot
prove which attempt it terminates must not terminate any attempt.

*claim_epoch* is the non-saturating claim-identity fence, the
``claim_epoch`` value of the handler's own claim view. The
displayed attempt counter saturates at the smallint ceiling,
where a reclaim plus a redispatch would hand the stale handler
and the live one the same (worker, attempt) pair; the claim
epoch keeps advancing, so the stale write can only no-op.
``None`` never satisfies the equality, the same
cannot-prove-it doctrine *attempt* applies.

The result reaches the backend in exactly one of two forms:
``result``, the actor's result dict, which the backend serializes
exactly once (orjson via :func:`taskq._json.dumps_jsonb_str`,
Expand Down Expand Up @@ -1919,6 +1939,7 @@ async def mark_succeeded_with_conn(
*,
result_bytes: bytes | None = None,
attempt: int | None = None,
claim_epoch: int | None = None,
) -> bool:
"""Mark a job succeeded using the supplied connection.

Expand All @@ -1932,8 +1953,8 @@ async def mark_succeeded_with_conn(
``result`` / ``result_bytes`` follow the same two-form contract as
:meth:`mark_succeeded`, pass exactly one, or neither for a NULL
result. ``fallback_result_ttl`` follows the same resolution rule
as :meth:`mark_succeeded`. ``attempt`` follows the same
attempt-epoch fence as :meth:`mark_succeeded`.
as :meth:`mark_succeeded`. ``attempt`` and ``claim_epoch`` follow
the same fencing as :meth:`mark_succeeded`.
"""
...

Expand All @@ -1947,6 +1968,7 @@ async def mark_failed_or_retry(
progress_state: dict[str, object] | None = None,
*,
attempt: int | None = None,
claim_epoch: int | None = None,
) -> JobRow:
"""Mark a running job failed, or schedule a retry *retry_delay* later.

Expand Down Expand Up @@ -1983,6 +2005,7 @@ async def mark_cancelled(
progress_state: dict[str, object] | None = None,
*,
attempt: int | None = None,
claim_epoch: int | None = None,
) -> bool: ...

async def write_cancel_escalation(
Expand Down Expand Up @@ -2010,13 +2033,17 @@ async def mark_snoozed(
progress_state: dict[str, object] | None = None,
outcome: SnoozeOutcome = "snoozed",
attempt: int | None = None,
claim_epoch: int | None = None,
denial_reason: DenialReason = "capacity",
) -> Literal["scheduled", "failed", "noop"]:
"""Release a running job back to the queue without consuming retry
budget.

*attempt* is the attempt-identity epoch, see
:meth:`mark_succeeded`; a fenced-out write returns ``"noop"``.
*claim_epoch* is the claim-identity fence, see
:meth:`mark_succeeded`; it applies to all three arms, the two
terminal deadline exits included.

A non-terminal snooze/denial writes NO ``job_attempts`` /
``job_events`` rows, it is admission control or a voluntary
Expand Down Expand Up @@ -2073,6 +2100,7 @@ async def mark_retry_after(
progress_seq: int = 0,
progress_state: dict[str, object] | None = None,
attempt: int | None = None,
claim_epoch: int | None = None,
) -> Literal["scheduled", "failed:DeadlineExceeded", "failed:MaxAttemptsExceeded", "noop"]: ...

async def mark_interrupted(
Expand All @@ -2084,6 +2112,7 @@ async def mark_interrupted(
hold: timedelta,
progress_seq: int = 0,
progress_state: dict[str, object] | None = None,
claim_epoch: int | None = None,
) -> Literal["pending", "scheduled", "failed:DeadlineExceeded", "noop"]:
"""Release a running attempt this worker cannot finish because the
process is going away.
Expand Down Expand Up @@ -2121,7 +2150,9 @@ async def mark_interrupted(
*attempt* is the attempt-identity epoch, see
:meth:`mark_succeeded`. Here it is required, not optional: a
release that cannot prove which attempt it is handing back must
not touch the row (``"noop"``).
not touch the row (``"noop"``). *claim_epoch* is the
claim-identity fence, see :meth:`mark_succeeded`, applied to
both arms, the deadline exit included.
"""
...

Expand Down
1 change: 1 addition & 0 deletions src/taskq/backend/_records.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,7 @@ def _job_row_from_record(rec: "asyncpg.Record") -> JobRow:
retry_backoff=rec["retry_backoff"], # type: ignore[arg-type] # Why: DB text column; domain is CHECK-constrained to the Literal's values
retry_jitter=rec["retry_jitter"],
assignment_routed=rec["assignment_routed"],
claim_epoch=rec["claim_epoch"],
)


Expand Down
40 changes: 26 additions & 14 deletions src/taskq/backend/_sql_fragments.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,26 +87,38 @@
# attempt epoch the caller presents, and a fence conjunct edited in one
# statement but not its siblings is exactly the drift that lets a stale
# handler's write land (see the attempt-epoch fencing note in
# backend/_sql_templates.py's render()). The aliased spelling is the multi-arm
# arbiters' (they resolve ids through the params CTE); the bound spelling is
# the single-row mark_succeeded / mark_failed / mark_cancelled UPDATEs, which
# bind the worker id and the attempt epoch directly at per-statement
# positions, so the bound fragment is a function of the attempt bind's
# placeholder number ($8 in mark_succeeded / mark_failed, $5 in
# mark_cancelled). Substituted by name into the templates so the rendered
# statements stay byte-identical to the hand-maintained conjuncts; the
# in-memory twin mirrors the predicate through its own _fenced helper
# backend/_sql_templates.py's render()). Both spellings also carry the
# claim-epoch conjunct: the row's claim_epoch must equal the epoch the
# caller was dispatched under, so a write from a claim that dispatch has
# since superseded (a retry re-claimed the row) no-ops even when the
# attempt number survives the ceiling wrap. The epoch is a non-saturating
# bigint stamped only by the dispatch claim, and a NULL bind never matches
# (SQL equality against NULL is NULL, so a caller that presents no claim
# view fences itself out rather than matching every row). The aliased
# spelling is the multi-arm arbiters' (they resolve ids through the params
# CTE, which binds the caller's claim_epoch beside the attempt); the bound
# spelling is the single-row mark_succeeded / mark_failed / mark_cancelled
# UPDATEs, which bind the worker id and the two epochs directly at
# per-statement positions, so the bound fragment is a function of the
# attempt bind's placeholder number ($8 in mark_succeeded / mark_failed,
# $5 in mark_cancelled) and the epoch bind's ($9 and $6, each directly
# after its attempt). Substituted by name into the templates so the
# rendered statements stay byte-identical to the hand-maintained conjuncts;
# the in-memory twin mirrors the predicate through its own _fenced helper
# (testing/_terminal.py), the same one-predicate discipline on the Python
# side.
JOB_FENCE_SQL: Final[str] = (
"AND j.status = 'running'\n"
" AND j.locked_by_worker = (SELECT worker_id FROM params)\n"
" AND j.attempt = (SELECT attempt FROM params)"
" AND j.attempt = (SELECT attempt FROM params)\n"
" AND j.claim_epoch = (SELECT claim_epoch FROM params)"
)

# The bound spelling's attempt-epoch placeholder, substituted at the three
# single-row call sites ($8 in mark_succeeded / mark_failed, $5 in
# mark_cancelled): one fence text, per-statement bind positions.
# The bound spelling's attempt-epoch and claim-epoch placeholders,
# substituted at the three single-row call sites ($8/$9 in mark_succeeded /
# mark_failed, $5/$6 in mark_cancelled): one fence text, per-statement bind
# positions.
JOB_FENCE_BOUND_SQL: Final[str] = (
"id = $1 AND status = 'running' AND locked_by_worker = $2 AND attempt = ${attempt_bind}"
"id = $1 AND status = 'running' AND locked_by_worker = $2 "
"AND attempt = ${attempt_bind} AND claim_epoch = ${epoch_bind}"
)
Loading
Loading