Skip to content

3.x.x: read only the due fanouts in the CTV claim lane, through a partial index, so a claim never scans settled history (#668) - #679

Merged
RobertClarke merged 4 commits into
3.x.xfrom
RobertClarke/prism-668-fanout-lane-index
Oct 5, 2026
Merged

RobertClarke merged 4 commits into
3.x.xfrom
RobertClarke/prism-668-fanout-lane-index

Conversation

@RobertClarke

@RobertClarke RobertClarke commented Oct 5, 2026 •

Copy link
Copy Markdown
Member

Fixes #668 (closed by hand on merge; closing keywords do not fire on 3.x.x).

The production pair will migrate mainnet's whole history. Settled CTV fanouts stay in qbit_ctv_fanout_artifacts after their 1,000th confirmation, and mainnet adds about 65,000 to 130,000 of them a year at #521's block rate. Before this change every fanout claim read all of them.

Problem

The claim lane matched settled fanouts on its status and schedule predicates and dropped them only after reading them:

  • settlement_status IN (…,'confirmed') admits every settled fanout.
  • OR fanout_txid = (checkpoint) and the volatile clock_timestamp() bound left no usable index condition.
  • The result was a sequential scan of the whole table on every claim, which a broadcaster pass repeats once per fanout it attempts.

Before, at 1,000,000 settled fanouts, 7,500 watched and 377 due (prepared, generic plan, warm):

Update on qbit_ctv_fanout_artifacts a  (actual time=371.347..371.353 rows=1 loops=1)
  Buffers: shared hit=57436 read=69480
  ...
  ->  Seq Scan on qbit_ctv_fanout_artifacts a_1  (actual time=0.029..363.388 rows=377 loops=1)
        Filter: ((claim_token IS NULL) AND (settlement_status = ANY ('{broadcastable,broadcast_submitted,failed,confirmed}'::text[])) AND ((next_broadcast_attempt_at IS NULL) OR (next_broadcast_attempt_at <= clock_timestamp())) AND (...))
        Rows Removed by Filter: 1007125
Execution Time: 372.205 ms

Change

Migration 024 (023_fanout_lane_index.sql). It adds qbit_ctv_fanout_artifacts_lane_idx ON (next_broadcast_attempt_at, fanout_txid). It is a partial index over exactly the fanouts the lane may still claim, apart from the deep checkpoint:

WHERE settlement_status IN ('broadcastable','broadcast_submitted','failed')
   OR (settlement_status = 'confirmed' AND confirmed_depth < 1000)

The lane (Ledger::fanout_lane_sql, now one named statement). It gathers its candidates into one array, then looks them up by primary key:

  • Never attempted: next_broadcast_attempt_at IS NULL, an index range.
  • Due: next_broadcast_attempt_at <= statement_timestamp(), a second index range. statement_timestamp() is stable, so it serves as an index bound in custom and generic plans alike.
  • Checkpoint: the newest deep fanout, through qbit_prism_fanout_checkpoint_idx, as before.

It then applies FANOUT_CLAIMABLE_SQL, its own clock_timestamp() schedule test, claim_token IS NULL, the same order and FOR UPDATE OF a SKIP LOCKED LIMIT 1, all unchanged.

  • Behaviour change: a fanout that falls due while the claim statement itself runs waits for the next poll.
  • Predicate: the candidate query repeats the index predicate from one constant, FANOUT_LANE_INDEXED_SQL.

The survey (#654) is unchanged. It was measured as well: it reads the fanouts scheduled later than now through broadcast_candidate_idx, i.e. the watched fanouts waiting for their next check. Settled ones have past schedules.

After, same data:

Update on qbit_ctv_fanout_artifacts a  (actual time=2.131..2.134 rows=1 loops=1)
  Buffers: shared hit=3298
  CTE next
    ->  Limit
          InitPlan 1 (returns $0)
            ->  Append  (actual rows=378 loops=1)
                  ->  Index Only Scan using qbit_ctv_fanout_artifacts_lane_idx  (actual rows=2 loops=1)
                        Index Cond: (next_broadcast_attempt_at IS NULL)
                  ->  Index Only Scan using qbit_ctv_fanout_artifacts_lane_idx  (actual rows=375 loops=1)
                        Index Cond: (next_broadcast_attempt_at <= statement_timestamp())
                  ->  Subquery Scan on "*SELECT* 3"  -> Limit -> Index Only Scan using qbit_prism_fanout_checkpoint_idx  (actual rows=1 loops=1)
          ->  LockRows -> Sort -> Nested Loop
                ->  Index Scan using qbit_ctv_fanout_artifacts_pkey on qbit_ctv_fanout_artifacts a_1  (actual rows=377 loops=1)
                      Index Cond: (fanout_txid = ANY ($0))
Execution Time: 2.195 ms

Timings

The setup:

  • PostgreSQL 16, warm cache (shared_buffers 512 MB; the 1M heap is about 1 GB).
  • The lane statement prepared as sqlx prepares it; median of executions 3 to 7, which includes the generic plan.
  • 7,500 watched fanouts, several times the 1,000 to 2,000 that today's block rate keeps under 1,000 deep.
settled fanouts due now before after
100,000 377 63 ms, seq scan 1.6 ms
100,000 7,502 (all) 67 ms, seq scan 28 ms
1,000,000 377 357 to 372 ms, seq scan 1.8 to 2.0 ms
1,000,000 7,502 (all) 412 ms, seq scan 38 ms

What a claim costs now. Each due fanout costs one index entry and one primary-key lookup, then a sort finds the first. Settled history only deepens the primary key, which is why the all-due row moves from 28 ms to 38 ms between 100,000 and 1,000,000.

  • When all are due: a fanout under 1,000 deep is rechecked 5 s after each check, so a broadcaster that can't keep up finds most watched fanouts due and reads them all.
  • The survey: under 6 ms in the same runs (0.1 ms when all are due).
  • Whole claim poll (survey, lane, release and commits): about 10 to 24 ms at 377 due and about 45 to 55 ms when all are due, both at 1,000,000 settled.

Upgrade

024 is additive, as 019 and 020 are: no capability, no shutdown proof, and not offline. A binary that doesn't know the index never reads it.

It is applied online, as 013 is (ONLINE_MIGRATIONS):

  • On an existing ledger, migrate (or a start with PRISM_POSTGRES_INIT_SCHEMA=1) builds the index with CREATE INDEX CONCURRENTLY after the migration transaction commits. It runs on the runner's own connection, without statement or lock timeouts, and records 24 once the index is valid.
  • No write to qbit_ctv_fanout_artifacts waits for the build: not a found block's landing (persist_fanouts), not chain reconciliation, and not the broadcasters of frontends still running.
  • The build takes about 0.6 s at 1,000,000 settled fanouts (warm), against 0.2 s for a plain build.
  • An interrupted build leaves an invalid index that the next run drops and rebuilds.
  • A fresh or empty source applies the file inside the migration transaction.
  • Numbered 024: 3.x.x: hold block submission for the whole cluster from the ledger, whatever each frontend's switch says (#664) #682 took 023 (the cluster-wide block submission hold, applied offline). An upgrade from 22 applies 023 inside the migration transaction, in its stopped window, and then builds 024 online after the commit.

docs/prism-ledger-ops.md gains "The claim lane and settled history (024, #668)", and docs/prism-rust-migration.md gains the 024 paragraph and lists 024 with the online migrations.

Regression test

ledger_postgres::fanout_lane_plan::a_fanout_claim_poll_never_reads_the_settled_history is gated and added to test/prism-gated-tests.txt.

  • Setup: 20,000 settled and 500 watched fanouts beside two due ones.
  • Statements: it prepares both statements of a claim poll, the survey and the lane, and runs EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) through five custom plans and the generic one.
  • Requirements:
    • neither statement plans a sequential scan of the fanout table;
    • the lane reads qbit_ctv_fanout_artifacts_lane_idx and visits at most 16 fanout rows (its two due ones and the checkpoint, each read as a candidate and looked up);
    • the survey visits no more than the watched fanouts;
    • the lane claims exactly the two due fanouts;
    • claim_fanout then claims a broadcastable fanout.
  • Checked against the old code:
    • the pre-024 lane fails with EXECUTE lane('plan-1','plan',60) scanned the fanout table;
    • a single-branch IS NULL OR <= statement_timestamp() candidate query fails with visited 508 fanout rows, at most 16 allowed. It reads every watched index entry as a filter, not a range.

ledger_postgres::fanout_lane_plan::migration_024_builds_the_lane_index_without_blocking_fanout_writes covers the online upgrade:

  • It upgrades a ledger at 23 while a fanout write is open.
  • The concurrent build waits for that write, and another fanout write lands meanwhile.
  • Then the index is valid, every required version is recorded, and the lane claims through it.
  • With 024 built inside the migration transaction instead, it fails with canceling statement due to lock timeout.

Two ungated unit tests (ledger::fanout::tests) pin the lane's copied SQL:

  • the candidate predicate against 024's index predicate, so drift no longer silently turns a claim back into a scan;
  • the checkpoint (FANOUT_CHECKPOINT_SQL) against the one FANOUT_CLAIMABLE_SQL admits.

Migration pins (offer_lifecycle, session_sequence, index_trim, ledger_2x, whose 2.x.x undo now drops 024's index), the share-hash backfill test's online set and scripts/prism-recovery-evidence.sql include 024.

Testing

Local PostgreSQL 16, gated and required, on the final commit:

  • Integration suites: ledger_postgres (201), offer_lifecycle, candidate_window_migration, audit_body_normalization, audit_reconstruction_permit, ctv_fanout_bookkeeping, ledger_single_execution, refresh_liveness, cluster_row_fences, api_database and migration_rollback.
  • Lib: ledger:: and broadcaster:: serially (163).
  • Earlier commit: config_cli and self_check_cli also passed on the first commit. A full parallel lib run there gave 651 passed and 5 lock-timeout or deadline failures in coordinator and candidate tests, the known load flake. All 5 pass serially on a fresh database.
  • Checks: cargo fmt --check, cargo clippy --workspace --all-targets -D warnings, and the repository consistency scripts.

Follow-ups, not in this PR

  • The public GET /public/v1/fanouts/pending (api/read_models.rs) still reads every fanout. Its NOT IN ('confirmed','reorged') can't use an index; the equivalent IN ('awaiting_maturity','broadcastable','broadcast_submitted','failed') would let qbit_ctv_fanout_artifacts_status_idx serve it.
  • When every watched fanout is due, each claim reads all of them: 28 to 38 ms at 7,500. That is the 5 s recheck of every fanout under 1,000 deep (broadcaster::confirmed), which a broadcaster can't sustain at mainnet's window. A longer recheck interval as the depth grows would bound it. It is a product choice, not a settled-history cost.
  • clear-fatal-state reconciliation reads every deep-confirmed fanout and calls getblockhash once for each. It is an operator-only path, linear in the settled history.

🤖 Generated with Claude Code

…tial index, so a claim never scans settled history (#668)

Settled fanouts stay in qbit_ctv_fanout_artifacts after their 1,000th
confirmation, and mainnet adds about 65,000 to 130,000 a year at #521's
block rate. The claim lane matched them on its status and schedule
predicates and dropped them only after reading them: a sequential scan of
the whole table on every claim, which a broadcaster pass repeats once per
fanout it attempts. EXPLAIN (ANALYZE, BUFFERS) on PostgreSQL 16, warm
cache, prepared, per claim, 7,500 watched fanouts: 63 ms at 100,000 settled
fanouts and 357 to 412 ms at 1,000,000 (1 GB heap).

Migration 023 adds qbit_ctv_fanout_artifacts_lane_idx, a partial index over
the fanouts the lane may still claim (to broadcast or check, or confirmed
under 1,000 deep), keyed by next_broadcast_attempt_at. The lane
(Ledger::fanout_lane_sql) gathers its candidates into one array first: the
due ones as two ranges of that index, never attempted and scheduled at or
before statement_timestamp() (stable, so the index serves it as a bound),
and the deep checkpoint from qbit_prism_fanout_checkpoint_idx. It looks
them up by primary key and applies its full predicate and order as before.
The only change in behaviour: a fanout falling due during the claim
statement itself waits for the next poll.

After, same data: 1.6 ms (100,000 settled, 377 due) and 1.8 to 2.0 ms
(1,000,000 settled, 377 due), the generic plan included. A claim now costs
what the due fanouts cost; the settled history only deepens the primary
key. When every watched fanout is due, as when the broadcaster cannot
recheck each one every 5 s, it reads them all: 28 ms at 100,000 settled and
38 ms at 1,000,000, against 67 and 412 ms before.

023 is additive like 019 and 020: no capability, no shutdown proof, not
offline. Building the index reads the table once (0.2 s at 1,000,000
settled fanouts, warm) and holds a SHARE lock on the fanout table until the
migration commits, right after the build.

Test: ledger_postgres::fanout_lane_plan plans and executes both statements
of a claim poll, the survey and the lane, prepared, over 20,000 settled and
500 watched fanouts, through five custom plans and the generic one. It
requires no sequential scan of the fanout table from either, the lane index
read and at most 16 fanout rows visited by the lane (two due and the
checkpoint), and the survey within the watched fanouts. With the pre-023
selection it fails ("scanned the fanout table"). Migration pins, the
recovery-evidence script and the gated-test list include 023;
prism-ledger-ops.md and prism-rust-migration.md describe the lane, its
costs and the upgrade.

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-05T23:01:31.981912Z 9ab2b14 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.

RobertClarke and others added 3 commits October 5, 2026 18:02
…so no fanout write waits for it, and pin the lane's copied SQL (#668)

Review of #679. 023 built its index with a plain CREATE INDEX inside the
migration transaction, which holds a SHARE lock on
qbit_ctv_fanout_artifacts until the commit. A found block's landing
writes that table (persist_fanouts), as do chain reconciliation and the
broadcasters of frontends still running, since 023 needs no shutdown
proof; a migration waiting behind one open fanout write held all of
them up to its 5 s lock timeout. 023 is now an online migration, as 013
is (ONLINE_MIGRATIONS): on an existing ledger the runner builds the index
with CREATE INDEX CONCURRENTLY after the migration transaction commits,
on its own connection without statement or lock timeouts, and records
23 once the index is valid. A fresh or empty source applies the file
inside the transaction. The build takes about 0.6 s for 1,000,000
settled fanouts on a warm cache (0.2 s for a plain build).

ledger_postgres::fanout_lane_plan::migration_023_builds_the_lane_index_without_blocking_fanout_writes
upgrades a ledger at 22 while a fanout write is open: the build waits
for it, another fanout write lands meanwhile, then the index is valid,
every required version is recorded and the lane claims through it. With
the in-transaction build it fails ("canceling statement due to lock
timeout"). The share-hash backfill test's online set, the cutover
rehearsal's step label and the docs include 023.

The lane's candidates take the checkpoint from one constant,
FANOUT_CHECKPOINT_SQL. Two unit tests that need no database pin the
lane's copied SQL: its candidate predicate against 023's index predicate,
and its checkpoint against the one FANOUT_CLAIMABLE_SQL admits. The plan
test counts a lossy bitmap's rechecked rows as visited, and
fanout_lane_sql says why the candidates' bound is statement_timestamp()
while the selection keeps the lane's clock_timestamp() test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Brings in #674 and #680; neither adds a migration, so 023 keeps its number.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… lane index becomes migration 024

#682 took 023 for the cluster-wide block submission hold, which is
offline and transactional. The fanout lane index is now 024:
024_fanout_lane_index.sql, REQUIRED_SCHEMA_VERSIONS, NATIVE_MIGRATIONS,
ONLINE_MIGRATIONS (13, 17, 24) and derive_online, so 023 stays in the
migration transaction and only 024 is built online after the commit.
The 2.x.x undo drops 024's index before 023's hold; the version pins,
the recovery-evidence script, the share-hash backfill test's online set,
the cutover rehearsal's step label, the gated-test name and the docs say
024. claim_fanout keeps #682's hold check before the survey and the lane.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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