Repository navigation
fix: fence terminal writes on a non-saturating claim epoch - #369
Merged
Merged
Conversation
ZEAZX26
approved these changes
Sep 20, 2026
The displayed attempt counter saturates at the smallint ceiling, so a reclaim plus a redispatch there gave a stale handler and the live one the same (worker, attempt) fence: the stale mark_succeeded won and the live write read WorkerOwnershipMismatch. Every row now carries claim_epoch (bigint, DEFAULT 0), the dispatch claim bumps it by exactly 1, and every terminal/ownership write that fenced on attempt gains the equality conjunct against the writer's own claim view. The reclaim sweeps leave the column: the next claim's bump is what stales the previous writer. The in-memory twin mirrors the semantics.
Behavior-level pins driving the real backends: the issue's reproduction at the attempt ceiling (seed 32766, claim, reclaim, re-claim, the stale write refused and the live write landing with its own outcome), the attempt-5 control, strict epoch increase across claims at the ceiling, and every fenced arm (all nine mark_* methods, every arm class) parametrized over backend_pair so the twin and PG refuse the stale epoch and land the live one identically. Existing suites thread the epoch beside the attempt everywhere a claim's stamps are presented.
Three dishonest epoch shapes in the test surface, all teaching the exact attempt/epoch conflation the fence exists to prevent: * the blipping terminal-write double bound claim_epoch=attempt; the worker presents its own claim view now, so the double forwards the caller's epoch instead of manufacturing it from the attempt counter (the two diverge at the smallint ceiling and after attempt refunds); * create_running_job seeded claim_epoch=attempt under a comment claiming the claim advances both; the comment now states the real shape (a refund-free history, epoch >= attempt, diverged shapes seeded separately); * run_actor defaulted claim_epoch=0, a silently no-op terminal write for any test that dispatches first; the default is 1, the one-claim shape attempt's own default mirrors.
The archive pins drive a twice-claimed job (real dispatch, deferral release, redispatch) through the real archive machinery and assert the archived row reads the epoch its last claim stamped, the value the live row read at archival: on the PG CTE (jobs_archive) and on the in-memory twin (_ArchivedJobRow). Under a mutation that drops claim_epoch from COPY_FROM_COLUMNS the PG pin fails with the exact lying-column shape (archived claim_epoch 0 against a live epoch 2), so the pin detects the defect it targets. The mark_interrupted replay pin now replays the LANDED release's own fence values, so its 'noop' comes from the release's idempotency (the row left running, the equality fence no longer matches) instead of from the None-never-matches refusal the epoch-less call used to hit.
The invariant paragraph was restated in full at eight sites (the migration, the dispatch claim comment, the terminal-template header, the JobRow docstring, the _terminal.py module header, architecture.md, retries.md, cancellation.md, and the upgrading guide). The migration keeps the canonical statement; every other site keeps the local fact its reader needs and points at 01.00.18_02_pre_claim_epoch.sql, so the statement can no longer drift out of sync with itself.
The CI hang (test_cron_disabled_schedules_gauge, >300s pytest-timeout in the test (3.13) leg) showed the test coroutine still pending on an idle module event loop parked in epoll with NO timer pending: no wait_for, sleep, or command_timeout was active, so the suspension was an un-timed await. Every await in the test's own path is bounded except one: _setup_worker's raw setup connection. asyncpg's connect timeout covers only the handshake; the schema drop, the migration run, and the actor-config insert ran with no server-side statement_timeout or lock_timeout of their own, so a stalled shared test container under -n 4 suspends the test forever on an in-flight query - exactly the observed signature - and the only diagnostic was pytest-timeout firing 300s later. Bound the phase: an explicit connect timeout on the setup connection plus session-level statement_timeout/lock_timeout covering the schema drop, the migration run (apply_pending still applies its own, tighter SET LOCAL lock_timeout inside each migration transaction), and the actor-config insert. A stalled server now fails the test in seconds with a precise asyncpg TimeoutError instead of a 300s silent hang.
rcbevans
force-pushed
the
fix/claim-epoch-fence
branch
from
September 20, 2026 23:45
93b7f5c to
7607beb
Compare
rcbevans
added a commit
that referenced
this pull request
Sep 30, 2026
…eads (#619) _job_row_from_record has bound claim_epoch into every JobRow since 01.00.18_02_pre_claim_epoch.sql (#369), but the bench's FakeRecord was frozen the day before that landed and never grew the key, so every run_bench.py pass over the rows group died with KeyError: 'claim_epoch'. The fake record now carries claim_epoch=1 (a mid-claim running row, so the epoch the dispatch claim just bumped to), the B variant decodes the same fence field instead of silently skipping work A must do, and the correctness check compares it. FakeRecord's lookup type is fixed to match what it models (asyncpg.Record lookups are Any, not object), which drops the file's pyright noise from 73 to 32 errors, none on touched lines. No metric was renamed: the meaning of every number is unchanged.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #361
Design: epoch vs display counter
The displayed
attemptcounter keeps its saturating claim stamp(
LEAST(j.attempt + 1, 32767)) unchanged: the clamp is what keeps a rowparked at the smallint ceiling from poisoning a whole claim round with a
smallint-out-of-range driver error, and its consumer-facing budget/display
semantics do not move. A counter that stops advancing cannot fence, so the
fix adds a second column and splits the two jobs:
jobs.claim_epoch bigint NOT NULL DEFAULT 0(andjobs_archive),migration
01.00.18_02_pre_claim_epoch.sql(forward-only, NULL-free,constant default: an
ADD COLUMNwith a non-volatile default ismetadata-only on PG 11+, no rewrite). The ledger key
01.00.18_02:presits behind the landed
01.00.18_01_pre_actor_retry_curvewithoutcolliding on the
{version}:{phase}identity.claim_epoch = j.claim_epoch + 1beside the attempt clamp: a bigintnever saturates, so consecutive claims of one row always hold distinct
identities.
attemptgains theconjunct
claim_epoch = <the writer's own claim view>:mark_succeeded,mark_failed,mark_cancelled,mark_retry,mark_snoozed(all three arms),mark_retry_after_consume_{true,false}(all four/three arms),mark_interrupted(both arms). The worker threads the epoch from itsclaim view (
JobRow.claim_epoch, andctx.claim_epochfor theshutdown release) beside
attempt=job.attemptat every call site.Nonebinds NULL and never satisfies the equality: the samecannot-prove-it doctrine the attempt conjunct applies.
Invariant
Between two fenced writes to the same row, a successful claim must have
bumped
claim_epoch. The reclaim sweeps that clear locks(
_SWEEP_1_SQL's re-pend/crash/cancel arms, the heartbeat isolate)deliberately leave the column untouched; the NEXT claim's bump is what
stales the previous writer. Writer order per row: claim (bump) -> maybe
reclaim (leave) -> claim (bump) -> terminal write (fence on the epoch its
own claim returned). Fences compare EQUALITY, never magnitude, so epoch 0
on pre-migration rows is simply the one identity no claim can ever stamp
(the first claim of any row writes 1). The invariant is spelled out in the
migration and the
JobRow.claim_epochdocstring; the in-memory testingbackend mirrors the semantics exactly (its claim bumps, its fences compare
the writer's view).
Red-green evidence
Red: with the epoch conjunct replaced by a no-op (the pre-fix fence
shapes),
test_ceiling_stale_mark_succeeded_is_refused_live_b_landsfails at
assert landed is FalsereceivingTrue- the staleexecution's
mark_succeeded(32767)lands and the live execution readsWorkerOwnershipMismatch, the issue's exact defect. The attempt-5control keeps passing under the bypass (away from the ceiling the attempt
number still advances).
Green, on testcontainers PostgreSQL (real claim CTE, real reclaim sweep):
False), live B'smark_failed_or_retrylandsfailed/BoomError, no stale result onthe row, epochs 1 then 2 at a clamped attempt 32767;
by epoch, live write lands);
ceiling (
[1, 2, 3, 4]) while attempt stays clamped;(
tests/test_claim_epoch_fencing.py, 8 drivers x {pg, memory}): thestale epoch's write is refused through the same machinery as the worker
fence and the live epoch's write lands with its own outcome.
Verification tallies
-m 'not integration'): 7282 passed, 4 skipped-m integration, testcontainers PG): 2372passed, 2 skipped
repro/control/monotonicity + 16 arm pins over both backends)
tests/test_index_audit.py: 32 passed. The claim statement's changeis a SET-clause addition only (no WHERE/join/order change), so the row
finding shape is untouched; the dispatch plan's depth bounds stay pinned
by
tests/test_dispatch_backlog_depth_bound.py(1k/30k corpora, greenin the run above).
ruff check src/taskq tests: clean;ruff format --checkon everytouched file: clean.
pyright src/taskq tests: 0 errors, 0 warnings.One flake observed once during development
(
test_dispatch_failure_is_visible_in_a_metric_not_only_a_log_line,passes in isolation and in the final run).
Rebase onto the fragment refactor
Rebased onto main's typed-outcome/prune work: the fence is no longer
hand-restated per statement, both spellings of the fence fragment
(
JOB_FENCE_SQL,JOB_FENCE_BOUND_SQLin_sql_fragments.py) carry theepoch conjunct themselves, so all 17 fenced arms across the 8 statement
templates keep it by construction, the bound sites name their epoch bind
explicitly (
format(attempt_bind=8, epoch_bind=9),attempt_bind=5, epoch_bind=6), and the in-memory twin's_fencedhelper gains the sameconjunct. The bind-arity net's density and caller-walk pins hold (a
drifted caller fails the net before it fails a database), and the two
direct-SQL test callers the refactor added thread the epoch at the right
positions.