Skip to content

3.x.x: time CTV fanout claim leases on the taker's monotonic clock, and label session timeouts and hung refreshes by the dependency they wait on (#654, #655) - #667

Merged
RobertClarke merged 5 commits into
3.x.xfrom
RobertClarke/prism-654-655-ctv-claims-clock
Oct 5, 2026
Merged

RobertClarke merged 5 commits into
3.x.xfrom
RobertClarke/prism-654-655-ctv-claims-clock

Conversation

@RobertClarke

@RobertClarke RobertClarke commented Oct 5, 2026 •

Copy link
Copy Markdown
Member

Closes #654. Closes #655.

Both are follow-ups to #581/#646 and are needed before go-live for the PRISM 3 production pair. Safety held before. Both are liveness and attribution problems.

Problem

#654: CTV fanout claims still decided a lease by the database clock.

  • claim_fanout took a fanout once claim_expires_at <= clock_timestamp().
  • Every holder write required claim_expires_at > clock_timestamp().
  • Retries compared next_broadcast_attempt_at with the same clock.
  • Forward step (which a failover can cause): a live claim looked expired. A second frontend took the fanout over and broadcast it again; the node deduplicates it. The holder's settlement write was then refused.
  • Backward step: a dead holder's claim waited lease + step, and an attempt or check scheduled before the step waited its delay + step.

#655: two database-stall paths were still labelled backend-rpc-unavailable.

  • The Stratum session's own timeouts (session allocation timed out, job persistence timed out, job resume timed out) could not tell what the backend was waiting on.
  • A template refresh that hangs on the database records no database failure, so the stale-readiness refusal that followed blamed the node.

Change

#654: the observed lease of #581, applied to fanout claims

Migration 022 (fanout_claim_observed_lease), offline like 021:

  • Adds claim_renewals and claim_lease_seconds to qbit_ctv_fanout_artifacts.
  • Adds the partial index qbit_ctv_fanout_artifacts_claimed_idx.
  • Declares the capability fanout_claim_observed_lease = 1.
  • The migrator refuses any instance that has not reported stopped or drained.

Takeover.

  • Every fanout claim poll surveys the claimed fanouts first (Ledger::fanout_claim_survey_sql).
  • It times each version (claim_token, claim_renewals) on the frontend's own monotonic clock. The ClaimObserver, its survey decoding and its takeable-claim filter are now shared by candidates and fanouts in ledger/claim_observer.rs, with one observer per kind of claim.
  • It takes a fanout over only after watching the same version for the whole lease, by compare and set on that version (FOR UPDATE SKIP LOCKED). This runs before the lane.
  • The lane takes only unclaimed, due fanouts. A claimed fanout is taken over whatever its schedule, unless it is held at infinity.

Holder.

  • Every write is fenced on the token alone: renewal, scan progress, CPFP reservation and package, settlement and hand-backs.
  • Its lease is its own monotonic deadline. The broadcaster's 90 s attempt deadline is below the 120 s lease that every renewal takes, and every renewal is sent inside the attempt.
  • Both values are now named constants, with a compile-time check that the deadline stays inside the lease.

Retries and checks.

  • The survey makes due, at once, every unclaimed fanout whose last write is later than the clock, which proves a backward step.
  • A shutdown release keeps its schedule, but never later than the clock.
  • A backward step therefore delays an attempt or a check by less than its own delay, never by the step.

Other.

  • Every statement that clears a fanout claim also clears its lease and version.
  • ledger::revoke_fanout_claims replaces the tests' ad hoc claim_expires_at rewrites. It touches only claimed fanouts, and no schedule.
  • docs/prism-ledger-ops.md replaces "Not changed" with a section covering the contract, the cost, revocation, broadcast-ctv and the upgrade.

#655: a timeout names the dependency the work was waiting on

Mechanism: crate::waiting.

  • Work marks each step that waits on the ledger database (on_database) into a tracker.
  • The timer reads the tracker when its deadline passes, while the work is still pending. Dropping the work would end its marks.
  • The tracker reaches the work through a task-local, as READ_DEADLINE does, so the MiningBackend trait and its eight implementations are unchanged.
  • Shared work never marks a waiter's tracker. The resume flight's shared reconstruction has its own tracker, which every waiting session follows.

