Repository navigation
3.x.x: the pending fanouts feeds read the status index instead of every fanout (#688) - #849
Merged
Merged
Conversation
Codex Review Summary: ✅ CompletedThis 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. |
…ry fanout (#688) ## Problem `/public/v1/fanouts/pending` and `/audit/fanouts/pending` share one statement (`pending_fanouts` in `api/read_models.rs`). It filtered `a.settlement_status NOT IN ('confirmed','reorged')`. `NOT IN` is not an index condition, so every response cache miss read every fanout, settled ones included. A whole-table scan of this shape costs 63-67 ms at 100,000 settled fanouts and about 400 ms at 1,000,000 (#668's measurements of the claim lane; this statement itself was not timed). ## Change - The statement moves, unchanged apart from the filter and whitespace, to `crates/qbit-prism-server/src/api/queries/pending_fanouts.sql`, so the tests run the exact text the server runs (the `include_str!` pattern `api_2x` already uses for the hashrate queries). - The filter is now `a.settlement_status IN ('awaiting_maturity','broadcastable','broadcast_submitted','failed')`: the six values of the CHECK in `001_share_ledger.sql` minus the two settled ones. No later migration changes that CHECK (checked every file under `crates/qbit-prism-server/migrations/`; only 001 defines it). `qbit_ctv_fanout_artifacts_status_idx` (settlement_status, block_hash) now serves the statement. - Read-only, public and performance-only. Same rows, order, `total_count` and paging; the response is unchanged byte for byte for the same data. The pool-acquire key (`api/read_models.rs::pending_fanouts#1::fetch_one(& state . pool)`) is unchanged. - One trade-off: an explicit list leaves out a status it does not name, where `NOT IN` listed it. With today's schema the two are identical. A future migration that adds a pending status must also add it here; the guard tests below fail until it does. During a rolling upgrade to such a release, frontends still on this binary would leave that status out of both feeds. - Not bounded by the plan test: the parent-block join (`qbit_pool_blocks`), which predates #688 and runs as a primary-key lookup per pending fanout here. Plan on the test's fixture (20,000 settled fanouts over 2,000 blocks, 40 in a pending status), the same for custom and generic plans: Index Scan on `qbit_ctv_fanout_artifacts_status_idx` (40 rows read, 12 removed by the retry-schedule filter), Nested Loop to `qbit_pool_blocks_pkey`. Before: Seq Scan of the fanout table. ## Tests New `ledger_postgres::pending_fanouts_plan` (`tests/support/pending_fanouts_plan.rs`): - `a_pending_fanouts_page_never_reads_the_settled_history` (gated): over 19,500 deep-confirmed and 500 reorged fanouts, and pending fanouts under immature, mature and candidate blocks, seven pages of the prepared statement, run under `plan_cache_mode=force_custom_plan` and then `force_generic_plan` (`pg_prepared_statements` confirms both ran), read the status index, read the fanout table in one scan (so EXPLAIN's per-loop counts are exact), never seq-scan it, visit at most the pending rows plus slack, and return the right page and count. `nodes`/`reads` are shared with `fanout_lane_plan` (made `pub(super)`). - `the_pending_feeds_keep_the_not_in_output` (gated): every status the migrated schema's CHECK accepts × {never attempted, due, waiting out a retry}, under confirmed blocks (immature, mature, two at one height) and every other chain state. The verbatim pre-#688 `NOT IN` statement and the new one serialize to the same bytes on every page for limits 1, 3, 7, 32, 33, 100 and 1000, including the empty page past the end. The pages together are checked to list every due pending fanout of a confirmed block once, in order. - `the_pending_feeds_list_every_status_but_the_settled_ones` (ungated): the list plus `confirmed`/`reorged` is exactly 001's CHECK. The gated equality test checks the same against the migrated schema's live constraint, so a status a later migration adds fails both until it is listed or named settled. Both gated tests are added to `test/prism-gated-tests.txt`. Run locally on PostgreSQL 16.15 (private cluster, fsync on): - `cargo test --locked -p qbit-prism-server --test ledger_postgres -- --test-threads=4 pending_fanouts_plan fanout_lane_plan`: 5 passed. The gate manifest recorded `executed` for both new gated tests and both `fanout_lane_plan` tests. - `cargo test --locked -p qbit-prism-server --test api_database shared_database_serves_all_contracts_and_global_reward_ranks`: passed (it drives both pending feeds through the router across statuses, retry delays and parent chain states). - Negative controls, each reverted afterwards: the plan test on the old `NOT IN` statement fails (`scanned the fanout table`); dropping `'failed'` from the list fails all three tests; adding a status to the live CHECK fails the equality test's split guard, and with that guard bypassed the byte comparison fails (`NOT IN gave …`). - `cargo fmt --all -- --check`: clean. - `cargo clippy --locked -p qbit-prism-server --all-targets -- -D warnings`: clean (only the three known vendored sqlx-core warnings). - `python3 scripts/check_prism_pool_acquires.py`: passes. ## CI must cover - `prism-native-postgres`: the two new gated tests, and "Prove every Rust PRISM gated test executed" with the updated list. - The full `ledger_postgres`, `api_database` and lib suites, which were not run locally. Refs #688 🤖 Generated with [Claude Code](https://claude.com/claude-code) Squashed commits: 642126b 3.x.x: the pending fanouts feeds read the status index instead of every fanout (#688) 80ae9d3 3.x.x: pending fanouts plan test forces both plan modes and exact row counts (#688) 7a8b139 3.x.x: pending fanouts test attributes #668's figures to the claim lane (#688) Co-Authored-By: Claude Opus 5.5 <[email protected]>
kiwidream
force-pushed
the
orca/688-pending-fanouts-status-index
branch
from
November 12, 2026 21:42
7a8b139 to
cb181ed
Compare
kiwidream
added a commit
that referenced
this pull request
Nov 13, 2026
… nobody serves (#857) ## Problem The public dashboard queries run on the read pool on every cache miss, and several of them do work that nobody reads, or that the rollups and existing indexes already hold (#857). The issue's findings came from a code read. Each one was checked here against real plans and timings, and old and new SQL were compared on the same data. ## Measurements Seeded data: 200,000 shares over 25 h from 500 miners, a 50,000-share reward window (difficulty 6,250,000,000), 5,000 blocks, rollups current. Each figure is the median of five `EXPLAIN ANALYZE` runs of the prepared statement, on PostgreSQL 16 on a shared dev host. | Query (per cache miss) | 3.1.1 | Now | Ledger rows read | | --- | --- | --- | --- | | Miner page share summary | 4.83 ms | 0.22 ms | 24,774 → 783 | | Miner page reward share | 93.8 ms | 58.5 ms | 106,496 → 106,496 (the window itself) | | Pool summary snapshot + sums | 143.4 ms | 52.0 + 7.5 ms | 298,485 → 106,496 + 865 | | Blocks page, `active`, 15 rows | 3.81 ms | 0.97 ms | none | ## Each finding 1. **Miner page: whole-pool 3-hour sum. Changed.** `pool_h3_difficulty` from `dashboard_miner_share_summary.sql` was read by nothing: `miner()` never reads it, it is not in any response, and nothing else in the repo reads it. The `pool` CTE and the key are dropped. 2. **Miner page: whole reward window grouped for one miner. Changed.** `miner()` reads three figures from `reward_leaderboard(…, Some(id))`: the miner's row's `share_percent` (null without a row), its `counted_share_difficulty`, and the window's `counted_window_weight`. The new `dashboard_miner_reward_share.sql` computes exactly those in one aggregate over the same `qbit_prism_window` rows, with the same numeric expressions. It skips grouping and ranking every miner and attributing blocks to them. Materialising the window is unavoidable, because the share is a fraction of the whole window's counted weight. So the saving is the per-miner work, about a third here. The leaderboard route itself is unchanged. 3. **Pool snapshot (`dashboard_pool_snapshot.sql`).** - **24 hours of raw shares. Changed**, following the chart rollups (`dashboard_hashrate_rollups.sql`). The sums now come from the new `dashboard_pool_hashrate_rollups.sql`, and the 3-hour participants from the miner rollups' `UNION` with the raw parts. For each window `[ended_at − span, ended_at]`, the query reads: - the 5-minute rollups for whole buckets before the current one; - raw shares at or below the watermark in the window's two partial buckets (its leading slice, and the current bucket up to `ended_at`); - raw shares past the watermark. The three spans are whole multiples of 5 minutes, so they share one current slice. - **No watermark, or a stale one:** when there is no watermark row, or the share at the watermark is older than the 24 hours (rollups disabled, stalled or still backfilling), the query reads the 24 hours' raw range instead. So a lagging watermark never turns the tail into a walk longer than the range it saves, at any share rate. Unlike the charts, which walk everything past their watermark. - **No rollup schema:** a database without it (a public replica may lack it) runs the old raw scan, now `dashboard_pool_hashrate.sql`, chosen as the charts choose. - **Separate statement:** the sums are read by `read_models::pool_hashrate_sums`, apart from the snapshot. Each takes its own `clock_timestamp()` and snapshot, milliseconds apart: the same answer on the same data, while under concurrent writes the two groups of fields can be milliseconds apart. That adds a `to_regclass` check and a pool acquisition per miss, as the charts have. - **Four `count(*)` over the blocks. Changed** to one pass with `FILTER`. - **`total_mined_bits` over all carry-forward history. Left alone.** No rollup or counter holds the total. An exact one needs a new table or trigger, which means a migration, and this change has none. 4. **Blocks page (`dashboard_blocks.sql`). Changed.** - **The rewrite:** the `public_blocks` CTE (`block.*`, referenced twice, so materialised over every block) and its `CASE` filter are gone. The page filters on plain columns, one `UNION ALL` branch per filter, each behind a one-time test of `$3`. - **Why it now uses the index:** the `active` branch's own predicate (`chain_state = 'confirmed'`) implies the index's (`chain_state <> 'reversed'`). So an `active` page is an ordered read of `qbit_pool_blocks_public_recent_idx` that stops at its page, under custom and generic plans alike. A single `$3`-dependent `OR` would keep generic plans off the index. - **Why `reversed` and `all` don't:** they include reversed rows, which the partial index excludes, so they still scan. The total count still counts the matching blocks. ## Same responses on the same data `dashboard_queries_answer_what_their_3_1_1_queries_answer` (tests/api_2x.rs) runs the 3.1.1 SQL, kept verbatim as test fixtures under `tests/fixtures/dashboard_queries_3_1_1/`, and the new SQL on the same data, and compares the JSON. **The clock:** every comparison runs on a pool whose sessions resolve `clock_timestamp()`, the only clock either side reads, to a function in a test schema placed before `pg_catalog` in their `search_path`. It is pinned at one fixed instant, 150 s into its 5-minute bucket and weeks before the wall clock. The phases the rollups can serve are compared at that instant and four more: bucket-aligned (every window's leading slice empty), a second into the bucket, its last second and a fractional one. The test asserts which path each phase reads: the rollups after they advance, at every instant, and the raw 24 hours before that and with the watermark a day behind. So the old and new statements answer at one instant, every window's first bucket is partial at the pinned instant, the shares placed on the exact 24-hour, 3-hour, 1-hour and bucket edges are on the edges they read on every run, no mismatch is retried, and a statement that read the real clock would fail every run. ### What can differ from 3.1.1 - **Shares younger than 24 hours that a detach removed.** `share-archive detach --retention-days 0`, on a network whose payout window is under a day of shares (signet, regtest), can detach a partition holding shares less than 24 hours old. 3.1.1's raw scan stopped counting them. The new sums keep counting them through the 5-minute rollups for whole buckets, as the hashrate charts already do; the partial buckets, read raw, drop them. Until the rollup sweep moves the watermark past the detached partition's newest share, the readiness check can find no attached share at or below it and read the raw 24 hours instead, which drops them too; the next sweep brings them back. So `h24` (and in the extreme `h3`, `h1` and `participants_3h`) can differ from 3.1.1 on the same database, and agree with the charts. Accepted. With any retention of a day or more a detached partition holds no share younger than 24 hours, so this cannot happen. `docs/prism-share-ledger-partitioning.md`'s reader inventory states it. - **Concurrent writes:** the snapshot and the sums are separate statements, milliseconds apart (above). **The data:** - an empty database; - shares on both sides of every window start and 5-minute bucket edge, others spread over 26 h, and one in the future; - a miner with one share, and a miner with none; - blocks in every chain state, including a reversed one, a disconnected-but-published one (public `reversed`), and two at one height; - miners that tell the 3-hour participants from the 24-hour ones: - eve only older than 3 hours, in a whole bucket, just before the window and past the watermark; - frank, grace and henry only in the current, 3-hour or 24-hour partial slice; - each with no rollup progress, with the rollups current, with shares past the watermark (in the current bucket, in each window's partial bucket, in an already rolled bucket, and from a miner the rollups have never seen), and with the watermark set a day behind while the rollups hold more than it. Mutation checks: - Four deliberate bugs in the participants CTE each fail the test: - the rollup bound widened to 24 hours; - the slice list widened; - the boundary branch dropped; - the tail time filter dropped. - Reverting the watermark-age rule fails both the equivalence test and the plan test. - Making the 24-hour slice's lower bound exclusive (`>` for `>=`) in `dashboard_pool_hashrate_rollups.sql` fails the equivalence test, which only a share on the exact window start can show. So does making the whole buckets' lower bound exclusive. Both fail in the "current watermark" phase, where the rollup path is read. Shares past the watermark sit on each side of every window's start, at the pinned instant and after it, and two miners sit only on either side of the 3-hour start: making the tail's 24-hour bound or its 3-hour participants bound exclusive, or dropping its upper bound, fails the test in the "lagging watermark" phase. **What it compares:** - the miner share summary, minus the dropped key, for four miners; - the reward share at three difficulties, against the 3.1.1 leaderboard's row and totals; - the pool snapshot plus sums, through both the raw and the rollups SQL, at two difficulties; - the blocks page for every filter and six pages, including past the end. The Rust that turns these into the public responses is unchanged, apart from reading the same three figures from the new query in `miner()`. ## Plan assertions These follow the style of #849 and the chart rollups' plan test. - `an_active_blocks_page_reads_the_public_recent_index_under_any_plan`: 5,000 blocks, with `force_custom_plan` and `force_generic_plan`, each at `random_page_cost` 4 and 1.1, for three pages. Every plan reads `qbit_pool_blocks_public_recent_idx`, and that read stops at the page. - `pool_hashrate_sums_read_only_the_partial_buckets_and_the_lag`: 20,000 rolled shares over 25 h, at both page costs, in four states. With the watermark current, then with 300 shares past it, the rollups query reads at most 1,000 ledger rows plus the lag and makes no one-sided ledger scan, while the raw query it replaces reads over 19,000. With the watermark a day behind, and with no progress row, it reads the 24-hour range, no more than the raw scan, again with no one-sided scan. - Mutation check: pointed at the 3.1.1 SQL, both tests fail. ## Tests run All cargo commands ran through the host gate with `CARGO_PROFILE_DEV_DEBUG=line-tables-only`, against a private PostgreSQL 16 cluster. - `PRISM_TEST_PG_BIN_DIR=/usr/lib/postgresql/16/bin test/prism-native-tests.sh cargo-args --offline -p qbit-prism-server --test api_2x --test window_multiplier_invariant`: 12 and 1 passed, the three new tests included. - After the pinned clock: `PRISM_TEST_PG_BIN_DIR=/usr/lib/postgresql/16/bin test/prism-native-tests.sh cargo-args --offline --locked -p qbit-prism-server --test api_2x -- --test-threads=4 dashboard_queries_answer pool_hashrate_sums an_active_blocks_page`: 3 passed, all recorded `executed`; with either mutation above, the equivalence test fails. `cargo fmt`, `cargo clippy` and the pool-acquire guard as below: clean. The follow-up had two more `/code-review xhigh` rounds in an Opus 5.5 subagent; their findings are fixed (a wall-clock epoch that left the rollup path uncompared at bucket-aligned instants, missing timeouts on the pinned pool, the readiness fallback after a detach). - The follow-up's last commit (more instants, tail edges, readiness assertions) applies the second review round's own findings and was not reviewed locally again; Codex reviews it. - The same with `--test api_database --test api_contract -- --test-threads=4`: 3 and 6 passed. - `cargo test --offline -p qbit-prism-server --lib -- api::`: 43 passed. - `cargo fmt --all -- --check`: clean. - `cargo clippy --offline --locked -p qbit-prism-server --all-targets -- -D warnings`: clean, apart from the three known vendored sqlx-core warnings. - `python3 scripts/check_prism_pool_acquires.py`: passes. The new sites are `miner_reward_share` (1) and `pool_hashrate_sums` (2), both public. - Local review: two `/code-review xhigh`-level rounds in an Opus 5.5 subagent. Their findings are fixed: - the invariant's missing site, which would have turned CI red; - test data that couldn't tell the participants' windows apart; - a tail walk unbounded without rollup progress or with a stale watermark; - tail shares placed by a stale clock. ## Docs `docs/prism-share-ledger-partitioning.md`'s reader inventory no longer lists `dashboard_pool_snapshot.sql` as an `accepted_at`-range reader. It lists `dashboard_pool_hashrate.sql` with those readers, and `dashboard_pool_hashrate_rollups.sql` in a row of its own, with the detach case above. It merges cleanly with open PR #848, which changes a line further down the same file. ## Not in scope `OFFSET` pagination and the `strpos(lower(...))` searches, as the issue says. ## What CI must cover The PostgreSQL-gated suites, `api_2x` in particular, and the lib suite. Refs #857 🤖 Generated with [Claude Code](https://claude.com/claude-code) Squashed commits: 1cce087 3.x.x: the miner page, pool summary and blocks page stop reading what nobody serves (#857) ae57486 3.x.x: the dashboard equivalence test reads one pinned clock, and the partitioning doc lists the pool summary's new readers (#857) 387b570 3.x.x: the dashboard equivalence test pins one fixed mid-bucket instant, and the reader row covers the readiness fallback after a detach (#857) 7987d38 3.x.x: the dashboard equivalence test compares at five clock instants and on every tail edge, and asserts which path it reads (#857) fb26a94 Merge 3.x.x (fa8ac84) into orca/857-dashboard-queries: take in the PostgreSQL 16.15 service pin (#866) 0cdbb30 Merge 3.x.x (234ff1c) into orca/857-dashboard-queries: take in the landed 3.1.2 PRs and the collate test fix (#874) Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.
Problem
/public/v1/fanouts/pendingand/audit/fanouts/pendingshare one statement (pending_fanoutsinapi/read_models.rs). It filtereda.settlement_status NOT IN ('confirmed','reorged').NOT INis not an index condition, so every response cache miss read every fanout, settled ones included. A whole-table scan of this shape costs 63-67 ms at 100,000 settled fanouts and about 400 ms at 1,000,000 (#668's measurements of the claim lane; this statement itself was not timed).Change
crates/qbit-prism-server/src/api/queries/pending_fanouts.sql, so the tests run the exact text the server runs (theinclude_str!patternapi_2xalready uses for the hashrate queries).a.settlement_status IN ('awaiting_maturity','broadcastable','broadcast_submitted','failed'): the six values of the CHECK in001_share_ledger.sqlminus the two settled ones. No later migration changes that CHECK (checked every file undercrates/qbit-prism-server/migrations/; only 001 defines it).qbit_ctv_fanout_artifacts_status_idx(settlement_status, block_hash) now serves the statement.total_countand paging; the response is unchanged byte for byte for the same data. The pool-acquire key (api/read_models.rs::pending_fanouts#1::fetch_one(& state . pool)) is unchanged.NOT INlisted it. With today's schema the two are identical. A future migration that adds a pending status must also add it here; the guard tests below fail until it does. During a rolling upgrade to such a release, frontends still on this binary would leave that status out of both feeds.qbit_pool_blocks), which predates 3.x.x: the public /public/v1/fanouts/pending query reads every fanout (NOT IN is not an index condition) #688 and runs as a primary-key lookup per pending fanout here.Plan on the test's fixture (20,000 settled fanouts over 2,000 blocks, 40 in a pending status), the same for custom and generic plans: Index Scan on
qbit_ctv_fanout_artifacts_status_idx(40 rows read, 12 removed by the retry-schedule filter), Nested Loop toqbit_pool_blocks_pkey. Before: Seq Scan of the fanout table.Tests
New
ledger_postgres::pending_fanouts_plan(tests/support/pending_fanouts_plan.rs):a_pending_fanouts_page_never_reads_the_settled_history(gated): over 19,500 deep-confirmed and 500 reorged fanouts, and pending fanouts under immature, mature and candidate blocks, seven pages of the prepared statement, run underplan_cache_mode=force_custom_planand thenforce_generic_plan(pg_prepared_statementsconfirms both ran), read the status index, read the fanout table in one scan (so EXPLAIN's per-loop counts are exact), never seq-scan it, visit at most the pending rows plus slack, and return the right page and count.nodes/readsare shared withfanout_lane_plan(madepub(super)).the_pending_feeds_keep_the_not_in_output(gated): every status the migrated schema's CHECK accepts × {never attempted, due, waiting out a retry}, under confirmed blocks (immature, mature, two at one height) and every other chain state. The verbatim pre-3.x.x: the public /public/v1/fanouts/pending query reads every fanout (NOT IN is not an index condition) #688NOT INstatement and the new one serialize to the same bytes on every page for limits 1, 3, 7, 32, 33, 100 and 1000, including the empty page past the end. The pages together are checked to list every due pending fanout of a confirmed block once, in order.the_pending_feeds_list_every_status_but_the_settled_ones(ungated): the list plusconfirmed/reorgedis exactly 001's CHECK. The gated equality test checks the same against the migrated schema's live constraint, so a status a later migration adds fails both until it is listed or named settled.Both gated tests are added to
test/prism-gated-tests.txt.Run locally on PostgreSQL 16.15 (private cluster, fsync on):
cargo test --locked -p qbit-prism-server --test ledger_postgres -- --test-threads=4 pending_fanouts_plan fanout_lane_plan: 5 passed. The gate manifest recordedexecutedfor both new gated tests and bothfanout_lane_plantests.cargo test --locked -p qbit-prism-server --test api_database shared_database_serves_all_contracts_and_global_reward_ranks: passed (it drives both pending feeds through the router across statuses, retry delays and parent chain states).NOT INstatement fails (scanned the fanout table); dropping'failed'from the list fails all three tests; adding a status to the live CHECK fails the equality test's split guard, and with that guard bypassed the byte comparison fails (NOT IN gave …).cargo fmt --all -- --check: clean.cargo clippy --locked -p qbit-prism-server --all-targets -- -D warnings: clean (only the three known vendored sqlx-core warnings).python3 scripts/check_prism_pool_acquires.py: passes.CI must cover
prism-native-postgres: the two new gated tests, and "Prove every Rust PRISM gated test executed" with the updated list.ledger_postgres,api_databaseand lib suites, which were not run locally.Refs #688
🤖 Generated with Claude Code
Open in [code]smith · Need help on this PR? Tag
@codesmith-botwith what you need.