diff --git a/docs/architecture.md b/docs/architecture.md index c4e4fac9c..03929c89a 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -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`. diff --git a/docs/guides/cancellation.md b/docs/guides/cancellation.md index 8d4c29c67..062252c19 100644 --- a/docs/guides/cancellation.md +++ b/docs/guides/cancellation.md @@ -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. diff --git a/docs/guides/retries.md b/docs/guides/retries.md index df504984a..9adcde74e 100644 --- a/docs/guides/retries.md +++ b/docs/guides/retries.md @@ -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. --- diff --git a/docs/guides/upgrading.md b/docs/guides/upgrading.md index f13bd9bad..7167207b9 100644 --- a/docs/guides/upgrading.md +++ b/docs/guides/upgrading.md @@ -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 = `: +`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. diff --git a/src/taskq/backend/_dispatch_sql.py b/src/taskq/backend/_dispatch_sql.py index 005c5cc2f..0ea6f0593 100644 --- a/src/taskq/backend/_dispatch_sql.py +++ b/src/taskq/backend/_dispatch_sql.py @@ -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 diff --git a/src/taskq/backend/_protocol.py b/src/taskq/backend/_protocol.py index 37606e497..57187852a 100644 --- a/src/taskq/backend/_protocol.py +++ b/src/taskq/backend/_protocol.py @@ -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) @@ -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. @@ -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`, @@ -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. @@ -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`. """ ... @@ -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. @@ -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( @@ -2010,6 +2033,7 @@ 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 @@ -2017,6 +2041,9 @@ async def mark_snoozed( *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 @@ -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( @@ -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. @@ -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. """ ... diff --git a/src/taskq/backend/_records.py b/src/taskq/backend/_records.py index fceefff46..7fa875f8e 100644 --- a/src/taskq/backend/_records.py +++ b/src/taskq/backend/_records.py @@ -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"], ) diff --git a/src/taskq/backend/_sql_fragments.py b/src/taskq/backend/_sql_fragments.py index 3c21598be..e0736998a 100644 --- a/src/taskq/backend/_sql_fragments.py +++ b/src/taskq/backend/_sql_fragments.py @@ -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}" ) diff --git a/src/taskq/backend/_sql_templates.py b/src/taskq/backend/_sql_templates.py index 4e06c8e23..27c3c4eb6 100644 --- a/src/taskq/backend/_sql_templates.py +++ b/src/taskq/backend/_sql_templates.py @@ -86,6 +86,7 @@ "snooze_count", "rate_limit_blocked_count", "interrupt_count", + "claim_epoch", "retry_base_seconds", "retry_cap_seconds", "retry_backoff", @@ -98,8 +99,9 @@ # (enqueue_batch_fast_fixup) from the server clock, never the caller's # Python clock, or carries a DDL default the COPY lets apply # (created_at/scheduled_at now(), NULL schedule_to_close / -# result_expires_at, and the zero-defaulted denial counters, which an -# enqueued job has no reason to pre-set). ``status`` is NOT omitted: the +# result_expires_at, the zero-defaulted denial counters, and +# claim_epoch, which only the dispatch claim ever assigns, an enqueued +# row is born at epoch 0). ``status`` is NOT omitted: the # COPY writes COPY_ENQUEUE_STATUS explicitly so the INSERT trigger never # fires for a row whose runnability the fixup has not yet decided (see # enqueue_batch_fast_fixup). COPY_FROM_COLUMNS stays intact: it is @@ -113,6 +115,7 @@ "snooze_count", "rate_limit_blocked_count", "interrupt_count", + "claim_epoch", } ) COPY_ENQUEUE_COLUMNS: Final[tuple[str, ...]] = tuple( @@ -261,6 +264,16 @@ def render(schema: str) -> SqlTemplates: # through the same machinery as the worker fence (rowcount 0 → # False / WorkerOwnershipMismatch / "noop", no publish). # + # CLAIM-EPOCH FENCING: every fenced template carries one conjunct + # deeper still, ``claim_epoch = $m``, the writer's own claim view + # (JobRow.claim_epoch, threaded beside attempt from every call + # site). Attempt saturates at the smallint ceiling (the claim's + # LEAST clamp, _dispatch_sql.py); the epoch does not, so a stale + # handler and the live one can never share a fence. NULL never + # satisfies the equality, the same cannot-prove-it doctrine the + # attempt conjunct applies. See 01.00.18_02_pre_claim_epoch.sql + # for the invariant. + # # duration_ms is computed IN the statement from the same # database-written timestamp pair Python used to receive and # multiply back, but server-side, with exact numeric arithmetic @@ -289,7 +302,7 @@ def render(schema: str) -> SqlTemplates: ), progress_seq = $5, progress_state = CASE WHEN $6::jsonb IS NOT NULL THEN COALESCE(progress_state, '{{}}'::jsonb) || $6::jsonb ELSE progress_state END - WHERE {JOB_FENCE_BOUND_SQL.format(attempt_bind=8)} + WHERE {JOB_FENCE_BOUND_SQL.format(attempt_bind=8, epoch_bind=9)} RETURNING * ), holder AS ( SELECT id FROM "{s}".workers WHERE id = $2 FOR KEY SHARE @@ -328,7 +341,7 @@ def render(schema: str) -> SqlTemplates: error_traceback = $5, progress_seq = $6, progress_state = CASE WHEN $7::jsonb IS NOT NULL THEN COALESCE(progress_state, '{{}}'::jsonb) || $7::jsonb ELSE progress_state END - WHERE {JOB_FENCE_BOUND_SQL.format(attempt_bind=8)} + WHERE {JOB_FENCE_BOUND_SQL.format(attempt_bind=8, epoch_bind=9)} RETURNING * ), holder AS ( SELECT id FROM "{s}".workers WHERE id = $2 FOR KEY SHARE @@ -398,7 +411,8 @@ def render(schema: str) -> SqlTemplates: -- scheduled_at and every deadline comparison read it, so the -- retried and deadline arms partition exactly. GREATEST($3::interval, {MIN_DEFERRAL_INTERVAL_SQL}) AS effective_delay, - $9::int AS attempt + $9::int AS attempt, + $10::bigint AS claim_epoch ), retried AS ( UPDATE "{s}".jobs j @@ -527,7 +541,7 @@ def render(schema: str) -> SqlTemplates: ELSE '{CANCEL_ORIGIN_COOPERATIVE}' END, progress_seq = $3, progress_state = CASE WHEN $4::jsonb IS NOT NULL THEN COALESCE(progress_state, '{{}}'::jsonb) || $4::jsonb ELSE progress_state END - WHERE {JOB_FENCE_BOUND_SQL.format(attempt_bind=5)} + WHERE {JOB_FENCE_BOUND_SQL.format(attempt_bind=5, epoch_bind=6)} RETURNING * ), holder AS ( SELECT id FROM "{s}".workers WHERE id = $2 FOR KEY SHARE @@ -720,7 +734,8 @@ def render(schema: str) -> SqlTemplates: -- record of a starved-out job names WHICH starvation it was -- (saturation vs a store outage), the observability the row -- counters alone cannot carry. - $9::text AS denial_reason + $9::text AS denial_reason, + $10::bigint AS claim_epoch ), snoozed AS ( UPDATE "{s}".jobs j @@ -916,7 +931,8 @@ def render(schema: str) -> SqlTemplates: $3::interval AS delay, $4::int AS progress_seq, $5::jsonb AS progress_state, - $6::int AS attempt + $6::int AS attempt, + $7::bigint AS claim_epoch ), snoozed AS ( UPDATE "{s}".jobs j @@ -1168,7 +1184,8 @@ def render(schema: str) -> SqlTemplates: GREATEST($3::interval, {MIN_DEFERRAL_INTERVAL_SQL}) AS effective_delay, $4::int AS progress_seq, $5::jsonb AS progress_state, - $6::int AS attempt + $6::int AS attempt, + $7::bigint AS claim_epoch ), snoozed AS ( UPDATE "{s}".jobs j @@ -1384,7 +1401,8 @@ def render(schema: str) -> SqlTemplates: THEN GREATEST($4::interval, {MIN_DEFERRAL_INTERVAL_SQL}) ELSE interval '0' END AS effective_hold, $5::int AS progress_seq, - $6::jsonb AS progress_state + $6::jsonb AS progress_state, + $7::bigint AS claim_epoch ), released AS ( UPDATE "{s}".jobs j diff --git a/src/taskq/backend/_terminal.py b/src/taskq/backend/_terminal.py index ad2597843..fedd4b770 100644 --- a/src/taskq/backend/_terminal.py +++ b/src/taskq/backend/_terminal.py @@ -32,12 +32,13 @@ Invariants preserved verbatim from the three-statement form: * The UPDATE stays the single arbiter: its fencing WHERE (``status = - 'running' AND locked_by_worker = $2``, now one epoch deeper with the - attempt conjunct ``AND attempt = $k``, the handler's dispatch-time - job-row attempt snapshot threaded from every call site: a stale - attempt's write after a same-worker reclaim/redispatch no-ops exactly - like a different worker's late write, fencing stale attempts so their - terminal writes cannot land on rows they no longer own) + 'running' AND locked_by_worker = $2``, two epochs deeper with the + attempt conjunct ``AND attempt = $k`` and the claim-epoch conjunct + ``AND claim_epoch = $m``, the handler's own claim view, threaded from + every call site, so a stale execution's write after a reclaim and + redispatch no-ops exactly like a different worker's late write, at the + attempt ceiling included; the invariant lives in + ``01.00.18_02_pre_claim_epoch.sql``) decides everything, and an empty ``upd`` CTE makes the INSERT CTEs insert nothing and the final ``SELECT`` return no row, the exact ``rec is None`` / ``WorkerOwnershipMismatch`` / ``False`` contract, @@ -319,6 +320,7 @@ async def _mark_succeeded_on_conn( *, result_bytes: bytes | None = None, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: """Terminal success write: ONE statement (UPDATE + attempt + event). @@ -338,6 +340,15 @@ async def _mark_succeeded_on_conn( 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 caller's own claim view (JobRow + .claim_epoch). The attempt counter saturates at the smallint ceiling, + where a reclaim plus a redispatch leaves the stale handler and the + live one holding the SAME (worker, attempt) pair, the stale write + would otherwise win; the epoch always advances, so the stale write + can only no-op. ``None`` binds NULL, which never satisfies the + equality, the same cannot-prove-it doctrine *attempt* applies. + ``result_bytes`` carries the caller's own orjson encoding of *result* (the worker consumer serializes exactly once and passes the bytes); the dict form serializes here. The two are mutually exclusive. @@ -399,6 +410,7 @@ async def _mark_succeeded_on_conn( _progress_jsonb_escaped(progress_state), fallback_result_ttl, attempt, + claim_epoch, ) if rec is None: return False @@ -427,6 +439,7 @@ async def _mark_succeeded( *, result_bytes: bytes | None = None, attempt: int | None = None, + claim_epoch: int | None = None, acquire_timeout: float = DEFAULT_TERMINAL_POOL_ACQUIRE_TIMEOUT_S, ) -> bool: # No explicit transaction: the fused statement is atomic by itself (a @@ -450,6 +463,7 @@ async def _mark_succeeded( max_result_bytes, result_bytes=result_bytes, attempt=attempt, + claim_epoch=claim_epoch, ) @@ -467,6 +481,7 @@ async def _mark_failed_or_retry( progress_state: dict[str, object] | None = None, *, attempt: int | None = None, + claim_epoch: int | None = None, acquire_timeout: float = DEFAULT_TERMINAL_POOL_ACQUIRE_TIMEOUT_S, ) -> JobRow: if retry_delay is None: @@ -479,6 +494,7 @@ async def _mark_failed_or_retry( progress_seq, progress_state, attempt=attempt, + claim_epoch=claim_epoch, acquire_timeout=acquire_timeout, ) return await _mark_retry( @@ -491,6 +507,7 @@ async def _mark_failed_or_retry( progress_seq, progress_state, attempt=attempt, + claim_epoch=claim_epoch, acquire_timeout=acquire_timeout, ) @@ -505,6 +522,7 @@ async def _mark_failed( progress_state: dict[str, object] | None, *, attempt: int | None = None, + claim_epoch: int | None = None, acquire_timeout: float = DEFAULT_TERMINAL_POOL_ACQUIRE_TIMEOUT_S, ) -> JobRow: # No explicit transaction, see _mark_succeeded. The rare @@ -528,6 +546,7 @@ async def _mark_failed( progress_seq, _progress_jsonb_escaped(progress_state), attempt, + claim_epoch, ) if rec is None: actual = await _select_owner(conn, sql, job_id) @@ -557,6 +576,7 @@ async def _mark_retry( progress_state: dict[str, object] | None, *, attempt: int | None = None, + claim_epoch: int | None = None, acquire_timeout: float = DEFAULT_TERMINAL_POOL_ACQUIRE_TIMEOUT_S, ) -> JobRow: branch: SqlOutcomeBranch @@ -577,6 +597,7 @@ async def _mark_retry( progress_seq, _progress_jsonb_escaped(progress_state), attempt, + claim_epoch, ) if rec is None: actual = await _select_owner(conn, sql, job_id) @@ -633,6 +654,7 @@ async def _mark_cancelled( progress_state: dict[str, object] | None = None, *, attempt: int | None = None, + claim_epoch: int | None = None, acquire_timeout: float = DEFAULT_TERMINAL_POOL_ACQUIRE_TIMEOUT_S, ) -> bool: async with pool.acquire(timeout=acquire_timeout) as conn: @@ -643,6 +665,7 @@ async def _mark_cancelled( progress_seq, _progress_jsonb_escaped(progress_state), attempt, + claim_epoch, ) if rec is None: return False @@ -771,6 +794,7 @@ async def _mark_snoozed( outcome: SnoozeOutcome = "snoozed", *, attempt: int | None = None, + claim_epoch: int | None = None, denial_reason: DenialReason = "capacity", acquire_timeout: float = DEFAULT_TERMINAL_POOL_ACQUIRE_TIMEOUT_S, ) -> Literal["scheduled", "failed", "noop"]: @@ -798,6 +822,7 @@ async def _mark_snoozed( outcome, attempt, denial_reason, + claim_epoch, ) if rec is None: return "noop" @@ -876,6 +901,7 @@ async def _mark_retry_after( progress_state: dict[str, object] | None = None, *, attempt: int | None = None, + claim_epoch: int | None = None, acquire_timeout: float = DEFAULT_TERMINAL_POOL_ACQUIRE_TIMEOUT_S, ) -> Literal["scheduled", "failed:DeadlineExceeded", "failed:MaxAttemptsExceeded", "noop"]: branch: SqlOutcomeBranch @@ -893,6 +919,7 @@ async def _mark_retry_after( progress_seq, _progress_jsonb_escaped(progress_state), attempt, + claim_epoch, ) if rec is None: return "noop" @@ -987,6 +1014,7 @@ async def _mark_interrupted( hold: timedelta, progress_seq: int = 0, progress_state: dict[str, object] | None = None, + claim_epoch: int | None = None, acquire_timeout: float = DEFAULT_TERMINAL_POOL_ACQUIRE_TIMEOUT_S, ) -> Literal["pending", "scheduled", "failed:DeadlineExceeded", "noop"]: """Release a running attempt this worker cannot finish (process going @@ -1009,6 +1037,7 @@ async def _mark_interrupted( hold, progress_seq, _progress_jsonb_escaped(progress_state), + claim_epoch, ) if rec is None: # Fenced out, the row moved (reclaim, a terminal write, or an diff --git a/src/taskq/backend/postgres.py b/src/taskq/backend/postgres.py index e7bb041e9..5d63867e1 100644 --- a/src/taskq/backend/postgres.py +++ b/src/taskq/backend/postgres.py @@ -512,6 +512,7 @@ async def mark_succeeded_with_conn( *, result_bytes: bytes | None = None, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: return await _mark_succeeded_on_conn( conn, @@ -525,6 +526,7 @@ async def mark_succeeded_with_conn( self._deps.settings.result_max_bytes, result_bytes=result_bytes, attempt=attempt, + claim_epoch=claim_epoch, ) async def mark_succeeded( @@ -538,6 +540,7 @@ async def mark_succeeded( *, result_bytes: bytes | None = None, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: return await _mark_succeeded( self._worker_pool, @@ -551,6 +554,7 @@ async def mark_succeeded( self._deps.settings.result_max_bytes, result_bytes=result_bytes, attempt=attempt, + claim_epoch=claim_epoch, acquire_timeout=self._deps.settings.dispatcher_command_timeout, ) @@ -564,6 +568,7 @@ async def mark_failed_or_retry( progress_state: dict[str, object] | None = None, *, attempt: int | None = None, + claim_epoch: int | None = None, ) -> JobRow: return await _mark_failed_or_retry( self._worker_pool, @@ -575,6 +580,7 @@ async def mark_failed_or_retry( progress_seq, progress_state, attempt=attempt, + claim_epoch=claim_epoch, acquire_timeout=self._deps.settings.dispatcher_command_timeout, ) @@ -586,6 +592,7 @@ async def mark_cancelled( progress_state: dict[str, object] | None = None, *, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: # Why _worker_pool (supersession of the original heartbeat routing, # which had no documented rationale, original v0.1.0 wiring): the @@ -616,6 +623,7 @@ async def mark_cancelled( progress_seq, progress_state, attempt=attempt, + claim_epoch=claim_epoch, acquire_timeout=self._deps.settings.dispatcher_command_timeout, ) @@ -660,6 +668,7 @@ 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"]: return await _mark_snoozed( @@ -673,6 +682,7 @@ async def mark_snoozed( progress_state=progress_state, outcome=outcome, attempt=attempt, + claim_epoch=claim_epoch, denial_reason=denial_reason, acquire_timeout=self._deps.settings.dispatcher_command_timeout, ) @@ -687,6 +697,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"]: return await _mark_retry_after( self._worker_pool, @@ -698,6 +709,7 @@ async def mark_retry_after( progress_seq=progress_seq, progress_state=progress_state, attempt=attempt, + claim_epoch=claim_epoch, acquire_timeout=self._deps.settings.dispatcher_command_timeout, ) @@ -710,6 +722,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"]: return await _mark_interrupted( self._worker_pool, @@ -720,6 +733,7 @@ async def mark_interrupted( hold=hold, progress_seq=progress_seq, progress_state=progress_state, + claim_epoch=claim_epoch, acquire_timeout=self._deps.settings.dispatcher_command_timeout, ) diff --git a/src/taskq/context.py b/src/taskq/context.py index 6f620b373..cf3e22375 100644 --- a/src/taskq/context.py +++ b/src/taskq/context.py @@ -88,6 +88,13 @@ class JobContext[P: BaseModel]: actor: str queue: str attempt: int + # The non-saturating claim-identity fence, the row's claim_epoch at + # dispatch: the displayed attempt counter saturates at the smallint + # ceiling, so a reclaim plus a redispatch there would hand a stale + # handler and the live one the same (worker, attempt) pair. The + # backend's terminal writes fence on this epoch beside attempt; the + # shutdown release threads it from here. + claim_epoch: int worker_id: UUID payload: P jobs: SubJobEnqueuer diff --git a/src/taskq/migrations/01.00.18_02_pre_claim_epoch.sql b/src/taskq/migrations/01.00.18_02_pre_claim_epoch.sql new file mode 100644 index 000000000..7a6539391 --- /dev/null +++ b/src/taskq/migrations/01.00.18_02_pre_claim_epoch.sql @@ -0,0 +1,75 @@ +-- Non-saturating claim-epoch fence for the terminal/ownership writes. +-- +-- The claim stamps the DISPLAYED attempt counter with a saturating +-- increment (``attempt = LEAST(j.attempt + 1, 32767)``, +-- backend/_dispatch_sql.py) so a row parked at the smallint ceiling +-- cannot turn a whole claim round into a smallint-out-of-range driver +-- error. At the ceiling the value stops advancing, which means the +-- terminal-write fences (``status = 'running' AND locked_by_worker = $n +-- AND attempt = $k``) can no longer tell a stale execution from the live +-- one: a reclaim plus a redispatch to the same worker leaves both the +-- stale handler and the live handler holding the same +-- (worker, attempt) pair, and the stale execution's mark_succeeded wins +-- while the live one is fenced out. The displayed counter must keep its +-- saturating, consumer-visible semantics, so the fix is a SECOND column: +-- +-- claim_epoch is the row's non-saturating claim counter. Every +-- successful dispatch claim bumps it by exactly 1 (bigint: it does not +-- saturate, no reachable workload approaches 2^63 claims of one row). +-- Every terminal/ownership write that fences on ``attempt`` gains the +-- equality conjunct ``claim_epoch = $n`` and binds the epoch from its +-- own claim view (JobRow.claim_epoch, the value the dispatch round +-- returned). Because fences compare EQUALITY, never magnitude, the +-- epoch's only requirement is uniqueness across consecutive claims of +-- the same row, and +1 per claim provides that without bound. +-- +-- INVARIANT: between two terminal/ownership writes that both fence on +-- claim_epoch, a successful claim of the same row MUST have bumped it. +-- The reclaim sweeps that clear locks (sweep 1's re-pend/crash/cancel +-- arms, the heartbeat isolate) deliberately leave claim_epoch +-- untouched: the reclaim itself hands the row back, and the NEXT claim +-- bumps it. A stale writer's epoch therefore goes stale at the moment a +-- new claim exists, on every path, including at the attempt ceiling +-- where attempt alone can no longer distinguish the two executions. +-- Writer order per row is: claim (bump) -> maybe reclaim (leave) -> +-- claim (bump) -> terminal write (fence on the epoch its own claim +-- returned). No writer except the dispatch claim ever assigns the +-- column. +-- +-- The in-memory testing backend mirrors the semantics exactly +-- (taskq/testing/_dispatch.py bumps on claim, taskq/testing/_terminal.py +-- fences on equality), so the equivalence tier exercises the same +-- fence. +-- +-- ROLLING DEPLOY: additive with a default, applied while old pods run: +-- the previous release's statements name their columns explicitly and +-- never read this one. This release's claim bumps it unconditionally, +-- which is safe against old workers too: an old worker's terminal write +-- never references the column, and the fence it does not carry is the +-- defect this migration ships the fix for. Forward-only; there is no +-- down migration. +-- +-- OPS NOTE (locks): ADD COLUMN with a non-volatile default is +-- metadata-only on PG >= 11 (no table rewrite; the default is stored in +-- pg_attribute and read from there), so this add does not stall a +-- fleet. Existing rows read 0, which is correct rather than merely +-- harmless: fences compare equality, so epoch 0 is simply the one +-- epoch no claim of a pre-migration row can ever be stamped with (the +-- first post-migration claim stamps 1), and a pre-migration stale +-- writer (which binds no epoch at all) is fenced out by its missing +-- attempt proof exactly as before. +ALTER TABLE "{schema}".jobs + ADD COLUMN IF NOT EXISTS claim_epoch bigint NOT NULL DEFAULT 0; +ALTER TABLE "{schema}".jobs_archive + ADD COLUMN IF NOT EXISTS claim_epoch bigint NOT NULL DEFAULT 0; + +COMMENT ON COLUMN "{schema}".jobs.claim_epoch IS + 'Non-saturating claim-epoch fence. Bumped by exactly 1 on every ' + 'successful dispatch claim; the reclaim sweeps that clear locks leave ' + 'it untouched (the next claim bumps it). Every terminal/ownership ' + 'write that fences on attempt also fences on this column equalling ' + 'the epoch from its own claim view, so a reclaim plus redispatch can ' + 'never leave a stale execution and the live one sharing a fence, ' + 'including at the attempt ceiling where the displayed attempt counter ' + 'saturates. Fences compare equality, never magnitude; writers other ' + 'than the dispatch claim never assign this column.'; diff --git a/src/taskq/retry.py b/src/taskq/retry.py index 50badba24..52d6a45db 100644 --- a/src/taskq/retry.py +++ b/src/taskq/retry.py @@ -973,14 +973,16 @@ async def safe_mark_failed_or_retry( *, log: structlog.stdlib.BoundLogger | None = None, attempt: int | None = None, + claim_epoch: int | None = None, ) -> JobRow | None: """Wrap mark_failed_or_retry, catching WorkerOwnershipMismatch . Returns the persisted JobRow on success, or None on ownership mismatch (signals the caller to skip the on_retry_exhausted hook). *attempt* is the attempt-identity epoch threaded from the handler's job-row - snapshot, see ``Backend.mark_failed_or_retry``; a fenced-out epoch - surfaces here as the same None a worker-fence miss produces. + snapshot, and *claim_epoch* the claim-identity epoch, see + ``Backend.mark_failed_or_retry``; a fenced-out epoch surfaces here as + the same None a worker-fence miss produces. """ logger: structlog.stdlib.BoundLogger = ( log if log is not None else structlog.get_logger("taskq.retry") @@ -994,6 +996,7 @@ async def safe_mark_failed_or_retry( progress_seq=progress_seq, progress_state=progress_state, attempt=attempt, + claim_epoch=claim_epoch, ) except WorkerOwnershipMismatch as exc: logger.warning( diff --git a/src/taskq/testing/_dispatch.py b/src/taskq/testing/_dispatch.py index 6d19f27b7..3146e9a24 100644 --- a/src/taskq/testing/_dispatch.py +++ b/src/taskq/testing/_dispatch.py @@ -417,6 +417,13 @@ async def _dispatch_batch( # number is absorbed by _write_attempt's keep-the-first- # record guard, exactly PG's ON CONFLICT doctrine. attempt=min(row.attempt + 1, SMALLINT_MAX), + # The non-saturating claim-identity fence, the twin of + # PG's ``claim_epoch = j.claim_epoch + 1`` in the same + # statement: the displayed counter saturates at the + # ceiling, the epoch does not, and every terminal/ownership + # write that fences on attempt also fences on this column + # equalling the epoch of the writer's own claim view. + claim_epoch=row.claim_epoch + 1, ) self._jobs[row.id] = updated # Mirrors PG's claim (backend/_dispatch.py): no job_events row , diff --git a/src/taskq/testing/_runner.py b/src/taskq/testing/_runner.py index 77b7e5798..b624d1bc5 100644 --- a/src/taskq/testing/_runner.py +++ b/src/taskq/testing/_runner.py @@ -1056,6 +1056,7 @@ async def run_until_drained(backend: "InMemoryBackend", *, cancel_polling: bool error_info=error_info, retry_delay=None, attempt=job.attempt, + claim_epoch=job.claim_epoch, ) # Production's generic-exception escape routes this failure # through _handle_generic_exception and applies the batch diff --git a/src/taskq/testing/_terminal.py b/src/taskq/testing/_terminal.py index 10c3983f4..438d088e8 100644 --- a/src/taskq/testing/_terminal.py +++ b/src/taskq/testing/_terminal.py @@ -127,20 +127,35 @@ def _round_trip_progress_state(state: dict[str, object]) -> dict[str, object]: raise exc from None -def _fenced(row: JobRow, worker_id: UUID, attempt: int | None) -> bool: +def _fenced( + row: JobRow, + worker_id: UUID, + attempt: int | None, + claim_epoch: int | None, +) -> bool: """True when *row* fails the terminal-write fence: the SQL arms' - ``status = 'running' AND locked_by_worker = ... AND attempt = ...`` - conjuncts (the ``JOB_FENCE_SQL`` fragment in backend/_sql_fragments.py, - the bound spelling's ``JOB_FENCE_BOUND_SQL`` single-row form). + ``status = 'running' AND locked_by_worker = ... AND attempt = ... + AND claim_epoch = ...`` conjuncts (the ``JOB_FENCE_SQL`` fragment in + backend/_sql_fragments.py, the bound spelling's ``JOB_FENCE_BOUND_SQL`` + single-row form). One helper, not a hand-restated predicate per method: the fence is the invariant every terminal write leans on, a conjunct edited in one twin method but not its siblings would let a stale handler's write land - exactly where the SQL fence refuses it. ``attempt is None`` (a caller - that cannot present the epoch) never matches, mirroring PG's NULL bind - never satisfying the equality. + exactly where the SQL fence refuses it. ``attempt is None`` or + ``claim_epoch is None`` (a caller that cannot present the epochs) never + matches, mirroring PG's NULL binds never satisfying the equality. The + claim epoch rides beside the attempt because at the attempt ceiling, + where the displayed counter stops advancing, the non-saturating claim + epoch is what keeps a stale handler's write off the re-dispatched + attempt. """ - return row.status != "running" or row.locked_by_worker != worker_id or row.attempt != attempt + return ( + row.status != "running" + or row.locked_by_worker != worker_id + or row.attempt != attempt + or row.claim_epoch != claim_epoch + ) async def _mark_succeeded( @@ -154,6 +169,7 @@ async def _mark_succeeded( *, result_bytes: bytes | None = None, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: # Caller-input validation precedes the state fence, matching the PG # terminal's order (its guards run before the fencing UPDATE): a @@ -211,7 +227,7 @@ async def _mark_succeeded( # The fence folds the missing row into the same check (_fenced's # docstring carries the conjuncts' contract, the attempt-epoch # mirror included). - if row is None or _fenced(row, worker_id, attempt): + if row is None or _fenced(row, worker_id, attempt, claim_epoch): return False now = self._clock.now() # Mirror the PG COALESCE: stored (operator-owned) result_ttl applied at @@ -280,6 +296,7 @@ async def _mark_succeeded_with_conn( *, result_bytes: bytes | None = None, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: return await _mark_succeeded( self, @@ -291,6 +308,7 @@ async def _mark_succeeded_with_conn( fallback_result_ttl, result_bytes=result_bytes, attempt=attempt, + claim_epoch=claim_epoch, ) @@ -304,6 +322,7 @@ async def _mark_failed_or_retry( progress_state: dict[str, object] | None = None, *, attempt: int | None = None, + claim_epoch: int | None = None, ) -> JobRow: row = self._jobs.get(job_id) if row is None: @@ -324,7 +343,11 @@ async def _mark_failed_or_retry( if row.status != "running": raise WorkerOwnershipMismatch(job_id, worker_id, row.locked_by_worker) - if row.locked_by_worker != worker_id or row.attempt != attempt: + if ( + row.locked_by_worker != worker_id + or row.attempt != attempt + or row.claim_epoch != claim_epoch + ): raise WorkerOwnershipMismatch(job_id, worker_id, row.locked_by_worker) if retry_delay is not None: @@ -494,13 +517,14 @@ async def _mark_cancelled( progress_state: dict[str, object] | None = None, *, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: row = self._jobs.get(job_id) if row is None: return False # Attempt-epoch fence, one predicate shared with the sibling writes # (_fenced's docstring). - if _fenced(row, worker_id, attempt): + if _fenced(row, worker_id, attempt, claim_epoch): return False now = self._clock.now() @@ -752,6 +776,7 @@ 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"]: # Caller-input validation precedes the state fence, matching the PG @@ -768,7 +793,7 @@ async def _mark_snoozed( row = self._jobs.get(job_id) # The fence folds the missing row into the same check; a fenced-out # epoch returns "noop" through the same machinery as the worker fence. - if row is None or _fenced(row, worker_id, attempt): + if row is None or _fenced(row, worker_id, attempt, claim_epoch): return "noop" now = self._clock.now() @@ -991,11 +1016,12 @@ 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"]: row = self._jobs.get(job_id) # Attempt-epoch fence, one predicate shared with the sibling writes # (_fenced's docstring); a fenced-out epoch returns "noop". - if row is None or _fenced(row, worker_id, attempt): + if row is None or _fenced(row, worker_id, attempt, claim_epoch): return "noop" now = self._clock.now() @@ -1262,6 +1288,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"]: row = self._jobs.get(job_id) # The fence mirrors the SQL arm conjunct-for-conjunct: the shared @@ -1269,7 +1296,11 @@ async def _mark_interrupted( # extra cancel conjunct (cancel_phase = 0: an operator cancel in # flight wins and reads back as "noop", since a row with a cancel # timestamp set is cancelled, never re-available). - if row is None or _fenced(row, worker_id, attempt) or row.cancel_phase != CancelPhase.NONE: + if ( + row is None + or _fenced(row, worker_id, attempt, claim_epoch) + or row.cancel_phase != CancelPhase.NONE + ): return "noop" now = self._clock.now() diff --git a/src/taskq/testing/actor.py b/src/taskq/testing/actor.py index 31ce96b0b..40243d05d 100644 --- a/src/taskq/testing/actor.py +++ b/src/taskq/testing/actor.py @@ -193,6 +193,7 @@ async def mark_succeeded( *, result_bytes: bytes | None = None, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: self.mark_succeeded_calls.append((job_id, worker_id, result, result_bytes)) return self._land_terminal_write(job_id, "succeeded") @@ -209,6 +210,7 @@ async def mark_succeeded_with_conn( *, result_bytes: bytes | None = None, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: return await self.mark_succeeded( job_id, @@ -219,6 +221,7 @@ async def mark_succeeded_with_conn( fallback_result_ttl, result_bytes=result_bytes, attempt=attempt, + claim_epoch=claim_epoch, ) async def mark_failed_or_retry( @@ -231,6 +234,7 @@ async def mark_failed_or_retry( progress_state: dict[str, object] | None = None, *, attempt: int | None = None, + claim_epoch: int | None = None, ) -> JobRow: self.mark_failed_or_retry_calls.append( { @@ -250,6 +254,7 @@ async def mark_cancelled( progress_state: dict[str, object] | None = None, *, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: self.mark_cancelled_calls.append( { @@ -285,6 +290,7 @@ 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"]: self.mark_snoozed_calls.append( @@ -311,6 +317,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"]: self.mark_retry_after_calls.append( { @@ -333,6 +340,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"]: self.mark_interrupted_calls.append( { diff --git a/src/taskq/testing/fixtures.py b/src/taskq/testing/fixtures.py index 1f471f5b8..ef72d74de 100644 --- a/src/taskq/testing/fixtures.py +++ b/src/taskq/testing/fixtures.py @@ -213,6 +213,7 @@ async def __call__( backend: InMemoryBackend, job_id: JobId | UUID | None = ..., attempt: int = ..., + claim_epoch: int = ..., snooze_count: int = ..., cancel_event: asyncio.Event | None = ..., actor: str = ..., @@ -311,6 +312,13 @@ async def run_actor( backend: InMemoryBackend, job_id: JobId | UUID | None = None, attempt: int = 1, + # The same one-claim default attempt carries: a fresh dispatch + # hands the actor attempt 1 and epoch 1, so the context's epoch + # fence is satisfiable against a row the fixture's caller just + # dispatched. A caller that overrides either value must keep the + # pair consistent with the row it dispatched (fences compare the + # epoch for equality; a stale one no-ops the terminal write). + claim_epoch: int = 1, snooze_count: int = 0, cancel_event: asyncio.Event | None = None, actor: str = "test_actor", @@ -338,6 +346,7 @@ async def run_actor( actor=actor, queue=queue, attempt=attempt, + claim_epoch=claim_epoch, snooze_count=snooze_count, payload=ctx_payload, cancel_event=evt, diff --git a/src/taskq/testing/in_memory.py b/src/taskq/testing/in_memory.py index 0ea91b1cd..dd350a56b 100644 --- a/src/taskq/testing/in_memory.py +++ b/src/taskq/testing/in_memory.py @@ -574,6 +574,7 @@ async def mark_succeeded( *, result_bytes: bytes | None = None, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: return await _mark_succeeded( self, @@ -585,6 +586,7 @@ async def mark_succeeded( fallback_result_ttl, result_bytes=result_bytes, attempt=attempt, + claim_epoch=claim_epoch, ) async def mark_succeeded_with_conn( @@ -599,6 +601,7 @@ async def mark_succeeded_with_conn( *, result_bytes: bytes | None = None, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: return await _mark_succeeded_with_conn( self, @@ -611,6 +614,7 @@ async def mark_succeeded_with_conn( fallback_result_ttl, result_bytes=result_bytes, attempt=attempt, + claim_epoch=claim_epoch, ) async def mark_failed_or_retry( @@ -623,6 +627,7 @@ async def mark_failed_or_retry( progress_state: dict[str, object] | None = None, *, attempt: int | None = None, + claim_epoch: int | None = None, ) -> JobRow: return await _mark_failed_or_retry( self, @@ -633,6 +638,7 @@ async def mark_failed_or_retry( progress_seq, progress_state, attempt=attempt, + claim_epoch=claim_epoch, ) async def mark_cancelled( @@ -643,9 +649,16 @@ async def mark_cancelled( progress_state: dict[str, object] | None = None, *, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: return await _mark_cancelled( - self, job_id, worker_id, progress_seq, progress_state, attempt=attempt + self, + job_id, + worker_id, + progress_seq, + progress_state, + attempt=attempt, + claim_epoch=claim_epoch, ) async def write_cancel_escalation( @@ -675,6 +688,7 @@ 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"]: return await _mark_snoozed( @@ -687,6 +701,7 @@ async def mark_snoozed( progress_state=progress_state, outcome=outcome, attempt=attempt, + claim_epoch=claim_epoch, denial_reason=denial_reason, ) @@ -700,6 +715,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"]: return await _mark_retry_after( self, @@ -710,6 +726,7 @@ async def mark_retry_after( progress_seq=progress_seq, progress_state=progress_state, attempt=attempt, + claim_epoch=claim_epoch, ) async def mark_interrupted( @@ -721,6 +738,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"]: return await _mark_interrupted( self, @@ -730,6 +748,7 @@ async def mark_interrupted( hold=hold, progress_seq=progress_seq, progress_state=progress_state, + claim_epoch=claim_epoch, ) # ── Attempt history ──────────────────────────────────────────────── diff --git a/src/taskq/testing/job_context.py b/src/taskq/testing/job_context.py index cbd84ddbb..c386c6047 100644 --- a/src/taskq/testing/job_context.py +++ b/src/taskq/testing/job_context.py @@ -47,6 +47,9 @@ class JobContext[P: BaseModel]: actor: str queue: str attempt: int + # Mirrors the production context's claim-identity fence (see + # taskq.context.JobContext.claim_epoch). + claim_epoch: int payload: P cancel_event: asyncio.Event worker_id: UUID diff --git a/src/taskq/testing/pg.py b/src/taskq/testing/pg.py index 92773438c..c258dea77 100644 --- a/src/taskq/testing/pg.py +++ b/src/taskq/testing/pg.py @@ -233,12 +233,12 @@ async def create_running_job( await conn.execute( f"""INSERT INTO "{schema}".jobs ( id, actor, queue, payload, max_attempts, retry_kind, - status, priority, attempt, scheduled_at, + status, priority, attempt, claim_epoch, scheduled_at, locked_by_worker, lock_expires_at, started_at, last_heartbeat_at, cancel_phase, cancel_requested_at, schedule_to_close ) VALUES ( $1, $2, $3, $4::jsonb, $5, $6, - 'running', 0, $7, clock_timestamp(), + 'running', 0, $7, $13, clock_timestamp(), $8, $9, clock_timestamp(), clock_timestamp(), $10, $11, $12 )""", # noqa: S608 @@ -254,6 +254,18 @@ async def create_running_job( cancel_phase, cancel_requested_at, schedule_to_close, + # The epoch seed models the refund-free history this helper + # represents: a row that reached attempt N through N claims, each + # of which stamped attempt and claim_epoch together, so the row's + # epoch is N and the fences under test are satisfiable by + # presenting the row's own values. attempt and claim_epoch are + # distinct counters that DO diverge in production (the attempt + # saturates at the smallint ceiling and non-terminal releases + # refund it; the epoch only ever increments, so the row's epoch is + # always >= its attempt); the equality fences treat a diverged row + # identically, and a test that needs a diverged shape seeds the + # two columns separately. + attempt, ) if with_events: detail = dumps_str( diff --git a/src/taskq/worker/_consumer.py b/src/taskq/worker/_consumer.py index 3e5d1d243..14b790518 100644 --- a/src/taskq/worker/_consumer.py +++ b/src/taskq/worker/_consumer.py @@ -778,6 +778,7 @@ async def consume_one_job( actor=job.actor, queue=job.queue, attempt=job.attempt, + claim_epoch=job.claim_epoch, snooze_count=job.snooze_count, worker_id=worker_id, payload=validated_payload, @@ -965,6 +966,7 @@ async def consume_one_job( job.id, worker_id, attempt=job.attempt, + claim_epoch=job.claim_epoch, hold=release_hold, progress_seq=_cancel_seq, progress_state=_cancel_state_for_write, @@ -1060,6 +1062,7 @@ async def consume_one_job( progress_seq=_cancel_seq, progress_state=_cancel_state_for_write, attempt=job.attempt, + claim_epoch=job.claim_epoch, ), log=job_log, job=job, @@ -1328,6 +1331,7 @@ async def _run_actor_in_tx() -> object: progress_state=_pstate, fallback_result_ttl=fallback_result_ttl, attempt=job.attempt, + claim_epoch=job.claim_epoch, ) except _TERMINAL_WRITE_INFRA_EXCEPTIONS as infra_exc: _log_terminal_write_failed(log, job, None, infra_exc) @@ -1602,6 +1606,7 @@ async def _consume_autonomous( progress_state=_pstate, fallback_result_ttl=fallback_result_ttl, attempt=job.attempt, + claim_epoch=job.claim_epoch, ), log=log, job=job, diff --git a/src/taskq/worker/_handlers.py b/src/taskq/worker/_handlers.py index 99b353616..a3309961c 100644 --- a/src/taskq/worker/_handlers.py +++ b/src/taskq/worker/_handlers.py @@ -590,6 +590,7 @@ async def _handle_timeout( progress_state=progress_state, log=log, attempt=job.attempt, + claim_epoch=job.claim_epoch, ), log=log, job=job, @@ -654,6 +655,7 @@ async def _handle_timeout( progress_state=progress_state, log=log, attempt=job.attempt, + claim_epoch=job.claim_epoch, ), log=log, job=job, @@ -709,6 +711,7 @@ async def _handle_snooze( progress_seq=progress_seq, progress_state=progress_state, attempt=job.attempt, + claim_epoch=job.claim_epoch, ), log=log, job=job, @@ -804,6 +807,7 @@ async def _handle_retry_after( progress_seq=progress_seq, progress_state=progress_state, attempt=job.attempt, + claim_epoch=job.claim_epoch, ), log=log, job=job, @@ -922,6 +926,7 @@ async def _handle_reservation_class_denied( progress_seq=progress_seq, progress_state=progress_state, attempt=job.attempt, + claim_epoch=job.claim_epoch, denial_reason=denial_reason, ), log=log, @@ -1060,6 +1065,7 @@ async def _handle_generic_exception( progress_state=progress_state, log=log, attempt=job.attempt, + claim_epoch=job.claim_epoch, ), log=log, job=job, @@ -1122,6 +1128,7 @@ async def _handle_generic_exception( progress_state=progress_state, log=log, attempt=job.attempt, + claim_epoch=job.claim_epoch, ), log=log, job=job, diff --git a/src/taskq/worker/dispatch.py b/src/taskq/worker/dispatch.py index 47dbb1397..48592571a 100644 --- a/src/taskq/worker/dispatch.py +++ b/src/taskq/worker/dispatch.py @@ -704,6 +704,7 @@ async def _release_slot_conn( actor=job.actor, queue=job.queue, attempt=job.attempt, + claim_epoch=job.claim_epoch, snooze_count=job.snooze_count, worker_id=worker_id, payload=validated_payload, diff --git a/src/taskq/worker/run.py b/src/taskq/worker/run.py index 7a013650b..e8df985d8 100644 --- a/src/taskq/worker/run.py +++ b/src/taskq/worker/run.py @@ -529,11 +529,15 @@ async def _stub_terminal_write( """ if cancelled: landed = await shield_with_retrieval( - backend.mark_cancelled(job.id, worker_id, attempt=job.attempt) + backend.mark_cancelled( + job.id, worker_id, attempt=job.attempt, claim_epoch=job.claim_epoch + ) ) else: landed = await shield_with_retrieval( - backend.mark_succeeded(job.id, worker_id, None, attempt=job.attempt) + backend.mark_succeeded( + job.id, worker_id, None, attempt=job.attempt, claim_epoch=job.claim_epoch + ) ) if not landed: _consumer_log.debug( @@ -625,6 +629,7 @@ async def consumer_loop_stub( actor=job.actor, queue=job.queue, attempt=job.attempt, + claim_epoch=job.claim_epoch, snooze_count=job.snooze_count, worker_id=worker_id, payload=_StubPayload(), @@ -816,6 +821,7 @@ async def di_consumer_loop( timedelta(seconds=10), metadata_update={"released_reason": "actor-not-found"}, attempt=job.attempt, + claim_epoch=job.claim_epoch, ) except Exception: _consumer_log.exception( diff --git a/src/taskq/worker/shutdown.py b/src/taskq/worker/shutdown.py index 13872b8b1..789cd61b0 100644 --- a/src/taskq/worker/shutdown.py +++ b/src/taskq/worker/shutdown.py @@ -485,6 +485,7 @@ async def orchestrate_shutdown( active.job_id, worker_id, attempt=active.ctx.attempt, + claim_epoch=active.ctx.claim_epoch, hold=hold, progress_seq=_seq, progress_state=_state if _buf is not None and _buf.dirty else None, diff --git a/tests/_progress_context.py b/tests/_progress_context.py index afbcdaa27..ebed2c44f 100644 --- a/tests/_progress_context.py +++ b/tests/_progress_context.py @@ -36,6 +36,7 @@ def make_progress_context( actor: str = "test_actor", queue: str = "default", attempt: int = 1, + claim_epoch: int = 0, backend: InMemoryBackend | None = None, settings: WorkerSettings | None = None, redis_client: Any = None, @@ -60,6 +61,7 @@ def make_progress_context( actor=actor, queue=queue, attempt=attempt, + claim_epoch=claim_epoch, worker_id=worker_id, payload=PassthroughPayload(), cancel_event=asyncio.Event(), diff --git a/tests/test_attempt_ceiling_full_cycle_pg.py b/tests/test_attempt_ceiling_full_cycle_pg.py index b51e1b95a..658b613fd 100644 --- a/tests/test_attempt_ceiling_full_cycle_pg.py +++ b/tests/test_attempt_ceiling_full_cycle_pg.py @@ -138,6 +138,7 @@ async def test_clamped_transient_job_terminalises_failed_through_the_budget_arm( timedelta(seconds=30), consume_budget=True, attempt=_CEILING, + claim_epoch=1, ) assert outcome == "failed:MaxAttemptsExceeded", ( "a transient row at the ceiling is already past its max_attempts, so " @@ -222,6 +223,7 @@ async def test_clamped_indefinite_job_survives_two_full_claim_fail_cycles( ), retry_delay=timedelta(seconds=5), attempt=_CEILING, + claim_epoch=claimed[job_id].claim_epoch, ) assert retried_row.status == "scheduled", ( "an indefinite row with no schedule_to_close retries on its " diff --git a/tests/test_backend_equivalence.py b/tests/test_backend_equivalence.py index fa141456d..d490600c1 100644 --- a/tests/test_backend_equivalence.py +++ b/tests/test_backend_equivalence.py @@ -694,7 +694,7 @@ async def test_snooze_cycle_refunds_attempt_round_trip( assert row.attempt == 1 result = await backend_pair.mark_snoozed( - job_id, wid, timedelta(seconds=30), attempt=row.attempt + job_id, wid, timedelta(seconds=30), attempt=row.attempt, claim_epoch=row.claim_epoch ) assert result == "scheduled" @@ -745,7 +745,11 @@ async def test_snooze_past_deadline_transitions_to_failed( epoch_row = await backend_pair.get(job_id) assert epoch_row is not None result = await backend_pair.mark_snoozed( - job_id, wid, timedelta(seconds=30), attempt=epoch_row.attempt + job_id, + wid, + timedelta(seconds=30), + attempt=epoch_row.attempt, + claim_epoch=epoch_row.claim_epoch, ) assert result == "failed" @@ -788,7 +792,12 @@ async def test_retry_after_consume_true_increments_attempt( assert row.attempt == 1 result = await backend_pair.mark_retry_after( - job_id, wid, timedelta(seconds=10), consume_budget=True, attempt=row.attempt + job_id, + wid, + timedelta(seconds=10), + consume_budget=True, + attempt=row.attempt, + claim_epoch=row.claim_epoch, ) assert result == "scheduled" @@ -818,7 +827,12 @@ async def test_retry_after_consume_false_refunds_attempt( assert row.attempt == 1 result = await backend_pair.mark_retry_after( - job_id, wid, timedelta(seconds=10), consume_budget=False, attempt=row.attempt + job_id, + wid, + timedelta(seconds=10), + consume_budget=False, + attempt=row.attempt, + claim_epoch=row.claim_epoch, ) assert result == "scheduled" @@ -850,7 +864,12 @@ async def test_retry_after_exhausts_budget_transitions_to_failed( epoch_row = await backend_pair.get(job_id) assert epoch_row is not None result = await backend_pair.mark_retry_after( - job_id, wid, timedelta(seconds=10), consume_budget=True, attempt=epoch_row.attempt + job_id, + wid, + timedelta(seconds=10), + consume_budget=True, + attempt=epoch_row.attempt, + claim_epoch=epoch_row.claim_epoch, ) assert result == "failed:MaxAttemptsExceeded" @@ -886,7 +905,12 @@ async def test_retry_after_indefinite_tier_ignores_max_attempts( epoch_row = await backend_pair.get(job_id) assert epoch_row is not None result = await backend_pair.mark_retry_after( - job_id, wid, timedelta(seconds=10), consume_budget=True, attempt=epoch_row.attempt + job_id, + wid, + timedelta(seconds=10), + consume_budget=True, + attempt=epoch_row.attempt, + claim_epoch=epoch_row.claim_epoch, ) assert result == "scheduled" @@ -927,6 +951,7 @@ async def test_reservation_unavailable_produces_metadata_annotated_snooze( metadata_update={"awaiting": "reservation:gpu_pool"}, outcome="reservation_denied", attempt=epoch_row.attempt, + claim_epoch=epoch_row.claim_epoch, ) assert result == "scheduled" @@ -979,6 +1004,7 @@ async def test_admission_denial_at_exhausted_budget_still_reschedules( timedelta(seconds=30), outcome="rate_limit_denied", attempt=epoch_row.attempt, + claim_epoch=epoch_row.claim_epoch, ) assert result == "scheduled", ( "an admission denial terminally failed a job that never got a slot" @@ -1021,6 +1047,7 @@ async def test_admission_denial_past_schedule_to_close_fails_on_the_deadline( timedelta(seconds=30), outcome="rate_limit_denied", attempt=epoch_row.attempt, + claim_epoch=epoch_row.claim_epoch, ) assert result == "failed" @@ -1040,14 +1067,22 @@ async def test_mark_snoozed_idempotent_returns_noop(backend_pair: Backend) -> No epoch_row = await backend_pair.get(job_id) assert epoch_row is not None result1 = await backend_pair.mark_snoozed( - job_id, wid, timedelta(seconds=30), attempt=epoch_row.attempt + job_id, + wid, + timedelta(seconds=30), + attempt=epoch_row.attempt, + claim_epoch=epoch_row.claim_epoch, ) assert result1 == "scheduled" # The second call presents the SAME (now stale) epoch the worker would # hold - the status fence turns it into "noop". result2 = await backend_pair.mark_snoozed( - job_id, wid, timedelta(seconds=30), attempt=epoch_row.attempt + job_id, + wid, + timedelta(seconds=30), + attempt=epoch_row.attempt, + claim_epoch=epoch_row.claim_epoch, ) assert result2 == "noop" @@ -1064,13 +1099,23 @@ async def test_mark_retry_after_idempotent_returns_noop( epoch_row = await backend_pair.get(job_id) assert epoch_row is not None result1 = await backend_pair.mark_retry_after( - job_id, wid, timedelta(seconds=10), consume_budget=True, attempt=epoch_row.attempt + job_id, + wid, + timedelta(seconds=10), + consume_budget=True, + attempt=epoch_row.attempt, + claim_epoch=epoch_row.claim_epoch, ) assert result1 == "scheduled" # The second call presents the SAME (now stale) epoch - "noop". result2 = await backend_pair.mark_retry_after( - job_id, wid, timedelta(seconds=10), consume_budget=True, attempt=epoch_row.attempt + job_id, + wid, + timedelta(seconds=10), + consume_budget=True, + attempt=epoch_row.attempt, + claim_epoch=epoch_row.claim_epoch, ) assert result2 == "noop" @@ -1105,7 +1150,7 @@ async def test_mark_interrupted_releases_pending_at_zero_hold( assert row.attempt == 1 outcome = await backend_pair.mark_interrupted( - job_id, wid, attempt=row.attempt, hold=timedelta(0) + job_id, wid, attempt=row.attempt, claim_epoch=row.claim_epoch, hold=timedelta(0) ) assert outcome == "pending" @@ -1146,7 +1191,7 @@ async def test_mark_interrupted_holds_the_release_until_the_process_is_gone( assert row is not None outcome = await backend_pair.mark_interrupted( - job_id, wid, attempt=row.attempt, hold=timedelta(seconds=30) + job_id, wid, attempt=row.attempt, claim_epoch=row.claim_epoch, hold=timedelta(seconds=30) ) assert outcome == "scheduled" @@ -1198,7 +1243,7 @@ async def test_mark_interrupted_operator_cancel_in_flight_wins( assert row is not None outcome = await backend_pair.mark_interrupted( - job_id, wid, attempt=row.attempt, hold=timedelta(0) + job_id, wid, attempt=row.attempt, claim_epoch=row.claim_epoch, hold=timedelta(0) ) assert outcome == "noop", ( "the interrupt write must decline a row under an operator cancel - " @@ -1233,7 +1278,7 @@ async def test_mark_interrupted_past_the_jobs_deadline_fails_on_it( assert row is not None outcome = await backend_pair.mark_interrupted( - job_id, wid, attempt=row.attempt, hold=timedelta(seconds=30) + job_id, wid, attempt=row.attempt, claim_epoch=row.claim_epoch, hold=timedelta(seconds=30) ) assert outcome == "failed:DeadlineExceeded" @@ -1271,13 +1316,13 @@ async def test_mark_interrupted_fenced_out_by_a_stale_epoch_or_wrong_worker( # Stale epoch (the row already moved past it). outcome = await backend_pair.mark_interrupted( - job_id, wid, attempt=row.attempt - 1, hold=timedelta(0) + job_id, wid, attempt=row.attempt, claim_epoch=row.claim_epoch - 1, hold=timedelta(0) ) assert outcome == "noop" # Wrong worker. outcome = await backend_pair.mark_interrupted( - job_id, new_uuid(), attempt=row.attempt, hold=timedelta(0) + job_id, new_uuid(), attempt=row.attempt, claim_epoch=row.claim_epoch, hold=timedelta(0) ) assert outcome == "noop" @@ -1286,15 +1331,19 @@ async def test_mark_interrupted_fenced_out_by_a_stale_epoch_or_wrong_worker( assert row.status == "running" and row.locked_by_worker == wid assert row.attempt == 1 and row.interrupt_count == 0 - # And the landed release is itself not replayable at the same epoch. + # And the landed release is itself not replayable at the same epoch: + # the same fence values that landed "pending" match nothing once the + # row has left running. outcome = await backend_pair.mark_interrupted( - job_id, wid, attempt=row.attempt, hold=timedelta(0) + job_id, wid, attempt=row.attempt, claim_epoch=row.claim_epoch, hold=timedelta(0) ) assert outcome == "pending" - replayed = await backend_pair.mark_interrupted(job_id, wid, attempt=1, hold=timedelta(0)) + replayed = await backend_pair.mark_interrupted( + job_id, wid, attempt=row.attempt, claim_epoch=row.claim_epoch, hold=timedelta(0) + ) assert replayed == "noop", ( - "the released epoch no longer matches the row (status moved, and the " - "re-claim advances past it); a release cannot be replayed" + "a landed release cannot land twice at the same fence: the row " + "left running, so the equality fence no longer matches" ) row = await backend_pair.get(job_id) assert row is not None and row.interrupt_count == 1 @@ -1399,7 +1448,9 @@ async def test_mark_succeeded_transitions_row_and_emits_attempt( epoch_row = await backend_pair.get(job_id) assert epoch_row is not None - result = await backend_pair.mark_succeeded(job_id, wid, {"ok": True}, attempt=epoch_row.attempt) + result = await backend_pair.mark_succeeded( + job_id, wid, {"ok": True}, attempt=epoch_row.attempt, claim_epoch=epoch_row.claim_epoch + ) assert result is True row = await backend_pair.get(job_id) @@ -1414,7 +1465,7 @@ async def test_mark_succeeded_transitions_row_and_emits_attempt( # second call is idempotent - returns False, no second attempt row # (the stale epoch presentation is the worker's own no-op shape) result2 = await backend_pair.mark_succeeded( - job_id, wid, {"ok": True}, attempt=epoch_row.attempt + job_id, wid, {"ok": True}, attempt=epoch_row.attempt, claim_epoch=epoch_row.claim_epoch ) assert result2 is False attempts2 = await backend_pair.get_attempts(job_id) @@ -1439,7 +1490,12 @@ async def test_mark_failed_or_retry_terminal_branch( epoch_row = await backend_pair.get(job_id) assert epoch_row is not None row = await backend_pair.mark_failed_or_retry( - job_id, wid, error_info, retry_delay=None, attempt=epoch_row.attempt + job_id, + wid, + error_info, + retry_delay=None, + attempt=epoch_row.attempt, + claim_epoch=epoch_row.claim_epoch, ) assert row.status == "failed" # locked=True: mark_failed_or_retry does not clear lock fields (PG SQL omits them) @@ -1473,7 +1529,9 @@ async def test_mark_cancelled_transitions_row_and_emits_attempt( epoch_row = await backend_pair.get(job_id) assert epoch_row is not None - result = await backend_pair.mark_cancelled(job_id, wid, attempt=epoch_row.attempt) + result = await backend_pair.mark_cancelled( + job_id, wid, attempt=epoch_row.attempt, claim_epoch=epoch_row.claim_epoch + ) assert result is True row = await backend_pair.get(job_id) @@ -1487,7 +1545,9 @@ async def test_mark_cancelled_transitions_row_and_emits_attempt( # second call is idempotent - returns False, no second attempt row # (the stale epoch presentation is the worker's own no-op shape) - result2 = await backend_pair.mark_cancelled(job_id, wid, attempt=epoch_row.attempt) + result2 = await backend_pair.mark_cancelled( + job_id, wid, attempt=epoch_row.attempt, claim_epoch=epoch_row.claim_epoch + ) assert result2 is False attempts2 = await backend_pair.get_attempts(job_id) assert len(attempts2) == 1 @@ -1511,7 +1571,9 @@ async def test_result_size_bytes_set_on_mark_succeeded(backend_pair: Backend) -> job_id, wid = await _enqueue_dispatch_any(backend_pair) epoch_row = await backend_pair.get(job_id) assert epoch_row is not None - ok = await backend_pair.mark_succeeded(job_id, wid, result_payload, attempt=epoch_row.attempt) + ok = await backend_pair.mark_succeeded( + job_id, wid, result_payload, attempt=epoch_row.attempt, claim_epoch=epoch_row.claim_epoch + ) assert ok is True row = await backend_pair.get(job_id) @@ -1528,7 +1590,9 @@ async def test_result_size_bytes_none_when_result_is_none(backend_pair: Backend) job_id, wid = await _enqueue_dispatch_any(backend_pair) epoch_row = await backend_pair.get(job_id) assert epoch_row is not None - await backend_pair.mark_succeeded(job_id, wid, None, attempt=epoch_row.attempt) + await backend_pair.mark_succeeded( + job_id, wid, None, attempt=epoch_row.attempt, claim_epoch=epoch_row.claim_epoch + ) row = await backend_pair.get(job_id) assert row is not None @@ -1559,7 +1623,12 @@ async def test_mark_failed_or_retry_ownership_mismatch_raises(backend_pair: Back assert epoch_row is not None with pytest.raises(WorkerOwnershipMismatch) as exc_info: await backend_pair.mark_failed_or_retry( - job_id, wrong_wid, error_info, retry_delay=None, attempt=epoch_row.attempt + job_id, + wrong_wid, + error_info, + retry_delay=None, + attempt=epoch_row.attempt, + claim_epoch=epoch_row.claim_epoch, ) exc = exc_info.value assert exc.job_id == job_id @@ -1574,7 +1643,9 @@ async def test_mark_succeeded_wrong_worker_returns_false(backend_pair: Backend) epoch_row = await backend_pair.get(job_id) assert epoch_row is not None - result = await backend_pair.mark_succeeded(job_id, wrong_wid, None, attempt=epoch_row.attempt) + result = await backend_pair.mark_succeeded( + job_id, wrong_wid, None, attempt=epoch_row.attempt, claim_epoch=epoch_row.claim_epoch + ) # InMemoryBackend returns False for wrong worker (not an error path) assert result is False @@ -1746,7 +1817,11 @@ async def test_mark_snoozed_delay_exactly_equal_remaining_budget_fails( epoch_row = await backend_pair.get(job_id) assert epoch_row is not None result = await backend_pair.mark_snoozed( - job_id, wid, timedelta(seconds=0), attempt=epoch_row.attempt + job_id, + wid, + timedelta(seconds=0), + attempt=epoch_row.attempt, + claim_epoch=epoch_row.claim_epoch, ) # == boundary: effective new_scheduled_at == schedule_to_close → guard # is >, so NOT rejected @@ -1767,7 +1842,11 @@ async def test_mark_snoozed_delay_exceeds_deadline_fails( epoch_row = await backend_pair.get(job_id) assert epoch_row is not None result = await backend_pair.mark_snoozed( - job_id, wid, timedelta(seconds=30), attempt=epoch_row.attempt + job_id, + wid, + timedelta(seconds=30), + attempt=epoch_row.attempt, + claim_epoch=epoch_row.claim_epoch, ) assert result == "failed" @@ -1784,7 +1863,9 @@ async def test_write_cancel_request_on_succeeded_job_returns_false( job_id, wid = await _enqueue_dispatch_any(backend_pair) epoch_row = await backend_pair.get(job_id) assert epoch_row is not None - await backend_pair.mark_succeeded(job_id, wid, None, attempt=epoch_row.attempt) + await backend_pair.mark_succeeded( + job_id, wid, None, attempt=epoch_row.attempt, claim_epoch=epoch_row.claim_epoch + ) result = await backend_pair.write_cancel_request(job_id, reason=None) assert result is False @@ -1803,7 +1884,12 @@ async def test_write_cancel_request_on_failed_job_returns_false( epoch_row = await backend_pair.get(job_id) assert epoch_row is not None await backend_pair.mark_failed_or_retry( - job_id, wid, error_info, retry_delay=None, attempt=epoch_row.attempt + job_id, + wid, + error_info, + retry_delay=None, + attempt=epoch_row.attempt, + claim_epoch=epoch_row.claim_epoch, ) result = await backend_pair.write_cancel_request(job_id, reason=None) @@ -2102,7 +2188,7 @@ async def test_indefinite_tier_fail_retry_succeed(backend_pair: Backend) -> None # scheduled_at from it (single arbiter). retry_delay = _compute_backoff(policy, 1) row_after = await backend_pair.mark_failed_or_retry( - job_id, wid, error_info, retry_delay, attempt=row.attempt + job_id, wid, error_info, retry_delay, attempt=row.attempt, claim_epoch=row.claim_epoch ) assert row_after.status == "scheduled" assert row_after.attempt == 1 @@ -2122,7 +2208,13 @@ async def test_indefinite_tier_fail_retry_succeed(backend_pair: Backend) -> None assert dispatched[0].attempt == 2 assert dispatched[0].status == "running" - await backend_pair.mark_succeeded(job_id, wid, {"ok": True}, attempt=dispatched[0].attempt) + await backend_pair.mark_succeeded( + job_id, + wid, + {"ok": True}, + attempt=dispatched[0].attempt, + claim_epoch=dispatched[0].claim_epoch, + ) row = await backend_pair.get(job_id) assert row is not None assert row.status == "succeeded" diff --git a/tests/test_backend_mark_succeeded.py b/tests/test_backend_mark_succeeded.py index f0c73ccb5..584f42304 100644 --- a/tests/test_backend_mark_succeeded.py +++ b/tests/test_backend_mark_succeeded.py @@ -50,6 +50,7 @@ async def test_pg_conn_aware_commits_on_supplied_connection( worker_id, {"ok": True}, attempt=1, + claim_epoch=1, ) assert ok is True @@ -85,6 +86,7 @@ async def test_pg_conn_aware_rolls_back_with_caller( worker_id, {"ok": True}, attempt=1, + claim_epoch=1, ) assert ok is True raise RuntimeError("simulate caller rollback") @@ -119,7 +121,7 @@ async def test_in_memory_delegation() -> None: job_id = dispatched[0].id ok = await backend.mark_succeeded_with_conn( - None, job_id, backend._worker_id, {"ok": True}, attempt=1 + None, job_id, backend._worker_id, {"ok": True}, attempt=1, claim_epoch=1 ) # type: ignore[reportPrivateUsage] # Why: test-only access to in-memory backend internals assert ok is True @@ -143,7 +145,9 @@ async def test_pg_autonomous_mark_succeeded_still_works( await create_worker(conn, schema, worker_id) job_id = await create_running_job(conn, schema, worker_id) - ok = await backend.mark_succeeded(JobId(job_id), worker_id, {"ok": True}, attempt=1) + ok = await backend.mark_succeeded( + JobId(job_id), worker_id, {"ok": True}, attempt=1, claim_epoch=1 + ) assert ok is True async with deps.worker_pool.acquire() as conn: @@ -170,7 +174,9 @@ async def test_in_memory_autonomous_mark_succeeded_still_works() -> None: assert len(dispatched) == 1 job_id = dispatched[0].id - ok = await backend.mark_succeeded(job_id, backend._worker_id, {"ok": True}, attempt=1) # type: ignore[reportPrivateUsage] # Why: test-only access to in-memory backend internals + ok = await backend.mark_succeeded( + job_id, backend._worker_id, {"ok": True}, attempt=1, claim_epoch=1 + ) # type: ignore[reportPrivateUsage] # Why: test-only access to in-memory backend internals assert ok is True row = await backend.get(job_id) diff --git a/tests/test_backend_protocol.py b/tests/test_backend_protocol.py index 81367e2d1..0691aecc4 100644 --- a/tests/test_backend_protocol.py +++ b/tests/test_backend_protocol.py @@ -640,11 +640,13 @@ def test_status_literal_type(self) -> None: def test_field_count(self) -> None: # field list + tags + the two denial/snooze counters # (snooze_count, rate_limit_blocked_count) + the interrupt counter - # (interrupt_count) + the four retry-curve scalars read back off + # (interrupt_count) + the claim-epoch fence (claim_epoch, the + # non-saturating claim identity the terminal writes fence on) + + # the four retry-curve scalars read back off # the jobs row (retry_base/retry_cap/retry_backoff/retry_jitter - # the reclaim sweep's policy source) + the assignment-routed # marker (re-pend routing by the actor's stored assignment). - expected = 46 + expected = 47 assert len(fields(JobRow)) == expected def test_frozen(self) -> None: diff --git a/tests/test_batch_abort_finalizer.py b/tests/test_batch_abort_finalizer.py index 2f310ac1d..46bc6f927 100644 --- a/tests/test_batch_abort_finalizer.py +++ b/tests/test_batch_abort_finalizer.py @@ -225,7 +225,10 @@ async def test_clock_jump_does_not_fail_snoozed_job(self) -> None: job.id, worker_id, snooze.delay, + # make_job_row's row carries the claim_epoch default (0), the + # epoch this write must present. attempt=1, + claim_epoch=0, ) assert tri == "scheduled", f"mark_snoozed returned {tri!r}, expected 'scheduled'" @@ -392,10 +395,16 @@ async def test_snooze_keeps_ceiling_fixed_not_attempt(self) -> None: snooze = Snooze(timedelta(seconds=2)) + # Every simulated re-dispatch below advances the claim epoch (the + # twin's claim bumps it); the snooze refund hands back only the + # attempt increment, never the epoch. + claimed_epoch = 0 for i in range(10): # Snooze: running → scheduled, max_attempts unchanged, the # claim's increment refunded (1 → 0). - tri = await backend.mark_snoozed(job.id, worker_id, snooze.delay, attempt=1) + tri = await backend.mark_snoozed( + job.id, worker_id, snooze.delay, attempt=1, claim_epoch=claimed_epoch + ) assert tri == "scheduled", f"snooze {i + 1} returned {tri!r}" row = await backend.get(job.id) @@ -416,5 +425,7 @@ async def test_snooze_keeps_ceiling_fixed_not_attempt(self) -> None: row, status="running", attempt=1, + claim_epoch=row.claim_epoch + 1, locked_by_worker=worker_id, ) + claimed_epoch = backend._jobs[job.id].claim_epoch diff --git a/tests/test_cancel_fence_arms.py b/tests/test_cancel_fence_arms.py index d02bd401d..b61917b2c 100644 --- a/tests/test_cancel_fence_arms.py +++ b/tests/test_cancel_fence_arms.py @@ -102,7 +102,9 @@ async def test_mark_snoozed_refuses_in_flight_cancel(self) -> None: job_id, wid = await _enqueue_and_dispatch(backend) _set_in_flight_cancel(backend, job_id) - result = await backend.mark_snoozed(job_id, wid, timedelta(seconds=30), attempt=1) + result = await backend.mark_snoozed( + job_id, wid, timedelta(seconds=30), attempt=1, claim_epoch=1 + ) assert result == "noop", ( "a snooze landing mid-cancel must not reschedule the row: the " @@ -121,7 +123,7 @@ async def test_mark_retry_after_consume_true_refuses_in_flight_cancel(self) -> N _set_in_flight_cancel(backend, job_id) result = await backend.mark_retry_after( - job_id, wid, timedelta(seconds=10), consume_budget=True, attempt=1 + job_id, wid, timedelta(seconds=10), consume_budget=True, attempt=1, claim_epoch=1 ) assert result == "noop", ( @@ -140,7 +142,7 @@ async def test_mark_retry_after_consume_false_refuses_in_flight_cancel(self) -> _set_in_flight_cancel(backend, job_id) result = await backend.mark_retry_after( - job_id, wid, timedelta(seconds=10), consume_budget=False, attempt=1 + job_id, wid, timedelta(seconds=10), consume_budget=False, attempt=1, claim_epoch=1 ) assert result == "noop", ( @@ -159,7 +161,9 @@ async def test_deferral_arms_still_defer_clean_rows(self) -> None: backend = _make_backend() job_id, wid = await _enqueue_and_dispatch(backend) - result = await backend.mark_snoozed(job_id, wid, timedelta(seconds=30), attempt=1) + result = await backend.mark_snoozed( + job_id, wid, timedelta(seconds=30), attempt=1, claim_epoch=1 + ) assert result == "scheduled" row = await backend.get(job_id) assert row is not None @@ -194,7 +198,9 @@ async def test_snoozed_mid_cancel_id_lands_in_one_list_only(self) -> None: # The consumer snoozes mid-drain. Before the fix this wipes the # operator's cancel columns and re-pends the row behind the cursor. - snoozed = await backend.mark_snoozed(job_id, wid, timedelta(seconds=30), attempt=1) + snoozed = await backend.mark_snoozed( + job_id, wid, timedelta(seconds=30), attempt=1, claim_epoch=1 + ) # Round 2: the drain re-walks from the cursor. second = await backend.cancel_where(_match_all_filter(), reason="bulk-drain") @@ -260,7 +266,9 @@ async def test_zombie_terminal_write_cannot_land_after_interrupt_reclaim(self) - # Shutdown interrupts the running attempt (zero hold: the row lands # 'pending' immediately; the process is going away). - released = await backend.mark_interrupted(job_id, wid, attempt=1, hold=timedelta(0)) + released = await backend.mark_interrupted( + job_id, wid, attempt=1, claim_epoch=1, hold=timedelta(0) + ) assert released == "pending" row = await backend.get(job_id) assert row is not None @@ -283,7 +291,9 @@ async def test_zombie_terminal_write_cannot_land_after_interrupt_reclaim(self) - ) # The zombie's terminal write at the old epoch must be fenced out. - zombie_landed = await backend.mark_succeeded(job_id, wid, {"zombie": True}, attempt=1) + zombie_landed = await backend.mark_succeeded( + job_id, wid, {"zombie": True}, attempt=1, claim_epoch=1 + ) assert zombie_landed is False, ( "the interrupted handler's terminal write landed on the " "re-dispatched attempt: the interrupt refund re-created the " @@ -295,7 +305,10 @@ async def test_zombie_terminal_write_cannot_land_after_interrupt_reclaim(self) - assert row.status == "running" # The live execution's own terminal write lands. - assert await backend.mark_succeeded(job_id, wid, {"live": True}, attempt=2) is True + assert ( + await backend.mark_succeeded(job_id, wid, {"live": True}, attempt=2, claim_epoch=2) + is True + ) row = await backend.get(job_id) assert row is not None assert row.status == "succeeded" @@ -393,13 +406,13 @@ async def _pair_set_in_flight_cancel(backend: Backend, job_id: JobId, phase: Can _ARM_CALLS = { "snoozed": lambda backend, job_id, wid: backend.mark_snoozed( - job_id, wid, timedelta(seconds=30), attempt=1 + job_id, wid, timedelta(seconds=30), attempt=1, claim_epoch=1 ), "retry_after_consume_true": lambda backend, job_id, wid: backend.mark_retry_after( - job_id, wid, timedelta(seconds=10), consume_budget=True, attempt=1 + job_id, wid, timedelta(seconds=10), consume_budget=True, attempt=1, claim_epoch=1 ), "retry_after_consume_false": lambda backend, job_id, wid: backend.mark_retry_after( - job_id, wid, timedelta(seconds=10), consume_budget=False, attempt=1 + job_id, wid, timedelta(seconds=10), consume_budget=False, attempt=1, claim_epoch=1 ), } diff --git a/tests/test_cancel_hook.py b/tests/test_cancel_hook.py index 8f1d84ee3..008c7bd41 100644 --- a/tests/test_cancel_hook.py +++ b/tests/test_cancel_hook.py @@ -103,6 +103,7 @@ def _make_ctx() -> JobContext[BaseModel]: actor="test", queue="default", attempt=1, + claim_epoch=0, worker_id=new_uuid(), payload=_StubPayload(), jobs=SubJobEnqueuer( diff --git a/tests/test_cancel_phase_property.py b/tests/test_cancel_phase_property.py index 0017d845a..fe34ca5aa 100644 --- a/tests/test_cancel_phase_property.py +++ b/tests/test_cancel_phase_property.py @@ -123,6 +123,7 @@ def _make_ctx() -> JobContext[BaseModel]: actor="test", queue="default", attempt=1, + claim_epoch=0, worker_id=new_uuid(), payload=_StubPayload(), jobs=SubJobEnqueuer( diff --git a/tests/test_cancel_registry.py b/tests/test_cancel_registry.py index 709b6ca08..7cbc5f3bd 100644 --- a/tests/test_cancel_registry.py +++ b/tests/test_cancel_registry.py @@ -49,6 +49,7 @@ def _make_ctx(job_id: UUID) -> JobContext[BaseModel]: actor="test", queue="default", attempt=1, + claim_epoch=0, worker_id=new_uuid(), payload=_FakePayload(), jobs=SubJobEnqueuer( diff --git a/tests/test_cancel_state_reset_on_retry.py b/tests/test_cancel_state_reset_on_retry.py index f6e5e0a2b..800c35b3e 100644 --- a/tests/test_cancel_state_reset_on_retry.py +++ b/tests/test_cancel_state_reset_on_retry.py @@ -163,7 +163,9 @@ async def test_mark_failed_or_retry_clears_cancel_state(backend_pair: Backend) - job_id, worker_id = await _enqueue_and_dispatch(backend_pair) await _force_cancel_escalated(backend_pair, job_id) - await backend_pair.mark_failed_or_retry(job_id, worker_id, _ERROR, timedelta(0), attempt=1) + await backend_pair.mark_failed_or_retry( + job_id, worker_id, _ERROR, timedelta(0), attempt=1, claim_epoch=1 + ) await _assert_clean_slate_on_next_attempt(backend_pair, job_id) @@ -174,7 +176,9 @@ async def test_mark_snoozed_refuses_a_row_carrying_a_cancel_phase( job_id, worker_id = await _enqueue_and_dispatch(backend_pair) await _force_cancel_escalated(backend_pair, job_id) - outcome = await backend_pair.mark_snoozed(job_id, worker_id, timedelta(0), attempt=1) + outcome = await backend_pair.mark_snoozed( + job_id, worker_id, timedelta(0), attempt=1, claim_epoch=1 + ) assert outcome == "noop" row = await backend_pair.get(job_id) @@ -192,7 +196,7 @@ async def test_mark_retry_after_refuses_a_row_carrying_a_cancel_phase( await _force_cancel_escalated(backend_pair, job_id) outcome = await backend_pair.mark_retry_after( - job_id, worker_id, timedelta(0), consume_budget=consume_budget, attempt=1 + job_id, worker_id, timedelta(0), consume_budget=consume_budget, attempt=1, claim_epoch=1 ) assert outcome == "noop" @@ -208,7 +212,9 @@ async def test_terminal_failure_preserves_cancel_state(backend_pair: Backend) -> job_id, worker_id = await _enqueue_and_dispatch(backend_pair) await _force_cancel_escalated(backend_pair, job_id) - await backend_pair.mark_failed_or_retry(job_id, worker_id, _ERROR, None, attempt=1) + await backend_pair.mark_failed_or_retry( + job_id, worker_id, _ERROR, None, attempt=1, claim_epoch=1 + ) row = await backend_pair.get(job_id) assert row is not None diff --git a/tests/test_claim_epoch_fencing.py b/tests/test_claim_epoch_fencing.py new file mode 100644 index 000000000..e357e39f6 --- /dev/null +++ b/tests/test_claim_epoch_fencing.py @@ -0,0 +1,575 @@ +"""Claim-epoch fencing: the terminal-write fence survives the attempt ceiling. + +The terminal writes are fenced on ``(status='running', locked_by_worker, +attempt)`` and the claim stamps the displayed counter with a saturating +``LEAST(attempt + 1, 32767)``. At the ceiling the value stops advancing, so +a reclaim plus a redispatch to the same worker gives the stale execution and +the live one the SAME fence: the stale ``mark_succeeded`` wins and the live +one reads ``WorkerOwnershipMismatch``, a failed job recorded as succeeded +(reachable with ``retry_kind='indefinite'``, about 9.1 hours of tight +retrying at the 1 s deferral floor). + +The fix fences every terminal/ownership write on a SECOND, non-saturating +column, ``claim_epoch``: the dispatch claim bumps it by exactly 1 per claim +(bigint), the reclaim sweeps that clear locks leave it, and every write +that fences on ``attempt`` also fences on ``claim_epoch`` equalling the +epoch of the writer's own claim view. The displayed counter keeps its +saturating, budget-display semantics unchanged. + +The pins here are behavior-level and drive the REAL backends: + +* the issue's exact reproduction at the ceiling on testcontainers PG, plus + the attempt-5 control and the strict-increase pin; +* every fenced arm (all nine ``mark_*`` methods, every arm class the + templates carry) parametrized over ``backend_pair`` - the stale write is + refused and the live write lands with its own outcome, on PG and on the + in-memory twin alike. +""" + +# ruff: noqa: S608 # Why: every f-string SQL below interpolates only this test's own fixture-validated schema identifier; every value is $-bound. + +import asyncio +from collections.abc import Callable, Coroutine +from datetime import UTC, datetime, timedelta +from typing import TYPE_CHECKING, Any +from uuid import UUID + +import pytest + +from taskq._ids import new_base62, new_job_id, new_uuid +from taskq.backend import Backend, EnqueueArgs +from taskq.backend._protocol import ErrorInfo, JobId, JobRow +from taskq.backend.postgres import PostgresBackend +from taskq.exceptions import WorkerOwnershipMismatch +from taskq.testing.fixtures import JobsApp +from taskq.testing.in_memory import InMemoryBackend +from taskq.testing.pg import create_worker +from taskq.worker._leader_shared import prune_terminal_jobs + +if TYPE_CHECKING: + import asyncpg + from asyncpg.pool import PoolConnectionProxy + + type _PGConn = asyncpg.Connection[asyncpg.Record] | PoolConnectionProxy[asyncpg.Record] +else: + type _PGConn = object # pyright: ignore[reportInvalidTypeForm] # Why: asyncpg classes are not subscriptable at runtime + +pytestmark = pytest.mark.integration + +#: The domain ceiling of the ``jobs.attempt`` smallint column. +_CEILING = 32767 +#: A past timestamp: a row scheduled here is due on any backend clock. +_PAST = datetime(2025, 1, 1, tzinfo=UTC) +#: A lock lease the reclaim sweep can age out in one tick. +_TICK_LEASE = timedelta(microseconds=1) +_ERROR_B = ErrorInfo(error_class="BoomError", error_message="live b", error_traceback=None) +_ERROR_A = ErrorInfo(error_class="StaleA", error_message="stale a", error_traceback=None) + + +# ── Part A: the issue's reproduction, on real PG ───────────────────────── + + +async def _park( + conn: _PGConn, + schema: str, + actor: str, + *, + attempt: int, + retry_kind: str, +) -> UUID: + """Seed one claimable pending job at *attempt*. + + ``retry_kind='indefinite'`` is the production route to the ceiling: its + budget is the deadline, not ``max_attempts``. ``retry_base_seconds=0`` + keeps the reclaim sweep's reschedule delay at zero so a reclaimed row is + immediately claimable again. + """ + job_id = new_uuid() + await conn.execute( + f'INSERT INTO "{schema}".jobs ' + "(id, actor, queue, payload, status, scheduled_at, attempt, " + " max_attempts, retry_kind, retry_base_seconds, retry_cap_seconds) " + "VALUES ($1, $2, 'default', '{}'::jsonb, 'pending', " + " clock_timestamp() - interval '5 minutes', $3, 3, $4, 0, 0)", + job_id, + actor, + attempt, + retry_kind, + ) + return job_id + + +async def _register(conn: _PGConn, schema: str, actor: str, worker_id: UUID) -> None: + await conn.execute( + f'INSERT INTO "{schema}".actor_config (actor, queue) VALUES ($1, $2) ' + "ON CONFLICT (actor) DO NOTHING", + actor, + "default", + ) + await create_worker(conn, schema, worker_id) + + +async def _expire_lease(conn: _PGConn, schema: str, job_id: JobId) -> None: + """Age one claimed row's lock past expiry so the reclaim sweep owns it.""" + await conn.execute( + f"UPDATE \"{schema}\".jobs SET lock_expires_at = clock_timestamp() - interval '1 second' " + "WHERE id = $1", + job_id, + ) + + +async def _row(conn: _PGConn, schema: str, job_id: JobId) -> dict[str, object]: + rec = await conn.fetchrow( + f'SELECT status, attempt, claim_epoch, error_class, result FROM "{schema}".jobs ' + "WHERE id = $1", + job_id, + ) + assert rec is not None + return dict(rec) + + +class TestCeilingReproduction: + """The issue's repro chain, driven through the real claim and sweep SQL.""" + + async def test_ceiling_stale_mark_succeeded_is_refused_live_b_lands( + self, jobs_app: JobsApp + ) -> None: + deps = jobs_app.deps + backend = jobs_app.backend + schema = deps.settings.schema_name + actor = f"ceiling_repro_{new_base62(6)}".lower() + worker_id = new_uuid() + + async with deps.worker_pool.acquire() as conn: + await _register(conn, schema, actor, worker_id) + job_id = JobId( + await _park(conn, schema, actor, attempt=_CEILING - 1, retry_kind="indefinite") + ) + + # Claim A: attempt clamps to the ceiling, the epoch advances. + a = await backend.dispatch_batch( + worker_id=worker_id, + queues=["default"], + limit=10, + lock_lease=timedelta(seconds=30), + ) + assert [r.id for r in a] == [job_id] + assert a[0].attempt == _CEILING + assert a[0].claim_epoch == 1 + + # Reclaim: the lease expires, the sweep hands the row back. + await _expire_lease(conn, schema, job_id) + assert ( + await PostgresBackend.sweep_expired_locks( + conn, timedelta(0), timedelta(0), schema=schema + ) + == 1 + ) + # The sweep's re-pend floors its reschedule at + # MIN_DEFERRAL_INTERVAL; wait it out on the server clock. + await asyncio.sleep(1.1) + + # Claim B: the SAME attempt number (the clamp), a NEW epoch. + b = await backend.dispatch_batch( + worker_id=worker_id, + queues=["default"], + limit=10, + lock_lease=timedelta(seconds=30), + ) + assert [r.id for r in b] == [job_id] + assert b[0].attempt == _CEILING, "the clamp must reuse the attempt number" + assert b[0].claim_epoch == 2, "the epoch must never reuse a claim's identity" + + # Stale A's terminal write carries the ceiling attempt and the + # stale epoch: refused, exactly like a different worker's late + # write. (This is the write that USED to win and record the + # failed job as succeeded.) + landed = await backend.mark_succeeded( + job_id, worker_id, {"from": "STALE_A"}, attempt=_CEILING, claim_epoch=1 + ) + assert landed is False, ( + "the stale claim's success write must be fenced out at the " + "ceiling: attempt alone can no longer distinguish the two " + "executions, the epoch does" + ) + + # Live B's terminal write lands with B's outcome. + row = await backend.mark_failed_or_retry( + job_id, worker_id, _ERROR_B, None, attempt=_CEILING, claim_epoch=2 + ) + assert row.status == "failed" + assert row.error_class == "BoomError" + + final = await _row(conn, schema, job_id) + assert final["status"] == "failed" + assert final["error_class"] == "BoomError" + assert final["result"] is None, "no stale result may ride the row" + assert final["claim_epoch"] == 2 + + async def test_control_attempt_five_behaviour_is_unchanged(self, jobs_app: JobsApp) -> None: + """The pre-epoch control from the repro, unchanged by the fix: away + from the ceiling the attempt number already advanced, so the stale + write was fenced before and must still be fenced.""" + deps = jobs_app.deps + backend = jobs_app.backend + schema = deps.settings.schema_name + actor = f"ceiling_ctl_{new_base62(6)}".lower() + worker_id = new_uuid() + + async with deps.worker_pool.acquire() as conn: + await _register(conn, schema, actor, worker_id) + job_id = JobId(await _park(conn, schema, actor, attempt=5, retry_kind="indefinite")) + + a = await backend.dispatch_batch( + worker_id=worker_id, + queues=["default"], + limit=10, + lock_lease=timedelta(seconds=30), + ) + assert [r.id for r in a] == [job_id] + assert a[0].attempt == 6 + assert a[0].claim_epoch == 1 + + await _expire_lease(conn, schema, job_id) + assert ( + await PostgresBackend.sweep_expired_locks( + conn, timedelta(0), timedelta(0), schema=schema + ) + == 1 + ) + # The sweep's re-pend floors its reschedule at + # MIN_DEFERRAL_INTERVAL; wait it out on the server clock. + await asyncio.sleep(1.1) + + b = await backend.dispatch_batch( + worker_id=worker_id, + queues=["default"], + limit=10, + lock_lease=timedelta(seconds=30), + ) + assert [r.id for r in b] == [job_id] + assert b[0].attempt == 7, "away from the ceiling the counter advances" + assert b[0].claim_epoch == 2 + + # Stale A: stale attempt AND stale epoch, refused either way. + assert ( + await backend.mark_succeeded( + job_id, worker_id, {"from": "STALE_A"}, attempt=6, claim_epoch=1 + ) + is False + ) + # The stale attempt number alone is still a fence: a writer + # presenting a wrong attempt against the live epoch lands + # nothing. + assert ( + await backend.mark_succeeded( + job_id, worker_id, {"from": "STALE_A"}, attempt=6, claim_epoch=2 + ) + is False + ) + row = await backend.mark_failed_or_retry( + job_id, worker_id, _ERROR_B, None, attempt=7, claim_epoch=2 + ) + assert row.status == "failed" + assert row.error_class == "BoomError" + + final = await _row(conn, schema, job_id) + assert final["status"] == "failed" + assert final["error_class"] == "BoomError" + + async def test_epoch_strictly_increases_across_claims_at_the_ceiling( + self, jobs_app: JobsApp + ) -> None: + """N reclaim/redispatch cycles at the ceiling: attempt is clamped + every time, the epoch never repeats. A monotone epoch is what makes + every fence comparison unambiguous.""" + deps = jobs_app.deps + backend = jobs_app.backend + schema = deps.settings.schema_name + actor = f"ceiling_mono_{new_base62(6)}".lower() + worker_id = new_uuid() + + async with deps.worker_pool.acquire() as conn: + await _register(conn, schema, actor, worker_id) + job_id = JobId( + await _park(conn, schema, actor, attempt=_CEILING - 1, retry_kind="indefinite") + ) + + seen_epochs: list[int] = [] + for _ in range(4): + claimed = await backend.dispatch_batch( + worker_id=worker_id, + queues=["default"], + limit=10, + lock_lease=timedelta(seconds=30), + ) + assert [r.id for r in claimed] == [job_id] + assert claimed[0].attempt == _CEILING, "the clamp holds across cycles" + seen_epochs.append(claimed[0].claim_epoch) + + await _expire_lease(conn, schema, job_id) + assert ( + await PostgresBackend.sweep_expired_locks( + conn, timedelta(0), timedelta(0), schema=schema + ) + == 1 + ) + # The sweep's re-pend floors its reschedule at + # MIN_DEFERRAL_INTERVAL; wait it out on the server clock. + await asyncio.sleep(1.1) + + assert seen_epochs == [1, 2, 3, 4], ( + f"the epoch must strictly increase across claims at the ceiling; saw {seen_epochs}" + ) + + +# ── Part B: every fenced arm, on both backends ─────────────────────────── + + +async def _expire_and_reclaim(backend: Backend) -> None: + """Age every lease past expiry on the backend's own clock, then run the + reclaim sweep itself (never a row mutation), and clear the sweep's + MIN_DEFERRAL_INTERVAL reschedule floor so the re-pended row is due.""" + if isinstance(backend, InMemoryBackend): + from taskq.testing._runner import advance_clock_to + + def travel() -> None: + # Time-travel a day past the current twin time: past the + # microsecond lease and past the sweep's reschedule floor, + # the twin's own documented clock surface. + advance_clock_to(backend, backend._clock.now() + timedelta(days=1)) # pyright: ignore[reportPrivateUsage] # Why: the twin-tier pin owns the clock handle; the runner's advance_clock_to is the documented surface. + + travel() + reclaimed = await backend.reclaim_expired_locks(timedelta(0), timedelta(0)) + travel() + else: + await asyncio.sleep(0.05) + reclaimed = await backend.reclaim_expired_locks(timedelta(0), timedelta(0)) + # The sweep's re-pend floors its reschedule at + # MIN_DEFERRAL_INTERVAL; wait it out on the server clock. + await asyncio.sleep(1.1) + assert reclaimed == 1, "the reclaim sweep must hand the expired row back" + + +async def _seed_and_claim(backend: Backend) -> tuple[JobId, UUID, tuple[int, int], tuple[int, int]]: + """Enqueue, claim, then reclaim + re-claim: the stale/live epoch shape. + + Returns ``(job_id, worker_id, stale_pair, live_pair)``: the stale pair + is the FIRST claim's (attempt, epoch), the live pair the second + claim's. Both claims go through the backend's real dispatch, and the + reclaim through its real sweep, so the epoch's advance is the shipped + semantics, not a simulated mutation. + """ + actor = f"epoch_pin_{new_base62(6)}".lower() + if isinstance(backend, InMemoryBackend): + backend.register_actor_config(actor=actor) + worker_id = backend._worker_id # type: ignore[reportPrivateUsage] # Why: the twin's dispatch stamps this id; the pins hold the same handle the workers do. + else: + pool = backend._dispatcher_pool # type: ignore[reportPrivateUsage] # Why: the PG branch needs an actor_config row and a workers row; the pins hold the backend's own pool handle. + assert pool is not None + pg_schema: str = backend._schema_name # type: ignore[reportPrivateUsage] + worker_id = new_uuid() + async with pool.acquire() as conn: + await conn.execute( + f'INSERT INTO "{pg_schema}".actor_config (actor, queue) ' + "VALUES ($1, 'default') ON CONFLICT (actor) DO NOTHING", + actor, + ) + await conn.execute( + f'INSERT INTO "{pg_schema}".workers (id, hostname, pid, queues) ' + "VALUES ($1, $2, $3, $4)", + worker_id, + "test-host", + 12345, + ["default"], + ) + + job_id = new_job_id() + await backend.enqueue( + EnqueueArgs( + id=job_id, + actor=actor, + queue="default", + payload={"key": "value"}, + max_attempts=3, + retry_kind="indefinite", + scheduled_at=_PAST, + # A zero retry curve keeps the reclaim's reschedule delay at + # zero: the reclaimed row is claimable again immediately. + retry_base=timedelta(0), + retry_cap=timedelta(0), + retry_jitter=0.0, + ) + ) + + first = await backend.dispatch_batch( + worker_id=worker_id, queues=["default"], limit=1, lock_lease=_TICK_LEASE + ) + assert len(first) == 1 + stale = (first[0].attempt, first[0].claim_epoch) + + await _expire_and_reclaim(backend) + + second = await backend.dispatch_batch( + worker_id=worker_id, queues=["default"], limit=1, lock_lease=_TICK_LEASE + ) + assert len(second) == 1 and second[0].id == job_id + live = (second[0].attempt, second[0].claim_epoch) + assert live[1] == stale[1] + 1, "the epoch must advance by exactly one per claim" + return job_id, worker_id, stale, live + + +# (name, driver(backend, job_id, worker_id, attempt, epoch), expected +# refusal observable, expected live observable) - one entry per fenced +# method/arm class. A method missing here is a fence gap. +_FENCED_ARMS = ( + ( + "mark_succeeded", + lambda b, j, w, a, e: b.mark_succeeded(j, w, {"from": "LIVE_B"}, attempt=a, claim_epoch=e), + False, + True, + ), + ( + "mark_cancelled", + lambda b, j, w, a, e: b.mark_cancelled(j, w, attempt=a, claim_epoch=e), + False, + True, + ), + ( + "mark_snoozed", + lambda b, j, w, a, e: b.mark_snoozed(j, w, timedelta(seconds=30), attempt=a, claim_epoch=e), + "noop", + "scheduled", + ), + ( + "mark_retry_after_consume_true", + lambda b, j, w, a, e: b.mark_retry_after( + j, w, timedelta(seconds=30), consume_budget=True, attempt=a, claim_epoch=e + ), + "noop", + "scheduled", + ), + ( + "mark_retry_after_consume_false", + lambda b, j, w, a, e: b.mark_retry_after( + j, w, timedelta(seconds=30), consume_budget=False, attempt=a, claim_epoch=e + ), + "noop", + "scheduled", + ), + ( + "mark_failed_or_retry_retry_arm", + lambda b, j, w, a, e: b.mark_failed_or_retry( + j, w, _ERROR_A, timedelta(seconds=30), attempt=a, claim_epoch=e + ), + "raise", + "scheduled", + ), + ( + "mark_failed_or_retry_fail_arm", + lambda b, j, w, a, e: b.mark_failed_or_retry( + j, w, _ERROR_A, None, attempt=a, claim_epoch=e + ), + "raise", + "failed", + ), + ( + "mark_interrupted", + lambda b, j, w, a, e: b.mark_interrupted(j, w, attempt=a, hold=timedelta(0), claim_epoch=e), + "noop", + "pending", + ), +) + + +@pytest.mark.parametrize( + ("arm", "driver", "refused", "live_outcome"), + _FENCED_ARMS, + ids=[arm[0] for arm in _FENCED_ARMS], +) +async def test_every_fenced_arm_refuses_the_stale_epoch_and_lands_the_live_one( + backend_pair: Backend, + arm: str, + driver: "Callable[[Backend, JobId, UUID, int, int], Coroutine[Any, Any, object]]", + refused: object, + live_outcome: object, +) -> None: + """Each fenced arm refuses the stale claim's write and lands the live + claim's own outcome, on both backends. + + A stale epoch (a reclaim + redispatch happened after this writer's + claim) must no-op through the same machinery the worker fence uses; + the live epoch lands the write with its own outcome. Away from the + ceiling the attempt number advances alongside the epoch, so the stale + writer here presents its true-at-the-time attempt and only the epoch + distinguishes it from the live claim's write. + """ + backend = backend_pair + job_id, worker_id, stale, live = await _seed_and_claim(backend) + + if refused == "raise": + with pytest.raises(WorkerOwnershipMismatch): + await driver(backend, job_id, worker_id, stale[0], stale[1]) + else: + observed = await driver(backend, job_id, worker_id, stale[0], stale[1]) + assert observed == refused, ( + f"{arm}: the stale claim's write must be fenced out (got {observed!r})" + ) + + observed_live = await driver(backend, job_id, worker_id, live[0], live[1]) + if isinstance(observed_live, JobRow): + assert observed_live.status == live_outcome, ( + f"{arm}: the live claim's write must land with its own outcome" + ) + else: + assert observed_live == live_outcome, ( + f"{arm}: the live claim's write must land (got {observed_live!r})" + ) + + +# ── Part C: the archive carries the true epoch ─────────────────────────── + + +async def test_archived_row_keeps_the_live_row_claim_epoch(jobs_app: JobsApp) -> None: + """A twice-claimed job that goes terminal and then through the real + archive CTE lands in jobs_archive with the epoch its last claim + stamped, the value the live row read at archival. + + The archive INSERT names its columns through COPY_FROM_COLUMNS; the + claim_epoch entry there is what keeps the archived identity true. A + row archived without it would read the default 0 forever, an epoch + no claim can ever have stamped, and the column's contract (bumped by + exactly 1 per claim) would be false for every archived row. + """ + deps = jobs_app.deps + backend = jobs_app.backend + schema = deps.settings.schema_name + job_id, worker_id, _stale, live = await _seed_and_claim(backend) + + row = await backend.get(job_id) + assert row is not None + assert row.claim_epoch == live[1] + + assert ( + await backend.mark_succeeded( + job_id, worker_id, {"done": True}, attempt=live[0], claim_epoch=live[1] + ) + is True + ) + + async with deps.worker_pool.acquire() as conn: + result = await prune_terminal_jobs( + conn, + retention_per_status={"succeeded": timedelta(0)}, + archive_retention=timedelta(days=365), + batch_size=100, + schema=schema, + ) + assert result.archived == 1 + + async with deps.worker_pool.acquire() as conn: + archived = await conn.fetchrow( + f'SELECT claim_epoch FROM "{schema}".jobs_archive WHERE id = $1', job_id + ) + assert archived is not None + assert archived["claim_epoch"] == live[1] == 2 diff --git a/tests/test_clock_domain_isolation.py b/tests/test_clock_domain_isolation.py index bac9b2a31..eedc8dc7a 100644 --- a/tests/test_clock_domain_isolation.py +++ b/tests/test_clock_domain_isolation.py @@ -392,6 +392,7 @@ async def test_retry_backoff_not_voided_by_negative_skew(pg_dsn: str) -> None: ErrorInfo(error_class="ValueError", error_message="boom", error_traceback=None), timedelta(seconds=30), attempt=1, + claim_epoch=1, ) assert row.status == "scheduled" @@ -440,6 +441,7 @@ async def test_retry_deadline_arbitrated_server_side(pg_dsn: str) -> None: ErrorInfo(error_class="ValueError", error_message="boom", error_traceback=None), timedelta(seconds=30), attempt=1, + claim_epoch=1, ) assert row.status == "failed" assert row.error_class == "DeadlineExceeded" @@ -558,6 +560,7 @@ async def test_retry_survives_worker_clock_skew_deadline_disagreement(pg_dsn: st ErrorInfo(error_class="RuntimeError", error_message="boom", error_traceback=None), decision.retry_delay, attempt=1, + claim_epoch=1, ) if job_id is live_job: assert updated.status == "scheduled", ( diff --git a/tests/test_consumer.py b/tests/test_consumer.py index b3609a025..2597384db 100644 --- a/tests/test_consumer.py +++ b/tests/test_consumer.py @@ -2229,6 +2229,7 @@ async def mark_failed_or_retry( progress_state: dict[str, object] | None = None, *, attempt: int | None = None, + claim_epoch: int | None = None, ) -> JobRow: raise WorkerOwnershipMismatch(job_id=job_id, expected=worker_id, actual=new_uuid()) diff --git a/tests/test_consumer_coverage.py b/tests/test_consumer_coverage.py index 36f1b0c94..5a4fffb48 100644 --- a/tests/test_consumer_coverage.py +++ b/tests/test_consumer_coverage.py @@ -106,6 +106,7 @@ async def mark_succeeded_with_conn( *, result_bytes: bytes | None = None, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: self.mark_succeeded_with_conn_calls.append((conn, job_id, worker_id, result)) return await self.mark_succeeded( @@ -559,6 +560,7 @@ async def actor(_job: object, _ctx: JobContext[BaseModel]) -> object: actor=job.actor, queue=job.queue, attempt=job.attempt, + claim_epoch=job.claim_epoch, worker_id=_WORKER_ID, payload=EmptyPayload(), jobs=enqueuer, @@ -623,6 +625,7 @@ async def actor(_job: object, _ctx: JobContext[BaseModel]) -> dict[str, object]: actor=job.actor, queue=job.queue, attempt=job.attempt, + claim_epoch=job.claim_epoch, worker_id=_WORKER_ID, payload=EmptyPayload(), jobs=enqueuer, diff --git a/tests/test_consumer_helper.py b/tests/test_consumer_helper.py index 05786a46f..6f0e81b3b 100644 --- a/tests/test_consumer_helper.py +++ b/tests/test_consumer_helper.py @@ -323,6 +323,7 @@ async def mark_succeeded( *, result_bytes: bytes | None = None, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: write_started.set() await asyncio.sleep(0.05) diff --git a/tests/test_consumer_result_serialization.py b/tests/test_consumer_result_serialization.py index 92b0bcaee..83345463e 100644 --- a/tests/test_consumer_result_serialization.py +++ b/tests/test_consumer_result_serialization.py @@ -77,6 +77,7 @@ async def mark_succeeded_with_conn( *, result_bytes: bytes | None = None, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: self.mark_succeeded_with_conn_calls.append((conn, job_id, worker_id, result, result_bytes)) return await self.mark_succeeded( diff --git a/tests/test_consumer_sub_enqueue.py b/tests/test_consumer_sub_enqueue.py index 628366459..6da74a23a 100644 --- a/tests/test_consumer_sub_enqueue.py +++ b/tests/test_consumer_sub_enqueue.py @@ -122,6 +122,7 @@ async def mark_succeeded_with_conn( *, result_bytes: bytes | None = None, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: self.mark_succeeded_with_conn_calls.append((conn, job_id, worker_id, result)) return await self.mark_succeeded( @@ -380,6 +381,7 @@ async def actor(_job: object, _ctx: JobContext[BaseModel]) -> object: actor=job.actor, queue=job.queue, attempt=job.attempt, + claim_epoch=job.claim_epoch, worker_id=_WORKER_ID, payload=EmptyPayload(), jobs=enqueuer, diff --git a/tests/test_consumer_terminal_guards.py b/tests/test_consumer_terminal_guards.py index 32d8b7b0b..92b57df90 100644 --- a/tests/test_consumer_terminal_guards.py +++ b/tests/test_consumer_terminal_guards.py @@ -92,6 +92,7 @@ async def mark_succeeded_with_conn( *, result_bytes: bytes | None = None, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: return await self.mark_succeeded( job_id, @@ -379,6 +380,7 @@ async def mark_succeeded_with_conn( *, result_bytes: bytes | None = None, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: self.mark_succeeded_calls.append((job_id, worker_id, result, result_bytes)) return False @@ -514,6 +516,7 @@ async def mark_succeeded( *, result_bytes: bytes | None = None, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: self.mark_succeeded_calls.append((job_id, worker_id, result, result_bytes)) return False @@ -530,6 +533,7 @@ async def mark_cancelled( progress_state: dict[str, object] | None = None, *, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: self.mark_cancelled_calls.append( { @@ -788,6 +792,7 @@ async def mark_cancelled( progress_state: dict[str, object] | None = None, *, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: self.mark_cancelled_calls.append( { @@ -958,6 +963,7 @@ async def mark_succeeded( *, result_bytes: bytes | None = None, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: self.mark_succeeded_calls.append((job_id, worker_id, result, result_bytes)) return attempt == self._live_attempt diff --git a/tests/test_context.py b/tests/test_context.py index 4cd7e9ea9..09795b08c 100644 --- a/tests/test_context.py +++ b/tests/test_context.py @@ -45,6 +45,7 @@ def _make_context(**overrides: object) -> JobContext[BaseModel]: "actor": "test_actor", "queue": "default", "attempt": 1, + "claim_epoch": 0, "worker_id": new_uuid(), "payload": _Payload(), "jobs": _make_enqueuer(), @@ -93,6 +94,7 @@ def test_jobs_field_is_required() -> None: actor="test_actor", queue="default", attempt=1, + claim_epoch=0, worker_id=new_uuid(), payload=_Payload(), log=bind_job_context( diff --git a/tests/test_cooperative_cancel_outcome.py b/tests/test_cooperative_cancel_outcome.py index f144167ef..5bb88370c 100644 --- a/tests/test_cooperative_cancel_outcome.py +++ b/tests/test_cooperative_cancel_outcome.py @@ -92,6 +92,7 @@ async def mark_succeeded_with_conn( *, result_bytes: bytes | None = None, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: # The consumer serializes the actor's return exactly once and hands # the backend ``result_bytes`` (the dict form stays None on that diff --git a/tests/test_count_active_jobs.py b/tests/test_count_active_jobs.py index f5b2f1c74..0d0bd41f5 100644 --- a/tests/test_count_active_jobs.py +++ b/tests/test_count_active_jobs.py @@ -71,7 +71,9 @@ async def test_count_active_jobs_terminal_excluded() -> None: dispatched = await backend.dispatch_batch( backend._worker_id, ["default"], limit=1, lock_lease=timedelta(seconds=60) ) - await backend.mark_succeeded(dispatched[0].id, backend._worker_id, None, attempt=1) + await backend.mark_succeeded( + dispatched[0].id, backend._worker_id, None, attempt=1, claim_epoch=1 + ) assert await backend.count_active_jobs(["default"]) == 0 diff --git a/tests/test_denial_and_retention_bounds.py b/tests/test_denial_and_retention_bounds.py index d478da06d..8c770e1fd 100644 --- a/tests/test_denial_and_retention_bounds.py +++ b/tests/test_denial_and_retention_bounds.py @@ -103,7 +103,8 @@ async def _relock_for_next_dispatch( " lock_expires_at = clock_timestamp() + interval '60 seconds', " " started_at = clock_timestamp(), " " last_heartbeat_at = clock_timestamp(), " - " attempt = attempt + 1 " + " attempt = attempt + 1, " + " claim_epoch = claim_epoch + 1 " "WHERE id = $1", job_id, worker_id, @@ -111,7 +112,7 @@ async def _relock_for_next_dispatch( async def _current_attempt(conn: asyncpg.Connection, schema: str, job_id: UUID) -> int: - """The row's current attempt epoch - the denial-cycle writes' fence bind.""" + """The row's current attempt number - the denial-cycle writes' fence bind.""" attempt: int | None = await conn.fetchval( f'SELECT attempt FROM "{schema}".jobs WHERE id = $1', # noqa: S608 # Why: schema is a test-fixture identifier, validated against _IDENT_RE upstream; job_id is $-bound. job_id, @@ -120,6 +121,20 @@ async def _current_attempt(conn: asyncpg.Connection, schema: str, job_id: UUID) return attempt +async def _current_claim_epoch(conn: asyncpg.Connection, schema: str, job_id: UUID) -> int: + """The row's current claim epoch - the denial-cycle writes' second fence bind. + + The relock below bumps it beside the attempt (a real claim advances + both), so the epoch is read fresh each cycle too. + """ + epoch: int | None = await conn.fetchval( + f'SELECT claim_epoch FROM "{schema}".jobs WHERE id = $1', # noqa: S608 + job_id, + ) + assert epoch is not None + return epoch + + async def _count(conn: asyncpg.Connection, schema: str, table: str, job_id: UUID) -> int: count: int | None = await conn.fetchval( f'SELECT count(*) FROM "{schema}".{table} WHERE job_id = $1', # noqa: S608 @@ -155,6 +170,7 @@ async def _drive_denial_loop( # dispatch's attempt increment, so the write carries the row's # CURRENT epoch, read fresh each cycle. attempt=await _current_attempt(conn, schema, job_id), + claim_epoch=await _current_claim_epoch(conn, schema, job_id), ) assert outcome == "scheduled", f"denial cycle did not snooze: {outcome!r}" await _relock_for_next_dispatch(conn, schema, job_id, worker_id) @@ -420,6 +436,7 @@ async def test_denial_rows_are_reclaimable_by_retention( # The attempt-epoch fence: the row's CURRENT epoch, # read fresh each cycle (the relock below increments it). attempt=await _current_attempt(conn, schema, job_id), + claim_epoch=await _current_claim_epoch(conn, schema, job_id), ) if outcome != "scheduled": terminal_outcome = outcome diff --git a/tests/test_denial_observability.py b/tests/test_denial_observability.py index aedf26289..dc0b4fcb4 100644 --- a/tests/test_denial_observability.py +++ b/tests/test_denial_observability.py @@ -245,6 +245,7 @@ async def test_denial_on_non_retryable_at_budget_reschedules_and_spends_no_budge _DELAY, outcome="reservation_denied", attempt=1, + claim_epoch=1, ) assert result == "scheduled", ( "an admission denial must reschedule the job, never terminalise it" @@ -283,6 +284,10 @@ async def test_repeated_denials_never_exhaust_the_budget() -> None: cycles = 5 # far beyond the 1-attempt budget claimed_attempt = 1 + # The refund makes attempt and epoch diverge: every cycle's snooze + # hands the attempt increment back, but the epoch never refunds (each + # new claim bumps it), so the epoch is tracked beside the attempt. + claimed_epoch = 1 for _ in range(cycles): result = await backend.mark_snoozed( job_id, @@ -290,6 +295,7 @@ async def test_repeated_denials_never_exhaust_the_budget() -> None: _DELAY, outcome="rate_limit_denied", attempt=claimed_attempt, + claim_epoch=claimed_epoch, ) assert result == "scheduled", "no number of denials may terminalise a job" clock.advance(_DELAY + timedelta(seconds=1)) @@ -298,6 +304,7 @@ async def test_repeated_denials_never_exhaust_the_budget() -> None: dispatched = await backend.dispatch_batch(worker_id, ["default"], 1, timedelta(seconds=60)) assert [r.id for r in dispatched] == [job_id] claimed_attempt = dispatched[0].attempt + claimed_epoch = dispatched[0].claim_epoch row = await backend.get(job_id) assert row is not None @@ -330,6 +337,7 @@ async def test_denial_past_the_close_deadline_fails_through_the_deadline_path() _DELAY, outcome="reservation_denied", attempt=1, + claim_epoch=1, ) assert result == "failed" @@ -350,7 +358,7 @@ async def test_retry_after_consume_true_on_non_retryable_at_budget_fails() -> No backend, job_id, worker_id = await _mem_job(max_attempts=1, retry_kind="non_retryable") result = await backend.mark_retry_after( - job_id, worker_id, _DELAY, consume_budget=True, attempt=1 + job_id, worker_id, _DELAY, consume_budget=True, attempt=1, claim_epoch=1 ) assert result == "failed:MaxAttemptsExceeded" @@ -377,6 +385,7 @@ async def test_denial_on_job_with_close_deadline_keeps_rescheduling() -> None: _DELAY, outcome="reservation_denied", attempt=1, + claim_epoch=1, ) assert result == "scheduled" @@ -414,6 +423,9 @@ async def test_actor_deferral_is_unbounded_and_never_spends_budget() -> None: cycles = 5 # far beyond the 1-attempt budget zero_delay = timedelta(0) + # The epoch tracks the cycles: every re-claim bumps it, the refund + # never hands it back (only the attempt increment is refunded). + claimed_epoch = 1 for _ in range(cycles): result = await backend.mark_snoozed( job_id, @@ -421,8 +433,10 @@ async def test_actor_deferral_is_unbounded_and_never_spends_budget() -> None: zero_delay, outcome="snoozed", attempt=1, + claim_epoch=claimed_epoch, ) assert result == "scheduled" + claimed_epoch += 1 # Advance past the floored deferral and promote, exactly as the # leader sweep does; pre-floor this is a no-op on an already- # pending job, post-floor it is the promotion that makes the @@ -447,7 +461,7 @@ async def test_actor_deferral_is_unbounded_and_never_spends_budget() -> None: # The consume_budget=False arm carries the same contract. result = await backend.mark_retry_after( - job_id, worker_id, _DELAY, consume_budget=False, attempt=1 + job_id, worker_id, _DELAY, consume_budget=False, attempt=1, claim_epoch=claimed_epoch ) assert result == "scheduled" row = await backend.get(job_id) @@ -476,7 +490,7 @@ async def test_zero_delay_deferrals_reschedule_at_least_min_deferral_interval_ou # Snooze: the actor-requested deferral. backend, job_id, worker_id = await _mem_job(max_attempts=10, retry_kind="transient") - result = await backend.mark_snoozed(job_id, worker_id, timedelta(0), attempt=1) + result = await backend.mark_snoozed(job_id, worker_id, timedelta(0), attempt=1, claim_epoch=1) assert result == "scheduled" row = await backend.get(job_id) assert row is not None @@ -491,6 +505,7 @@ async def test_zero_delay_deferrals_reschedule_at_least_min_deferral_interval_ou timedelta(0), outcome="reservation_denied", attempt=1, + claim_epoch=1, ) assert result == "scheduled" row = await backend.get(job_id) @@ -501,7 +516,7 @@ async def test_zero_delay_deferrals_reschedule_at_least_min_deferral_interval_ou # RetryAfter(consume_budget=False): the arm's twin. backend, job_id, worker_id = await _mem_job(max_attempts=10, retry_kind="transient") result = await backend.mark_retry_after( - job_id, worker_id, timedelta(0), consume_budget=False, attempt=1 + job_id, worker_id, timedelta(0), consume_budget=False, attempt=1, claim_epoch=1 ) assert result == "scheduled" row = await backend.get(job_id) @@ -518,7 +533,7 @@ async def test_consuming_retry_after_keeps_its_raw_zero_delay() -> None: backend, job_id, worker_id = await _mem_job(max_attempts=10, retry_kind="transient") result = await backend.mark_retry_after( - job_id, worker_id, timedelta(0), consume_budget=True, attempt=1 + job_id, worker_id, timedelta(0), consume_budget=True, attempt=1, claim_epoch=1 ) assert result == "scheduled" @@ -560,6 +575,7 @@ async def test_every_admission_denial_is_counted_including_the_last_before_expir _DELAY, outcome="reservation_denied", attempt=1, + claim_epoch=1, ) assert result == "scheduled" row = await backend.get(job_id) @@ -579,6 +595,7 @@ async def test_every_admission_denial_is_counted_including_the_last_before_expir _DELAY, outcome="reservation_denied", attempt=dispatched[0].attempt, + claim_epoch=dispatched[0].claim_epoch, ) assert result == "failed" @@ -612,6 +629,7 @@ async def test_admission_denial_writes_no_event_or_attempt_rows() -> None: _DELAY, outcome="rate_limit_denied", attempt=1, + claim_epoch=1, ) assert result == "scheduled" diff --git a/tests/test_di_acceptance.py b/tests/test_di_acceptance.py index c014b6ac6..73d02da38 100644 --- a/tests/test_di_acceptance.py +++ b/tests/test_di_acceptance.py @@ -70,6 +70,7 @@ async def mark_succeeded( *, result_bytes: object = None, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: return True @@ -83,6 +84,7 @@ async def mark_succeeded_with_conn( *, result_bytes: object = None, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: return True @@ -92,6 +94,7 @@ async def mark_cancelled( worker_id: object, *, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: return True @@ -341,6 +344,7 @@ async def di_actor( actor="di_actor", queue="default", attempt=1, + claim_epoch=0, worker_id=new_uuid(), payload=_Payload(), jobs=SubJobEnqueuer( diff --git a/tests/test_di_actor_scope.py b/tests/test_di_actor_scope.py index 2c11bc829..1d0dd622a 100644 --- a/tests/test_di_actor_scope.py +++ b/tests/test_di_actor_scope.py @@ -64,6 +64,7 @@ def _make_job_ctx() -> JobContext[_Payload]: actor="test_actor", queue="default", attempt=1, + claim_epoch=0, worker_id=new_uuid(), payload=_Payload(), jobs=SubJobEnqueuer( diff --git a/tests/test_disowned_jobs.py b/tests/test_disowned_jobs.py index dd4f426c4..113715943 100644 --- a/tests/test_disowned_jobs.py +++ b/tests/test_disowned_jobs.py @@ -61,6 +61,7 @@ async def mark_failed_or_retry( progress_state: dict[str, object] | None = None, *, attempt: int | None = None, + claim_epoch: int | None = None, ) -> JobRow: raise OSError("connection reset by peer") @@ -75,6 +76,7 @@ async def mark_succeeded( *, result_bytes: bytes | None = None, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: raise OSError("connection reset by peer") @@ -183,6 +185,7 @@ async def mark_succeeded_with_conn( *, result_bytes: bytes | None = None, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: raise OSError("connection reset by peer") @@ -678,6 +681,7 @@ async def mark_snoozed( *, metadata_update: dict[str, object] | None = None, attempt: int | None = None, + claim_epoch: int | None = None, ) -> str: shutdown_event.set() raise OSError("connection reset by peer") diff --git a/tests/test_dispatch_claim_writes_no_event_rows.py b/tests/test_dispatch_claim_writes_no_event_rows.py index 60f67b40e..80d8bcd0c 100644 --- a/tests/test_dispatch_claim_writes_no_event_rows.py +++ b/tests/test_dispatch_claim_writes_no_event_rows.py @@ -103,7 +103,9 @@ async def test_executed_job_leaves_exactly_its_terminal_event( worker_id, ["default"], limit=1, lock_lease=timedelta(seconds=deps.settings.lock_lease) ) assert len(rows) == 1 - ok = await backend.mark_succeeded(job_id, worker_id, result={"ok": True}, attempt=1) + ok = await backend.mark_succeeded( + job_id, worker_id, result={"ok": True}, attempt=1, claim_epoch=1 + ) assert ok is True async with deps.worker_pool.acquire() as conn: diff --git a/tests/test_enqueue_coverage.py b/tests/test_enqueue_coverage.py index a306e4517..7b4a0a6b5 100644 --- a/tests/test_enqueue_coverage.py +++ b/tests/test_enqueue_coverage.py @@ -63,6 +63,7 @@ def _full_record(*, job_id: UUID | None = None) -> dict[str, object]: "status": "pending", "priority": 0, "attempt": 0, + "claim_epoch": 0, "max_attempts": 3, "retry_kind": "transient", "schedule_to_close": None, diff --git a/tests/test_examples_wiring.py b/tests/test_examples_wiring.py index be68ca1c5..6df798406 100644 --- a/tests/test_examples_wiring.py +++ b/tests/test_examples_wiring.py @@ -120,6 +120,7 @@ async def mark_succeeded( *, result_bytes: object = None, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: return True @@ -133,6 +134,7 @@ async def mark_succeeded_with_conn( *, result_bytes: object = None, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: return True @@ -142,6 +144,7 @@ async def mark_cancelled( worker_id: object, *, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: return True diff --git a/tests/test_fleet_capacity_pressure.py b/tests/test_fleet_capacity_pressure.py index b72bc7d96..36c0696e0 100644 --- a/tests/test_fleet_capacity_pressure.py +++ b/tests/test_fleet_capacity_pressure.py @@ -94,6 +94,7 @@ async def test_a_denied_job_spends_no_retry_budget(pg_dsn: str, outcome: str) -> timedelta(seconds=30), outcome=outcome, # pyright: ignore[reportArgumentType] # Why: the parametrize ids are exactly the SnoozeOutcome denial literals. attempt=claimed[0].attempt, + claim_epoch=claimed[0].claim_epoch, ) assert result == "scheduled", ( f"a {outcome} returned {result!r} instead of rescheduling the job. A job " @@ -146,6 +147,7 @@ async def test_repeated_denials_never_end_a_job(pg_dsn: str) -> None: timedelta(seconds=30), outcome="rate_limit_denied", attempt=claimed[0].attempt, + claim_epoch=claimed[0].claim_epoch, ) assert result == "scheduled", ( f"denial round {round_index} returned {result!r}. After " @@ -202,6 +204,7 @@ async def test_a_denial_writes_no_failed_attempt_history(pg_dsn: str) -> None: timedelta(seconds=30), outcome="rate_limit_denied", attempt=claimed[0].attempt, + claim_epoch=claimed[0].claim_epoch, ) written = await _attempt_rows(fleet, job_id) @@ -241,6 +244,7 @@ async def test_capacity_denied_work_is_picked_up_by_a_different_pod( timedelta(seconds=30), outcome="reservation_denied", attempt=claimed[0].attempt, + claim_epoch=claimed[0].claim_epoch, ) # The pod that was refused capacity is replaced, as a deploy diff --git a/tests/test_fleet_pod_lifecycle.py b/tests/test_fleet_pod_lifecycle.py index 40bfdfb64..f087c5a96 100644 --- a/tests/test_fleet_pod_lifecycle.py +++ b/tests/test_fleet_pod_lifecycle.py @@ -301,6 +301,7 @@ async def test_a_snoozed_job_survives_the_pod_that_snoozed_it(pg_dsn: str) -> No fleet.pod("pod-1").worker_id, timedelta(hours=1), attempt=claimed[0].attempt, + claim_epoch=claimed[0].claim_epoch, ) assert outcome == "scheduled", ( f"the snooze returned {outcome!r} rather than scheduling the job; the " @@ -384,7 +385,10 @@ async def test_concurrent_pods_cannot_both_finish_the_same_job(pg_dsn: str) -> N ) stale_write_landed = await fleet.pod("stale").backend.mark_succeeded( - job_id, fleet.pod("stale").worker_id, attempt=claimed[0].attempt + job_id, + fleet.pod("stale").worker_id, + attempt=claimed[0].attempt, + claim_epoch=claimed[0].claim_epoch, ) assert stale_write_landed is False, ( "a pod whose claim on this job was already reclaimed reported the job " diff --git a/tests/test_fleet_throttle_visibility.py b/tests/test_fleet_throttle_visibility.py index 172d254cb..939eb1cae 100644 --- a/tests/test_fleet_throttle_visibility.py +++ b/tests/test_fleet_throttle_visibility.py @@ -91,6 +91,7 @@ async def _work(_payload: FleetPayload, _ctx: object) -> str: timedelta(seconds=0), outcome="rate_limit_denied", attempt=job.attempt, + claim_epoch=job.claim_epoch, ) continue admitted += 1 diff --git a/tests/test_heartbeat_post_tx_contract.py b/tests/test_heartbeat_post_tx_contract.py index 7a75dae30..3ee43840b 100644 --- a/tests/test_heartbeat_post_tx_contract.py +++ b/tests/test_heartbeat_post_tx_contract.py @@ -46,6 +46,7 @@ def _make_ctx(job_id: JobId, worker_id: UUID) -> JobContext[BaseModel]: actor="test_actor", queue="default", attempt=1, + claim_epoch=0, worker_id=worker_id, payload=_StubPayload(), jobs=SubJobEnqueuer(loop_scope_resolved=None, worker_pool=None, backend=None), diff --git a/tests/test_in_memory_backend.py b/tests/test_in_memory_backend.py index 0ce602e74..9e1a70833 100644 --- a/tests/test_in_memory_backend.py +++ b/tests/test_in_memory_backend.py @@ -116,6 +116,11 @@ async def _make_running_row( lock_expires_at=now + timedelta(seconds=30), started_at=now, attempt=1, + # A running row owned by a worker exists because a claim stamped + # it: carry the epoch that claim wrote (the twin's dispatch bumps + # claim_epoch on every claim), so the terminal-write fences under + # test see the shape production hands them. + claim_epoch=1, ) backend._jobs[job_id] = running_row # type: ignore[reportPrivateUsage] # Why: test-only private access to set up running row fixture return job_id, running_row @@ -382,6 +387,7 @@ async def test_happy_path_returns_true(self) -> None: backend._worker_id, # type: ignore[reportPrivateUsage] # Why: test-only private access result={"ok": True}, attempt=1, + claim_epoch=1, ) assert result is True @@ -397,14 +403,17 @@ async def test_noop_returns_false(self) -> None: job_id, _ = await _make_running_row(backend) wid = backend._worker_id # type: ignore[reportPrivateUsage] # Why: test-only private access - assert await backend.mark_succeeded(job_id, wid, None, attempt=1) is True - assert await backend.mark_succeeded(job_id, wid, None, attempt=1) is False + assert await backend.mark_succeeded(job_id, wid, None, attempt=1, claim_epoch=1) is True + assert await backend.mark_succeeded(job_id, wid, None, attempt=1, claim_epoch=1) is False async def test_wrong_worker_returns_false(self) -> None: backend = _make_backend() job_id, _ = await _make_running_row(backend) wrong_worker = new_uuid() - assert await backend.mark_succeeded(job_id, wrong_worker, None, attempt=1) is False + assert ( + await backend.mark_succeeded(job_id, wrong_worker, None, attempt=1, claim_epoch=1) + is False + ) async def test_non_running_returns_false(self) -> None: backend = _make_backend() @@ -433,6 +442,7 @@ async def test_retry_path_returns_scheduled_row(self) -> None: # derives scheduled_at = now + 10s == next_scheduled. next_scheduled - _START, attempt=1, + claim_epoch=1, ) assert result.status == "scheduled" assert result.attempt == 1 @@ -454,6 +464,7 @@ async def test_terminal_failure_path(self) -> None: error_info, retry_delay=None, attempt=1, + claim_epoch=1, ) assert result.status == "failed" assert result.finished_at is not None @@ -474,6 +485,7 @@ async def test_non_retryable_goes_to_failed(self) -> None: error_info, retry_delay=None, attempt=1, + claim_epoch=1, ) assert result.status == "failed" @@ -495,6 +507,7 @@ async def test_ownership_mismatch_raises(self) -> None: error_info, None, attempt=1, + claim_epoch=1, ) async def test_already_terminal_raises_ownership_mismatch(self) -> None: @@ -502,7 +515,7 @@ async def test_already_terminal_raises_ownership_mismatch(self) -> None: job_id, _ = await _make_running_row(backend) wid = backend._worker_id # type: ignore[reportPrivateUsage] # Why: test-only private access - await backend.mark_succeeded(job_id, wid, None, attempt=1) + await backend.mark_succeeded(job_id, wid, None, attempt=1, claim_epoch=1) error_info = ErrorInfo( error_class="ValueError", @@ -510,7 +523,9 @@ async def test_already_terminal_raises_ownership_mismatch(self) -> None: error_traceback=None, ) with pytest.raises(WorkerOwnershipMismatch): - await backend.mark_failed_or_retry(job_id, wid, error_info, None, attempt=1) + await backend.mark_failed_or_retry( + job_id, wid, error_info, None, attempt=1, claim_epoch=1 + ) class TestMarkCancelled: @@ -519,7 +534,7 @@ async def test_happy_path_returns_true(self) -> None: job_id, _ = await _make_running_row(backend) wid = backend._worker_id # type: ignore[reportPrivateUsage] # Why: test-only private access - assert await backend.mark_cancelled(job_id, wid, attempt=1) is True + assert await backend.mark_cancelled(job_id, wid, attempt=1, claim_epoch=1) is True row = await backend.get(job_id) assert row is not None assert row.status == "cancelled" @@ -529,8 +544,8 @@ async def test_noop_returns_false(self) -> None: job_id, _ = await _make_running_row(backend) wid = backend._worker_id # type: ignore[reportPrivateUsage] # Why: test-only private access - assert await backend.mark_cancelled(job_id, wid, attempt=1) is True - assert await backend.mark_cancelled(job_id, wid, attempt=1) is False + assert await backend.mark_cancelled(job_id, wid, attempt=1, claim_epoch=1) is True + assert await backend.mark_cancelled(job_id, wid, attempt=1, claim_epoch=1) is False async def test_wrong_worker_returns_false(self) -> None: backend = _make_backend() @@ -627,7 +642,9 @@ async def test_happy_path_returns_scheduled(self) -> None: wid = backend._worker_id # type: ignore[reportPrivateUsage] # Why: test-only private access delay = timedelta(seconds=30) - assert await backend.mark_snoozed(job_id, wid, delay, attempt=1) == "scheduled" + assert ( + await backend.mark_snoozed(job_id, wid, delay, attempt=1, claim_epoch=1) == "scheduled" + ) row = await backend.get(job_id) assert row is not None assert row.status == "scheduled" @@ -640,8 +657,10 @@ async def test_noop_returns_noop(self) -> None: wid = backend._worker_id # type: ignore[reportPrivateUsage] # Why: test-only private access delay = timedelta(seconds=30) - assert await backend.mark_snoozed(job_id, wid, delay, attempt=1) == "scheduled" - assert await backend.mark_snoozed(job_id, wid, delay, attempt=1) == "noop" + assert ( + await backend.mark_snoozed(job_id, wid, delay, attempt=1, claim_epoch=1) == "scheduled" + ) + assert await backend.mark_snoozed(job_id, wid, delay, attempt=1, claim_epoch=1) == "noop" async def test_metadata_update(self) -> None: backend = _make_backend() @@ -651,7 +670,12 @@ async def test_metadata_update(self) -> None: delay = timedelta(seconds=30) assert ( await backend.mark_snoozed( - job_id, wid, delay, metadata_update={"snooze_reason": "busy"}, attempt=1 + job_id, + wid, + delay, + metadata_update={"snooze_reason": "busy"}, + attempt=1, + claim_epoch=1, ) == "scheduled" ) @@ -663,7 +687,10 @@ async def test_wrong_worker_returns_noop(self) -> None: backend = _make_backend() job_id, _ = await _make_running_row(backend) delay = timedelta(seconds=30) - assert await backend.mark_snoozed(job_id, new_uuid(), delay, attempt=1) == "noop" + assert ( + await backend.mark_snoozed(job_id, new_uuid(), delay, attempt=1, claim_epoch=1) + == "noop" + ) # ── Attempt history ──────────────────────────────────────────────────── @@ -772,7 +799,7 @@ async def test_case_c_terminal_returns_false(self) -> None: backend = _make_backend() job_id, _ = await _make_running_row(backend) wid = backend._worker_id # type: ignore[reportPrivateUsage] # Why: test-only private access - await backend.mark_succeeded(job_id, wid, None, attempt=1) + await backend.mark_succeeded(job_id, wid, None, attempt=1, claim_epoch=1) assert await backend.write_cancel_request(job_id, None) is False @@ -1401,8 +1428,8 @@ async def test_mark_succeeded_bool(self) -> None: backend = _make_backend() job_id, _ = await _make_running_row(backend) wid = backend._worker_id # type: ignore[reportPrivateUsage] # Why: test-only private access - r1 = await backend.mark_succeeded(job_id, wid, None, attempt=1) - r2 = await backend.mark_succeeded(job_id, wid, None, attempt=1) + r1 = await backend.mark_succeeded(job_id, wid, None, attempt=1, claim_epoch=1) + r2 = await backend.mark_succeeded(job_id, wid, None, attempt=1, claim_epoch=1) assert r1 is True assert r2 is False @@ -1410,8 +1437,8 @@ async def test_mark_cancelled_bool(self) -> None: backend = _make_backend() job_id, _ = await _make_running_row(backend) wid = backend._worker_id # type: ignore[reportPrivateUsage] # Why: test-only private access - r1 = await backend.mark_cancelled(job_id, wid, attempt=1) - r2 = await backend.mark_cancelled(job_id, wid, attempt=1) + r1 = await backend.mark_cancelled(job_id, wid, attempt=1, claim_epoch=1) + r2 = await backend.mark_cancelled(job_id, wid, attempt=1, claim_epoch=1) assert r1 is True assert r2 is False @@ -1433,8 +1460,8 @@ async def test_mark_snoozed_bool(self) -> None: job_id, _ = await _make_running_row(backend) wid = backend._worker_id # type: ignore[reportPrivateUsage] # Why: test-only private access delay = timedelta(seconds=30) - r1 = await backend.mark_snoozed(job_id, wid, delay, attempt=1) - r2 = await backend.mark_snoozed(job_id, wid, delay, attempt=1) + r1 = await backend.mark_snoozed(job_id, wid, delay, attempt=1, claim_epoch=1) + r2 = await backend.mark_snoozed(job_id, wid, delay, attempt=1, claim_epoch=1) assert r1 == "scheduled" assert r2 == "noop" @@ -1613,6 +1640,7 @@ async def test_running_jobs_not_counted(self) -> None: lock_expires_at=now + timedelta(seconds=30), started_at=now, attempt=1, + claim_epoch=1, ) # Second enqueue should succeed because running is not counted @@ -1653,6 +1681,7 @@ async def test_lock_expires_after_clock_advance(self) -> None: lock_expires_at=now + lock_lease, started_at=now, attempt=1, + claim_epoch=1, ) backend._jobs[job_id] = running_row # type: ignore[reportPrivateUsage] # Why: test-only private access @@ -1738,6 +1767,68 @@ async def test_old_succeeded_archived_recent_untouched(self) -> None: assert await backend.get(jid) is not None assert await backend.get_archived(jid) is None + async def test_archived_row_carries_the_claimed_epoch(self) -> None: + """A job the fleet claimed twice (dispatch, deferral release, + redispatch) and then archived carries the epoch its last claim + stamped: the twin's archive moves the row whole, mirroring the + PG CTE's explicit column list, so the archived identity is the + live row's at the moment of archival, never a reset 0.""" + from taskq.testing._runner import advance_clock_to + from taskq.testing.clock import FakeClock + + clock = FakeClock(_START) + backend = InMemoryBackend( + clock=clock, cancellation_grace_period=_GRACE, cleanup_grace_period=_GRACE + ) + backend.register_actor_config(actor="test_actor") + + row = await backend.enqueue(_enqueue_args()) + first = await backend.dispatch_batch( + backend._worker_id, # type: ignore[reportPrivateUsage] + ["default"], + limit=1, + lock_lease=timedelta(seconds=60), + ) + assert first[0].claim_epoch == 1 + await backend.mark_snoozed( + row.id, + backend._worker_id, # type: ignore[reportPrivateUsage] + timedelta(seconds=30), + attempt=first[0].attempt, + claim_epoch=first[0].claim_epoch, + ) + advance_clock_to(backend, clock.now() + timedelta(minutes=1)) + assert await backend.scheduled_to_pending() == 1 + second = await backend.dispatch_batch( + backend._worker_id, # type: ignore[reportPrivateUsage] + ["default"], + limit=1, + lock_lease=timedelta(seconds=60), + ) + assert second[0].id == row.id + assert second[0].claim_epoch == 2 + + assert ( + await backend.mark_succeeded( + row.id, + backend._worker_id, # type: ignore[reportPrivateUsage] + None, + attempt=second[0].attempt, + claim_epoch=second[0].claim_epoch, + ) + is True + ) + advance_clock_to(backend, clock.now() + timedelta(minutes=1)) + + result = backend.archive_terminal_jobs( + retention=timedelta(0), archive_retention=timedelta(days=365) + ) + assert result.archived == 1 + + archived = await backend.get_archived(row.id) + assert archived is not None + assert archived.row.claim_epoch == second[0].claim_epoch == 2 + async def test_per_status_retention(self) -> None: """per-status retention - succeeded/cancelled archived at 35d, failed retained at 35d when failure retention=90d. Uses the `statuses` diff --git a/tests/test_in_memory_cancel.py b/tests/test_in_memory_cancel.py index d33562596..c2420993d 100644 --- a/tests/test_in_memory_cancel.py +++ b/tests/test_in_memory_cancel.py @@ -71,6 +71,7 @@ async def _make_running_job(backend: InMemoryBackend) -> tuple[JobId, UUID]: lock_expires_at=now + timedelta(seconds=60), started_at=now, attempt=1, + claim_epoch=1, ) backend._jobs[args.id] = running_row return args.id, wid @@ -237,7 +238,7 @@ async def test_cancel_events_cleaned_up_on_terminal(self) -> None: # pending job transitions to cancelled). For a running job, # we can mark it cancelled directly. wid = backend._worker_id - await backend.mark_cancelled(job_id, wid, attempt=1) + await backend.mark_cancelled(job_id, wid, attempt=1, claim_epoch=1) # tick_cancel_polling should clean up the tracking dicts await backend.tick_cancel_polling() @@ -307,7 +308,7 @@ async def test_cooperative_cancel_stamps_error_class(self) -> None: backend = _make_backend() job_id, worker_id = await _make_running_job(backend) - assert await backend.mark_cancelled(job_id, worker_id, attempt=1) is True + assert await backend.mark_cancelled(job_id, worker_id, attempt=1, claim_epoch=1) is True row = await backend.get(job_id) assert row is not None @@ -338,7 +339,7 @@ async def test_cancel_origins_are_distinguishable_on_the_row(self) -> None: ) await backend.enqueue(pending_args) - assert await backend.mark_cancelled(coop_job, coop_worker, attempt=1) is True + assert await backend.mark_cancelled(coop_job, coop_worker, attempt=1, claim_epoch=1) is True # The abandon path requires the escalated phase the forcing ladder reaches. backend._jobs[abandon_job] = _dc_replace(backend._jobs[abandon_job], cancel_phase=2) assert await backend.mark_abandoned(abandon_job) is True @@ -372,7 +373,7 @@ async def test_cancelled_attempt_records_its_reason(self) -> None: backend = _make_backend() job_id, worker_id = await _make_running_job(backend) - assert await backend.mark_cancelled(job_id, worker_id, attempt=1) is True + assert await backend.mark_cancelled(job_id, worker_id, attempt=1, claim_epoch=1) is True attempts = await backend.get_attempts(job_id) assert len(attempts) == 1 @@ -457,7 +458,7 @@ async def test_phase_1_cancel_stamps_the_cooperative_marker(self) -> None: job_id, worker_id = await _make_running_job(backend) assert await backend.write_cancel_request(job_id, "operator stop") is True - assert await backend.mark_cancelled(job_id, worker_id, attempt=1) is True + assert await backend.mark_cancelled(job_id, worker_id, attempt=1, claim_epoch=1) is True row = await backend.get(job_id) assert row is not None @@ -478,7 +479,7 @@ async def test_phase_2_cancel_stamps_the_forced_marker(self) -> None: assert await backend.write_cancel_request(job_id, "operator stop") is True assert await backend.write_cancel_escalation(job_id, worker_id, 2) is True - assert await backend.mark_cancelled(job_id, worker_id, attempt=1) is True + assert await backend.mark_cancelled(job_id, worker_id, attempt=1, claim_epoch=1) is True row = await backend.get(job_id) assert row is not None diff --git a/tests/test_in_memory_dispatch.py b/tests/test_in_memory_dispatch.py index 876df37c6..02f19c5af 100644 --- a/tests/test_in_memory_dispatch.py +++ b/tests/test_in_memory_dispatch.py @@ -668,6 +668,7 @@ async def test_claim_and_denial_write_no_event_rows() -> None: timedelta(seconds=10), outcome="reservation_denied", attempt=dispatched[0].attempt, + claim_epoch=dispatched[0].claim_epoch, ) assert outcome == "scheduled" @@ -1039,6 +1040,7 @@ async def test_running_row_written_without_a_lease_gets_one_stamped(self) -> Non row, status="running", attempt=1, + claim_epoch=1, started_at=_START, locked_by_worker=new_uuid(), lock_expires_at=None, diff --git a/tests/test_in_memory_read_isolation.py b/tests/test_in_memory_read_isolation.py index 9a6d308d1..baab382e0 100644 --- a/tests/test_in_memory_read_isolation.py +++ b/tests/test_in_memory_read_isolation.py @@ -148,7 +148,7 @@ async def test_mark_succeeded_does_not_store_caller_result_by_reference() -> Non assert len(claimed) == 1 result: dict[str, object] = {"value": 1} - await backend.mark_succeeded(row.id, worker_id, result, attempt=1) + await backend.mark_succeeded(row.id, worker_id, result, attempt=1, claim_epoch=1) result["injected"] = True fresh = await backend.get(row.id) @@ -167,7 +167,9 @@ async def test_list_result_from_result_bytes_does_not_alias_storage() -> None: worker_id = new_uuid() claimed = await backend.dispatch_batch(worker_id, ["default"], 10, timedelta(seconds=60)) assert len(claimed) == 1 - await backend.mark_succeeded(row.id, worker_id, result_bytes=b"[1, 2]", attempt=1) + await backend.mark_succeeded( + row.id, worker_id, result_bytes=b"[1, 2]", attempt=1, claim_epoch=1 + ) first = await backend.get(row.id) assert first is not None @@ -191,7 +193,7 @@ async def test_get_archived_row_does_not_alias_storage() -> None: worker_id = new_uuid() claimed = await backend.dispatch_batch(worker_id, ["default"], 10, timedelta(seconds=60)) assert len(claimed) == 1 - await backend.mark_succeeded(row.id, worker_id, {"value": 1}, attempt=1) + await backend.mark_succeeded(row.id, worker_id, {"value": 1}, attempt=1, claim_epoch=1) clock.advance(timedelta(days=1)) archive_terminal_jobs( @@ -216,7 +218,7 @@ async def test_get_events_rows_do_not_alias_storage() -> None: worker_id = new_uuid() claimed = await backend.dispatch_batch(worker_id, ["default"], 10, timedelta(seconds=60)) assert len(claimed) == 1 - await backend.mark_succeeded(row.id, worker_id, {"value": 1}, attempt=1) + await backend.mark_succeeded(row.id, worker_id, {"value": 1}, attempt=1, claim_epoch=1) events = await backend.get_events(row.id) assert events, "expected at least one state-change event" @@ -263,7 +265,7 @@ async def test_get_attempts_rows_do_not_alias_storage() -> None: worker_id = new_uuid() claimed = await backend.dispatch_batch(worker_id, ["default"], 10, timedelta(seconds=60)) assert len(claimed) == 1 - await backend.mark_succeeded(row.id, worker_id, {"value": 1}, attempt=1) + await backend.mark_succeeded(row.id, worker_id, {"value": 1}, attempt=1, claim_epoch=1) attempts = await backend.get_attempts(row.id) assert attempts, "expected the success attempt to be recorded" @@ -320,6 +322,7 @@ async def test_mark_failed_or_retry_returned_row_does_not_alias_storage() -> Non ErrorInfo(error_class="TestError", error_message="boom", error_traceback=None), None, attempt=1, + claim_epoch=1, ) returned.payload["injected"] = True diff --git a/tests/test_in_memory_terminal_writes.py b/tests/test_in_memory_terminal_writes.py index 3947e9f54..81f4c8eba 100644 --- a/tests/test_in_memory_terminal_writes.py +++ b/tests/test_in_memory_terminal_writes.py @@ -103,10 +103,12 @@ async def test_mark_succeeded_single_attempt_and_event(self) -> None: backend = _make_backend() job_id, wid = await _enqueue_and_dispatch(backend) - r1 = await backend.mark_succeeded(job_id, wid, result={"ok": True}, attempt=1) + r1 = await backend.mark_succeeded( + job_id, wid, result={"ok": True}, attempt=1, claim_epoch=1 + ) assert r1 is True - r2 = await backend.mark_succeeded(job_id, wid, result=None, attempt=1) + r2 = await backend.mark_succeeded(job_id, wid, result=None, attempt=1, claim_epoch=1) assert r2 is False attempts = await backend.get_attempts(job_id) @@ -128,7 +130,9 @@ async def test_mark_failed_or_retry_terminal_single_attempt_and_event(self) -> N error_message="boom", error_traceback=None, ) - result = await backend.mark_failed_or_retry(job_id, wid, error_info, None, attempt=1) + result = await backend.mark_failed_or_retry( + job_id, wid, error_info, None, attempt=1, claim_epoch=1 + ) assert result.status == "failed" attempts = await backend.get_attempts(job_id) @@ -146,10 +150,10 @@ async def test_mark_cancelled_single_attempt_and_event(self) -> None: backend = _make_backend() job_id, wid = await _enqueue_and_dispatch(backend) - r1 = await backend.mark_cancelled(job_id, wid, attempt=1) + r1 = await backend.mark_cancelled(job_id, wid, attempt=1, claim_epoch=1) assert r1 is True - r2 = await backend.mark_cancelled(job_id, wid, attempt=1) + r2 = await backend.mark_cancelled(job_id, wid, attempt=1, claim_epoch=1) assert r2 is False attempts = await backend.get_attempts(job_id) @@ -175,11 +179,16 @@ async def test_bool_returning_wrong_worker_returns_false(self) -> None: job_id, _wid = await _enqueue_and_dispatch(backend) wrong_worker = new_uuid() - assert await backend.mark_succeeded(job_id, wrong_worker, None, attempt=1) is False - assert await backend.mark_cancelled(job_id, wrong_worker, attempt=1) is False + assert ( + await backend.mark_succeeded(job_id, wrong_worker, None, attempt=1, claim_epoch=1) + is False + ) + assert await backend.mark_cancelled(job_id, wrong_worker, attempt=1, claim_epoch=1) is False assert ( - await backend.mark_snoozed(job_id, wrong_worker, timedelta(seconds=30), attempt=1) + await backend.mark_snoozed( + job_id, wrong_worker, timedelta(seconds=30), attempt=1, claim_epoch=1 + ) == "noop" ) @@ -194,14 +203,16 @@ async def test_mark_failed_or_retry_wrong_worker_raises(self) -> None: error_traceback=None, ) with pytest.raises(WorkerOwnershipMismatch): - await backend.mark_failed_or_retry(job_id, wrong_worker, error_info, None, attempt=1) + await backend.mark_failed_or_retry( + job_id, wrong_worker, error_info, None, attempt=1, claim_epoch=1 + ) async def test_mark_failed_or_retry_already_terminal_raises(self) -> None: """Already-terminal raises WorkerOwnershipMismatch (PG rowcount=0).""" backend = _make_backend() job_id, wid = await _enqueue_and_dispatch(backend) - await backend.mark_succeeded(job_id, wid, None, attempt=1) + await backend.mark_succeeded(job_id, wid, None, attempt=1, claim_epoch=1) error_info = ErrorInfo( error_class="ValueError", @@ -209,7 +220,9 @@ async def test_mark_failed_or_retry_already_terminal_raises(self) -> None: error_traceback=None, ) with pytest.raises(WorkerOwnershipMismatch) as exc_info: - await backend.mark_failed_or_retry(job_id, wid, error_info, None, attempt=1) + await backend.mark_failed_or_retry( + job_id, wid, error_info, None, attempt=1, claim_epoch=1 + ) assert exc_info.value.job_id == job_id assert exc_info.value.expected == wid # The succeeded row cleared its lock holder (PG's mark_succeeded @@ -266,7 +279,7 @@ class TestSingleAttemptRowPerTransition: async def test_mark_succeeded_attempt_and_event(self) -> None: backend = _make_backend() job_id, wid = await _enqueue_and_dispatch(backend) - await backend.mark_succeeded(job_id, wid, None, attempt=1) + await backend.mark_succeeded(job_id, wid, None, attempt=1, claim_epoch=1) attempts = await backend.get_attempts(job_id) assert len(attempts) == 1 @@ -284,7 +297,7 @@ async def test_mark_failed_terminal_attempt_and_event(self) -> None: error_message="boom", error_traceback=None, ) - await backend.mark_failed_or_retry(job_id, wid, error_info, None, attempt=1) + await backend.mark_failed_or_retry(job_id, wid, error_info, None, attempt=1, claim_epoch=1) attempts = await backend.get_attempts(job_id) assert len(attempts) == 1 @@ -308,6 +321,7 @@ async def test_mark_failed_retry_attempt_and_event(self) -> None: error_info, retry_delay=timedelta(seconds=10), attempt=1, + claim_epoch=1, ) attempts = await backend.get_attempts(job_id) @@ -322,7 +336,7 @@ async def test_mark_failed_retry_attempt_and_event(self) -> None: async def test_mark_cancelled_attempt_and_event(self) -> None: backend = _make_backend() job_id, wid = await _enqueue_and_dispatch(backend) - await backend.mark_cancelled(job_id, wid, attempt=1) + await backend.mark_cancelled(job_id, wid, attempt=1, claim_epoch=1) attempts = await backend.get_attempts(job_id) assert len(attempts) == 1 @@ -335,7 +349,7 @@ async def test_mark_cancelled_attempt_and_event(self) -> None: async def test_mark_snoozed_attempt_and_event(self) -> None: backend = _make_backend() job_id, wid = await _enqueue_and_dispatch(backend) - await backend.mark_snoozed(job_id, wid, timedelta(seconds=30), attempt=1) + await backend.mark_snoozed(job_id, wid, timedelta(seconds=30), attempt=1, claim_epoch=1) # A snooze is a deferral, not an execution: no attempt row and no # event row - the row's snooze_count is its whole durable record. @@ -371,7 +385,7 @@ async def test_first_call_true_second_false(self) -> None: job_id, wid = await _enqueue_and_dispatch(backend) delay = timedelta(seconds=30) - r1 = await backend.mark_snoozed(job_id, wid, delay, attempt=1) + r1 = await backend.mark_snoozed(job_id, wid, delay, attempt=1, claim_epoch=1) assert r1 == "scheduled" row = await backend.get(job_id) @@ -379,7 +393,7 @@ async def test_first_call_true_second_false(self) -> None: assert row.status == "scheduled" assert row.locked_by_worker is None - r2 = await backend.mark_snoozed(job_id, wid, delay, attempt=1) + r2 = await backend.mark_snoozed(job_id, wid, delay, attempt=1, claim_epoch=1) assert r2 == "noop" async def test_metadata_update_merges(self) -> None: @@ -393,6 +407,7 @@ async def test_metadata_update_merges(self) -> None: delay, metadata_update={"a": 1}, attempt=1, + claim_epoch=1, ) row = await backend.get(job_id) @@ -411,6 +426,7 @@ async def test_metadata_update_none_preserves_existing(self) -> None: delay, metadata_update={"existing": 42}, attempt=1, + claim_epoch=1, ) # Snooze again won't work (already scheduled), but test the @@ -420,7 +436,9 @@ async def test_metadata_update_none_preserves_existing(self) -> None: row = backend._jobs[job_id2] # type: ignore[reportPrivateUsage] # Why: test-only private access backend._jobs[job_id2] = replace(row, metadata={"pre": "existing"}) # type: ignore[reportPrivateUsage] # Why: test-only private access - await backend.mark_snoozed(job_id2, wid2, delay, metadata_update=None, attempt=1) + await backend.mark_snoozed( + job_id2, wid2, delay, metadata_update=None, attempt=1, claim_epoch=1 + ) row2 = await backend.get(job_id2) assert row2 is not None assert row2.metadata == {"pre": "existing"} @@ -431,7 +449,7 @@ async def test_snoozed_attempt_outcome(self) -> None: backend = _make_backend() job_id, wid = await _enqueue_and_dispatch(backend) delay = timedelta(seconds=30) - await backend.mark_snoozed(job_id, wid, delay, attempt=1) + await backend.mark_snoozed(job_id, wid, delay, attempt=1, claim_epoch=1) attempts = await backend.get_attempts(job_id) assert len(attempts) == 0 @@ -542,6 +560,10 @@ def _bump_to_attempt(backend: InMemoryBackend, job_id: JobId, attempt: int) -> N backend._jobs[job_id] = replace( # type: ignore[reportPrivateUsage] # Why: test-only private access row, attempt=attempt, + # A real reclaim + redispatch also advances the claim epoch (the + # twin's claim bumps it every claim); the simulated redispatch + # must move both or the fence under test is not the shipped one. + claim_epoch=row.claim_epoch + 1, ) @@ -564,7 +586,7 @@ async def test_mark_succeeded_stale_attempt_no_ops(self) -> None: job_id, wid = await _enqueue_and_dispatch(backend) _bump_to_attempt(backend, job_id, 2) - assert await backend.mark_succeeded(job_id, wid, None, attempt=1) is False, ( + assert await backend.mark_succeeded(job_id, wid, None, attempt=1, claim_epoch=1) is False, ( "a stale attempt's success write must not terminate the redispatched attempt" ) row = await backend.get(job_id) @@ -593,7 +615,7 @@ async def test_mark_succeeded_live_attempt_lands(self) -> None: job_id, wid = await _enqueue_and_dispatch(backend) _bump_to_attempt(backend, job_id, 2) - assert await backend.mark_succeeded(job_id, wid, None, attempt=2) is True + assert await backend.mark_succeeded(job_id, wid, None, attempt=2, claim_epoch=2) is True row = await backend.get(job_id) assert row is not None assert row.status == "succeeded" @@ -603,7 +625,7 @@ async def test_mark_cancelled_stale_attempt_no_ops(self) -> None: job_id, wid = await _enqueue_and_dispatch(backend) _bump_to_attempt(backend, job_id, 2) - assert await backend.mark_cancelled(job_id, wid, attempt=1) is False + assert await backend.mark_cancelled(job_id, wid, attempt=1, claim_epoch=1) is False row = await backend.get(job_id) assert row is not None assert row.status == "running" @@ -619,14 +641,16 @@ async def test_mark_cancelled_live_attempt_lands(self) -> None: job_id, wid = await _enqueue_and_dispatch(backend) _bump_to_attempt(backend, job_id, 2) - assert await backend.mark_cancelled(job_id, wid, attempt=2) is True + assert await backend.mark_cancelled(job_id, wid, attempt=2, claim_epoch=2) is True async def test_mark_snoozed_stale_attempt_no_ops(self) -> None: backend = _make_backend() job_id, wid = await _enqueue_and_dispatch(backend) _bump_to_attempt(backend, job_id, 2) - result = await backend.mark_snoozed(job_id, wid, timedelta(seconds=30), attempt=1) + result = await backend.mark_snoozed( + job_id, wid, timedelta(seconds=30), attempt=1, claim_epoch=1 + ) assert result == "noop" row = await backend.get(job_id) assert row is not None @@ -644,7 +668,9 @@ async def test_mark_snoozed_live_attempt_lands(self) -> None: job_id, wid = await _enqueue_and_dispatch(backend) _bump_to_attempt(backend, job_id, 2) - result = await backend.mark_snoozed(job_id, wid, timedelta(seconds=30), attempt=2) + result = await backend.mark_snoozed( + job_id, wid, timedelta(seconds=30), attempt=2, claim_epoch=2 + ) assert result == "scheduled" async def test_mark_retry_after_stale_attempt_no_ops(self) -> None: @@ -652,7 +678,9 @@ async def test_mark_retry_after_stale_attempt_no_ops(self) -> None: job_id, wid = await _enqueue_and_dispatch(backend) _bump_to_attempt(backend, job_id, 2) - result = await backend.mark_retry_after(job_id, wid, timedelta(seconds=10), attempt=1) + result = await backend.mark_retry_after( + job_id, wid, timedelta(seconds=10), attempt=1, claim_epoch=1 + ) assert result == "noop" row = await backend.get(job_id) assert row is not None @@ -664,7 +692,7 @@ async def test_mark_retry_after_live_attempt_lands(self) -> None: _bump_to_attempt(backend, job_id, 2) result = await backend.mark_retry_after( - job_id, wid, timedelta(seconds=10), consume_budget=False, attempt=2 + job_id, wid, timedelta(seconds=10), consume_budget=False, attempt=2, claim_epoch=2 ) assert result == "scheduled" @@ -683,7 +711,9 @@ async def test_mark_failed_or_retry_stale_attempt_raises_mismatch(self) -> None: error_traceback=None, ) with pytest.raises(WorkerOwnershipMismatch): - await backend.mark_failed_or_retry(job_id, wid, error_info, None, attempt=1) + await backend.mark_failed_or_retry( + job_id, wid, error_info, None, attempt=1, claim_epoch=1 + ) row = await backend.get(job_id) assert row is not None assert row.status == "running" @@ -711,7 +741,7 @@ async def test_mark_failed_or_retry_live_attempt_lands(self) -> None: error_traceback=None, ) result = await backend.mark_failed_or_retry( - job_id, wid, error_info, timedelta(seconds=10), attempt=2 + job_id, wid, error_info, timedelta(seconds=10), attempt=2, claim_epoch=2 ) assert result.status == "scheduled" @@ -728,18 +758,23 @@ class TestWrongWorkerIdHandling: async def test_mark_succeeded_wrong_worker_false(self) -> None: backend = _make_backend() job_id, _wid = await _enqueue_and_dispatch(backend) - assert await backend.mark_succeeded(job_id, new_uuid(), None, attempt=1) is False + assert ( + await backend.mark_succeeded(job_id, new_uuid(), None, attempt=1, claim_epoch=1) + is False + ) async def test_mark_cancelled_wrong_worker_false(self) -> None: backend = _make_backend() job_id, _wid = await _enqueue_and_dispatch(backend) - assert await backend.mark_cancelled(job_id, new_uuid(), attempt=1) is False + assert await backend.mark_cancelled(job_id, new_uuid(), attempt=1, claim_epoch=1) is False async def test_mark_snoozed_wrong_worker_false(self) -> None: backend = _make_backend() job_id, _wid = await _enqueue_and_dispatch(backend) assert ( - await backend.mark_snoozed(job_id, new_uuid(), timedelta(seconds=30), attempt=1) + await backend.mark_snoozed( + job_id, new_uuid(), timedelta(seconds=30), attempt=1, claim_epoch=1 + ) == "noop" ) @@ -752,7 +787,9 @@ async def test_mark_failed_or_retry_wrong_worker_raises(self) -> None: error_traceback=None, ) with pytest.raises(WorkerOwnershipMismatch): - await backend.mark_failed_or_retry(job_id, new_uuid(), error_info, None, attempt=1) + await backend.mark_failed_or_retry( + job_id, new_uuid(), error_info, None, attempt=1, claim_epoch=1 + ) # ── mark_cancelled preserves cancel_phase ───────────────────── @@ -768,7 +805,7 @@ async def test_cancel_phase_preserved_on_mark_cancelled_phase1(self) -> None: job_id, wid = await _enqueue_and_dispatch(backend) _set_cancel_phase(backend, job_id, 1) - await backend.mark_cancelled(job_id, wid, attempt=1) + await backend.mark_cancelled(job_id, wid, attempt=1, claim_epoch=1) row = await backend.get(job_id) assert row is not None assert row.status == "cancelled" @@ -779,7 +816,7 @@ async def test_cancel_phase_preserved_on_mark_cancelled_phase2(self) -> None: job_id, wid = await _enqueue_and_dispatch(backend) _set_cancel_phase(backend, job_id, 2) - await backend.mark_cancelled(job_id, wid, attempt=1) + await backend.mark_cancelled(job_id, wid, attempt=1, claim_epoch=1) row = await backend.get(job_id) assert row is not None assert row.status == "cancelled" @@ -804,7 +841,9 @@ async def test_payload_validation_error_terminal_failure(self) -> None: error_message=str(raw_payload), error_traceback=None, ) - result = await backend.mark_failed_or_retry(job_id, wid, error_info, None, attempt=1) + result = await backend.mark_failed_or_retry( + job_id, wid, error_info, None, attempt=1, claim_epoch=1 + ) assert result.status == "failed" assert result.error_class == "PayloadValidationError" @@ -1041,6 +1080,7 @@ async def test_cancel_phase1_reset_on_retry(self) -> None: error_info, retry_delay=timedelta(seconds=10), attempt=1, + claim_epoch=1, ) assert result.status == "scheduled" assert result.cancel_phase == CancelPhase.NONE @@ -1064,6 +1104,7 @@ async def test_cancel_phase2_reset_on_retry(self) -> None: error_info, retry_delay=timedelta(seconds=10), attempt=1, + claim_epoch=1, ) assert result.status == "scheduled" assert result.cancel_phase == CancelPhase.NONE @@ -1094,6 +1135,7 @@ async def test_mark_succeeded_applies_progress(self) -> None: progress_seq=5, progress_state={"pct": 100}, attempt=1, + claim_epoch=1, ) row = await backend.get(job_id) @@ -1118,6 +1160,7 @@ async def test_mark_failed_applies_progress(self) -> None: progress_seq=3, progress_state={"step": "failed"}, attempt=1, + claim_epoch=1, ) row = await backend.get(job_id) @@ -1141,6 +1184,7 @@ async def test_progress_state_none_preserves_existing(self) -> None: progress_seq=1, progress_state=None, attempt=1, + claim_epoch=1, ) updated = await backend.get(job_id) @@ -1264,7 +1308,9 @@ async def test_in_memory_snooze_refunds_attempt(self) -> None: assert row is not None assert row.attempt == 1 - result = await backend.mark_snoozed(job_id, wid, timedelta(seconds=30), attempt=1) + result = await backend.mark_snoozed( + job_id, wid, timedelta(seconds=30), attempt=1, claim_epoch=1 + ) assert result == "scheduled" row = await backend.get(job_id) @@ -1288,7 +1334,9 @@ async def test_in_memory_snooze_clears_last_heartbeat_at(self) -> None: assert row is not None assert row.last_heartbeat_at is not None - result = await backend.mark_snoozed(job_id, wid, timedelta(seconds=30), attempt=1) + result = await backend.mark_snoozed( + job_id, wid, timedelta(seconds=30), attempt=1, claim_epoch=1 + ) assert result == "scheduled" row = await backend.get(job_id) @@ -1312,7 +1360,9 @@ async def test_in_memory_snooze_past_deadline_fails(self) -> None: schedule_to_close=deadline, ) - result = await backend.mark_snoozed(job_id, wid, timedelta(seconds=30), attempt=1) + result = await backend.mark_snoozed( + job_id, wid, timedelta(seconds=30), attempt=1, claim_epoch=1 + ) assert result == "failed" row = await backend.get(job_id) @@ -1332,7 +1382,9 @@ async def test_in_memory_snooze_within_deadline_succeeds(self) -> None: schedule_to_close=deadline, ) - result = await backend.mark_snoozed(job_id, wid, timedelta(seconds=5), attempt=1) + result = await backend.mark_snoozed( + job_id, wid, timedelta(seconds=5), attempt=1, claim_epoch=1 + ) assert result == "scheduled" row = await backend.get(job_id) @@ -1343,7 +1395,9 @@ async def test_in_memory_snooze_no_deadline_succeeds(self) -> None: backend = _make_backend() job_id, wid = await _enqueue_and_dispatch(backend) - result = await backend.mark_snoozed(job_id, wid, timedelta(seconds=30), attempt=1) + result = await backend.mark_snoozed( + job_id, wid, timedelta(seconds=30), attempt=1, claim_epoch=1 + ) assert result == "scheduled" async def test_snooze_past_deadline_consumer_side_attempt_shape(self) -> None: @@ -1354,7 +1408,7 @@ async def test_snooze_past_deadline_consumer_side_attempt_shape(self) -> None: schedule_to_close=deadline, ) - await backend.mark_snoozed(job_id, wid, timedelta(seconds=30), attempt=1) + await backend.mark_snoozed(job_id, wid, timedelta(seconds=30), attempt=1, claim_epoch=1) attempts = await backend.get_attempts(job_id) assert len(attempts) == 1 @@ -1373,7 +1427,7 @@ async def test_in_memory_snooze_past_deadline_event_row(self) -> None: schedule_to_close=deadline, ) - await backend.mark_snoozed(job_id, wid, timedelta(seconds=30), attempt=1) + await backend.mark_snoozed(job_id, wid, timedelta(seconds=30), attempt=1, claim_epoch=1) events = await backend.get_events(job_id) state_changes = [e for e in events if e.kind == "state_change"] @@ -1406,6 +1460,7 @@ async def test_in_memory_snooze_outcome_reservation_denied(self) -> None: metadata_update={"awaiting": "reservation:gpu_pool"}, outcome="reservation_denied", attempt=1, + claim_epoch=1, ) assert result == "scheduled" @@ -1453,6 +1508,7 @@ async def test_in_memory_denial_refunds_claim_attempt(self, outcome: str) -> Non timedelta(seconds=30), outcome=outcome, # type: ignore[arg-type] # Why: parametrized SnoozeOutcome literal attempt=1, + claim_epoch=1, ) assert result == "scheduled" @@ -1476,7 +1532,7 @@ async def test_in_memory_denial_at_budget_ceiling_reschedules(self, outcome: str job_id, wid = await _enqueue_and_dispatch(backend, max_attempts=3, retry_kind="transient") row = backend._jobs[job_id] # type: ignore[reportPrivateUsage] # Why: test-only private access - backend._jobs[job_id] = replace(row, attempt=3) # type: ignore[reportPrivateUsage] # Why: test-only private access + backend._jobs[job_id] = replace(row, attempt=3, claim_epoch=3) # type: ignore[reportPrivateUsage] # Why: test-only private access result = await backend.mark_snoozed( job_id, @@ -1484,6 +1540,7 @@ async def test_in_memory_denial_at_budget_ceiling_reschedules(self, outcome: str timedelta(seconds=30), outcome=outcome, # type: ignore[arg-type] # Why: parametrized SnoozeOutcome literal attempt=3, + claim_epoch=3, ) assert result == "scheduled", "a denial must never produce a terminal failure" @@ -1516,6 +1573,9 @@ async def test_in_memory_repeated_denials_never_exhaust_budget(self) -> None: locked_by_worker=wid, lock_expires_at=_START + timedelta(seconds=60), attempt=row.attempt + 1, + # Each simulated cycle is a reclaim + redispatch, so the + # claim epoch advances with the attempt (twin's claim). + claim_epoch=row.claim_epoch + 1, ) current = backend._jobs[job_id] # type: ignore[reportPrivateUsage] # Why: test-only private access result = await backend.mark_snoozed( @@ -1524,6 +1584,7 @@ async def test_in_memory_repeated_denials_never_exhaust_budget(self) -> None: timedelta(seconds=30), outcome="rate_limit_denied", attempt=current.attempt, + claim_epoch=current.claim_epoch, ) assert result == "scheduled", f"denial {expected} terminalised the job" @@ -1545,10 +1606,14 @@ async def test_in_memory_snooze_idempotent_returns_noop(self) -> None: backend = _make_backend() job_id, wid = await _enqueue_and_dispatch(backend) - result1 = await backend.mark_snoozed(job_id, wid, timedelta(seconds=30), attempt=1) + result1 = await backend.mark_snoozed( + job_id, wid, timedelta(seconds=30), attempt=1, claim_epoch=1 + ) assert result1 == "scheduled" - result2 = await backend.mark_snoozed(job_id, wid, timedelta(seconds=30), attempt=1) + result2 = await backend.mark_snoozed( + job_id, wid, timedelta(seconds=30), attempt=1, claim_epoch=1 + ) assert result2 == "noop" attempts = await backend.get_attempts(job_id) @@ -1574,7 +1639,7 @@ async def test_in_memory_mark_retry_after_consume_true_increments(self) -> None: assert row.attempt == 1 result = await backend.mark_retry_after( - job_id, wid, timedelta(seconds=10), consume_budget=True, attempt=1 + job_id, wid, timedelta(seconds=10), consume_budget=True, attempt=1, claim_epoch=1 ) assert result == "scheduled" @@ -1615,7 +1680,7 @@ async def test_in_memory_mark_retry_after_consume_false_preserves(self) -> None: assert row.attempt == 1 result = await backend.mark_retry_after( - job_id, wid, timedelta(seconds=10), consume_budget=False, attempt=1 + job_id, wid, timedelta(seconds=10), consume_budget=False, attempt=1, claim_epoch=1 ) assert result == "scheduled" @@ -1645,10 +1710,10 @@ async def test_in_memory_mark_retry_after_max_attempts_fails(self) -> None: job_id, wid = await _enqueue_and_dispatch(backend, max_attempts=3, retry_kind="transient") row = backend._jobs[job_id] # type: ignore[reportPrivateUsage] # Why: test-only private access - backend._jobs[job_id] = replace(row, attempt=3) # type: ignore[reportPrivateUsage] # Why: test-only private access + backend._jobs[job_id] = replace(row, attempt=3, claim_epoch=3) # type: ignore[reportPrivateUsage] # Why: test-only private access result = await backend.mark_retry_after( - job_id, wid, timedelta(seconds=10), consume_budget=True, attempt=3 + job_id, wid, timedelta(seconds=10), consume_budget=True, attempt=3, claim_epoch=3 ) assert result == "failed:MaxAttemptsExceeded" @@ -1686,10 +1751,10 @@ async def test_in_memory_mark_retry_after_indefinite_tier_ignores_max_attempts(s job_id, wid = await _enqueue_and_dispatch(backend, max_attempts=3, retry_kind="indefinite") row = backend._jobs[job_id] # type: ignore[reportPrivateUsage] # Why: test-only private access - backend._jobs[job_id] = replace(row, attempt=5) # type: ignore[reportPrivateUsage] # Why: test-only private access + backend._jobs[job_id] = replace(row, attempt=5, claim_epoch=5) # type: ignore[reportPrivateUsage] # Why: test-only private access result = await backend.mark_retry_after( - job_id, wid, timedelta(seconds=10), consume_budget=True, attempt=5 + job_id, wid, timedelta(seconds=10), consume_budget=True, attempt=5, claim_epoch=5 ) assert result == "scheduled" @@ -1710,7 +1775,7 @@ async def test_retry_after_past_deadline_consumer_side_fails(self) -> None: job_id, wid = await _enqueue_and_dispatch(backend, schedule_to_close=deadline) result = await backend.mark_retry_after( - job_id, wid, timedelta(seconds=30), consume_budget=True, attempt=1 + job_id, wid, timedelta(seconds=30), consume_budget=True, attempt=1, claim_epoch=1 ) assert result == "failed:DeadlineExceeded" @@ -1748,12 +1813,12 @@ async def test_in_memory_mark_retry_after_idempotent_noop(self) -> None: job_id, wid = await _enqueue_and_dispatch(backend) result1 = await backend.mark_retry_after( - job_id, wid, timedelta(seconds=10), consume_budget=True, attempt=1 + job_id, wid, timedelta(seconds=10), consume_budget=True, attempt=1, claim_epoch=1 ) assert result1 == "scheduled" result2 = await backend.mark_retry_after( - job_id, wid, timedelta(seconds=10), consume_budget=True, attempt=1 + job_id, wid, timedelta(seconds=10), consume_budget=True, attempt=1, claim_epoch=1 ) assert result2 == "noop" @@ -1773,7 +1838,7 @@ async def test_in_memory_mark_retry_after_clears_last_heartbeat(self) -> None: assert row.last_heartbeat_at is not None result = await backend.mark_retry_after( - job_id, wid, timedelta(seconds=10), consume_budget=True, attempt=1 + job_id, wid, timedelta(seconds=10), consume_budget=True, attempt=1, claim_epoch=1 ) assert result == "scheduled" @@ -1835,7 +1900,7 @@ async def test_cleared_stored_ttl_falls_back_to_literal_at_completion(self) -> N ) ok = await backend.mark_succeeded( - job_id, wid, {"ok": True}, fallback_result_ttl=ttl, attempt=1 + job_id, wid, {"ok": True}, fallback_result_ttl=ttl, attempt=1, claim_epoch=1 ) assert ok is True @@ -1867,7 +1932,7 @@ async def test_stored_ttl_wins_over_fallback_at_completion(self) -> None: ) ok = await backend.mark_succeeded( - job_id, wid, {"ok": True}, fallback_result_ttl=ttl, attempt=1 + job_id, wid, {"ok": True}, fallback_result_ttl=ttl, attempt=1, claim_epoch=1 ) assert ok is True @@ -1890,7 +1955,7 @@ async def test_no_stored_no_fallback_keeps_enqueue_pinned_value(self) -> None: backend, clock, ttl, queue_wait=timedelta(seconds=45) ) - ok = await backend.mark_succeeded(job_id, wid, {"ok": True}, attempt=1) + ok = await backend.mark_succeeded(job_id, wid, {"ok": True}, attempt=1, claim_epoch=1) assert ok is True # The pinned expiry is already 40s in the past at completion, so @@ -2290,6 +2355,7 @@ async def _enqueue_and_succeed( progress_seq=2, progress_state={"pct": 100}, attempt=1, + claim_epoch=1, ) assert ok is True return dispatched[0].id diff --git a/tests/test_jobs_app.py b/tests/test_jobs_app.py index 23e96a9a7..aabd24a9f 100644 --- a/tests/test_jobs_app.py +++ b/tests/test_jobs_app.py @@ -159,7 +159,7 @@ async def test_jobs_app_enqueue_dispatch_round_trip( assert dispatched[0].status == "running" # Mark succeeded - reuse the same worker_id that acquired the lock - ok = await backend.mark_succeeded(job_id, worker_id, {"result": True}, attempt=1) + ok = await backend.mark_succeeded(job_id, worker_id, {"result": True}, attempt=1, claim_epoch=1) assert ok is True # Get attempts diff --git a/tests/test_json_non_str_keys.py b/tests/test_json_non_str_keys.py index 7a68bd331..0b2810599 100644 --- a/tests/test_json_non_str_keys.py +++ b/tests/test_json_non_str_keys.py @@ -59,6 +59,7 @@ def _make_ctx(job_id: object, buffer: _ProgressBuffer) -> JobContext[BaseModel]: actor="a", queue="default", attempt=1, + claim_epoch=0, worker_id=new_uuid(), payload=None, # type: ignore[arg-type] jobs=None, # type: ignore[arg-type] @@ -272,6 +273,7 @@ async def test_in_memory_terminal_progress_merge_stores_pg_jsonb_round_trip_valu "n": float("nan"), }, attempt=1, + claim_epoch=1, ) assert ok is True @@ -321,6 +323,7 @@ async def test_in_memory_snooze_metadata_update_stores_pg_jsonb_round_trip_value "n": float("nan"), }, attempt=1, + claim_epoch=1, ) assert ok == "scheduled" @@ -372,6 +375,7 @@ async def test_in_memory_snooze_metadata_update_with_nul_raises_value_error() -> timedelta(seconds=5), metadata_update={"k": "a\x00b"}, attempt=1, + claim_epoch=1, ) row = await backend.get(claimed[0].id) diff --git a/tests/test_leader_integration.py b/tests/test_leader_integration.py index 1a806b8a2..5e734565e 100644 --- a/tests/test_leader_integration.py +++ b/tests/test_leader_integration.py @@ -969,9 +969,11 @@ async def test_ti8_fanout_outstanding_counter_reaches_zero( now - timedelta(minutes=2), ) - # Mark first N-1 as succeeded + # Mark first N-1 as succeeded (the raw seed carries the + # claim_epoch default 0: a running row written by direct SQL, no + # claim ever stamped it) for jid in job_ids[:-1]: - await backend.mark_succeeded(JobId(jid), worker_id, None, attempt=1) + await backend.mark_succeeded(JobId(jid), worker_id, None, attempt=1, claim_epoch=0) # Force-expire the lock on the last job (simulates a crashed worker) crashed_jid = job_ids[-1] diff --git a/tests/test_mark_snoozed_boundary.py b/tests/test_mark_snoozed_boundary.py index ba58c10b9..ba0de108e 100644 --- a/tests/test_mark_snoozed_boundary.py +++ b/tests/test_mark_snoozed_boundary.py @@ -145,7 +145,9 @@ async def test_pg_zero_delay_snooze_is_floored_at_min_deferral_interval( ) before: datetime = await conn.fetchval("SELECT clock_timestamp()") - result = await app.backend.mark_snoozed(JobId(job_id), worker_id, timedelta(0), attempt=1) + result = await app.backend.mark_snoozed( + JobId(job_id), worker_id, timedelta(0), attempt=1, claim_epoch=1 + ) assert result == "scheduled" async with deps.worker_pool.acquire() as conn: # pyright: ignore[reportUnknownVariableType] # Why: same diff --git a/tests/test_max_pending.py b/tests/test_max_pending.py index bd22c5398..6f37940a4 100644 --- a/tests/test_max_pending.py +++ b/tests/test_max_pending.py @@ -114,7 +114,11 @@ async def test_scheduled_jobs_are_counted_in_max_pending() -> None: for row in dispatched: result = await backend.mark_snoozed( - row.id, worker_id, delay=timedelta(seconds=10), attempt=row.attempt + row.id, + worker_id, + delay=timedelta(seconds=10), + attempt=row.attempt, + claim_epoch=row.claim_epoch, ) assert result == "scheduled" @@ -221,7 +225,9 @@ async def test_count_after_job_completion_frees_capacity() -> None: assert len(dispatched) == 2 for row in dispatched: - ok = await backend.mark_succeeded(row.id, worker_id, result=None, attempt=row.attempt) + ok = await backend.mark_succeeded( + row.id, worker_id, result=None, attempt=row.attempt, claim_epoch=row.claim_epoch + ) assert ok is True # 2 jobs succeeded (excluded from count); 3 remaining pending → count == 3. @@ -401,7 +407,11 @@ async def test_max_pending_invariant(scenario: tuple[int, list[str]]) -> None: for row in backend._jobs.values(): if row.actor == actor and row.status == "running": await backend.mark_succeeded( - row.id, worker_id, result=None, attempt=row.attempt + row.id, + worker_id, + result=None, + attempt=row.attempt, + claim_epoch=row.claim_epoch, ) break diff --git a/tests/test_migrations.py b/tests/test_migrations.py index 5996e3546..31ceb0cd1 100644 --- a/tests/test_migrations.py +++ b/tests/test_migrations.py @@ -140,6 +140,7 @@ async def test_copy_enqueue_columns_are_copy_from_minus_server_stamped( "snooze_count", "rate_limit_blocked_count", "interrupt_count", + "claim_epoch", } assert set(COPY_ENQUEUE_COLUMNS) == set(COPY_FROM_COLUMNS) - omitted assert list(COPY_ENQUEUE_COLUMNS) == [c for c in COPY_FROM_COLUMNS if c not in omitted] diff --git a/tests/test_migrations_populated.py b/tests/test_migrations_populated.py index 22be64979..e3858058b 100644 --- a/tests/test_migrations_populated.py +++ b/tests/test_migrations_populated.py @@ -219,6 +219,9 @@ def _job_row( "snooze_count": i % 5, "rate_limit_blocked_count": i % 3, "interrupt_count": i % 2, + # The claim-epoch fence (01.00.18_02): deterministic non-zero + # values, same round-trip rationale as the counters above. + "claim_epoch": i % 7, # Retry-curve columns (01.00.12_03): deterministic non-default # values, same round-trip rationale as the counters above. "retry_base_seconds": 1.0 + (i % 10), diff --git a/tests/test_otel_integration.py b/tests/test_otel_integration.py index 5d6efab2e..edcc2c80e 100644 --- a/tests/test_otel_integration.py +++ b/tests/test_otel_integration.py @@ -78,6 +78,20 @@ # validator refuses anything under it. Nothing here waits on the lease: # rows are stamped with explicit expiry timestamps. +# The setup connection in _setup_worker is the only await surface in these +# tests with no bound of its own: asyncpg's connect timeout covers only the +# handshake, and nothing here sets a server-side statement/lock timeout, so +# a stalled Postgres (a wedged shared test container under xdist) suspends +# the test forever on an in-flight query with an idle event loop — the +# signature of the one 300s pytest-timeout hang this module produced in CI +# (loop parked in epoll with no timer pending, task still awaiting). These +# bounds convert that into a fast asyncpg TimeoutError naming the phase. +# Generous for an empty per-test schema (the full migration run measures +# ~1s); the teardown paths stay wait_for-bounded separately. +_SETUP_CONNECT_TIMEOUT = 10.0 +_SETUP_STATEMENT_TIMEOUT = "30s" +_SETUP_LOCK_TIMEOUT = "10s" + class _Payload(BaseModel): value: int = 1 @@ -110,8 +124,14 @@ async def _setup_worker( } ) - conn = await asyncpg.connect(str(settings.pg_dsn)) + conn = await asyncpg.connect(str(settings.pg_dsn), timeout=_SETUP_CONNECT_TIMEOUT) try: + # Session-level bounds on every statement below (the schema drop, the + # migration run, the actor-config insert): a stalled server or an + # unexpected DDL lock wait fails fast here instead of hanging the + # test until pytest-timeout fires. + await conn.execute(f"SET statement_timeout = '{_SETUP_STATEMENT_TIMEOUT}'") + await conn.execute(f"SET lock_timeout = '{_SETUP_LOCK_TIMEOUT}'") await conn.execute(f'DROP SCHEMA IF EXISTS "{settings.schema_name}" CASCADE') await apply_pending(conn, schema=settings.schema_name) await conn.execute( @@ -807,6 +827,7 @@ async def test_cancellation_phase_transitions( actor="_integration_test_actor", queue="default", attempt=1, + claim_epoch=0, worker_id=worker_id, payload=_Payload(), jobs=SubJobEnqueuer( diff --git a/tests/test_pinned_invariants.py b/tests/test_pinned_invariants.py index a5e905e1f..8eabf695e 100644 --- a/tests/test_pinned_invariants.py +++ b/tests/test_pinned_invariants.py @@ -546,7 +546,7 @@ def _args() -> EnqueueArgs: first.id, worker_id, ) - assert await backend.mark_succeeded(first.id, worker_id, {"ok": True}, attempt=0) + assert await backend.mark_succeeded(first.id, worker_id, {"ok": True}, attempt=0, claim_epoch=0) async with deps.worker_pool.acquire() as conn: status = await conn.fetchval(f'SELECT status FROM "{schema}".jobs WHERE id = $1', first.id) diff --git a/tests/test_postgres_cancel_paths.py b/tests/test_postgres_cancel_paths.py index 0a16e5db5..462413fb1 100644 --- a/tests/test_postgres_cancel_paths.py +++ b/tests/test_postgres_cancel_paths.py @@ -627,7 +627,7 @@ async def test_cancel_transitions_job_to_cancelled(self, clean_jobs_app: JobsApp async with deps.worker_pool.acquire() as conn: worker_id, job_id = await setup_running_job(conn, schema) - result = await backend.mark_cancelled(job_id, worker_id, attempt=1) + result = await backend.mark_cancelled(job_id, worker_id, attempt=1, claim_epoch=1) assert result is True async with deps.worker_pool.acquire() as conn: @@ -636,7 +636,7 @@ async def test_cancel_transitions_job_to_cancelled(self, clean_jobs_app: JobsApp assert row["status"] == "cancelled" # Idempotent: second call returns False - result2 = await backend.mark_cancelled(job_id, worker_id, attempt=1) + result2 = await backend.mark_cancelled(job_id, worker_id, attempt=1, claim_epoch=1) assert result2 is False @@ -669,7 +669,7 @@ async def test_cooperative_cancel_stamps_error_class(self, clean_jobs_app: JobsA async with deps.worker_pool.acquire() as conn: worker_id, job_id = await setup_running_job(conn, schema) - result = await backend.mark_cancelled(job_id, worker_id, attempt=1) + result = await backend.mark_cancelled(job_id, worker_id, attempt=1, claim_epoch=1) assert result is True async with deps.worker_pool.acquire() as conn: @@ -700,7 +700,7 @@ async def test_cancel_origins_are_distinguishable_on_the_row( abandon_worker, abandon_job = await setup_running_job(conn, schema) pending_job = await create_pending_job(conn, schema) - assert await backend.mark_cancelled(coop_job, coop_worker, attempt=1) is True + assert await backend.mark_cancelled(coop_job, coop_worker, attempt=1, claim_epoch=1) is True # The abandon path is only reachable once the cooperative window # has elapsed and the cancel escalated to forcing. assert await backend.write_cancel_request(abandon_job, None) is True @@ -768,7 +768,7 @@ async def test_phase_1_cancel_stamps_the_cooperative_marker( worker_id, job_id = await setup_running_job(conn, schema) assert await backend.write_cancel_request(job_id, "operator stop") is True - assert await backend.mark_cancelled(job_id, worker_id, attempt=1) is True + assert await backend.mark_cancelled(job_id, worker_id, attempt=1, claim_epoch=1) is True async with deps.worker_pool.acquire() as conn: row = await conn.fetchrow( @@ -797,7 +797,7 @@ async def test_phase_2_cancel_stamps_the_forced_marker(self, clean_jobs_app: Job assert await backend.write_cancel_request(job_id, "operator stop") is True assert await backend.write_cancel_escalation(job_id, worker_id, 2) is True # type: ignore[arg-type] # Why: Literal[2] not narrowed from int literal - assert await backend.mark_cancelled(job_id, worker_id, attempt=1) is True + assert await backend.mark_cancelled(job_id, worker_id, attempt=1, claim_epoch=1) is True async with deps.worker_pool.acquire() as conn: row = await conn.fetchrow( diff --git a/tests/test_postgres_denial_deadline_counts_final_denial.py b/tests/test_postgres_denial_deadline_counts_final_denial.py index 2dbb58f79..fd9203cde 100644 --- a/tests/test_postgres_denial_deadline_counts_final_denial.py +++ b/tests/test_postgres_denial_deadline_counts_final_denial.py @@ -59,6 +59,7 @@ async def test_final_denial_before_deadline_is_counted_on_postgres( timedelta(seconds=1), outcome="reservation_denied", attempt=1, + claim_epoch=1, ) assert result == "scheduled" @@ -96,6 +97,7 @@ async def test_final_denial_before_deadline_is_counted_on_postgres( timedelta(seconds=5), outcome="reservation_denied", attempt=1, + claim_epoch=1, ) assert result == "failed" diff --git a/tests/test_postgres_dispatch.py b/tests/test_postgres_dispatch.py index 8cb213a9c..328c85807 100644 --- a/tests/test_postgres_dispatch.py +++ b/tests/test_postgres_dispatch.py @@ -81,6 +81,7 @@ def _default_record() -> dict[str, Any]: "retry_backoff": "exponential", "retry_jitter": 0.2, "assignment_routed": False, + "claim_epoch": 0, } diff --git a/tests/test_postgres_reads.py b/tests/test_postgres_reads.py index d171ef120..b5c7dca1d 100644 --- a/tests/test_postgres_reads.py +++ b/tests/test_postgres_reads.py @@ -327,7 +327,7 @@ async def test_attempts_after_terminal_write(self, clean_jobs_app: JobsApp) -> N worker_id, ) - await backend.mark_succeeded(job_id, worker_id, {"ok": True}, attempt=1) + await backend.mark_succeeded(job_id, worker_id, {"ok": True}, attempt=1, claim_epoch=0) attempts = await backend.get_attempts(job_id) assert len(attempts) == 1 diff --git a/tests/test_postgres_retry_after.py b/tests/test_postgres_retry_after.py index 69f5ceb74..a87074808 100644 --- a/tests/test_postgres_retry_after.py +++ b/tests/test_postgres_retry_after.py @@ -56,7 +56,12 @@ async def test_mark_retry_after_consume_budget_true_snoozed( ) result = await backend.mark_retry_after( - JobId(job_id), worker_id, timedelta(seconds=5), consume_budget=True, attempt=1 + JobId(job_id), + worker_id, + timedelta(seconds=5), + consume_budget=True, + attempt=1, + claim_epoch=1, ) assert result == "scheduled" @@ -123,7 +128,12 @@ async def test_mark_retry_after_consume_budget_true_max_attempts_failed( ) result = await backend.mark_retry_after( - JobId(job_id), worker_id, timedelta(seconds=5), consume_budget=True, attempt=3 + JobId(job_id), + worker_id, + timedelta(seconds=5), + consume_budget=True, + attempt=3, + claim_epoch=3, ) assert result == "failed:MaxAttemptsExceeded" @@ -191,7 +201,12 @@ async def test_mark_retry_after_consume_budget_true_deadline_failed( ) result = await backend.mark_retry_after( - JobId(job_id), worker_id, timedelta(seconds=30), consume_budget=True, attempt=1 + JobId(job_id), + worker_id, + timedelta(seconds=30), + consume_budget=True, + attempt=1, + claim_epoch=1, ) assert result == "failed:DeadlineExceeded" @@ -261,7 +276,12 @@ async def test_mark_retry_after_consume_budget_true_noop( ) result = await backend.mark_retry_after( - JobId(job_id), worker_id, timedelta(seconds=5), consume_budget=True, attempt=1 + JobId(job_id), + worker_id, + timedelta(seconds=5), + consume_budget=True, + attempt=1, + claim_epoch=1, ) assert result == "noop" @@ -300,7 +320,12 @@ async def test_mark_retry_after_no_consume_snoozed( ) result = await backend.mark_retry_after( - JobId(job_id), worker_id, timedelta(seconds=5), consume_budget=False, attempt=1 + JobId(job_id), + worker_id, + timedelta(seconds=5), + consume_budget=False, + attempt=1, + claim_epoch=1, ) assert result == "scheduled" @@ -359,7 +384,12 @@ async def test_mark_retry_after_no_consume_deadline_failed( ) result = await backend.mark_retry_after( - JobId(job_id), worker_id, timedelta(seconds=30), consume_budget=False, attempt=1 + JobId(job_id), + worker_id, + timedelta(seconds=30), + consume_budget=False, + attempt=1, + claim_epoch=1, ) assert result == "failed:DeadlineExceeded" @@ -426,10 +456,12 @@ async def test_mark_retry_after_consume_budget_true_attempt_not_incremented( # Capture attempt before mark_retry_after async with deps.worker_pool.acquire() as conn: before = await conn.fetchrow( - f'SELECT attempt FROM "{schema}".jobs WHERE id = $1', job_id + f'SELECT attempt, claim_epoch FROM "{schema}".jobs WHERE id = $1', + job_id, ) assert before is not None expected_attempt = before["attempt"] + expected_epoch = before["claim_epoch"] # The attempt-epoch fence: the write carries the row's CURRENT # attempt (the re-dispatch below increments it every cycle). @@ -439,6 +471,7 @@ async def test_mark_retry_after_consume_budget_true_attempt_not_incremented( timedelta(seconds=1), consume_budget=True, attempt=expected_attempt, + claim_epoch=expected_epoch, ) assert result == "scheduled" @@ -508,7 +541,9 @@ async def test_mark_snoozed_snoozed_branch( schedule_to_close=datetime.now(UTC) + timedelta(hours=1), ) - result = await backend.mark_snoozed(JobId(job_id), worker_id, timedelta(seconds=5), attempt=1) + result = await backend.mark_snoozed( + JobId(job_id), worker_id, timedelta(seconds=5), attempt=1, claim_epoch=1 + ) assert result == "scheduled" async with deps.worker_pool.acquire() as conn: @@ -563,7 +598,9 @@ async def test_mark_snoozed_deadline_failed_branch( schedule_to_close=datetime.now(UTC) - timedelta(seconds=60), ) - result = await backend.mark_snoozed(JobId(job_id), worker_id, timedelta(seconds=5), attempt=1) + result = await backend.mark_snoozed( + JobId(job_id), worker_id, timedelta(seconds=5), attempt=1, claim_epoch=1 + ) assert result == "failed" async with deps.worker_pool.acquire() as conn: @@ -642,10 +679,10 @@ async def test_mark_snoozed_job_events_and_attempts_both_branches( # Exercise both branches result_s = await backend.mark_snoozed( - JobId(snoozed_job_id), worker_s, timedelta(seconds=5), attempt=1 + JobId(snoozed_job_id), worker_s, timedelta(seconds=5), attempt=1, claim_epoch=1 ) result_d = await backend.mark_snoozed( - JobId(deadline_job_id), worker_d, timedelta(seconds=5), attempt=1 + JobId(deadline_job_id), worker_d, timedelta(seconds=5), attempt=1, claim_epoch=1 ) assert result_s == "scheduled" assert result_d == "failed" @@ -760,6 +797,7 @@ async def test_admission_denial_never_terminally_fails_an_exhausted_job( timedelta(seconds=5), outcome=outcome, # pyright: ignore[reportArgumentType] attempt=3, + claim_epoch=3, ) assert result == "scheduled", ( "a denied job has no budget to spend: admission control must reschedule it, not fail it" @@ -830,6 +868,9 @@ async def test_repeated_admission_denials_reschedule_without_bound( # denials occur. denials = 5 claimed_attempt = 2 + # Each simulated re-claim advances the epoch beside the attempt: a + # real dispatch bumps both, and only the attempt is refunded. + claimed_epoch = 2 for cycle in range(denials): result = await backend.mark_snoozed( JobId(job_id), @@ -837,17 +878,20 @@ async def test_repeated_admission_denials_reschedule_without_bound( timedelta(seconds=1), outcome="rate_limit_denied", attempt=claimed_attempt, + claim_epoch=claimed_epoch, ) assert result == "scheduled", f"denial {cycle + 1} must reschedule, not terminalise" # Re-claim: a real dispatch increments attempt exactly as the # initial claim did, re-admitting the refunded row. claimed_attempt += 1 + claimed_epoch += 1 async with deps.worker_pool.acquire() as conn: await conn.execute( f"""UPDATE "{schema}".jobs SET status = 'running', attempt = $3, + claim_epoch = $4, locked_by_worker = $1, lock_expires_at = now() + interval '60 seconds', started_at = now(), @@ -856,6 +900,7 @@ async def test_repeated_admission_denials_reschedule_without_bound( worker_id, job_id, claimed_attempt, + claimed_epoch, ) async with deps.worker_pool.acquire() as conn: @@ -909,6 +954,9 @@ async def test_admission_denial_writes_no_attempt_or_event_rows( # the raw re-claim below plays the dispatcher's own increment, exactly # as test_repeated_admission_denials_reschedule_without_bound does. claimed_attempt = 1 + # The epoch rides the re-claims beside the attempt: a real dispatch + # bumps both, and only the attempt is refunded. + claimed_epoch = 1 for _ in range(3): assert ( await backend.mark_snoozed( @@ -917,15 +965,18 @@ async def test_admission_denial_writes_no_attempt_or_event_rows( timedelta(seconds=1), outcome="reservation_denied", attempt=claimed_attempt, + claim_epoch=claimed_epoch, ) == "scheduled" ) claimed_attempt += 1 + claimed_epoch += 1 async with deps.worker_pool.acquire() as conn: await conn.execute( f"""UPDATE "{schema}".jobs SET status = 'running', attempt = $3, + claim_epoch = $4, locked_by_worker = $1, lock_expires_at = now() + interval '60 seconds', started_at = now(), @@ -934,6 +985,7 @@ async def test_admission_denial_writes_no_attempt_or_event_rows( worker_id, job_id, claimed_attempt, + claimed_epoch, ) async with deps.worker_pool.acquire() as conn: @@ -993,6 +1045,7 @@ async def test_admission_denial_past_schedule_to_close_fails_on_the_deadline_pat timedelta(seconds=5), outcome="rate_limit_denied", attempt=3, + claim_epoch=3, ) assert result == "failed" diff --git a/tests/test_postgres_sweeps.py b/tests/test_postgres_sweeps.py index 912299c7a..773f90ded 100644 --- a/tests/test_postgres_sweeps.py +++ b/tests/test_postgres_sweeps.py @@ -1539,7 +1539,9 @@ async def test_exhausted_budget_retry_past_deadline_is_made_dispatchable( # Original failure: writes the (job_id, attempt=1) row in # job_attempts. - assert await backend.mark_failed_or_retry(job_id, worker_id, error, None, attempt=1) + assert await backend.mark_failed_or_retry( + job_id, worker_id, error, None, attempt=1, claim_epoch=1 + ) row = await conn.fetchrow( f'SELECT status, attempt FROM "{schema}".jobs WHERE id = $1', job_id ) @@ -1794,7 +1796,9 @@ async def test_admin_retry_of_past_deadline_job_is_not_swept_back( ) # The real dispatched run fails, writing job_attempts(job_id, 1). - assert await backend.mark_failed_or_retry(job_id, worker_id, error, None, attempt=1) + assert await backend.mark_failed_or_retry( + job_id, worker_id, error, None, attempt=1, claim_epoch=1 + ) attempts_before = await conn.fetch( f'SELECT attempt FROM "{schema}".job_attempts WHERE job_id = $1', job_id, @@ -1893,7 +1897,7 @@ async def test_transient_retry_past_deadline_is_swept_to_failed( ) assert await backend.mark_failed_or_retry( - job_id, worker_id, error, timedelta(minutes=5), attempt=1 + job_id, worker_id, error, timedelta(minutes=5), attempt=1, claim_epoch=1 ) retried = await conn.fetchrow( f'SELECT status, attempt FROM "{schema}".jobs WHERE id = $1', @@ -2254,7 +2258,7 @@ async def test_consumer_side_snooze_past_deadline_attempt_shape( assert dispatched_started_at is not None result = await backend.mark_snoozed( - JobId(job_id), worker_id, timedelta(seconds=30), attempt=1 + JobId(job_id), worker_id, timedelta(seconds=30), attempt=1, claim_epoch=1 ) assert result == "failed" diff --git a/tests/test_postgres_terminal_writes.py b/tests/test_postgres_terminal_writes.py index 50e9e550f..4a3b934ed 100644 --- a/tests/test_postgres_terminal_writes.py +++ b/tests/test_postgres_terminal_writes.py @@ -56,7 +56,9 @@ async def test_mark_succeeded(self, clean_jobs_app: JobsApp) -> None: async with deps.worker_pool.acquire() as conn: worker_id, job_id = await setup_running_job(conn, schema) - result = await backend.mark_succeeded(job_id, worker_id, {"ok": True}, attempt=1) + result = await backend.mark_succeeded( + job_id, worker_id, {"ok": True}, attempt=1, claim_epoch=1 + ) assert result is True async with deps.worker_pool.acquire() as conn: @@ -84,7 +86,7 @@ async def test_mark_cancelled(self, clean_jobs_app: JobsApp) -> None: async with deps.worker_pool.acquire() as conn: worker_id, job_id = await setup_running_job(conn, schema) - result = await backend.mark_cancelled(job_id, worker_id, attempt=1) + result = await backend.mark_cancelled(job_id, worker_id, attempt=1, claim_epoch=1) assert result is True async with deps.worker_pool.acquire() as conn: @@ -166,7 +168,9 @@ async def test_mark_failed_terminal(self, clean_jobs_app: JobsApp) -> None: error_message="boom", error_traceback=None, ) - row = await backend.mark_failed_or_retry(job_id, worker_id, error_info, None, attempt=1) + row = await backend.mark_failed_or_retry( + job_id, worker_id, error_info, None, attempt=1, claim_epoch=1 + ) assert row.status == "failed" assert row.finished_at is not None @@ -196,7 +200,7 @@ async def test_mark_failed_retry(self, clean_jobs_app: JobsApp) -> None: ) # The decision is a delay - the server derives scheduled_at from it. row = await backend.mark_failed_or_retry( - job_id, worker_id, error_info, timedelta(seconds=10), attempt=1 + job_id, worker_id, error_info, timedelta(seconds=10), attempt=1, claim_epoch=1 ) assert row.status == "scheduled" assert row.locked_by_worker is None @@ -221,7 +225,9 @@ async def test_mark_snoozed(self, clean_jobs_app: JobsApp) -> None: async with deps.worker_pool.acquire() as conn: worker_id, job_id = await setup_running_job(conn, schema) - result = await backend.mark_snoozed(job_id, worker_id, timedelta(seconds=30), attempt=1) + result = await backend.mark_snoozed( + job_id, worker_id, timedelta(seconds=30), attempt=1, claim_epoch=1 + ) assert result == "scheduled" async with deps.worker_pool.acquire() as conn: @@ -277,7 +283,9 @@ async def test_mark_snoozed_drifted_branch_raises_after_terminalising( monkeypatch.setattr(backend, "_sql", replace(sql, mark_snoozed=drifted)) with pytest.raises(AssertionError, match="mark_snoozed cannot emit outcome branch"): - await backend.mark_snoozed(job_id, worker_id, timedelta(seconds=30), attempt=1) + await backend.mark_snoozed( + job_id, worker_id, timedelta(seconds=30), attempt=1, claim_epoch=1 + ) async with deps.worker_pool.acquire() as conn: row = await conn.fetchrow( @@ -347,7 +355,7 @@ async def test_mark_succeeded_event(self, clean_jobs_app: JobsApp) -> None: async with deps.worker_pool.acquire() as conn: worker_id, job_id = await setup_running_job(conn, schema) - await backend.mark_succeeded(job_id, worker_id, {"ok": True}, attempt=1) + await backend.mark_succeeded(job_id, worker_id, {"ok": True}, attempt=1, claim_epoch=1) async with deps.worker_pool.acquire() as conn: events = await conn.fetch( @@ -372,7 +380,7 @@ async def test_cascade_delete(self, clean_jobs_app: JobsApp) -> None: async with deps.worker_pool.acquire() as conn: worker_id, job_id = await setup_running_job(conn, schema) - await backend.mark_succeeded(job_id, worker_id, {"ok": True}, attempt=1) + await backend.mark_succeeded(job_id, worker_id, {"ok": True}, attempt=1, claim_epoch=1) async with deps.worker_pool.acquire() as conn: # Verify attempt and event rows exist @@ -425,7 +433,10 @@ async def test_mark_succeeded_after_worker_row_cleanup(self, clean_jobs_app: Job # The stale-worker sweep beat the terminal write to it. await conn.execute(f'DELETE FROM "{schema}".workers WHERE id = $1', worker_id) - assert await backend.mark_succeeded(job_id, worker_id, {"ok": True}, attempt=1) is True + assert ( + await backend.mark_succeeded(job_id, worker_id, {"ok": True}, attempt=1, claim_epoch=1) + is True + ) async with deps.worker_pool.acquire() as conn: row = await conn.fetchrow(f'SELECT status FROM "{schema}".jobs WHERE id = $1', job_id) @@ -459,6 +470,7 @@ async def test_mark_failed_or_retry_after_worker_row_cleanup( ), timedelta(seconds=10), attempt=1, + claim_epoch=1, ) assert row.status == "scheduled" @@ -519,7 +531,7 @@ async def test_mark_succeeded_wrong_worker_false(self, clean_jobs_app: JobsApp) async with deps.worker_pool.acquire() as conn: _, job_id = await setup_running_job(conn, schema) - result = await backend.mark_succeeded(job_id, wrong_worker, None, attempt=1) + result = await backend.mark_succeeded(job_id, wrong_worker, None, attempt=1, claim_epoch=1) assert result is False async def test_mark_cancelled_wrong_worker_false(self, clean_jobs_app: JobsApp) -> None: @@ -531,7 +543,7 @@ async def test_mark_cancelled_wrong_worker_false(self, clean_jobs_app: JobsApp) async with deps.worker_pool.acquire() as conn: _, job_id = await setup_running_job(conn, schema) - result = await backend.mark_cancelled(job_id, wrong_worker, attempt=1) + result = await backend.mark_cancelled(job_id, wrong_worker, attempt=1, claim_epoch=1) assert result is False async def test_mark_failed_or_retry_wrong_worker_raises(self, clean_jobs_app: JobsApp) -> None: @@ -549,7 +561,9 @@ async def test_mark_failed_or_retry_wrong_worker_raises(self, clean_jobs_app: Jo error_traceback=None, ) with pytest.raises(WorkerOwnershipMismatch) as exc_info: - await backend.mark_failed_or_retry(job_id, wrong_worker, error_info, None, attempt=1) + await backend.mark_failed_or_retry( + job_id, wrong_worker, error_info, None, attempt=1, claim_epoch=1 + ) assert exc_info.value.job_id == job_id assert exc_info.value.expected == wrong_worker assert exc_info.value.actual == worker_id @@ -616,7 +630,7 @@ async def test_mark_retry_wrong_worker_raises_on_both_arms( ) with pytest.raises(WorkerOwnershipMismatch) as exc_info: await backend.mark_failed_or_retry( - job_id, wrong_worker, error_info, timedelta(seconds=30), attempt=1 + job_id, wrong_worker, error_info, timedelta(seconds=30), attempt=1, claim_epoch=1 ) assert exc_info.value.actual == worker_id @@ -646,7 +660,9 @@ async def test_mark_failed_or_retry_missing_job_raises_with_none( error_traceback=None, ) with pytest.raises(WorkerOwnershipMismatch) as exc_info: - await backend.mark_failed_or_retry(missing_job, worker_id, error_info, None, attempt=1) + await backend.mark_failed_or_retry( + missing_job, worker_id, error_info, None, attempt=1, claim_epoch=1 + ) assert exc_info.value.actual is None @@ -673,7 +689,9 @@ async def test_payload_validation_error_terminal_failure(self, clean_jobs_app: J error_message=str(raw_payload), error_traceback=None, ) - result = await backend.mark_failed_or_retry(job_id, worker_id, error_info, None, attempt=1) + result = await backend.mark_failed_or_retry( + job_id, worker_id, error_info, None, attempt=1, claim_epoch=1 + ) assert result.status == "failed" assert result.error_class == "PayloadValidationError" @@ -708,7 +726,7 @@ async def test_mark_succeeded_equivalence( # ── Memory backend ───────────────────────────────────────── mem_job_id, mem_worker = await enqueue_and_dispatch_memory(memory_jobs) mem_result = await memory_jobs.mark_succeeded( - mem_job_id, mem_worker, {"ok": True}, attempt=1 + mem_job_id, mem_worker, {"ok": True}, attempt=1, claim_epoch=1 ) assert mem_result is True mem_row = await memory_jobs.get(mem_job_id) @@ -727,7 +745,9 @@ async def test_mark_succeeded_equivalence( pg_job_id, pg_worker = await enqueue_and_dispatch_pg(backend) - pg_result = await backend.mark_succeeded(pg_job_id, pg_worker, {"ok": True}, attempt=1) + pg_result = await backend.mark_succeeded( + pg_job_id, pg_worker, {"ok": True}, attempt=1, claim_epoch=1 + ) assert pg_result is True async with deps.worker_pool.acquire() as conn: @@ -759,7 +779,7 @@ async def test_mark_failed_or_retry_equivalence( error_traceback=None, ) mem_row = await memory_jobs.mark_failed_or_retry( - mem_job_id, mem_worker, error_info, None, attempt=1 + mem_job_id, mem_worker, error_info, None, attempt=1, claim_epoch=1 ) assert mem_row.status == "failed" mem_attempts = await memory_jobs.get_attempts(mem_job_id) @@ -775,7 +795,7 @@ async def test_mark_failed_or_retry_equivalence( pg_job_id, pg_worker = await enqueue_and_dispatch_pg(backend, max_attempts=1) pg_row = await backend.mark_failed_or_retry( - pg_job_id, pg_worker, error_info, None, attempt=1 + pg_job_id, pg_worker, error_info, None, attempt=1, claim_epoch=1 ) assert pg_row.status == "failed" @@ -809,7 +829,9 @@ async def test_mark_snoozed_refunds_attempt(self, clean_jobs_app: JobsApp) -> No async with deps.worker_pool.acquire() as conn: worker_id, job_id = await setup_running_job(conn, schema, attempt=1) - result = await backend.mark_snoozed(job_id, worker_id, timedelta(seconds=30), attempt=1) + result = await backend.mark_snoozed( + job_id, worker_id, timedelta(seconds=30), attempt=1, claim_epoch=1 + ) assert result == "scheduled" async with deps.worker_pool.acquire() as conn: @@ -830,7 +852,9 @@ async def test_mark_snoozed_attempt_record_refunds_attempt( async with deps.worker_pool.acquire() as conn: worker_id, job_id = await setup_running_job(conn, schema, attempt=1) - result = await backend.mark_snoozed(job_id, worker_id, timedelta(seconds=30), attempt=1) + result = await backend.mark_snoozed( + job_id, worker_id, timedelta(seconds=30), attempt=1, claim_epoch=1 + ) assert result == "scheduled" async with deps.worker_pool.acquire() as conn: @@ -873,7 +897,9 @@ async def test_mark_snoozed_clears_last_heartbeat_at(self, clean_jobs_app: JobsA assert pre is not None assert pre["last_heartbeat_at"] is not None - result = await backend.mark_snoozed(job_id, worker_id, timedelta(seconds=30), attempt=1) + result = await backend.mark_snoozed( + job_id, worker_id, timedelta(seconds=30), attempt=1, claim_epoch=1 + ) assert result == "scheduled" async with deps.worker_pool.acquire() as conn: @@ -900,7 +926,9 @@ async def test_mark_snoozed_past_deadline_fails(self, clean_jobs_app: JobsApp) - async with deps.worker_pool.acquire() as conn: worker_id, job_id = await setup_running_job(conn, schema, schedule_to_close=close_at) - result = await backend.mark_snoozed(job_id, worker_id, timedelta(seconds=30), attempt=1) + result = await backend.mark_snoozed( + job_id, worker_id, timedelta(seconds=30), attempt=1, claim_epoch=1 + ) assert result == "failed" async with deps.worker_pool.acquire() as conn: @@ -929,7 +957,9 @@ async def test_mark_snoozed_within_deadline_succeeds(self, clean_jobs_app: JobsA async with deps.worker_pool.acquire() as conn: worker_id, job_id = await setup_running_job(conn, schema, schedule_to_close=close_at) - result = await backend.mark_snoozed(job_id, worker_id, timedelta(seconds=5), attempt=1) + result = await backend.mark_snoozed( + job_id, worker_id, timedelta(seconds=5), attempt=1, claim_epoch=1 + ) assert result == "scheduled" async with deps.worker_pool.acquire() as conn: @@ -965,6 +995,7 @@ async def test_mark_snoozed_outcome_reservation_denied(self, clean_jobs_app: Job metadata_update={"awaiting": "reservation:gpu_pool"}, outcome="reservation_denied", attempt=1, + claim_epoch=1, ) assert result == "scheduled" @@ -1027,6 +1058,7 @@ async def test_mark_snoozed_reservation_denied_at_max_attempts_reschedules( timedelta(seconds=30), outcome="reservation_denied", attempt=1, + claim_epoch=1, ) assert result == "scheduled", ( "a denial at the last attempt must reschedule the job, not " @@ -1073,10 +1105,14 @@ async def test_mark_snoozed_idempotent_returns_noop(self, clean_jobs_app: JobsAp async with deps.worker_pool.acquire() as conn: worker_id, job_id = await setup_running_job(conn, schema) - result1 = await backend.mark_snoozed(job_id, worker_id, timedelta(seconds=30), attempt=1) + result1 = await backend.mark_snoozed( + job_id, worker_id, timedelta(seconds=30), attempt=1, claim_epoch=1 + ) assert result1 == "scheduled" - result2 = await backend.mark_snoozed(job_id, worker_id, timedelta(seconds=30), attempt=1) + result2 = await backend.mark_snoozed( + job_id, worker_id, timedelta(seconds=30), attempt=1, claim_epoch=1 + ) assert result2 == "noop" async with deps.worker_pool.acquire() as conn: @@ -1105,7 +1141,7 @@ async def test_mark_retry_after_consume_budget_true_increments_attempt( worker_id, job_id = await setup_running_job(conn, schema, attempt=1) result = await backend.mark_retry_after( - job_id, worker_id, timedelta(seconds=30), consume_budget=True, attempt=1 + job_id, worker_id, timedelta(seconds=30), consume_budget=True, attempt=1, claim_epoch=1 ) assert result == "scheduled" @@ -1141,7 +1177,7 @@ async def test_mark_retry_after_consume_budget_false_refunds_attempt( worker_id, job_id = await setup_running_job(conn, schema, attempt=1) result = await backend.mark_retry_after( - job_id, worker_id, timedelta(seconds=30), consume_budget=False, attempt=1 + job_id, worker_id, timedelta(seconds=30), consume_budget=False, attempt=1, claim_epoch=1 ) assert result == "scheduled" @@ -1173,7 +1209,7 @@ async def test_mark_retry_after_max_attempts_exceeded_transitions_to_failed( ) result = await backend.mark_retry_after( - job_id, worker_id, timedelta(seconds=30), consume_budget=True, attempt=3 + job_id, worker_id, timedelta(seconds=30), consume_budget=True, attempt=3, claim_epoch=3 ) assert result == "failed:MaxAttemptsExceeded" @@ -1204,7 +1240,7 @@ async def test_mark_retry_after_indefinite_tier_ignores_max_attempts( ) result = await backend.mark_retry_after( - job_id, worker_id, timedelta(seconds=30), consume_budget=True, attempt=5 + job_id, worker_id, timedelta(seconds=30), consume_budget=True, attempt=5, claim_epoch=5 ) assert result == "scheduled" @@ -1233,7 +1269,7 @@ async def test_mark_retry_after_past_deadline_fails(self, clean_jobs_app: JobsAp worker_id, job_id = await setup_running_job(conn, schema, schedule_to_close=close_at) result = await backend.mark_retry_after( - job_id, worker_id, timedelta(seconds=30), consume_budget=True, attempt=1 + job_id, worker_id, timedelta(seconds=30), consume_budget=True, attempt=1, claim_epoch=1 ) assert result == "failed:DeadlineExceeded" @@ -1270,12 +1306,12 @@ async def test_mark_retry_after_idempotent_returns_noop(self, clean_jobs_app: Jo worker_id, job_id = await setup_running_job(conn, schema) result1 = await backend.mark_retry_after( - job_id, worker_id, timedelta(seconds=30), consume_budget=True, attempt=1 + job_id, worker_id, timedelta(seconds=30), consume_budget=True, attempt=1, claim_epoch=1 ) assert result1 == "scheduled" result2 = await backend.mark_retry_after( - job_id, worker_id, timedelta(seconds=30), consume_budget=True, attempt=1 + job_id, worker_id, timedelta(seconds=30), consume_budget=True, attempt=1, claim_epoch=1 ) assert result2 == "noop" @@ -1307,7 +1343,7 @@ async def test_mark_retry_after_clears_last_heartbeat_at(self, clean_jobs_app: J assert pre["last_heartbeat_at"] is not None result = await backend.mark_retry_after( - job_id, worker_id, timedelta(seconds=30), consume_budget=True, attempt=1 + job_id, worker_id, timedelta(seconds=30), consume_budget=True, attempt=1, claim_epoch=1 ) assert result == "scheduled" @@ -1371,7 +1407,7 @@ async def test_cleared_result_ttl_falls_back_to_literal_at_completion( ttl = timedelta(seconds=5) ok = await backend.mark_succeeded( - job_id, worker_id, {"ok": True}, fallback_result_ttl=ttl, attempt=1 + job_id, worker_id, {"ok": True}, fallback_result_ttl=ttl, attempt=1, claim_epoch=1 ) assert ok is True @@ -1408,7 +1444,7 @@ async def test_cleared_result_ttl_without_fallback_is_reaped( async with deps.worker_pool.acquire() as conn: worker_id, job_id = await self._seed_cleared_ttl_and_aged_job(clean_jobs_app, conn) - ok = await backend.mark_succeeded(job_id, worker_id, {"ok": True}, attempt=1) + ok = await backend.mark_succeeded(job_id, worker_id, {"ok": True}, attempt=1, claim_epoch=1) assert ok is True async with deps.worker_pool.acquire() as conn: @@ -1437,7 +1473,12 @@ async def test_stored_result_ttl_wins_over_fallback_at_completion( ) ok = await backend.mark_succeeded( - job_id, worker_id, {"ok": True}, fallback_result_ttl=timedelta(seconds=5), attempt=1 + job_id, + worker_id, + {"ok": True}, + fallback_result_ttl=timedelta(seconds=5), + attempt=1, + claim_epoch=1, ) assert ok is True @@ -1497,6 +1538,7 @@ async def test_clock_timestamp_used_in_transactional_path( {"ok": True}, fallback_result_ttl=timedelta(seconds=ttl_seconds), attempt=1, + claim_epoch=1, ) assert ok is True @@ -1561,6 +1603,7 @@ async def test_mark_failed_finished_at_uses_clock_timestamp_in_tx( 0, None, 1, + 1, ) assert rec is not None finished_at: datetime = rec["finished_at"] @@ -1601,8 +1644,10 @@ async def test_mark_snoozed_scheduled_at_uses_clock_timestamp_in_tx( 0, None, "snoozed", - # The trailing 1 is the attempt-epoch fence bind ($8) - - # the seeded row is at attempt 1. + # The fence binds: $8 the attempt epoch, $10 the claim + # epoch - the seeded row is at attempt 1, claimed once + # (the seeding helper stamps the epoch beside the + # attempt). 1, # $9 is the denial reason the caller reported. The statement # binds it on every path (the deadline arm's terminal event @@ -1610,6 +1655,7 @@ async def test_mark_snoozed_scheduled_at_uses_clock_timestamp_in_tx( # non-denial exit), so a direct caller binds the same default # the backend's mark_snoozed binds for a plain actor snooze. "capacity", + 1, ) assert rec is not None assert rec["outcome_branch"] == "snoozed" diff --git a/tests/test_progress_buffer.py b/tests/test_progress_buffer.py index 1a4b5eb5e..74daa1075 100644 --- a/tests/test_progress_buffer.py +++ b/tests/test_progress_buffer.py @@ -240,6 +240,7 @@ async def test_ctx_progress_snooze_preserves_seq_and_redispatch_continues() -> N progress_seq=progress_seq, progress_state=dict(buf.pending_state), attempt=1, + claim_epoch=1, ) assert result == "scheduled" diff --git a/tests/test_progress_flush.py b/tests/test_progress_flush.py index 7bf38cfd1..32d8146a1 100644 --- a/tests/test_progress_flush.py +++ b/tests/test_progress_flush.py @@ -169,6 +169,7 @@ async def test_progress_too_large_at_exactly_max_plus_one_byte() -> None: actor="test_actor", queue="default", attempt=1, + claim_epoch=0, worker_id=backend._worker_id, # type: ignore[reportPrivateUsage] # Why: fixture helper accesses private field for test setup. payload=PassthroughPayload(), cancel_event=asyncio.Event(), @@ -213,6 +214,7 @@ async def test_ctx_progress_out_of_range_percent_not_rejected() -> None: actor="test_actor", queue="default", attempt=1, + claim_epoch=0, worker_id=backend._worker_id, # type: ignore[reportPrivateUsage] # Why: fixture helper accesses private field for test setup. payload=PassthroughPayload(), cancel_event=asyncio.Event(), @@ -259,6 +261,7 @@ async def test_ctx_progress_unserializable_data_raises_type_error() -> None: actor="test_actor", queue="default", attempt=1, + claim_epoch=0, worker_id=backend._worker_id, # type: ignore[reportPrivateUsage] # Why: fixture helper accesses private field for test setup. payload=PassthroughPayload(), cancel_event=asyncio.Event(), diff --git a/tests/test_progress_publish.py b/tests/test_progress_publish.py index 49620901d..680f2761b 100644 --- a/tests/test_progress_publish.py +++ b/tests/test_progress_publish.py @@ -198,7 +198,7 @@ async def _acquire() -> AsyncGenerator[AsyncMock, None]: assert buf.pending_seq_delta == 0 assert buf.dirty is False - await backend.mark_succeeded(job_id, worker_id, None, progress_seq=1, attempt=1) + await backend.mark_succeeded(job_id, worker_id, None, progress_seq=1, attempt=1, claim_epoch=1) row = await backend.get(job_id) assert row is not None @@ -819,7 +819,7 @@ async def test_cancel_discards_buffer_no_flush_terminal_state_change() -> None: override_seq = cancel_buf.base_seq override_state = dict(cancel_buf.pending_state) - await backend.mark_cancelled(job_id, worker_id, progress_seq=0, attempt=1) + await backend.mark_cancelled(job_id, worker_id, progress_seq=0, attempt=1, claim_epoch=1) row = await backend.get(job_id) assert row is not None @@ -988,7 +988,9 @@ async def test_cancel_clean_buffer_passes_base_seq_not_zero() -> None: assert cancel_seq == 5 assert cancel_state == {"step": 5} - await backend.mark_cancelled(job_id, worker_id, progress_seq=cancel_seq, attempt=1) + await backend.mark_cancelled( + job_id, worker_id, progress_seq=cancel_seq, attempt=1, claim_epoch=1 + ) row = await backend.get(job_id) assert row is not None diff --git a/tests/test_reclaim_retry_budget_parity.py b/tests/test_reclaim_retry_budget_parity.py index 689e7d286..a2bdd11c6 100644 --- a/tests/test_reclaim_retry_budget_parity.py +++ b/tests/test_reclaim_retry_budget_parity.py @@ -131,7 +131,12 @@ async def _run_attempts_to(backend: Backend, job_id: JobId, target_attempt: int) if row.attempt >= target_attempt: return await backend.mark_failed_or_retry( - job_id, worker_id, _ERROR, timedelta(0), attempt=row.attempt + job_id, + worker_id, + _ERROR, + timedelta(0), + attempt=row.attempt, + claim_epoch=row.claim_epoch, ) await _make_due(backend, job_id) @@ -263,7 +268,12 @@ async def test_reclaim_leaves_the_attempt_counter_for_dispatch_to_advance( ) written = await backend_pair.mark_failed_or_retry( - job_id, worker_id, _ERROR, timedelta(0), attempt=next_row.attempt + job_id, + worker_id, + _ERROR, + timedelta(0), + attempt=next_row.attempt, + claim_epoch=next_row.claim_epoch, ) assert written is not None, ( "the terminal write for the attempt following a reclaim did not land - a " diff --git a/tests/test_reservation_denial_writes_no_events.py b/tests/test_reservation_denial_writes_no_events.py index 307384271..22eb41116 100644 --- a/tests/test_reservation_denial_writes_no_events.py +++ b/tests/test_reservation_denial_writes_no_events.py @@ -114,6 +114,7 @@ async def test_reservation_denial_writes_no_event_or_attempt_rows( _DELAY, outcome="reservation_denied", attempt=1, + claim_epoch=1, ) assert outcome == "scheduled" @@ -169,6 +170,7 @@ async def test_retry_after_without_budget_writes_no_event_or_attempt_rows( _DELAY, consume_budget=False, attempt=1, + claim_epoch=1, ) assert outcome == "scheduled" @@ -272,6 +274,7 @@ async def test_denial_loop_never_terminalises_and_never_spends_budget( # attempt = attempt + 1, so the write carries the dispatched # row's current epoch (rows[0].attempt). attempt=rows[0].attempt, + claim_epoch=rows[0].claim_epoch, ) async with clean_jobs_app.deps.worker_pool.acquire() as conn: # type: ignore[union-attr] # Why: as above. row = await conn.fetchrow( @@ -362,6 +365,7 @@ async def test_denial_at_exhausted_budget_reschedules_rather_than_failing( _DELAY, outcome="reservation_denied", attempt=1, + claim_epoch=1, ) assert outcome == "scheduled", ( f"a reservation denial on a budget-exhausted job returned {outcome!r}. " @@ -499,6 +503,7 @@ async def test_denied_job_runs_to_success_once_capacity_frees( timedelta(0), outcome="reservation_denied", attempt=rows[0].attempt, + claim_epoch=rows[0].claim_epoch, ) assert denial_outcome == "scheduled", ( f"cycle {cycle}: the denial returned {denial_outcome!r}. Denials " @@ -520,6 +525,7 @@ async def test_denied_job_runs_to_success_once_capacity_frees( worker_id, {"ok": True}, attempt=rows[0].attempt, + claim_epoch=rows[0].claim_epoch, ) assert succeeded, ( "the terminal success write matched no row after a denial streak. The " @@ -613,6 +619,7 @@ async def test_denied_job_past_its_close_deadline_fails_visibly_not_silently( timedelta(0), outcome="reservation_denied", attempt=rows[0].attempt, + claim_epoch=rows[0].claim_epoch, ) == "scheduled" ) diff --git a/tests/test_retry_adapter.py b/tests/test_retry_adapter.py index dc4cad1ec..aaa76d0cd 100644 --- a/tests/test_retry_adapter.py +++ b/tests/test_retry_adapter.py @@ -133,6 +133,7 @@ async def mark_failed_or_retry( progress_state: dict[str, object] | None = None, *, attempt: int | None = None, + claim_epoch: int | None = None, ) -> JobRow: raise self._exc diff --git a/tests/test_retry_inmemory.py b/tests/test_retry_inmemory.py index 68bd65522..c40848f03 100644 --- a/tests/test_retry_inmemory.py +++ b/tests/test_retry_inmemory.py @@ -384,6 +384,7 @@ def always_fail(payload: object, ctx: object) -> None: error_info, decision.retry_delay, attempt=1, + claim_epoch=1, ) assert row.status == "scheduled" assert row.attempt == 1 @@ -456,6 +457,7 @@ def always_fail(payload: object, ctx: object) -> None: error_info, decision.retry_delay, attempt=1, + claim_epoch=1, ) assert row.status == "failed" assert row.error_class == "DeadlineExceeded" @@ -899,6 +901,7 @@ 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"]: raise OSError("db socket closed mid-snooze-write") diff --git a/tests/test_retry_integration.py b/tests/test_retry_integration.py index a8dfa6e9c..d85538a48 100644 --- a/tests/test_retry_integration.py +++ b/tests/test_retry_integration.py @@ -61,11 +61,17 @@ async def _promote_scheduled_to_running( job_id: UUID, attempt: int, ) -> None: - """Update a scheduled job to running (simulates dispatch + promote).""" + """Update a scheduled job to running (simulates dispatch + promote). + + A real claim advances the claim epoch beside the attempt; the epoch + rides the promoted attempt so the next terminal write's fence sees + what dispatch would have stamped. + """ await conn.execute( f"""UPDATE \"{schema}\".jobs SET status = 'running', attempt = $1, + claim_epoch = $4, locked_by_worker = $2, lock_expires_at = now() + interval '60 seconds', started_at = now(), @@ -74,6 +80,10 @@ async def _promote_scheduled_to_running( attempt, worker_id, job_id, + # A separate bind: the smallint attempt column and the bigint + # epoch column cannot share one parameter (asyncpg deduces the + # type per parameter, and the two deduce differently). + attempt, ) @@ -133,6 +143,7 @@ async def test_transient_retry_succeeds_after_retries( error_info, decision_1.retry_delay, attempt=1, + claim_epoch=1, ) assert row_1.status == "scheduled" @@ -162,6 +173,7 @@ async def test_transient_retry_succeeds_after_retries( error_info, decision_2.retry_delay, attempt=2, + claim_epoch=2, ) assert row_2.status == "scheduled" @@ -171,7 +183,7 @@ async def test_transient_retry_succeeds_after_retries( async with deps.worker_pool.acquire() as conn: await _promote_scheduled_to_running(conn, schema, worker_id, job_id, attempt=3) - result = await backend.mark_succeeded(job_id, worker_id, {"ok": True}, attempt=3) + result = await backend.mark_succeeded(job_id, worker_id, {"ok": True}, attempt=3, claim_epoch=3) assert result is True # ── Assertions ────────────────────────────────────────────────── @@ -266,6 +278,7 @@ async def test_transient_exhaustion( error_info, decision_1.retry_delay, attempt=1, + claim_epoch=1, ) assert row_1.status == "scheduled" @@ -287,7 +300,9 @@ async def test_transient_exhaustion( ) assert isinstance(decision_2, Fail) - row_2 = await backend.mark_failed_or_retry(job_id, worker_id, error_info, None, attempt=2) + row_2 = await backend.mark_failed_or_retry( + job_id, worker_id, error_info, None, attempt=2, claim_epoch=2 + ) assert row_2.status == "failed" # ── Assertions ────────────────────────────────────────────────── @@ -368,7 +383,7 @@ async def test_cancel_skips_classifier() -> None: assert cancel_event.is_set() - cancelled = await backend.mark_cancelled(job_id, worker_id, attempt=1) + cancelled = await backend.mark_cancelled(job_id, worker_id, attempt=1, claim_epoch=1) assert cancelled is True row = await backend.get(job_id) @@ -565,7 +580,12 @@ async def test_indefinite_retry_polling_pattern( assert isinstance(decision, Retry), f"attempt {attempt_num} should be Retry" row_after = await backend.mark_failed_or_retry( - job_id, worker_id, error_info, decision.retry_delay, attempt=attempt_num + job_id, + worker_id, + error_info, + decision.retry_delay, + attempt=attempt_num, + claim_epoch=attempt_num, ) assert row_after.status == "scheduled" @@ -578,7 +598,9 @@ async def test_indefinite_retry_polling_pattern( async with deps.worker_pool.acquire() as conn: await _promote_scheduled_to_running(conn, schema, worker_id, job_id, attempt=11) - result = await backend.mark_succeeded(job_id, worker_id, {"ok": True}, attempt=11) + result = await backend.mark_succeeded( + job_id, worker_id, {"ok": True}, attempt=11, claim_epoch=11 + ) assert result is True async with deps.worker_pool.acquire() as conn: @@ -658,7 +680,7 @@ async def test_indefinite_retry_deadline_enforcement( assert isinstance(decision_1, Retry) row_1 = await backend.mark_failed_or_retry( - job_id, worker_id, error_info, decision_1.retry_delay, attempt=1 + job_id, worker_id, error_info, decision_1.retry_delay, attempt=1, claim_epoch=1 ) assert row_1.status == "scheduled" @@ -685,7 +707,7 @@ async def test_indefinite_retry_deadline_enforcement( # The SQL deadline guard arbitrates: the delay cannot land before the # (already-past) schedule_to_close, so the write fails the job. row_2 = await backend.mark_failed_or_retry( - job_id, worker_id, error_info, decision_2.retry_delay, attempt=2 + job_id, worker_id, error_info, decision_2.retry_delay, attempt=2, claim_epoch=2 ) assert row_2.status == "failed" assert row_2.error_class == "DeadlineExceeded" diff --git a/tests/test_retry_job_attempt_epoch_pk.py b/tests/test_retry_job_attempt_epoch_pk.py index be3fd77ca..8c60379b6 100644 --- a/tests/test_retry_job_attempt_epoch_pk.py +++ b/tests/test_retry_job_attempt_epoch_pk.py @@ -63,7 +63,9 @@ async def test_retry_job_attempt_monotonic_no_duplicate_key_on_re_run( ) # Epoch 1: the terminal write lands the attempt row at (job, 1). - assert await backend.mark_failed_or_retry(job_id, worker_id, error, None, attempt=1) + assert await backend.mark_failed_or_retry( + job_id, worker_id, error, None, attempt=1, claim_epoch=1 + ) row = await conn.fetchrow( f'SELECT status, attempt, max_attempts FROM "{schema}".jobs WHERE id = $1', job_id ) @@ -102,7 +104,9 @@ async def test_retry_job_attempt_monotonic_no_duplicate_key_on_re_run( # The second terminal write lands at the fresh (job, 2): under the # old epoch reset this write raised UniqueViolationError on # job_attempts_pkey. - assert await backend.mark_failed_or_retry(job_id, worker_id, error, None, attempt=2) + assert await backend.mark_failed_or_retry( + job_id, worker_id, error, None, attempt=2, claim_epoch=2 + ) final = await conn.fetchrow( f'SELECT status, attempt FROM "{schema}".jobs WHERE id = $1', job_id ) diff --git a/tests/test_retry_job_past_deadline_sweep_collision.py b/tests/test_retry_job_past_deadline_sweep_collision.py index 044c84534..89ed82e26 100644 --- a/tests/test_retry_job_past_deadline_sweep_collision.py +++ b/tests/test_retry_job_past_deadline_sweep_collision.py @@ -90,7 +90,9 @@ async def test_retry_past_deadline_does_not_wedge_the_deadline_sweep( ) # Epoch 1: the terminal write lands the attempt row at (job, 1). - assert await backend.mark_failed_or_retry(job_id, worker_id, error, None, attempt=1) + assert await backend.mark_failed_or_retry( + job_id, worker_id, error, None, attempt=1, claim_epoch=1 + ) failed = await conn.fetchrow( f'SELECT status, attempt FROM "{schema}".jobs WHERE id = $1', job_id ) @@ -193,7 +195,9 @@ async def test_retry_collision_does_not_wedge_sibling_rows_in_same_sweep_batch( schedule_to_close=datetime.now(UTC) + timedelta(minutes=5), with_events=False, ) - assert await backend.mark_failed_or_retry(collide_job_id, worker_id, error, None, attempt=1) + assert await backend.mark_failed_or_retry( + collide_job_id, worker_id, error, None, attempt=1, claim_epoch=1 + ) # Row B: an ordinary never-dispatched job whose deadline has simply # passed -- no retry, no prior attempt row, nothing to collide with. diff --git a/tests/test_retry_job_source_states_parity.py b/tests/test_retry_job_source_states_parity.py index 8a2e9460e..0aeeb6370 100644 --- a/tests/test_retry_job_source_states_parity.py +++ b/tests/test_retry_job_source_states_parity.py @@ -110,7 +110,9 @@ async def _run_to_succeeded(backend: Backend, job_id: JobId) -> None: """Drive the job to ``succeeded`` through the real claim-and-complete path.""" worker_id = await _worker_of(backend) attempt = await _claim(backend, job_id, worker_id) - await backend.mark_succeeded(job_id, worker_id, {"ok": True}, attempt=attempt) + await backend.mark_succeeded( + job_id, worker_id, {"ok": True}, attempt=attempt, claim_epoch=attempt + ) row = await backend.get(job_id) assert row is not None assert row.status == "succeeded", ( @@ -243,7 +245,9 @@ async def test_retry_job_still_re_runs_a_failed_job(backend_pair: Backend) -> No job_id = await _enqueue(backend_pair, max_attempts=1) worker_id = await _worker_of(backend_pair) attempt = await _claim(backend_pair, job_id, worker_id) - await backend_pair.mark_failed_or_retry(job_id, worker_id, _ERROR, None, attempt=attempt) + await backend_pair.mark_failed_or_retry( + job_id, worker_id, _ERROR, None, attempt=attempt, claim_epoch=attempt + ) before = await backend_pair.get(job_id) assert before is not None @@ -308,7 +312,9 @@ async def test_retry_job_clears_an_elapsed_deadline_and_the_row_dispatches( job_id = await _enqueue(backend_pair, max_attempts=1) worker_id = await _worker_of(backend_pair) attempt = await _claim(backend_pair, job_id, worker_id) - await backend_pair.mark_failed_or_retry(job_id, worker_id, _ERROR, None, attempt=attempt) + await backend_pair.mark_failed_or_retry( + job_id, worker_id, _ERROR, None, attempt=attempt, claim_epoch=attempt + ) # The deadline elapses while the job sits failed - an operator # investigating an incident routinely takes longer than a tight @@ -348,7 +354,9 @@ async def test_retry_job_preserves_a_future_deadline(backend_pair: Backend) -> N job_id = await _enqueue(backend_pair, max_attempts=1) worker_id = await _worker_of(backend_pair) attempt = await _claim(backend_pair, job_id, worker_id) - await backend_pair.mark_failed_or_retry(job_id, worker_id, _ERROR, None, attempt=attempt) + await backend_pair.mark_failed_or_retry( + job_id, worker_id, _ERROR, None, attempt=attempt, claim_epoch=attempt + ) future = _backend_now(backend_pair) + timedelta(days=1) await _force_schedule_to_close(backend_pair, job_id, future) diff --git a/tests/test_retry_job_stale_deadline_operator_footgun.py b/tests/test_retry_job_stale_deadline_operator_footgun.py index 635823cee..a35f7c365 100644 --- a/tests/test_retry_job_stale_deadline_operator_footgun.py +++ b/tests/test_retry_job_stale_deadline_operator_footgun.py @@ -104,7 +104,9 @@ async def test_retry_job_past_deadline_produces_a_dispatchable_row( with_events=False, ) - assert await backend.mark_failed_or_retry(job_id, worker_id, error, None, attempt=1) + assert await backend.mark_failed_or_retry( + job_id, worker_id, error, None, attempt=1, claim_epoch=1 + ) failed = await conn.fetchrow( f'SELECT status, attempt FROM "{schema}".jobs WHERE id = $1', job_id ) diff --git a/tests/test_round_trip_budgets.py b/tests/test_round_trip_budgets.py index 287a2f0a8..170294fd6 100644 --- a/tests/test_round_trip_budgets.py +++ b/tests/test_round_trip_budgets.py @@ -97,6 +97,7 @@ def _job_record(*, job_id: UUID | None = None, actor: str = "test_actor") -> _Re "retry_backoff": "exponential", "retry_jitter": 0.2, "assignment_routed": False, + "claim_epoch": 0, } ) diff --git a/tests/test_rt_actor_queue_move.py b/tests/test_rt_actor_queue_move.py index 872ca7be9..4b1297ce4 100644 --- a/tests/test_rt_actor_queue_move.py +++ b/tests/test_rt_actor_queue_move.py @@ -197,6 +197,7 @@ async def test_failure_retry_tail_is_served_only_by_the_retired_source_queue( ), timedelta(seconds=5), attempt=int(claimed["attempt"]), + claim_epoch=int(claimed["claim_epoch"]), ) status, queue = await _row_state(conn, schema, job_id) assert status == "scheduled" @@ -266,6 +267,7 @@ async def test_operator_retry_tail_is_served_only_by_the_retired_source_queue( ), None, attempt=int(claimed["attempt"]), + claim_epoch=int(claimed["claim_epoch"]), ) status, queue = await _row_state(conn, schema, job_id) assert status == "failed" diff --git a/tests/test_rt_boundary_reattack.py b/tests/test_rt_boundary_reattack.py index c96753e8d..4787938e5 100644 --- a/tests/test_rt_boundary_reattack.py +++ b/tests/test_rt_boundary_reattack.py @@ -165,6 +165,7 @@ async def test_unavailable_denial_with_past_deadline_terminalises_on_pg( _DELAY, outcome="rate_limit_denied", attempt=1, + claim_epoch=1, denial_reason="unavailable", ) @@ -218,6 +219,7 @@ async def test_unavailable_denial_at_exact_max_attempts_stays_scheduled_on_pg( _DELAY, outcome="rate_limit_denied", attempt=2, + claim_epoch=2, denial_reason="unavailable", ) @@ -272,6 +274,7 @@ async def test_capacity_denial_at_exact_max_attempts_reschedules_on_pg( _DELAY, outcome="rate_limit_denied", attempt=2, + claim_epoch=2, denial_reason="capacity", ) @@ -331,6 +334,7 @@ async def test_mirror_matches_the_three_unavailable_boundaries(self) -> None: _DELAY, outcome="rate_limit_denied", attempt=running.attempt, + claim_epoch=running.claim_epoch, denial_reason="unavailable", ) assert outcome == "failed", ( @@ -369,6 +373,7 @@ async def test_mirror_matches_the_three_unavailable_boundaries(self) -> None: _DELAY, outcome="reservation_denied", attempt=running.attempt, + claim_epoch=running.claim_epoch, denial_reason="unavailable", ) assert outcome == "scheduled", ( @@ -406,6 +411,7 @@ async def test_mirror_matches_the_three_unavailable_boundaries(self) -> None: _DELAY, outcome="reservation_denied", attempt=running.attempt, + claim_epoch=running.claim_epoch, denial_reason="capacity", ) assert outcome == "scheduled", ( diff --git a/tests/test_rt_cancelwatch_abandon_drain.py b/tests/test_rt_cancelwatch_abandon_drain.py index 3b00bc7ba..43cd8c1a0 100644 --- a/tests/test_rt_cancelwatch_abandon_drain.py +++ b/tests/test_rt_cancelwatch_abandon_drain.py @@ -100,6 +100,7 @@ def _make_ctx() -> JobContext[BaseModel]: actor="test", queue="default", attempt=1, + claim_epoch=0, worker_id=new_uuid(), payload=_StubPayload(), jobs=SubJobEnqueuer(loop_scope_resolved=None, worker_pool=None, backend=backend), diff --git a/tests/test_rt_cancelwatch_cross_worker_abandon.py b/tests/test_rt_cancelwatch_cross_worker_abandon.py index 991492405..6e6620046 100644 --- a/tests/test_rt_cancelwatch_cross_worker_abandon.py +++ b/tests/test_rt_cancelwatch_cross_worker_abandon.py @@ -94,6 +94,7 @@ def _make_ctx(job_id: JobId, worker_id: UUID) -> JobContext[BaseModel]: actor="test_actor", queue="default", attempt=1, + claim_epoch=0, worker_id=worker_id, payload=_StubPayload(), jobs=SubJobEnqueuer(loop_scope_resolved=None, worker_pool=None, backend=None), diff --git a/tests/test_rt_cancelwatch_poll_fencing.py b/tests/test_rt_cancelwatch_poll_fencing.py index ba29f7f56..e2f0d86de 100644 --- a/tests/test_rt_cancelwatch_poll_fencing.py +++ b/tests/test_rt_cancelwatch_poll_fencing.py @@ -82,6 +82,7 @@ def _make_ctx(job_id: JobId, worker_id: UUID) -> JobContext[BaseModel]: actor="test_actor", queue="default", attempt=1, + claim_epoch=0, worker_id=worker_id, payload=_StubPayload(), jobs=SubJobEnqueuer(loop_scope_resolved=None, worker_pool=None, backend=None), @@ -204,7 +205,7 @@ async def test_stale_cancel_request_on_terminal_row_is_inert( # The owner task completed between polls: the real terminal # write lands while the cancel request sits unobserved. assert await _mark_succeeded_on_conn( - conn, render(schema), job_id, worker_id, attempt=1 + conn, render(schema), job_id, worker_id, attempt=1, claim_epoch=1 ), "fixture broken: the owner's terminal write must apply" stale_flag = await conn.fetchval( f'SELECT cancel_requested_at FROM "{schema}".jobs WHERE id = $1', job_id @@ -323,7 +324,7 @@ async def test_escalation_then_terminal_write_no_reissue_storm( assert await _escalation_events(conn, schema, job_id) == 1 # The owner's terminal write lands after the escalation. assert await _mark_succeeded_on_conn( - conn, render(schema), job_id, worker_id, attempt=1 + conn, render(schema), job_id, worker_id, attempt=1, claim_epoch=1 ), "fixture broken: the owner's terminal write must still apply" # Age past the cleanup grace so every later tick's phase-3 arm fires diff --git a/tests/test_rt_cancelwatch_watchdog_budget.py b/tests/test_rt_cancelwatch_watchdog_budget.py index 0754dd921..950bc1c8d 100644 --- a/tests/test_rt_cancelwatch_watchdog_budget.py +++ b/tests/test_rt_cancelwatch_watchdog_budget.py @@ -150,6 +150,7 @@ def _make_ctx() -> JobContext[BaseModel]: actor="test", queue="default", attempt=1, + claim_epoch=0, worker_id=new_uuid(), payload=_StubPayload(), jobs=SubJobEnqueuer(loop_scope_resolved=None, worker_pool=None, backend=backend), diff --git a/tests/test_rt_diff_denial_interrupt_composition.py b/tests/test_rt_diff_denial_interrupt_composition.py index 057d77fd4..645c74c77 100644 --- a/tests/test_rt_diff_denial_interrupt_composition.py +++ b/tests/test_rt_diff_denial_interrupt_composition.py @@ -66,7 +66,11 @@ async def _denied_then_interrupted(side: DiffSide) -> None: side.record( "release", await side.backend.mark_interrupted( - jid, await side.worker("w2"), attempt=row.attempt, hold=timedelta(0) + jid, + await side.worker("w2"), + attempt=row.attempt, + claim_epoch=row.claim_epoch, + hold=timedelta(0), ), ) diff --git a/tests/test_rt_diff_harness.py b/tests/test_rt_diff_harness.py index b3e81c663..3393d2849 100644 --- a/tests/test_rt_diff_harness.py +++ b/tests/test_rt_diff_harness.py @@ -622,6 +622,13 @@ async def _attempt_epoch_of(self, token: str) -> int | None: row = await self.backend.get(self._jobs_by_token[token]) return None if row is None else row.attempt + async def _claim_epoch_of(self, token: str) -> int | None: + """The row's current claim epoch - the terminal writes' second fence + bind, threaded beside ``attempt`` exactly as the worker threads it + (the claim-epoch fence, 01.00.18_02).""" + row = await self.backend.get(self._jobs_by_token[token]) + return None if row is None else row.claim_epoch + async def mark_succeeded( self, token: str, @@ -638,6 +645,7 @@ async def mark_succeeded( if fallback_result_ttl_s is None else timedelta(seconds=fallback_result_ttl_s), attempt=await self._attempt_epoch_of(token), + claim_epoch=await self._claim_epoch_of(token), ) async def mark_failed_or_retry( @@ -655,6 +663,7 @@ async def mark_failed_or_retry( ErrorInfo(error_class=error_class, error_message=error_message, error_traceback=None), None if retry_delay_s is None else timedelta(seconds=retry_delay_s), attempt=await self._attempt_epoch_of(token), + claim_epoch=await self._claim_epoch_of(token), ) async def mark_cancelled(self, token: str, worker_token: str) -> bool: @@ -662,6 +671,7 @@ async def mark_cancelled(self, token: str, worker_token: str) -> bool: self._jobs_by_token[token], await self.worker(worker_token), attempt=await self._attempt_epoch_of(token), + claim_epoch=await self._claim_epoch_of(token), ) async def mark_snoozed( @@ -682,6 +692,7 @@ async def mark_snoozed( outcome=outcome, attempt=await self._attempt_epoch_of(token), denial_reason=denial_reason, + claim_epoch=await self._claim_epoch_of(token), ) async def mark_retry_after( @@ -698,6 +709,7 @@ async def mark_retry_after( timedelta(seconds=delay_s), consume_budget=consume_budget, attempt=await self._attempt_epoch_of(token), + claim_epoch=await self._claim_epoch_of(token), ) async def retry_job(self, token: str) -> bool: @@ -826,6 +838,7 @@ async def _job_observable(self, jid: JobId, now: datetime) -> dict[str, Any]: "snooze_count": row.snooze_count, "rate_limit_blocked_count": row.rate_limit_blocked_count, "interrupt_count": row.interrupt_count, + "claim_epoch": row.claim_epoch, "retry_base": _seconds(row.retry_base), "retry_cap": _seconds(row.retry_cap), "retry_backoff": row.retry_backoff, @@ -1148,6 +1161,7 @@ async def test_job_observable_projects_every_jobrow_field() -> None: retry_backoff="linear", retry_jitter=0.5, interrupt_count=4, + claim_epoch=7, assignment_routed=True, ) memory._jobs[JobId(planted.id)] = planted # pyright: ignore[reportPrivateUsage] # Why: test-only private seeding, the established same-module pattern (DiffSide.plant). @@ -1169,4 +1183,5 @@ async def test_job_observable_projects_every_jobrow_field() -> None: assert obs["retry_backoff"] == "linear" assert obs["retry_jitter"] == 0.5 assert obs["interrupt_count"] == 4 + assert obs["claim_epoch"] == 7 assert obs["assignment_routed"] is True diff --git a/tests/test_rt_diff_interrupt_reclaim_composition.py b/tests/test_rt_diff_interrupt_reclaim_composition.py index df1779900..932aa0f0f 100644 --- a/tests/test_rt_diff_interrupt_reclaim_composition.py +++ b/tests/test_rt_diff_interrupt_reclaim_composition.py @@ -117,7 +117,11 @@ async def _interrupt_reclaim_chain( # back with the claim's increment standing; the attempt did start # executing, so it is spent. released = await side.backend.mark_interrupted( - args.id, wid, attempt=claimed_row.attempt, hold=timedelta(0) + args.id, + wid, + attempt=claimed_row.attempt, + claim_epoch=claimed_row.claim_epoch, + hold=timedelta(0), ) assert released == "pending", ( f"the shutdown release of a cleanly-owned row must land pending; got {released!r}" @@ -243,7 +247,7 @@ async def scenario(side: DiffSide) -> None: assert row is not None released = await side.backend.mark_interrupted( - args.id, wid, attempt=row.attempt, hold=timedelta(0) + args.id, wid, attempt=row.attempt, claim_epoch=row.claim_epoch, hold=timedelta(0) ) side.record("first_release", released) @@ -260,7 +264,7 @@ async def scenario(side: DiffSide) -> None: side.record( "second_release", await side.backend.mark_interrupted( - args.id, wid, attempt=row2.attempt, hold=timedelta(0) + args.id, wid, attempt=row2.attempt, claim_epoch=row2.claim_epoch, hold=timedelta(0) ), ) @@ -372,7 +376,11 @@ async def test_interrupt_does_not_advance_the_reclaim_curve_with_jitter_on( assert claimed[0].attempt == 1 released = await backend.mark_interrupted( - job_id, worker_id, attempt=claimed[0].attempt, hold=timedelta(0) + job_id, + worker_id, + attempt=claimed[0].attempt, + claim_epoch=claimed[0].claim_epoch, + hold=timedelta(0), ) assert released == "pending" diff --git a/tests/test_rt_error_text_bounds.py b/tests/test_rt_error_text_bounds.py index 42a2ed213..c4d08fc96 100644 --- a/tests/test_rt_error_text_bounds.py +++ b/tests/test_rt_error_text_bounds.py @@ -65,7 +65,9 @@ async def test_mark_failed_truncates_1mb_error_text( worker_id, job_id = await create_workered_running_job(clean_pg_conn, schema) backend = pool_backend(settings, module_pg_pool) - row = await backend.mark_failed_or_retry(job_id, worker_id, _huge_error(), None, attempt=1) + row = await backend.mark_failed_or_retry( + job_id, worker_id, _huge_error(), None, attempt=1, claim_epoch=1 + ) assert row.status == "failed" stored = await clean_pg_conn.fetchrow( @@ -108,7 +110,7 @@ async def test_mark_retry_truncates_1mb_error_text( backend = pool_backend(settings, module_pg_pool) row = await backend.mark_failed_or_retry( - job_id, worker_id, _huge_error(), timedelta(seconds=1), attempt=1 + job_id, worker_id, _huge_error(), timedelta(seconds=1), attempt=1, claim_epoch=1 ) assert row.status == "scheduled" diff --git a/tests/test_rt_payload_pg_jsonb.py b/tests/test_rt_payload_pg_jsonb.py index 6bb3d1b7c..84379c25b 100644 --- a/tests/test_rt_payload_pg_jsonb.py +++ b/tests/test_rt_payload_pg_jsonb.py @@ -160,7 +160,9 @@ async def test_error_message_with_lone_surrogate_must_not_strand(pg_env: _PgEnv) ), ) - row = await pg_env.backend.mark_failed_or_retry(job_id, worker_id, error, None, attempt=1) + row = await pg_env.backend.mark_failed_or_retry( + job_id, worker_id, error, None, attempt=1, claim_epoch=1 + ) assert row.status == "failed", ( "contract: an unencodable exception message must fail the job with the defect " "visible (escaped/sanitized), never strand it running" @@ -189,7 +191,9 @@ async def test_error_message_with_nul_sanitized_lands_failed(pg_env: _PgEnv) -> error_traceback=sanitize_nul_str("bad\x00trace"), ) - row = await pg_env.backend.mark_failed_or_retry(job_id, worker_id, error, None, attempt=1) + row = await pg_env.backend.mark_failed_or_retry( + job_id, worker_id, error, None, attempt=1, claim_epoch=1 + ) assert row.status == "failed" async with pg_env.pool.acquire() as conn: @@ -218,6 +222,7 @@ async def test_nan_result_stores_null_and_succeeds(pg_env: _PgEnv) -> None: worker_id, result={"ratio": float("nan"), "inf": float("inf"), "ok": True}, attempt=1, + claim_epoch=1, ) assert ok, "contract: a NaN-bearing result is storable (as null), not a failure" @@ -330,6 +335,7 @@ async def test_progress_state_merge_last_writer_wins_on_type_change(pg_env: _PgE progress_seq=1, progress_state={"step": "one"}, attempt=1, + claim_epoch=1, ) assert ok diff --git a/tests/test_rt_storm_retry_ladder.py b/tests/test_rt_storm_retry_ladder.py index 44847de3f..1e6548e4f 100644 --- a/tests/test_rt_storm_retry_ladder.py +++ b/tests/test_rt_storm_retry_ladder.py @@ -138,6 +138,7 @@ def _set_running(backend: InMemoryBackend, job_id: JobId, *, attempt: int = 1) - row, status="running", attempt=attempt, + claim_epoch=attempt, locked_by_worker=_WORKER, lock_expires_at=_START - timedelta(seconds=1), started_at=_START - timedelta(seconds=30), @@ -376,7 +377,7 @@ async def test_zero_base_indefinite_failure_retry_cycles_at_zero_period_unfloore last_delay = decision.retry_delay await backend.mark_failed_or_retry( - job_id, _WORKER, error_info, decision.retry_delay, attempt=attempt + job_id, _WORKER, error_info, decision.retry_delay, attempt=attempt, claim_epoch=attempt ) row = await backend.get(job_id) assert row is not None @@ -439,7 +440,7 @@ async def test_deferral_arms_floor_zero_delay_but_failure_retry_does_not() -> No for job_id in (snoozer, failer): _set_running(backend, job_id, attempt=1) - await backend.mark_snoozed(snoozer, _WORKER, timedelta(0), attempt=1) + await backend.mark_snoozed(snoozer, _WORKER, timedelta(0), attempt=1, claim_epoch=1) snooze_row = await backend.get(snoozer) assert snooze_row is not None assert snooze_row.scheduled_at - _START == MIN_DEFERRAL_INTERVAL, ( @@ -453,6 +454,7 @@ async def test_deferral_arms_floor_zero_delay_but_failure_retry_does_not() -> No ErrorInfo(error_class="RuntimeError", error_message="x", error_traceback=None), timedelta(0), attempt=1, + claim_epoch=1, ) fail_row = await backend.get(failer) assert fail_row is not None diff --git a/tests/test_rt_storm_saturation_geometry.py b/tests/test_rt_storm_saturation_geometry.py index 004a9e82f..d0fbd98a3 100644 --- a/tests/test_rt_storm_saturation_geometry.py +++ b/tests/test_rt_storm_saturation_geometry.py @@ -247,7 +247,9 @@ async def slot_job(job_id: JobId) -> bool: # the landed attempt-epoch fence no-ops an epoch-less write # - the sibling PG test presents the row's epoch the same # way, mirroring the production caller's attempt=job.attempt. - return await backend.mark_succeeded(job_id, worker_id, {"ok": True}, attempt=1) + return await backend.mark_succeeded( + job_id, worker_id, {"ok": True}, attempt=1, claim_epoch=0 + ) async def heartbeat_tick() -> None: # The heartbeat.py loop shape: bounded acquire, then the @@ -301,7 +303,7 @@ async def leader_sweep() -> int: saturator = _Holder(worker_pool, _WORKER_POOL_SIZE) await saturator.hold() queued_write = asyncio.create_task( - backend.mark_succeeded(job_c, worker_id, {"ok": 1}, attempt=1) + backend.mark_succeeded(job_c, worker_id, {"ok": 1}, attempt=1, claim_epoch=0) ) await asyncio.sleep(_OBSERVE_S) assert not queued_write.done(), ( diff --git a/tests/test_rt_sweeps_parity.py b/tests/test_rt_sweeps_parity.py index 324435514..8e1f5dd63 100644 --- a/tests/test_rt_sweeps_parity.py +++ b/tests/test_rt_sweeps_parity.py @@ -181,6 +181,7 @@ async def _seed_memory(memory: InMemoryBackend, holder: UUID) -> dict[str, list[ row, status="running", attempt=1, + claim_epoch=1, locked_by_worker=holder, lock_expires_at=_START - expired_ago, started_at=_START - _STARTED_AGO, @@ -376,6 +377,7 @@ async def test_sweep1_double_reclaim_keeps_one_attempt_row_on_both_backends( row, status="running", attempt=1, + claim_epoch=1, locked_by_worker=memory_holder, lock_expires_at=_START - _PLAIN_LOCK_EXPIRED_AGO, started_at=_START - _STARTED_AGO, diff --git a/tests/test_rt_sweeps_started_at_fallback.py b/tests/test_rt_sweeps_started_at_fallback.py index 6926340fb..17cc32498 100644 --- a/tests/test_rt_sweeps_started_at_fallback.py +++ b/tests/test_rt_sweeps_started_at_fallback.py @@ -192,6 +192,7 @@ async def test_sweep1_null_started_at_contract_is_the_in_memory_twin() -> None: row, status="running", attempt=1, + claim_epoch=1, started_at=None, locked_by_worker=holder, lock_expires_at=_START - _EXPIRED_AGO, diff --git a/tests/test_scheduled_writers_audit.py b/tests/test_scheduled_writers_audit.py index f4076706c..29fcb097c 100644 --- a/tests/test_scheduled_writers_audit.py +++ b/tests/test_scheduled_writers_audit.py @@ -150,7 +150,9 @@ async def test_fr5_audit_only_authorised_paths_write_scheduled( # ── mark_succeeded on a running job → succeeded, not scheduled ── job = await _enqueue_running(backend) - result = await backend.mark_succeeded(job.id, worker_id, {"ok": True}, attempt=job.attempt) + result = await backend.mark_succeeded( + job.id, worker_id, {"ok": True}, attempt=job.attempt, claim_epoch=job.claim_epoch + ) assert result is True post = _get_job(backend, job.id) assert post.status == "succeeded" @@ -164,14 +166,21 @@ async def test_fr5_audit_only_authorised_paths_write_scheduled( error_traceback=None, ) row = await backend.mark_failed_or_retry( - job.id, worker_id, error_info, retry_delay=None, attempt=job.attempt + job.id, + worker_id, + error_info, + retry_delay=None, + attempt=job.attempt, + claim_epoch=job.claim_epoch, ) assert row.status == "failed" assert row.status != "scheduled" # ── mark_cancelled on a running job → cancelled, not scheduled ── job = await _enqueue_running(backend) - result = await backend.mark_cancelled(job.id, worker_id, attempt=job.attempt) + result = await backend.mark_cancelled( + job.id, worker_id, attempt=job.attempt, claim_epoch=job.claim_epoch + ) assert result is True post = _get_job(backend, job.id) assert post.status == "cancelled" @@ -183,7 +192,11 @@ async def test_fr5_audit_only_authorised_paths_write_scheduled( # running→scheduled deferral shape as mark_snoozed/mark_retry_after. job = await _enqueue_running(backend) released = await backend.mark_interrupted( - job.id, worker_id, attempt=job.attempt, hold=timedelta(seconds=30) + job.id, + worker_id, + attempt=job.attempt, + claim_epoch=job.claim_epoch, + hold=timedelta(seconds=30), ) assert released == "scheduled" post = _get_job(backend, job.id) @@ -193,7 +206,11 @@ async def test_fr5_audit_only_authorised_paths_write_scheduled( # job's own schedule_to_close fails the row on the deadline instead. job = await _enqueue_running(backend, schedule_to_close=_CLOCK_START + timedelta(seconds=5)) deadline_failed = await backend.mark_interrupted( - job.id, worker_id, attempt=job.attempt, hold=timedelta(seconds=60) + job.id, + worker_id, + attempt=job.attempt, + claim_epoch=job.claim_epoch, + hold=timedelta(seconds=60), ) assert deadline_failed == "failed:DeadlineExceeded" post = _get_job(backend, job.id) diff --git a/tests/test_shutdown_integration.py b/tests/test_shutdown_integration.py index 4fba2d773..07acdcded 100644 --- a/tests/test_shutdown_integration.py +++ b/tests/test_shutdown_integration.py @@ -127,6 +127,10 @@ def _fake_active_job( actor="test_actor", queue="default", attempt=1, + # The context's epoch is the claim's own stamp: a claimed row at + # attempt 1 carries epoch 1 (the claim advances both), the shape + # every shutdown release here reproduces. + claim_epoch=1, worker_id=new_uuid(), payload=PassthroughPayload(), jobs=SubJobEnqueuer( diff --git a/tests/test_shutdown_orchestrator.py b/tests/test_shutdown_orchestrator.py index dcff6cfbe..80775e2f5 100644 --- a/tests/test_shutdown_orchestrator.py +++ b/tests/test_shutdown_orchestrator.py @@ -89,6 +89,7 @@ def _make_fake_active_job( actor="test_actor", queue="default", attempt=1, + claim_epoch=0, worker_id=new_uuid(), payload=PassthroughPayload(), jobs=SubJobEnqueuer( diff --git a/tests/test_shutdown_release_until_exited.py b/tests/test_shutdown_release_until_exited.py index 3244029d9..6cf53a466 100644 --- a/tests/test_shutdown_release_until_exited.py +++ b/tests/test_shutdown_release_until_exited.py @@ -121,6 +121,7 @@ async def mark_interrupted( worker_id: UUID, *, attempt: int, + claim_epoch: int | None = None, hold: timedelta, progress_seq: int = 0, progress_state: dict[str, object] | None = None, @@ -179,6 +180,7 @@ async def mark_interrupted( worker_id: UUID, *, attempt: int, + claim_epoch: int | None = None, hold: timedelta, progress_seq: int = 0, progress_state: dict[str, object] | None = None, diff --git a/tests/test_shutdown_stubs.py b/tests/test_shutdown_stubs.py index 9b6ee9898..166f2865f 100644 --- a/tests/test_shutdown_stubs.py +++ b/tests/test_shutdown_stubs.py @@ -43,6 +43,7 @@ async def mark_succeeded( *, result_bytes: object = None, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: return True @@ -56,6 +57,7 @@ async def mark_succeeded_with_conn( *, result_bytes: object = None, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: return True @@ -65,6 +67,7 @@ async def mark_cancelled( worker_id: object, *, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: return True diff --git a/tests/test_singleton_violation_savepoint_isolation.py b/tests/test_singleton_violation_savepoint_isolation.py index f1d12befd..68f4ed7ca 100644 --- a/tests/test_singleton_violation_savepoint_isolation.py +++ b/tests/test_singleton_violation_savepoint_isolation.py @@ -92,6 +92,7 @@ def _full_record(*, job_id: UUID | None = None) -> dict[str, object]: "retry_backoff": "exponential", "retry_jitter": 0.2, "assignment_routed": False, + "claim_epoch": 0, } diff --git a/tests/test_snooze_max_attempts_overflow.py b/tests/test_snooze_max_attempts_overflow.py index 567666591..f91ff83d5 100644 --- a/tests/test_snooze_max_attempts_overflow.py +++ b/tests/test_snooze_max_attempts_overflow.py @@ -265,6 +265,7 @@ async def test_mark_snoozed_at_smallint_ceiling_does_not_overflow( _DELAY, outcome="reservation_denied", attempt=1, + claim_epoch=1, ) except asyncpg.DataError as exc: # pragma: no cover - the defect path pytest.fail( @@ -309,6 +310,7 @@ async def test_mark_retry_after_consume_false_at_ceiling_does_not_overflow( _DELAY, consume_budget=False, attempt=1, + claim_epoch=1, ) except asyncpg.DataError as exc: # pragma: no cover - the defect path pytest.fail( @@ -352,6 +354,7 @@ async def test_snooze_below_ceiling_keeps_ceiling_fixed( _DELAY, outcome="reservation_denied", attempt=1, + claim_epoch=1, ) assert outcome == "scheduled" @@ -422,6 +425,7 @@ async def test_in_memory_mark_snoozed_at_ceiling_keeps_ceiling_fixed() -> None: _DELAY, outcome="reservation_denied", attempt=1, + claim_epoch=1, ) assert outcome == "scheduled" @@ -444,6 +448,7 @@ async def test_in_memory_mark_retry_after_consume_false_at_ceiling_keeps_ceiling _DELAY, consume_budget=False, attempt=1, + claim_epoch=1, ) assert outcome == "scheduled" @@ -467,6 +472,7 @@ async def test_in_memory_snooze_below_ceiling_keeps_ceiling_fixed() -> None: _DELAY, outcome="reservation_denied", attempt=1, + claim_epoch=1, ) assert outcome == "scheduled" diff --git a/tests/test_snooze_property.py b/tests/test_snooze_property.py index badfa73d0..c6e197d4a 100644 --- a/tests/test_snooze_property.py +++ b/tests/test_snooze_property.py @@ -115,7 +115,9 @@ async def test_snooze_deterministic_outcome_and_attempt_round_trip( # attempt= the row's current epoch - the worker presents job.attempt # from its in-hand row (worker/_consumer.py); the fence refuses a # caller that cannot prove which attempt it terminates. - result = await backend.mark_snoozed(job_id, wid, delay, attempt=row.attempt) + result = await backend.mark_snoozed( + job_id, wid, delay, attempt=row.attempt, claim_epoch=row.claim_epoch + ) new_scheduled_at = _START + delay deadline_exceeded = schedule_to_close is not None and new_scheduled_at > schedule_to_close diff --git a/tests/test_state_transitions_equivalence.py b/tests/test_state_transitions_equivalence.py index 53aab1188..048913685 100644 --- a/tests/test_state_transitions_equivalence.py +++ b/tests/test_state_transitions_equivalence.py @@ -150,11 +150,13 @@ async def test_mark_failed_or_retry_already_terminal_equivalence( pg_worker_id, ["default"], limit=1, lock_lease=_LOCK_LEASE ) assert len(dispatched) == 1 - await pg_backend.mark_succeeded(pg_row.id, pg_worker_id, result={"ok": True}, attempt=1) + await pg_backend.mark_succeeded( + pg_row.id, pg_worker_id, result={"ok": True}, attempt=1, claim_epoch=1 + ) with pytest.raises(WorkerOwnershipMismatch): await pg_backend.mark_failed_or_retry( - pg_row.id, pg_worker_id, error_info, retry_delay=None, attempt=1 + pg_row.id, pg_worker_id, error_info, retry_delay=None, attempt=1, claim_epoch=1 ) mem_worker_id = mem_backend._worker_id # type: ignore[reportPrivateUsage] # Why: test-only private access @@ -173,11 +175,13 @@ async def test_mark_failed_or_retry_already_terminal_equivalence( ) assert len(mem_dispatched) == 1 mem_job_id = mem_dispatched[0].id - await mem_backend.mark_succeeded(mem_job_id, mem_worker_id, result={"ok": True}, attempt=1) + await mem_backend.mark_succeeded( + mem_job_id, mem_worker_id, result={"ok": True}, attempt=1, claim_epoch=1 + ) with pytest.raises(WorkerOwnershipMismatch): await mem_backend.mark_failed_or_retry( - mem_job_id, mem_worker_id, error_info, retry_delay=None, attempt=1 + mem_job_id, mem_worker_id, error_info, retry_delay=None, attempt=1, claim_epoch=1 ) @@ -309,7 +313,9 @@ async def _setup_job_pg( worker_id, ["default"], limit=1, lock_lease=_LOCK_LEASE ) assert len(dispatched) == 1 - result = await backend.mark_snoozed(row.id, worker_id, delay=timedelta(hours=1), attempt=1) + result = await backend.mark_snoozed( + row.id, worker_id, delay=timedelta(hours=1), attempt=1, claim_epoch=1 + ) assert result == "scheduled" return row.id @@ -385,11 +391,13 @@ async def _perform_transition_pg( assert count >= 1 elif (from_status, to_status) == ("running", "succeeded"): - ok = await backend.mark_succeeded(job_id, worker_id, result={"ok": True}, attempt=1) + ok = await backend.mark_succeeded( + job_id, worker_id, result={"ok": True}, attempt=1, claim_epoch=1 + ) assert ok is True elif (from_status, to_status) == ("running", "cancelled"): - ok = await backend.mark_cancelled(job_id, worker_id, attempt=1) + ok = await backend.mark_cancelled(job_id, worker_id, attempt=1, claim_epoch=1) assert ok is True elif (from_status, to_status) == ("running", "failed"): @@ -399,7 +407,7 @@ async def _perform_transition_pg( error_traceback=None, ) await backend.mark_failed_or_retry( - job_id, worker_id, error_info, retry_delay=None, attempt=1 + job_id, worker_id, error_info, retry_delay=None, attempt=1, claim_epoch=1 ) elif (from_status, to_status) == ("running", "crashed"): @@ -419,7 +427,7 @@ async def _perform_transition_pg( elif (from_status, to_status) == ("running", "scheduled"): result = await backend.mark_snoozed( - job_id, worker_id, delay=timedelta(seconds=30), attempt=1 + job_id, worker_id, delay=timedelta(seconds=30), attempt=1, claim_epoch=1 ) assert result == "scheduled" @@ -526,7 +534,9 @@ async def _setup_job_memory( worker_id, ["default"], limit=1, lock_lease=_LOCK_LEASE ) assert len(dispatched) == 1 - result = await backend.mark_snoozed(row.id, worker_id, delay=timedelta(hours=1), attempt=1) + result = await backend.mark_snoozed( + row.id, worker_id, delay=timedelta(hours=1), attempt=1, claim_epoch=1 + ) assert result == "scheduled" return row.id @@ -598,11 +608,13 @@ async def _perform_transition_memory( assert count >= 1 elif (from_status, to_status) == ("running", "succeeded"): - ok = await backend.mark_succeeded(job_id, worker_id, result={"ok": True}, attempt=1) + ok = await backend.mark_succeeded( + job_id, worker_id, result={"ok": True}, attempt=1, claim_epoch=1 + ) assert ok is True elif (from_status, to_status) == ("running", "cancelled"): - ok = await backend.mark_cancelled(job_id, worker_id, attempt=1) + ok = await backend.mark_cancelled(job_id, worker_id, attempt=1, claim_epoch=1) assert ok is True elif (from_status, to_status) == ("running", "failed"): @@ -612,7 +624,7 @@ async def _perform_transition_memory( error_traceback=None, ) await backend.mark_failed_or_retry( - job_id, worker_id, error_info, retry_delay=None, attempt=1 + job_id, worker_id, error_info, retry_delay=None, attempt=1, claim_epoch=1 ) elif (from_status, to_status) == ("running", "crashed"): @@ -633,7 +645,7 @@ async def _perform_transition_memory( elif (from_status, to_status) == ("running", "scheduled"): result = await backend.mark_snoozed( - job_id, worker_id, delay=timedelta(seconds=30), attempt=1 + job_id, worker_id, delay=timedelta(seconds=30), attempt=1, claim_epoch=1 ) assert result == "scheduled" diff --git a/tests/test_state_transitions_invalid.py b/tests/test_state_transitions_invalid.py index 97211ad8d..0b3bf8521 100644 --- a/tests/test_state_transitions_invalid.py +++ b/tests/test_state_transitions_invalid.py @@ -292,14 +292,18 @@ async def test_succeeded_mark_succeeded_noop(memory_jobs: InMemoryBackend) -> No with a no-op return, confirming idempotent terminal-write semantics. """ job_id, worker_id = await _enqueue_and_dispatch(memory_jobs) - ok = await memory_jobs.mark_succeeded(job_id, worker_id, result={"v": 1}, attempt=1) + ok = await memory_jobs.mark_succeeded( + job_id, worker_id, result={"v": 1}, attempt=1, claim_epoch=1 + ) assert ok is True row = await memory_jobs.get(job_id) assert row is not None assert row.status == "succeeded" - ok2 = await memory_jobs.mark_succeeded(job_id, worker_id, result={"v": 2}, attempt=1) + ok2 = await memory_jobs.mark_succeeded( + job_id, worker_id, result={"v": 2}, attempt=1, claim_epoch=1 + ) assert ok2 is False diff --git a/tests/test_state_transitions_pg.py b/tests/test_state_transitions_pg.py index 8ca711436..53be17701 100644 --- a/tests/test_state_transitions_pg.py +++ b/tests/test_state_transitions_pg.py @@ -92,7 +92,7 @@ async def test_full_lifecycle(self, clean_jobs_app: JobsApp) -> None: assert dispatched[0].attempt == 1 result = await backend.mark_snoozed( - job_id, worker_id, delay=timedelta(seconds=30), attempt=1 + job_id, worker_id, delay=timedelta(seconds=30), attempt=1, claim_epoch=1 ) assert result == "scheduled" @@ -129,7 +129,13 @@ async def test_full_lifecycle(self, clean_jobs_app: JobsApp) -> None: # The re-dispatch re-claims the refunded increment: 0 → 1. assert dispatched2[0].attempt == 1 - ok = await backend.mark_succeeded(job_id, worker_id, result={"ok": True}, attempt=1) + ok = await backend.mark_succeeded( + job_id, + worker_id, + result={"ok": True}, + attempt=dispatched2[0].attempt, + claim_epoch=dispatched2[0].claim_epoch, + ) assert ok is True async with deps.worker_pool.acquire() as conn: @@ -192,7 +198,9 @@ async def test_concurrent_cancel_and_snooze(self, clean_jobs_app: JobsApp) -> No name="concurrent-cancel", ) snooze_task = asyncio.create_task( - backend.mark_snoozed(job_id, worker_id, delay=timedelta(seconds=30), attempt=1), + backend.mark_snoozed( + job_id, worker_id, delay=timedelta(seconds=30), attempt=1, claim_epoch=1 + ), name="concurrent-snooze", ) @@ -269,7 +277,7 @@ async def test_lifecycle_transitions_match( ) assert len(dispatched) == 1 ok = await mem_backend.mark_succeeded( - mem_job_id, mem_worker_id, result={"ok": True}, attempt=1 + mem_job_id, mem_worker_id, result={"ok": True}, attempt=1, claim_epoch=1 ) assert ok is True @@ -288,7 +296,7 @@ async def test_lifecycle_transitions_match( ) assert len(dispatched) == 1 ok = await pg_backend.mark_succeeded( - pg_job_id, pg_worker_id, result={"ok": True}, attempt=1 + pg_job_id, pg_worker_id, result={"ok": True}, attempt=1, claim_epoch=1 ) assert ok is True @@ -415,7 +423,7 @@ async def test_polling_lifecycle(self, clean_jobs_app: JobsApp) -> None: assert len(dispatched) == 1 result = await backend.mark_snoozed( - job_id, worker_id, delay=timedelta(seconds=30), attempt=1 + job_id, worker_id, delay=timedelta(seconds=30), attempt=1, claim_epoch=1 ) assert result == "scheduled" @@ -439,7 +447,13 @@ async def test_polling_lifecycle(self, clean_jobs_app: JobsApp) -> None: ) assert len(dispatched2) == 1 - ok = await backend.mark_succeeded(job_id, worker_id, result={"ok": True}, attempt=1) + ok = await backend.mark_succeeded( + job_id, + worker_id, + result={"ok": True}, + attempt=dispatched2[0].attempt, + claim_epoch=dispatched2[0].claim_epoch, + ) assert ok is True expected_transitions = [ diff --git a/tests/test_state_transitions_round_trip.py b/tests/test_state_transitions_round_trip.py index e6c4cb186..717cf02f1 100644 --- a/tests/test_state_transitions_round_trip.py +++ b/tests/test_state_transitions_round_trip.py @@ -246,7 +246,9 @@ async def test_cancel_mid_snooze() -> None: assert job.status == "running" assert job.attempt == 1 - result = await backend.mark_snoozed(job.id, worker_id, delay=timedelta(seconds=30), attempt=1) + result = await backend.mark_snoozed( + job.id, worker_id, delay=timedelta(seconds=30), attempt=1, claim_epoch=1 + ) assert result == "scheduled" row = await backend.get(args.id) diff --git a/tests/test_state_transitions_unit.py b/tests/test_state_transitions_unit.py index 8008046a1..63043982c 100644 --- a/tests/test_state_transitions_unit.py +++ b/tests/test_state_transitions_unit.py @@ -115,7 +115,9 @@ async def test_running_to_succeeded(memory_jobs: InMemoryBackend) -> None: """running → succeeded via mark_succeeded.""" job_id, worker_id = await _enqueue_and_dispatch(memory_jobs) - result = await memory_jobs.mark_succeeded(job_id, worker_id, result={"value": 42}, attempt=1) + result = await memory_jobs.mark_succeeded( + job_id, worker_id, result={"value": 42}, attempt=1, claim_epoch=1 + ) assert result is True row = await memory_jobs.get(job_id) @@ -154,6 +156,7 @@ async def test_running_to_failed_retry_exhausted( ErrorInfo(error_class="ValueError", error_message="boom", error_traceback=None), retry_delay=None, attempt=1, + claim_epoch=1, ) assert updated.status == "failed" assert updated.error_class == "ValueError" @@ -189,6 +192,7 @@ async def test_running_to_failed_non_retryable( ErrorInfo(error_class="TypeError", error_message="non-retryable", error_traceback=None), retry_delay=None, attempt=1, + claim_epoch=1, ) assert updated.status == "failed" assert updated.error_class == "TypeError" @@ -211,7 +215,7 @@ async def test_running_to_failed_snooze_deadline( job_id, worker_id = await _enqueue_and_dispatch(memory_jobs, schedule_to_close=deadline) result = await memory_jobs.mark_snoozed( - job_id, worker_id, delay=timedelta(seconds=20), attempt=1 + job_id, worker_id, delay=timedelta(seconds=20), attempt=1, claim_epoch=1 ) assert result == "failed" @@ -238,7 +242,7 @@ async def test_running_to_failed_retry_after_deadline( job_id, worker_id = await _enqueue_and_dispatch(memory_jobs, schedule_to_close=deadline) result = await memory_jobs.mark_retry_after( - job_id, worker_id, delay=timedelta(seconds=20), attempt=1 + job_id, worker_id, delay=timedelta(seconds=20), attempt=1, claim_epoch=1 ) assert result == "failed:DeadlineExceeded" @@ -266,7 +270,7 @@ async def test_running_to_failed_max_attempts( ) result = await memory_jobs.mark_retry_after( - job_id, worker_id, delay=timedelta(seconds=5), consume_budget=True, attempt=1 + job_id, worker_id, delay=timedelta(seconds=5), consume_budget=True, attempt=1, claim_epoch=1 ) assert result == "failed:MaxAttemptsExceeded" @@ -294,7 +298,7 @@ async def test_running_to_scheduled_snooze( job_id, worker_id = await _enqueue_and_dispatch(memory_jobs) result = await memory_jobs.mark_snoozed( - job_id, worker_id, delay=timedelta(seconds=30), attempt=1 + job_id, worker_id, delay=timedelta(seconds=30), attempt=1, claim_epoch=1 ) assert result == "scheduled" @@ -330,7 +334,7 @@ async def test_running_to_scheduled_retry_after_consume( pre_attempt = (await memory_jobs.get(job_id)).attempt # type: ignore[union-attr] # Why: just dispatched, row exists result = await memory_jobs.mark_retry_after( - job_id, worker_id, delay=timedelta(seconds=5), consume_budget=True, attempt=1 + job_id, worker_id, delay=timedelta(seconds=5), consume_budget=True, attempt=1, claim_epoch=1 ) assert result == "scheduled" @@ -354,7 +358,12 @@ async def test_running_to_scheduled_retry_after_no_consume( pre_attempt = (await memory_jobs.get(job_id)).attempt # type: ignore[union-attr] # Why: just dispatched, row exists result = await memory_jobs.mark_retry_after( - job_id, worker_id, delay=timedelta(seconds=5), consume_budget=False, attempt=1 + job_id, + worker_id, + delay=timedelta(seconds=5), + consume_budget=False, + attempt=1, + claim_epoch=1, ) assert result == "scheduled" @@ -392,6 +401,7 @@ async def test_running_to_scheduled_reservation_denied( outcome="reservation_denied", metadata_update={"awaiting": "slot"}, attempt=1, + claim_epoch=1, ) assert result == "scheduled" @@ -448,6 +458,7 @@ async def test_denial_at_spent_budget_reschedules_not_fails( delay=timedelta(seconds=5), outcome="rate_limit_denied", attempt=1, + claim_epoch=1, ) assert result == "scheduled" @@ -496,6 +507,7 @@ async def test_denial_terminal_exit_is_the_deadline( delay=timedelta(seconds=30), outcome="rate_limit_denied", attempt=1, + claim_epoch=1, ) assert result == "failed" @@ -528,6 +540,7 @@ async def test_running_to_scheduled_transient_retry( # _START) derives scheduled_at = now + 30s == next_at. retry_delay=next_at - _START, attempt=1, + claim_epoch=1, ) assert updated.status == "scheduled" assert updated.scheduled_at == next_at @@ -638,7 +651,7 @@ async def test_running_to_cancelled_cooperative( assert row is not None assert row.cancel_phase == CancelPhase.COOPERATIVE - ok = await memory_jobs.mark_cancelled(job_id, worker_id, attempt=1) + ok = await memory_jobs.mark_cancelled(job_id, worker_id, attempt=1, claim_epoch=1) assert ok is True row = await memory_jobs.get(job_id) @@ -679,7 +692,7 @@ async def test_running_to_cancelled_forced( assert row is not None assert row.cancel_phase == CancelPhase.FORCED - ok = await memory_jobs.mark_cancelled(job_id, worker_id, attempt=1) + ok = await memory_jobs.mark_cancelled(job_id, worker_id, attempt=1, claim_epoch=1) assert ok is True row = await memory_jobs.get(job_id) @@ -695,7 +708,7 @@ async def test_running_to_cancelled_forced( # cause, or the column carries no information. coop_id, coop_worker = await _enqueue_and_dispatch(memory_jobs) await memory_jobs.write_cancel_request(coop_id, reason="user") - assert await memory_jobs.mark_cancelled(coop_id, coop_worker, attempt=1) is True + assert await memory_jobs.mark_cancelled(coop_id, coop_worker, attempt=1, claim_epoch=1) is True coop_row = await memory_jobs.get(coop_id) assert coop_row is not None assert coop_row.error_class != row.error_class, ( diff --git a/tests/test_stream.py b/tests/test_stream.py index 69b7bf953..db0c6c88a 100644 --- a/tests/test_stream.py +++ b/tests/test_stream.py @@ -350,7 +350,9 @@ async def _dispatch_to_running( """Transition a job from pending/scheduled to running via direct SQL. Simulates what dispatch_batch does: sets status, locked_by_worker, - lock_expires_at, started_at, last_heartbeat_at, and increments attempt. + lock_expires_at, started_at, last_heartbeat_at, and increments attempt + and claim_epoch (the claim advances both; the terminal write then + fences on the epoch this simulated claim stamped). """ async with pool.acquire() as conn: await conn.execute( @@ -360,7 +362,8 @@ async def _dispatch_to_running( "lock_expires_at = now() + interval '60 seconds', " "started_at = now(), " "last_heartbeat_at = now(), " - "attempt = attempt + 1 " + "attempt = attempt + 1, " + "claim_epoch = claim_epoch + 1 " "WHERE id = $2 AND status IN ('pending', 'scheduled')", worker_id, job_id, @@ -424,6 +427,7 @@ async def _collect() -> list[JobEvent]: progress_seq=0, progress_state=None, attempt=1, + claim_epoch=1, ) events = await asyncio.wait_for(task, timeout=5.0) @@ -476,6 +480,7 @@ async def _collect() -> list[JobEvent]: progress_seq=0, progress_state=None, attempt=1, + claim_epoch=1, ) events = await asyncio.wait_for(task, timeout=5.0) @@ -533,6 +538,7 @@ async def _collect() -> None: progress_seq=0, progress_state=None, attempt=1, + claim_epoch=1, ) await asyncio.wait_for(task, timeout=5.0) assert events[-1].terminal is True @@ -582,6 +588,7 @@ async def _collect() -> None: progress_seq=0, progress_state=None, attempt=1, + claim_epoch=1, ) await asyncio.wait_for(task, timeout=5.0) @@ -626,6 +633,7 @@ async def _collect() -> list[JobEvent]: progress_seq=0, progress_state=None, attempt=1, + claim_epoch=1, ) events = await asyncio.wait_for(task, timeout=5.0) @@ -671,6 +679,7 @@ async def _collect() -> list[JobEvent]: progress_seq=0, progress_state=None, attempt=1, + claim_epoch=1, ) events = await asyncio.wait_for(task, timeout=5.0) @@ -754,6 +763,7 @@ async def _collect() -> list[JobEvent]: progress_seq=3, progress_state=None, attempt=1, + claim_epoch=1, ) events = await asyncio.wait_for(task, timeout=5.0) @@ -825,6 +835,7 @@ async def _collect() -> list[JobEvent]: progress_seq=0, progress_state=None, attempt=1, + claim_epoch=1, ) events = await asyncio.wait_for(task, timeout=5.0) diff --git a/tests/test_sub_enqueue_property.py b/tests/test_sub_enqueue_property.py index 6e6995930..f114db743 100644 --- a/tests/test_sub_enqueue_property.py +++ b/tests/test_sub_enqueue_property.py @@ -111,6 +111,7 @@ async def mark_succeeded( *, result_bytes: object = None, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: self.mark_succeeded_calls.append(result) return True @@ -127,6 +128,7 @@ async def mark_succeeded_with_conn( *, result_bytes: object = None, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: self.mark_succeeded_with_conn_calls.append(result) return True @@ -141,6 +143,7 @@ async def mark_failed_or_retry( progress_state: object = None, *, attempt: int | None = None, + claim_epoch: int | None = None, ) -> JobRow: self.mark_failed_or_retry_calls.append(error_info) return make_job_row() @@ -153,6 +156,7 @@ async def mark_cancelled( progress_state: object = None, *, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: self.mark_cancelled_calls.append(job_id) return True @@ -168,6 +172,7 @@ async def mark_snoozed( progress_state: object = None, outcome: str = "snoozed", attempt: int | None = None, + claim_epoch: int | None = None, denial_reason: str = "capacity", ) -> Literal["scheduled", "failed", "noop"]: self.mark_snoozed_calls.append(job_id) @@ -183,6 +188,7 @@ async def mark_retry_after( progress_seq: int = 0, progress_state: object = None, attempt: int | None = None, + claim_epoch: int | None = None, ) -> Literal["scheduled", "failed:DeadlineExceeded", "failed:MaxAttemptsExceeded", "noop"]: self.mark_retry_after_calls.append(job_id) return "scheduled" diff --git a/tests/test_sync_actor.py b/tests/test_sync_actor.py index 9f1febe10..b5260753e 100644 --- a/tests/test_sync_actor.py +++ b/tests/test_sync_actor.py @@ -144,6 +144,7 @@ def _make_test_ctx( actor=actor_name, queue="default", attempt=1, + claim_epoch=0, worker_id=_WORKER_ID, payload=payload if payload is not None else SimplePayload(x=1), jobs=SubJobEnqueuer( diff --git a/tests/test_terminal_idempotency_property.py b/tests/test_terminal_idempotency_property.py index 3edb19777..18a8f5eb8 100644 --- a/tests/test_terminal_idempotency_property.py +++ b/tests/test_terminal_idempotency_property.py @@ -89,22 +89,28 @@ async def _apply_first_terminal_write( ) -> bool: """Apply the first terminal write and return True if it succeeded.""" if terminal_state == "succeeded": - result = await backend.mark_succeeded(job_id, worker_id, {"ok": True}, attempt=1) + result = await backend.mark_succeeded( + job_id, worker_id, {"ok": True}, attempt=1, claim_epoch=1 + ) return result is True if terminal_state == "failed": error_info = ErrorInfo( error_class="TestError", error_message="terminal failure", error_traceback=None ) - row = await backend.mark_failed_or_retry(job_id, worker_id, error_info, None, attempt=1) + row = await backend.mark_failed_or_retry( + job_id, worker_id, error_info, None, attempt=1, claim_epoch=1 + ) return row.status == "failed" if terminal_state == "cancelled": - result = await backend.mark_cancelled(job_id, worker_id, attempt=1) + result = await backend.mark_cancelled(job_id, worker_id, attempt=1, claim_epoch=1) return result is True if terminal_state == "snoozed": - result = await backend.mark_snoozed(job_id, worker_id, timedelta(seconds=30), attempt=1) + result = await backend.mark_snoozed( + job_id, worker_id, timedelta(seconds=30), attempt=1, claim_epoch=1 + ) return result == "scheduled" if terminal_state == "abandoned": @@ -128,14 +134,18 @@ async def _apply_second_terminal_write( Returns False if the second write unexpectedly succeeded. """ if terminal_state == "succeeded": - return await backend.mark_succeeded(job_id, worker_id, None, attempt=1) is False + return ( + await backend.mark_succeeded(job_id, worker_id, None, attempt=1, claim_epoch=1) is False + ) if terminal_state == "failed": error_info = ErrorInfo( error_class="TestError", error_message="terminal failure", error_traceback=None ) try: - await backend.mark_failed_or_retry(job_id, worker_id, error_info, None, attempt=1) + await backend.mark_failed_or_retry( + job_id, worker_id, error_info, None, attempt=1, claim_epoch=1 + ) except WorkerOwnershipMismatch: return True return False @@ -252,13 +262,15 @@ async def test_terminal_idempotency_pg( with pytest.raises(WorkerOwnershipMismatch): await backend.mark_failed_or_retry(job_id, worker_id, error_info, None) elif terminal_state == "succeeded": - result = await backend.mark_succeeded(job_id, worker_id, None, attempt=1) + result = await backend.mark_succeeded(job_id, worker_id, None, attempt=1, claim_epoch=1) assert result is False elif terminal_state == "cancelled": - result = await backend.mark_cancelled(job_id, worker_id, attempt=1) + result = await backend.mark_cancelled(job_id, worker_id, attempt=1, claim_epoch=1) assert result is False elif terminal_state == "snoozed": - result = await backend.mark_snoozed(job_id, worker_id, timedelta(seconds=60), attempt=1) + result = await backend.mark_snoozed( + job_id, worker_id, timedelta(seconds=60), attempt=1, claim_epoch=1 + ) assert result == "noop" elif terminal_state == "abandoned": result = await backend.mark_abandoned(job_id) @@ -312,7 +324,8 @@ async def _pg_enqueue_and_dispatch( " lock_expires_at = now() + interval '60 seconds', " " started_at = now(), " " last_heartbeat_at = now(), " - " attempt = 1 " + " attempt = 1, " + " claim_epoch = 1 " "WHERE id = $1", job_id, worker_id, @@ -345,21 +358,27 @@ async def _pg_apply_first_terminal_write( ) -> bool: """Apply the first terminal write on PG and return True if it succeeded.""" if terminal_state == "succeeded": - return await backend.mark_succeeded(job_id, worker_id, {"ok": True}, attempt=1) + return await backend.mark_succeeded( + job_id, worker_id, {"ok": True}, attempt=1, claim_epoch=1 + ) if terminal_state == "failed": error_info = ErrorInfo( error_class="TestError", error_message="terminal failure", error_traceback=None ) - row = await backend.mark_failed_or_retry(job_id, worker_id, error_info, None, attempt=1) + row = await backend.mark_failed_or_retry( + job_id, worker_id, error_info, None, attempt=1, claim_epoch=1 + ) return row.status == "failed" if terminal_state == "cancelled": - return await backend.mark_cancelled(job_id, worker_id, attempt=1) + return await backend.mark_cancelled(job_id, worker_id, attempt=1, claim_epoch=1) if terminal_state == "snoozed": return ( - await backend.mark_snoozed(job_id, worker_id, timedelta(seconds=30), attempt=1) + await backend.mark_snoozed( + job_id, worker_id, timedelta(seconds=30), attempt=1, claim_epoch=1 + ) == "scheduled" ) diff --git a/tests/test_terminal_result_serialization.py b/tests/test_terminal_result_serialization.py index 90625e9ca..434e02f1e 100644 --- a/tests/test_terminal_result_serialization.py +++ b/tests/test_terminal_result_serialization.py @@ -264,7 +264,9 @@ async def test_in_memory_result_bytes_round_trip_stores_decoded_result_and_exact payload = {"value": 42, "nested": {"a": [1, 2, 3]}} data = _json_dumps(payload) - ok = await backend.mark_succeeded(job_id, worker_id, result_bytes=data, attempt=1) + ok = await backend.mark_succeeded( + job_id, worker_id, result_bytes=data, attempt=1, claim_epoch=1 + ) assert ok is True row = await backend.get(job_id) @@ -327,7 +329,12 @@ async def test_in_memory_progress_state_with_nul_raises_value_error() -> None: with pytest.raises(ValueError, match="NUL"): await backend.mark_succeeded( - job_id, worker_id, {"done": True}, progress_state={"detail": "bad\x00value"}, attempt=1 + job_id, + worker_id, + {"done": True}, + progress_state={"detail": "bad\x00value"}, + attempt=1, + claim_epoch=1, ) row = await backend.get(job_id) @@ -356,7 +363,9 @@ async def test_in_memory_result_bytes_exactly_at_cap_is_stored() -> None: data = _json_dumps({"blob": "x" * 53}) assert len(data) == 64 - ok = await backend.mark_succeeded(job_id, worker_id, result_bytes=data, attempt=1) + ok = await backend.mark_succeeded( + job_id, worker_id, result_bytes=data, attempt=1, claim_epoch=1 + ) assert ok is True row = await backend.get(job_id) @@ -412,7 +421,9 @@ async def test_in_memory_non_object_valid_json_result_reads_back_like_pg() -> No backend = InMemoryBackend(clock=FakeClock(_START)) job_id, worker_id = await _in_memory_running_job(backend) - ok = await backend.mark_succeeded(job_id, worker_id, result_bytes=b"[1, 2]", attempt=1) + ok = await backend.mark_succeeded( + job_id, worker_id, result_bytes=b"[1, 2]", attempt=1, claim_epoch=1 + ) assert ok is True row = await backend.get(job_id) @@ -501,7 +512,7 @@ async def test_in_memory_dict_form_result_normalizes_to_pg_observable_state( backend = InMemoryBackend(clock=FakeClock(_START)) job_id, worker_id = await _in_memory_running_job(backend) - ok = await backend.mark_succeeded(job_id, worker_id, dict_result, attempt=1) + ok = await backend.mark_succeeded(job_id, worker_id, dict_result, attempt=1, claim_epoch=1) assert ok is True row = await backend.get(job_id) @@ -530,7 +541,9 @@ async def test_result_bytes_stored_in_pg(self, clean_jobs_app: JobsApp) -> None: payload: dict[str, object] = {"ok": True, "nested": {"a": [1, 2, 3]}} data = _json_dumps(payload) - ok = await backend.mark_succeeded(job_id, worker_id, result_bytes=data, attempt=1) + ok = await backend.mark_succeeded( + job_id, worker_id, result_bytes=data, attempt=1, claim_epoch=1 + ) assert ok is True async with deps.worker_pool.acquire() as conn: @@ -557,11 +570,14 @@ async def test_size_identical_to_plain_dict_call(self, clean_jobs_app: JobsApp) assert ( await backend.mark_succeeded( - bytes_job, bytes_worker, result_bytes=_json_dumps(payload), attempt=1 + bytes_job, bytes_worker, result_bytes=_json_dumps(payload), attempt=1, claim_epoch=1 ) is True ) - assert await backend.mark_succeeded(plain_job, plain_worker, payload, attempt=1) is True + assert ( + await backend.mark_succeeded(plain_job, plain_worker, payload, attempt=1, claim_epoch=1) + is True + ) async with deps.worker_pool.acquire() as conn: rows = await conn.fetch( @@ -644,7 +660,9 @@ async def test_non_object_json_result_round_trips_on_pg(self, clean_jobs_app: Jo async with deps.worker_pool.acquire() as conn: worker_id, job_id = await setup_running_job(conn, schema) - ok = await backend.mark_succeeded(job_id, worker_id, result_bytes=b"[1, 2]", attempt=1) + ok = await backend.mark_succeeded( + job_id, worker_id, result_bytes=b"[1, 2]", attempt=1, claim_epoch=1 + ) assert ok is True row = await backend.get(job_id) @@ -668,7 +686,7 @@ async def test_invalid_result_bytes_rejected_before_the_fence_on_a_terminal_job( async with deps.worker_pool.acquire() as conn: worker_id, job_id = await setup_running_job(conn, schema) - await backend.mark_succeeded(job_id, worker_id, {"done": True}, attempt=1) + await backend.mark_succeeded(job_id, worker_id, {"done": True}, attempt=1, claim_epoch=1) with pytest.raises(ValueError): await backend.mark_succeeded(job_id, worker_id, result_bytes=b"not json") @@ -692,11 +710,15 @@ async def test_dict_form_result_reads_back_json_round_tripped_on_pg( uuid_value = UUID("12345678-1234-5678-1234-567812345678") assert ( - await backend.mark_succeeded(uuid_job, uuid_worker, {"v": uuid_value}, attempt=1) + await backend.mark_succeeded( + uuid_job, uuid_worker, {"v": uuid_value}, attempt=1, claim_epoch=1 + ) is True ) assert ( - await backend.mark_succeeded(nan_job, nan_worker, {"v": float("nan")}, attempt=1) + await backend.mark_succeeded( + nan_job, nan_worker, {"v": float("nan")}, attempt=1, claim_epoch=1 + ) is True ) diff --git a/tests/test_terminal_write_retry.py b/tests/test_terminal_write_retry.py index b85f252ff..f5c18c9cd 100644 --- a/tests/test_terminal_write_retry.py +++ b/tests/test_terminal_write_retry.py @@ -56,6 +56,7 @@ async def mark_failed_or_retry( progress_state: dict[str, object] | None = None, *, attempt: int | None = None, + claim_epoch: int | None = None, ) -> JobRow: self._maybe_blip() return await super().mark_failed_or_retry( @@ -66,6 +67,7 @@ async def mark_failed_or_retry( progress_seq, progress_state, attempt=attempt, + claim_epoch=claim_epoch, ) async def mark_succeeded( @@ -79,6 +81,7 @@ async def mark_succeeded( *, result_bytes: bytes | None = None, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: self._maybe_blip() return await super().mark_succeeded( @@ -90,6 +93,7 @@ async def mark_succeeded( fallback_result_ttl, result_bytes=result_bytes, attempt=attempt, + claim_epoch=claim_epoch, ) @@ -392,10 +396,16 @@ async def mark_cancelled( progress_state: dict[str, object] | None = None, *, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: self._maybe_blip() return await super().mark_cancelled( - job_id, worker_id, progress_seq, progress_state, attempt=attempt + job_id, + worker_id, + progress_seq, + progress_state, + attempt=attempt, + claim_epoch=claim_epoch, ) diff --git a/tests/test_terminal_writes_chaos.py b/tests/test_terminal_writes_chaos.py index 7a8030a5d..59f33a450 100644 --- a/tests/test_terminal_writes_chaos.py +++ b/tests/test_terminal_writes_chaos.py @@ -125,8 +125,8 @@ async def test_concurrent_terminal_write_only_one_wins( # Race the two callers if method == "mark_succeeded": results = await asyncio.gather( - backend.mark_succeeded(job_id, worker_a, {"ok": True}, attempt=1), - backend.mark_succeeded(job_id, worker_b, {"ok": True}, attempt=1), + backend.mark_succeeded(job_id, worker_a, {"ok": True}, attempt=1, claim_epoch=1), + backend.mark_succeeded(job_id, worker_b, {"ok": True}, attempt=1, claim_epoch=1), return_exceptions=True, ) assert results == [True, False] @@ -134,10 +134,10 @@ async def test_concurrent_terminal_write_only_one_wins( elif method == "mark_failed_or_retry": results = await asyncio.gather( backend.mark_failed_or_retry( - job_id, worker_a, error_info, retry_delay=None, attempt=1 + job_id, worker_a, error_info, retry_delay=None, attempt=1, claim_epoch=1 ), backend.mark_failed_or_retry( - job_id, worker_b, error_info, retry_delay=None, attempt=1 + job_id, worker_b, error_info, retry_delay=None, attempt=1, claim_epoch=1 ), return_exceptions=True, ) @@ -148,8 +148,8 @@ async def test_concurrent_terminal_write_only_one_wins( elif method == "mark_cancelled": results = await asyncio.gather( - backend.mark_cancelled(job_id, worker_a, attempt=1), - backend.mark_cancelled(job_id, worker_b, attempt=1), + backend.mark_cancelled(job_id, worker_a, attempt=1, claim_epoch=1), + backend.mark_cancelled(job_id, worker_b, attempt=1, claim_epoch=1), return_exceptions=True, ) assert results == [True, False] @@ -167,8 +167,12 @@ async def test_concurrent_terminal_write_only_one_wins( elif method == "mark_snoozed": results = await asyncio.gather( - backend.mark_snoozed(job_id, worker_a, timedelta(seconds=30), attempt=1), - backend.mark_snoozed(job_id, worker_b, timedelta(seconds=30), attempt=1), + backend.mark_snoozed( + job_id, worker_a, timedelta(seconds=30), attempt=1, claim_epoch=1 + ), + backend.mark_snoozed( + job_id, worker_b, timedelta(seconds=30), attempt=1, claim_epoch=1 + ), return_exceptions=True, ) assert results == ["scheduled", "noop"] @@ -176,10 +180,20 @@ async def test_concurrent_terminal_write_only_one_wins( elif method == "mark_retry_after": results = await asyncio.gather( backend.mark_retry_after( - job_id, worker_a, timedelta(seconds=30), consume_budget=True, attempt=1 + job_id, + worker_a, + timedelta(seconds=30), + consume_budget=True, + attempt=1, + claim_epoch=1, ), backend.mark_retry_after( - job_id, worker_b, timedelta(seconds=30), consume_budget=True, attempt=1 + job_id, + worker_b, + timedelta(seconds=30), + consume_budget=True, + attempt=1, + claim_epoch=1, ), return_exceptions=True, ) @@ -345,7 +359,7 @@ async def test_transaction_rollback_on_mid_flight_failure( victim_task = asyncio.create_task( backend.mark_failed_or_retry( - job_id, worker_id, error_info, retry_delay=None, attempt=1 + job_id, worker_id, error_info, retry_delay=None, attempt=1, claim_epoch=1 ) ) diff --git a/tests/test_timeout_path_exit_hold.py b/tests/test_timeout_path_exit_hold.py index 02eb66c72..c560c5434 100644 --- a/tests/test_timeout_path_exit_hold.py +++ b/tests/test_timeout_path_exit_hold.py @@ -356,6 +356,7 @@ async def test_the_transactional_timeout_arm_parks_on_the_tracked_thread_too() - actor=job.actor, queue=job.queue, attempt=job.attempt, + claim_epoch=job.claim_epoch, worker_id=_WORKER_ID, payload=EmptyPayload(), jobs=enqueuer, diff --git a/tests/test_unique_for_caller_conn_serialization.py b/tests/test_unique_for_caller_conn_serialization.py index a03c8facb..f7c5d682b 100644 --- a/tests/test_unique_for_caller_conn_serialization.py +++ b/tests/test_unique_for_caller_conn_serialization.py @@ -88,6 +88,7 @@ def _full_record(*, job_id: UUID | None = None) -> dict[str, object]: "retry_backoff": "exponential", "retry_jitter": 0.2, "assignment_routed": False, + "claim_epoch": 0, } diff --git a/tests/test_unique_for_window_covers_success.py b/tests/test_unique_for_window_covers_success.py index cd728361a..2fa9e1bf9 100644 --- a/tests/test_unique_for_window_covers_success.py +++ b/tests/test_unique_for_window_covers_success.py @@ -116,7 +116,9 @@ async def test_second_enqueue_inside_the_window_dedups_onto_a_succeeded_job( worker_id = await _worker_of(backend_pair) attempt = await _claim(backend_pair, first.id, worker_id) - await backend_pair.mark_succeeded(first.id, worker_id, {"sent": True}, attempt=attempt) + await backend_pair.mark_succeeded( + first.id, worker_id, {"sent": True}, attempt=attempt, claim_epoch=attempt + ) done = await backend_pair.get(first.id) assert done is not None @@ -161,7 +163,9 @@ async def test_a_failed_job_does_not_block_the_identity_for_the_window( worker_id = await _worker_of(backend_pair) attempt = await _claim(backend_pair, first.id, worker_id) - await backend_pair.mark_failed_or_retry(first.id, worker_id, _ERROR, None, attempt=attempt) + await backend_pair.mark_failed_or_retry( + first.id, worker_id, _ERROR, None, attempt=attempt, claim_epoch=attempt + ) failed = await backend_pair.get(first.id) assert failed is not None diff --git a/tests/test_worker_di_bootstrap.py b/tests/test_worker_di_bootstrap.py index 64722e601..71280ec03 100644 --- a/tests/test_worker_di_bootstrap.py +++ b/tests/test_worker_di_bootstrap.py @@ -102,6 +102,7 @@ async def mark_succeeded( *, result_bytes: object = None, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: return True @@ -115,6 +116,7 @@ async def mark_succeeded_with_conn( *, result_bytes: object = None, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: return True @@ -124,6 +126,7 @@ async def mark_cancelled( worker_id: object, *, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: return True diff --git a/tests/test_worker_producer_wake.py b/tests/test_worker_producer_wake.py index b2a860193..083751328 100644 --- a/tests/test_worker_producer_wake.py +++ b/tests/test_worker_producer_wake.py @@ -295,6 +295,7 @@ async def mark_snoozed( *, metadata_update: dict[str, object] | None = None, attempt: int | None = None, + claim_epoch: int | None = None, ) -> str: snoozed.append(job_id) shutdown_event.set() # one job is enough - exit after it @@ -366,6 +367,7 @@ async def mark_succeeded( fallback_result_ttl: object = None, *, attempt: int | None = None, + claim_epoch: int | None = None, ) -> bool: shutdown_event.set() # exit after one job return True