Session timeouts.

  • All five run under waiting::timeout: allocation, persistence, resume, initial job delivery and payout-address validation.
  • An expiry is backend-database-unavailable when the work was on a database step, and backend-rpc-unavailable otherwise, as before.
  • The coordinator marks:
    • the ledger allocation;
    • each ledger read of resume and of the issuance-authority checks: clock, revision, window and the replacement lease's payout state;
    • persistence's batch and compact-repair writes.
  • Node calls, CPU work and admission waits stay unattributed. That includes a compact repair's lock, build admission and encode, as Codex asked.
  • A persistence that outlives the issued job's own deadline stays the database's, as 3.x.x: database clock steps stretch outbox retries and claim leases; a PostgreSQL outage holds only one alert rule #581 decided (IssuedPersistenceExpired).

Hung refresh.

Migration notes (D5)

022 is an offline upgrade, exactly like 021. Apply it together with 021 if both are pending.

  1. Stop every earlier frontend and broadcast-ctv and disable automatic restarts.
  2. Let every qbit_prism_instances row report stopped or drained.
  3. Migrate, then start only post-022 binaries.

A pre-022 binary takes fanout claims over by the database clock and never writes the columns a post-022 one times, so mixed versions are refused at every later connect by the capability. Migration 022 is independent of #663's share-hash backfill, which this branch includes.

Tests

#654. Six new tests. Each fails on b8aeb29 with its headline assertion and passes here:

test b8aeb29 failure
ledger_postgres::clock_steps::a_forward_database_clock_step_never_ends_a_live_fanout_claim_early a forward step handed a live fanout claim to another frontend
…::a_backward_database_clock_step_never_stretches_a_dead_fanout_holders_lease a backward step stretched a dead fanout holder's lease past its own length
…::a_backward_database_clock_step_never_stretches_a_fanout_retry a backward step stretched a fanout retry by the step
…::a_backward_step_then_one_renewal_never_strands_a_dead_fanout_holders_row a renewal after a backward step left a dead fanout holder's row waiting out the step
…::a_fanout_release_after_a_backward_step_never_stretches_its_next_attempt the released fanout is 7198.98 s out, though it was due when claimed
ctv_fanout_bookkeeping::a_forward_database_clock_step_mid_attempt_keeps_the_holders_claim_and_settlement (the real broadcaster, a forward step while its send is held) a forward step handed a live fanout claim to another frontend

These cover the claim lane, the holder fence and the retry schedule, forward and backward, built like tests/support/clock_steps.rs.

The live lost-reply tests (live_regtest::lost_reply_tests) kill a fanout's owner and hand its claim to a survivor. Their shared expire_dead_lease now revokes fanout claims as it does candidate claims. Both pass in CI and locally against the pinned qbitd 1.0.0.

#655. Four regressions fail on b8aeb29 with backend-rpc-unavailable and pass here:

  • allocation, persistence and resume stalled in a database step through the real coordinator;
  • a refresh held in its first ledger read past its deadline.

Controls:

  • a refresh held on the node past its deadline, or on the database within it, keeps the node's label;
  • an unmarked backend stall keeps backend-rpc-unavailable;
  • the in-flight entry clears on completion and on cancellation;
  • a persistence held in its compact repair's encode past a session deadline reads Unattributed. With the whole persistence marked it read Database and the test fails.

There are also seven unit tests for waiting, and a third-party backend test.

CI on 44d0a10 (this branch merged with 3.x.x ec29d74): every check green, including the four PostgreSQL shards (live_regtest in shard 0) and "Prove every Rust PRISM gated test executed".

Local runs on 44d0a10. Private PostgreSQL 16, PRISM_TEST_REQUIRE_INTEGRATION=1, --test-threads=4 unless noted:

suite passed failed ignored
--test ledger_postgres 199 0 0
--test ctv_fanout_bookkeeping 24 0 0
--test offer_lifecycle 22 0 0
--test migration_rollback (--test-threads=2) 10 0 2 (operator modes)
--test refresh_liveness 38 0 0
--test compact_runtime_e2e 35 0 0
--test ledger_single_execution 22 0 0
--test stratum_protocol / stratum_admission / readiness_rpc 49 / 6 / 11 0 1 / 0 / 0
--lib (--test-threads=2) 650 6, all passing on rerun (see below) 2
-p qbit-prism-load --test harness 150 0 0

