Skip to content

fix: fence terminal writes on a non-saturating claim epoch - #369

Merged
rcbevans merged 7 commits into
mainfrom
fix/claim-epoch-fence
Sep 21, 2026
Merged

rcbevans merged 7 commits into
mainfrom
fix/claim-epoch-fence

Conversation

@rcbevans

@rcbevans rcbevans commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Closes #361

Design: epoch vs display counter

The displayed attempt counter keeps its saturating claim stamp
(LEAST(j.attempt + 1, 32767)) unchanged: the clamp is what keeps a row
parked 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 (and jobs_archive),
    migration 01.00.18_02_pre_claim_epoch.sql (forward-only, NULL-free,
    constant default: an ADD COLUMN with a non-volatile default is
    metadata-only on PG 11+, no rewrite). The ledger key 01.00.18_02:pre
    sits behind the landed 01.00.18_01_pre_actor_retry_curve without
    colliding on the {version}:{phase} identity.
  • The dispatch claim (the only writer of the column) stamps
    claim_epoch = j.claim_epoch + 1 beside the attempt clamp: a bigint
    never saturates, so consecutive claims of one row always hold distinct
    identities.
  • Every terminal/ownership write that fenced on attempt gains the
    conjunct 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 its
    claim view (JobRow.claim_epoch, and ctx.claim_epoch for the
    shutdown release) beside attempt=job.attempt at every call site.
    None binds NULL and never satisfies the equality: the same
    cannot-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_epoch docstring; the in-memory testing
backend 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_lands
fails at assert landed is False receiving True - the stale
execution's mark_succeeded(32767) lands and the live execution reads
WorkerOwnershipMismatch, the issue's exact defect. The attempt-5
control keeps passing under the bypass (away from the ceiling the attempt
number still advances).

Green, on testcontainers PostgreSQL (real claim CTE, real reclaim sweep):

  • the ceiling repro lands: stale A's write refused (False), live B's
    mark_failed_or_retry lands failed/BoomError, no stale result on
    the row, epochs 1 then 2 at a clamped attempt 32767;
  • the attempt-5 control is unchanged (stale write refused by attempt and
    by epoch, live write lands);
  • the epoch strictly increases across four claim/reclaim cycles at the
    ceiling ([1, 2, 3, 4]) while attempt stays clamped;
  • every fenced arm is enumerated by a parametrized pin
    (tests/test_claim_epoch_fencing.py, 8 drivers x {pg, memory}): the
    stale 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

  • unit tier (-m 'not integration'): 7282 passed, 4 skipped
  • integration tier (-m integration, testcontainers PG): 2372
    passed, 2 skipped
  • of the integration tier, the new pin file: 19 passed (3 ceiling
    repro/control/monotonicity + 16 arm pins over both backends)
  • tests/test_index_audit.py: 32 passed. The claim statement's change
    is 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, green
    in the run above).
  • ruff check src/taskq tests: clean; ruff format --check on every
    touched 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_SQL in _sql_fragments.py) carry the
epoch 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 _fenced helper gains the same
conjunct. 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.

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
rcbevans force-pushed the fix/claim-epoch-fence branch from 93b7f5c to 7607beb Compare September 20, 2026 23:45
@rcbevans
rcbevans merged commit 59a4758 into main Sep 21, 2026
26 checks passed
@rcbevans
rcbevans deleted the fix/claim-epoch-fence branch September 21, 2026 00:02
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

at the attempt ceiling a stale write records a failed job as succeeded

2 participants