Repository navigation
3.x.x: Trim the share ledger indexes online (migration 011) - #369
Conversation
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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c75e42d01b
ℹ️ 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".
df4631a to
d29e641
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d29e641e7d
ℹ️ 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".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: cac3407ba0
ℹ️ 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".
836b081 to
d23be46
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d23be46831
ℹ️ 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".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 912b76a143
ℹ️ 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".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d19d17b2ec
ℹ️ 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".
0a416ca to
4d57301
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4d5730149b
ℹ️ 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".
Map the six secondary indexes of qbit_share_ledger to the native readers and trim them to what those readers use (#153): replace the seven-column share_seq covering index, which no native read ever used index-only, with a three-column one that makes the frozen qbit_prism_window page walk and the landing durable-range count index-only; drop payout_order_key from the miner index, which nothing reads; drop the job_issued_at and template_height indexes, which have no native consumer. WHERE accepted stays: the readers exclude rejected rows by contract (the window and rollup tests write them), and the predicate keeps the frozen 001 walk index-only without carrying the column. CREATE INDEX CONCURRENTLY cannot run in the migrator's transaction, so 011 is the first ONLINE_MIGRATIONS entry: its file is replayed in the scratch schema to derive the index definitions, applied inside the transaction on an empty ledger, and otherwise applied after the commit on a dedicated connection with CONCURRENTLY, under a schema-keyed session lock, recorded last. The runner inspects every reserved name before any DDL, rebuilds an invalid leftover, keeps an identical earlier build and refuses anything else by name. Four gated tests cover the empty-ledger path, a frozen 2.x.x source with rows, a build with a writer transaction held open, and resume/keep/refuse. The ops doc gains the index inventory and the production measurement runbook the issue's gate asks for; the migration guide the online apply. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Always defer online migrations for existing native schemas, including ledgers whose first share is still uncommitted. Keep fresh and empty legacy cutovers transactional under their writer locks. Poll the online advisory lock without holding a waiting statement snapshot, so simultaneous frontend upgrades cannot deadlock concurrent index builds. Scope the first-share regression observer to its own ledger.
The online runner decides its plan before any DDL: every index the migration creates and drops is looked up once, and each Rebuild and Drop step then runs DROP INDEX CONCURRENTLY by name. Between that look-up and the drops sit the CREATE INDEX CONCURRENTLY builds, which take hours on a large ledger, and nothing in that window stops an operator's DDL under a reserved name: the advisory lock orders only runners, and ALTER INDEX RENAME locks the index alone, so a release index can be moved aside and another created under its name (on any table) while a build holds the ledger. The stale plan then dropped an index the migration did not own, after the preflight had promised it would not. Each destructive step now looks its target up again as it is reached and drops only if the name still holds what the plan saw: the same table and definition, and for a rebuild still the invalid index an interrupted build left. Step::Drop carries the IndexDefinition for that instead of the table name. Anything else refuses the run, naming the index, what it reads as now and what the plan held, and, unlike the preflight refusals, what the run had already built and dropped by then, since that is no longer nothing; the next start plans afresh and keeps those. The recheck and the drop remain two statements, because CONCURRENTLY refuses a transaction block and PostgreSQL drops by name, so a change that lands in the round trip between them is still not caught. That window is milliseconds rather than the hours of a build and cannot be closed in SQL; the code says so. The new gated test holds the first build behind an open writer, swaps a drop target (and, in a second phase, the invalid index a rebuild would replace) for an operator's index on another table while it waits, and asserts the refusal, its account of what ran, the untouched operator index, and that the next start finishes the migration keeping the built indexes. Against the previous runner the same test fails because the operator's index is dropped. It is listed in test/prism-gated-tests.txt, which the proof job checks every executed gated test against.
Adding 011 to REQUIRED_SCHEMA_VERSIONS left the PL/pgSQL gate in
scripts/prism-recovery-evidence.sql at 2 through 10, so a native
database that startup refuses for lacking 011 still exported evidence,
against the script's stated requirement to mirror startup. The gated
regression that removes each declared version in turn caught it in CI
("missing required migration 11 was accepted").
Add 11 to the script's required_versions, and add a migration unit test
that reads the declaration back from the script and compares it with
REQUIRED_SCHEMA_VERSIONS, so the next drift fails in the fast unit job
rather than only under the PostgreSQL gate. Point the constant's doc at
the script.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
The online runner rechecks only the names it is about to drop. A replacement that was already valid at preflight is planned as Keep and never looked at again, and a build checks its own index only as it finishes; the other replacement's CREATE INDEX CONCURRENTLY then runs for hours on a large ledger, in which an operator can rename or replace either just as they can a drop target: the advisory lock orders only runners, and ALTER INDEX RENAME locks the index alone. The run still recorded 11 afterwards, so every later start trusted the record and accepted a database with a required replacement missing or altered. Every name the migration declares is now looked up once more inside the transaction that records the version, after MIGRATION_LOCK and before the INSERT: each created index must be valid on its table with exactly the declared definition, and each dropped name absent. Anything else refuses the run before the commit, naming the index, what it reads as now, what the migration declares, and what the run had already built and dropped; the version stays unrecorded and the next start plans afresh. The preflight, the drop rechecks and the post-build check stay; the phrasing of what a name holds now is shared with drop_planned. What remains open is the round trip between the look-up and the INSERT, since nothing here can lock an index against another session's DDL, not the hours of a build. The new gated test pre-builds one replacement so the run keeps it, holds the other build behind an open writer, renames the kept index and puts an operator's index under its name while the build waits, and asserts the refusal, that 11 is not recorded, that the operator's index and the renamed one are untouched, and that once the name is restored the next start records 11 keeping both indexes. Without the check the same test fails because the run records 11 over the swapped index. It is listed in test/prism-gated-tests.txt. Co-Authored-By: Claude Fable 5.1 <[email protected]>
PR #391 (offer found blocks before audit landing) landed on 3.x.x first and took migration 011 for the offer lifecycle: it added 11 to REQUIRED_SCHEMA_VERSIONS, to the required_versions array of scripts/prism-recovery-evidence.sql, and to the tests that spell that constant out. Rebasing this branch onto it renumbered the share ledger index trim to 012 on the Rust side (the migration file, NATIVE_MIGRATIONS, ONLINE_MIGRATIONS, REQUIRED_SCHEMA_VERSIONS, and the gated fixtures the branch had already updated), but three places kept the old number. scripts/prism-recovery-evidence.sql still required 2 through 11. The commit meant to add the trim to it ("require migration 011 in the recovery evidence export") was written while the trim was 011; after the rebase 3.x.x had already added 11 for the lifecycle, so that commit's change to the array disappeared in the conflict resolution and only its comment survived. Startup refuses a native database missing 12 (012 is recorded only once its concurrent index builds have finished), so the export accepted a database startup refuses. The unit test recovery_evidence_requires_the_migrations_startup_requires reports exactly that, and the gated regression assert_native_metadata_required would report "missing required migration 12 was accepted". Add 12. the_pre_ddl_declaration_fence_runs_whenever_6_or_11_is_recorded, from REQUIRED_SCHEMA_VERSIONS in the refusal it expects. The fence itself is right: a record carrying 11 without the candidate_offer_lifecycle row is refused before any DDL whether or not 12 is recorded, because 012 declares no capability; only the recorded set the refusal names grew. Derive the expected prefix from schema_version_list(REQUIRED_SCHEMA_VERSIONS) so the next migration does not stale it again. tests/offer_lifecycle.rs, also from #391 and PostgreSQL-gated, compared the record after Ledger::connect(initialize=true) with 2 through 11 and expected refusals naming that set. connect applies 012 online and records it before returning, so the record there is now 2 through 12, as the branch already made candidate_window_migration.rs, ledger_2x.rs, session_sequence.rs and window_reference.rs expect. Update ALL_VERSIONS and the three refusal prefixes; this file could not be run here without PostgreSQL. The six [2..11] assertions in tests/support/index_trim.rs are deliberate: undo_012 puts a database back to 11, and the others assert that a refused online run left 12 unrecorded. The [2, 3, 4, 5, 7, 8, 9, 10, 11] inputs in migration.rs model a selectively restored record with 11 and not 6; the fence looks only at 6 and 11, so they stay as they are. cargo fmt --all also reflows index_trim.rs and ledger_2x.rs, where this branch's own assertions exceeded rustfmt's default width. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Shard 3 of the PostgreSQL job fails in
migration_012_refuses_a_drop_target_swapped_while_it_built and
migration_012_refuses_to_record_when_a_kept_index_moved_while_it_built,
both at the `error.contains(refusal)` assertion of swap_during_build. It
is the same incomplete 011 -> 012 renumber as the previous commit, this
time in string literals. The online runner (ledger/migration/online.rs)
formats "refusing to continue migration {version}" and "refusing to
record migration {version}" from the version ONLINE_MIGRATIONS carries,
which is 12, and the text CI prints says 12, while the three expected
refusals handed to swap_during_build still said 11. Both tests failed
the same way on 4d57301, before the previous commit.
The literals stay literals rather than being derived. This file is
about migration 012 by name: its module doc, every test name, undo_012
and its DELETE ... WHERE version=12. ONLINE_MIGRATIONS is not public,
and the one public number, the last of REQUIRED_SCHEMA_VERSIONS, would
follow a future transactional 013 while the migration under test stayed
12, so deriving from it would break in exactly the case it is meant to
survive.
The same sweep found two comments in the file saying the run "records
11", and three lines in the "Migration 012" section of
docs/prism-rust-migration.md, written on this branch, that say the
runner records 11 and quote its refusal as "migration 11". Renumbered
too. Everything else in the crate, scripts and docs that still says 11
or 011 belongs to the offer lifecycle, or is a deliberate pre-012 state:
"back to 11", "a database at 11", and the [2..11] record assertions
after a refused run.
The two tests need PostgreSQL and did not run here. cargo fmt --all
--check and cargo clippy -p qbit-prism-server --all-targets -- -D
warnings pass.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Preserve upstream migration 012's startup fence and use 013 for the online index trim. Align the migration include, recovery gate, fixtures, expected refusals, integration gate names, and operator docs.
7505c7e to
b6af774
Compare
Closes nothing yet: the production gate of #153 stays open until an operator runs it. Part of #144 (first slice), tracker #263.
What changed
Migration
011_share_ledger_index_trim.sqltrims the six secondary indexes ofqbit_share_ledgerto the native query set, mapped index by index against every native reader (ledger/window.rs,ledger/audit.rs,api/queries/*.sql,rollups.sql,tools.rs,difficulty.rs,read_models.rs, and the 001qbit_prism_windowfunction the pool snapshot and reward leaderboard still call):accepted_seq_window_idx(share_seq DESC, 7 INCLUDE columns; 23 GB on production)share_seqwalk is planned on the primary key, so the payload never earns an index-only readaccepted_seq_walk_idxwithINCLUDE (job_issued_at, accepted_at, share_difficulty): exactly whatqbit_prism_window's page walk and the landing durable-range count read, and both become index-only on itaccepted_miner_recent_idx(21 GB)share_id), miner hashrate series and rollups (share_seq)accepted_miner_history_idxwithoutpayout_order_key, which nothing readsaccepted_window_idx(job_issued_at, share_seq DESC)job_issued_atis only ever a filter on ashare_seqwalktemplate_height_idxqbit_shares_since_template_heightis its only caller (kiwidream's correction on the issue) and now reads the primary key with a filteraccepted_recent_idxaccepted_block_suffix_idxPlan evidence, from a 400k-row synthetic ledger on PostgreSQL 16 (
VACUUM ANALYZEd, every native query run throughEXPLAIN (ANALYZE, BUFFERS)before and after): on the current index setaccepted_seq_window_idxandaccepted_window_idxget zero scans, the planner walking the primary key instead; after the trimaccepted_seq_walk_idxis chosen as an index-only scan (Heap Fetches: 0) for the frozen window function's page walk,max(share_seq)and the durable-range count, and every other query keeps its plan. Sizes on that ledger: 95 MB to 19 MB and 70 MB to 36 MB for the two replacements, 24 MB freed by the two drops.Deviation from the acceptance criteria:
WHERE acceptedstaysThe issue asks for the constant
WHERE acceptedpredicates and the matching query qualifiers to go. Two facts on 3.x.x argue against it, so this PR keeps them and says so:window_read_oracle,rollups_postgresandwindow_referencewriteaccepted = falserows and assert they are not counted. Removing the query-side qualifiers is a read-contract change, not a simplification.qbit_prism_windowpage walk stay index-only on the narrow index without carrying the column; 001 is a digest-checked fixture (3.x.x: Pin the migration source schema, refuse unknown storage versions, gate startup #285), so itsWHERE ledger.acceptedcannot be edited.Write cost is identical either way (every row satisfies the predicate), so nothing is lost by keeping it. Dropping it later is a one-line change to the migration plus 14 query sites if the contract is reconsidered.
How the migration applies: online
CREATE INDEX CONCURRENTLYcannot run in a transaction block, and the migrator applies every migration inside one transaction. 011 is the first migration inONLINE_MIGRATIONS:pg_get_indexdef); nothing parses SQL. A self-check refuses an online migration that changes anything but indexes, or redefines an index under its old name (theIF NOT EXISTStrap from the issue).migrate_schemareturns it andLedger::connectapplies it after the commit on a dedicated connection with no statement or lock timeout, under a session-level advisory lock keyed by the ledger's schema: every reserved name is inspected first, thenCREATE INDEX CONCURRENTLYfor each new index,DROP INDEX CONCURRENTLYfor each replaced one, and the version is recorded last. Appends continue throughout (tested with a writer transaction held open across the build).Tests
ledger_postgres::index_trim(registered intest/prism-gated-tests.txt): the empty-ledger transactional path and restart idempotence, a frozen 2.x.x source with rows, the non-blocking build with an open writer, and resume/keep/refuse under the reserved names plus the startup gate at 10.qbit-prism-servercrate against Dockerpostgres:16with the gate manifest checker (only the known localQBITD_BIN/PRISM_TEST_PG_BIN_DIRgaps fail),cargo fmt --check,cargo clippy --workspace --all-targets -D warnings. Run with--test-threads=4: at default parallelism this machine hits the 5 slock_timeouton the migration advisory lock, and an untouched origin/3.x.x checkout fails the same way, so that is the environment, not this change.Docs
docs/prism-rust-migration.md: the transaction caveat, the collision row, the startup gate list, and a new subsection on 011's online apply, resumability and planning the build on a large ledger.docs/prism-ledger-ops.md: a new "Share ledger indexes" inventory mapping every index to its readers, the dropped ones, theWHERE acceptedrationale, the pre-existing full scan indashboard_hashrate_rollups.sql, and the production measurement runbook (ANALYZE, statistics vs. row count, autovacuum,pg_stat_user_indexes, and theEXPLAINgate on the page walk).Left for the operator (acceptance criterion 3)
The production gate needs production Postgres access:
ANALYZE qbit_share_ledger, then the runbook queries, with the result recorded in #153 and #144. The commands are in the ops doc. Also worth a look before cutover: the transient disk footprint (the two replacements are built before the four drops) and runningmigratefrom a shell rather than a starting frontend on the production ledger.🤖 Generated with Claude Code
Need help on this PR? Tag
@codesmith-botwith what you need. Autofix is disabled.