Repository navigation
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
Conversation
…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]>
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
…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]>
This was referenced Oct 5, 2026
Closed
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.
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_artifactsafter 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 volatileclock_timestamp()bound left no usable index condition.Before, at 1,000,000 settled fanouts, 7,500 watched and 377 due (prepared, generic plan, warm):
Change
Migration 024 (
023_fanout_lane_index.sql). It addsqbit_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:The lane (
Ledger::fanout_lane_sql, now one named statement). It gathers its candidates into one array, then looks them up by primary key:next_broadcast_attempt_at IS NULL, an index range.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.qbit_prism_fanout_checkpoint_idx, as before.It then applies
FANOUT_CLAIMABLE_SQL, its ownclock_timestamp()schedule test,claim_token IS NULL, the same order andFOR UPDATE OF a SKIP LOCKED LIMIT 1, all unchanged.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:
Timings
The setup:
shared_buffers512 MB; the 1M heap is about 1 GB).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.
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):migrate(or a start withPRISM_POSTGRES_INIT_SCHEMA=1) builds the index withCREATE INDEX CONCURRENTLYafter 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.qbit_ctv_fanout_artifactswaits for the build: not a found block's landing (persist_fanouts), not chain reconciliation, and not the broadcasters of frontends still running.docs/prism-ledger-ops.mdgains "The claim lane and settled history (024, #668)", anddocs/prism-rust-migration.mdgains 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_historyis gated and added totest/prism-gated-tests.txt.EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)through five custom plans and the generic one.qbit_ctv_fanout_artifacts_lane_idxand visits at most 16 fanout rows (its two due ones and the checkpoint, each read as a candidate and looked up);claim_fanoutthen claims abroadcastablefanout.EXECUTE lane('plan-1','plan',60) scanned the fanout table;IS NULL OR <= statement_timestamp()candidate query fails withvisited 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_writescovers the online upgrade:canceling statement due to lock timeout.Two ungated unit tests (
ledger::fanout::tests) pin the lane's copied SQL:FANOUT_CHECKPOINT_SQL) against the oneFANOUT_CLAIMABLE_SQLadmits.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 andscripts/prism-recovery-evidence.sqlinclude 024.Testing
Local PostgreSQL 16, gated and required, on the final commit:
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_databaseandmigration_rollback.ledger::andbroadcaster::serially (163).config_cliandself_check_clialso 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.cargo fmt --check,cargo clippy --workspace --all-targets -D warnings, and the repository consistency scripts.Follow-ups, not in this PR
GET /public/v1/fanouts/pending(api/read_models.rs) still reads every fanout. ItsNOT IN ('confirmed','reorged')can't use an index; the equivalentIN ('awaiting_maturity','broadcastable','broadcast_submitted','failed')would letqbit_ctv_fanout_artifacts_status_idxserve it.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-statereconciliation reads every deep-confirmed fanout and callsgetblockhashonce for each. It is an operator-only path, linear in the settled history.🤖 Generated with Claude Code