On this loaded host (load average ~11) some lib modules hit canceling statement due to lock timeout or a tight lease deadline at 2–6 threads:

  • park_tests and connect::acquire migrate one schema per test under the database-wide migration advisory lock. b8aeb29 fails them the same way.
  • Two candidate lease timing tests.

All six, and their modules (23 tests), pass in three consecutive --test-threads=1 runs. The same applies to one migration_rollback test at 4 threads.

Also clean:

  • cargo fmt --all --check
  • cargo clippy --locked --workspace --all-targets -- -D warnings
  • check_prism_pool_acquires.py, check_deleted_test_map.py, check_e2e_scenarios.py
  • generate_prism_metrics.py --check, check_gate_env_reads.py, check_prism_settings.py
  • recovery_evidence_requires_the_migrations_startup_requires, which checks that scripts/prism-recovery-evidence.sql requires 022.

Plan check. EXPLAIN on 100k synthetic settled fanouts:

Review

Not run here

Risks

Follow-ups

🤖 Generated with Claude Code

RobertClarke and others added 2 commits October 5, 2026 14:57
…o a database clock step neither double-claims nor strands a fanout (#654)

#646 moved candidate claims onto an observed lease (#581), but CTV fanout
claims still compared `claim_expires_at` and `next_broadcast_attempt_at`
with `clock_timestamp()`. A forward database clock step, which a failover
can cause, made a live claim look expired: a second frontend took the
fanout over and broadcast it again, and the holder's settlement write was
refused. A backward step left a dead holder's claim waiting lease + step,
and an attempt or confirmation check scheduled before it waiting its delay
+ step.

Migration 022 (offline, as 021) adds `claim_renewals` and
`claim_lease_seconds` to `qbit_ctv_fanout_artifacts`, a partial index over
claimed fanouts and the `fanout_claim_observed_lease` capability. Fanout
claims now follow #581's contract:
- Every fanout claim poll surveys the claimed fanouts and times each
  version (token, renewals) on the frontend's own monotonic clock, through
  the same ClaimObserver, now shared in ledger/claim_observer.rs with one
  instance per kind of claim. It takes a fanout over only after watching the
  same version for the whole lease, by compare and set on that version,
  before the lane, which takes only unclaimed due fanouts. A claimed fanout
  is taken over whatever its schedule unless held at infinity.
- The holder is fenced on its token alone. Its lease is its own monotonic
  deadline: the broadcaster's 90 s attempt deadline is below the 120 s
  lease every renewal takes, now named constants with a compile-time check.
- The survey makes due, at once, every unclaimed fanout whose last write is
  later than the database clock (a backward step), and a shutdown release
  keeps its schedule but never later than the clock.
- Every statement that clears a fanout claim clears its lease and version.
- `ledger::revoke_fanout_claims` replaces the tests' ad hoc
  `claim_expires_at` rewrites.

The lane's claimable predicate is unchanged in meaning, written once and
shared by the lane, the takeover and the survey. EXPLAIN on 100k settled
fanouts: the survey is two index scans (0.3 ms); the lane's plan and cost
are the same as before.

Tests: five ledger clock-step tests (forward on a live claim and its
holder's writes; backward on a dead holder, on a retry, after one renewal,
and on a shutdown release) and a broadcaster test with a forward step in
the middle of an attempt. All six fail on b8aeb29 with their headline
assertion and pass here. The fanout tests that expired a claim by
rewriting `claim_expires_at` now revoke it, and assert that only a
takeover fences the old holder. Migration pins, the recovery-evidence
script, the pool-acquire inventory and the gated-test list include 022.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…hey were waiting on, so a database stall no longer reads as the node's (#655)

#646 labelled database refusals backend-database-unavailable but left two
paths blaming the node during a database stall. The Stratum session's own
timeouts (session allocation, job persistence, job resume, initial job
delivery) could not tell what the backend was waiting on, and a template
refresh that hung on the database, rather than failing, recorded no
database failure, so the stale-readiness refusal that followed named the
node.

A new crate::waiting module lets work name the steps it waits on the
ledger database, into a tracker its timer reads when the deadline passes,
while the work is still pending (dropping the work ends its marks). The
tracker reaches the work through a task-local, as READ_DEADLINE does, so
the MiningBackend trait and its implementations are unchanged. The
coordinator marks the ledger allocation, the whole issued persistence
(consistent with IssuedPersistenceExpired, so the label never depends on
which deadline passes first), each ledger step of resume and of the
issuance-authority reads, and every ledger step of a refresh. Node calls,
CPU work and admission stay unattributed and keep backend-rpc-unavailable.
Marks are never placed inside work shared between tasks: a waiter marks its
own await of a shared read, and the resume flight's shared reconstruction
keeps its own tracker, which each waiting session follows.

The session runs each backend call under waiting::timeout and labels an
expiry with StratumError::timed_out. The coordinator registers the refresh
in flight with its start and tracker; a submit refused for aged-out
readiness is the database's when the latest refresh failed on it (#646),
or when the refresh in flight has outlived its deadline, the health
timeout, and is still waiting on the database.

Tests: allocation, persistence and resume stalled on the database through
the real coordinator; a refresh held in its first ledger read past its
deadline; controls for a refresh held on the node or inside its deadline,
and for a backend stall it does not name; a third-party backend naming its
step; the tracker's own semantics. The four regressions fail on 3.x.x
b8aeb29 with backend-rpc-unavailable. Docs: the rejection registry, the
stratum admission note, the metric inventory and the load harness's
counted classes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 5, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-05T19:57:43.111159Z 44d0a10 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: aca451e924

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

RobertClarke and others added 2 commits October 5, 2026 15:35
…s, mark the replacement-lease payout read, and tighten the revocation hook (#654, #655)

CI shard 0 on aca451e: live_regtest's two fanout lost-reply tests waited
60 s for a survivor that, since #654, takes a dead owner's fanout over only
after watching its claim for the whole 120 s lease. Their shared
expire_dead_lease helper revoked candidate claims but only backdated
claim_expires_at for fanouts, which no longer ends a fanout claim. It now
revokes both kinds. Both tests pass locally against the pinned qbitd 1.0.0.

/code-review high on #667:
- prove_published_lease's payout_state read was unmarked, so an issuance
  under a replacement lease that stalled there still read as the node's.
  It is now an on_database step.
- revoke_fanout_claims touches only claimed fanouts and no schedule. A
  takeover does not wait for a schedule, and its due_now option could only
  make held (infinity) fanouts due.
- The survey reply decoding and the takeable-claim filter are shared in
  claim_observer.rs by the candidate and fanout claim polls.
- refresh_once_inner's failure flag no longer shadows on_database.
- Docs: a claimed fanout is held only at infinity (its own schedule is no
  hold); push a dead holder's fanout with broadcast-ctv by revoking its claim
  first; issued-job persistence counts as one database step as a whole,
  as IssuedPersistenceExpired does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…stence, so a session timeout in its repair's encoding or admission is not the database's (#655)

Codex on #667 (P2), and /code-review high: persist_issued_job marked the
whole issued persistence as a database step. On the compact repair path that
includes the repair lock, build-slot admission and the blocking encode, so a
session deadline passing during CPU work or admission read as the database's
although no statement was pending.

The two writes in save_with_dependency are now the marked steps: the issued
batcher's save, whose batcher does nothing but write batches, and the
compact repair's save. The clock, revision, window and payout reads were
already marked where they run. A persistence that outlives the issued job's
own deadline stays the database's, as #581 decided (IssuedPersistenceExpired),
and docs/prism-rejections.md now says which persistence steps are marked.

Test: a persistence whose repair is held in its encode at a session deadline
reads Unattributed. With the whole persistence marked it read Database (the
test fails); the batch-write stall test still reads the database's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…54-655-ctv-claims-clock

# Conflicts:
#	crates/qbit-prism-server/tests/ctv_fanout_bookkeeping.rs
#	docs/prism-rust-migration.md
#	test/prism-gated-tests.txt
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.

1 participant