Repository navigation
3.x.x: finish a deferred share-hash backfill while frontends serve, in throttled batches, and let the evidence export and self-check read it pending - #746
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. |
💡 Codex Reviewqbit-mining-bootstrap/crates/qbit-prism-server/src/ledger/migration/share_hashes.rs Lines 1077 to 1080 in fa7b9ad When ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
…n throttled batches, and let the evidence export and self-check read it pending migrate --defer-share-hashes leaves migration 2's share-hash backfill pending at share_hash_backfill_pending = 2 while frontends serve. The new qbit-prism-server backfill-share-hashes maps the rest and records 2. Plain migrate on such a database now takes the same path, at the default throttle, instead of rc.4's unthrottled batches, with or without #745's --offline-indexes, which changes only how 013 and 024 build. A Throttle bounds every batch: at most --max-batch share_seq values (5,000), one statement in a transaction of its own, cancelled at --statement-timeout-ms (2 s, at most 5 s) and retried at half its size, and a rest of took * (1 - d) / d after each, where d is --duty-cycle (0.5). Every native append updates the cluster row under ORDER_LOCK, and a snapshot held on the primary keeps that row's dead versions (#738), so no statement holds one longer than its timeout, and none is held between batches. Each bound is checked in one place, which the flags' parsers call before anything connects. The chunked double-credit check that runs before 2 is recorded keeps to the same throttle. A batch or chunk that times out at its smallest size says to run backfill-share-hashes with a smaller --max-batch, or else a larger --statement-timeout-ms up to the cap; plain migrate's error names that command, as migrate takes no throttle flags. While frontends serve, the transaction that records 2 waits at most 2 s for the migration lock or the cursor table's lock, and its statements keep to the throttle's timeout. An attempt that waits longer is rolled back, holding nothing, logged, and tried again after a backoff from 2 s doubling to 30 s, 20 times, about ten minutes in all. The run then stops, naming what held it and to run backfill-share-hashes again, which goes straight to the double-credit check and the record. The record of a backfill before anything serves is unchanged. The command refuses, before it maps anything, a backfill that does not permit serving, and it shares A1's checks under the runners' lock: the fence and the claim, 017's conversion bound, the frozen end and the double-credit refusal. On a database whose backfill has finished it maps nothing and succeeds, so a retry after a lost reply is safe. It prints what it did as JSON, already_complete included. The recovery evidence export now reads a database at fence 2, as every start does. It exports the cursor as one share_hashes_deferred record in place of the partial mapping, and the summarizer marks the share_hashes kind deferred with it and says so in a note. The preamble, which every parallel session runs, reads only the catalog, and the cursor is read last, after the integrity report, so an export holds the cursor table's lock only until it commits, right after. The refusal of a cursor at fence 1 names migrate --defer-share-hashes to serve and plain migrate to finish; one that a build before #669 started, with no fence, names plain migrate alone. A complete export's summary is unchanged, and the parallel export and summarizer stay byte-identical to the serial ones. The export checks each capability's value against the highest that startup accepts, from one declaration that a unit test compares with NATIVE_CAPABILITIES. self-check samples the backfill beside the heartbeats, in one read of the cursor and its fence under one 5 s deadline, and reports it in a share_hash_backfill field with a warning line, never as a failure: "pending" with the fence and the cursor, or "unknown" with why it could not be read, a connection failure's text withheld. The field is absent only when the read succeeded and nothing is pending. The start gate's warning, migrate --defer-share-hashes's output and the share-archive refusals while the backfill is pending name backfill-share-hashes as the way to finish it. The migration guide and the ledger runbook describe when and how to run it after go-live, its throttle, how to watch it, the record's retries, and how to compare evidence while it is pending. The recovery test helpers now refuse an export script edited after the test binary was built. The serial export runs the copy compiled in, while the parallel exporter and the summarizer read the file, so a full suite whose script changed under it compared two scripts' exports: the deferred export test once failed so, at the line the edit had moved. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ded 2 as done (Codex on #746) The record of 2 while frontends serve retried a failed attempt without asking whether it had committed. An attempt can commit and still fail: its COMMIT's reply lost with the connection, or cut short after the commit was written. A retry then met the cursor that commit had dropped, failed on the missing table, and reported a finished backfill as failed. Now every failed attempt is followed, before anything else, by a read of what it left, in one statement of a fresh transaction under the record's own timeouts: whether 2 is recorded, and whether the cursor table exists. With 2 recorded and the cursor gone the backfill is done: the run logs that the attempt's reply was lost or cancelled but 2 is recorded, and succeeds as any finished run does. With 2 unrecorded and the cursor in place nothing committed, and a wait past a lock or statement timeout is retried as before. Either other state was made by hand, since the one transaction that records 2 drops the cursor in the same commit, and is refused loudly rather than retried. A read that fails too stops the run, naming backfill-share-hashes, which finds 2 recorded or records it. The statement timeout still covers the COMMIT. Under synchronous replication a COMMIT waits for the standby with its xid running and its locks held, which #738 rules out for long, and a cancelled wait leaves the commit local, which PostgreSQL reports as done with a warning. The re-check covers every way an attempt can fail after its commit, and a comment by the record's transaction says why. A gated lib test injects the failure through a test-only fault hook, in the pattern of the candidate claims' faults: keyed by schema, it lets the first record attempt commit and then return PostgreSQL's 57014. The run reports the backfill done, with 2 recorded and the cursor and the fence gone. A unit test pins the four states the read can find. The migration guide and the ledger runbook say what the run does after a lost reply. Co-Authored-By: Claude Opus 5.5 <[email protected]>
fa7b9ad to
b4a8ab6
Compare
|
Re Codex's P2 above ("Recheck completion after a timed-out commit"): fixed in b4a8ab6, on top of the rebased A2 commit 59d2322. Both are now on 3.x.x c62ac57. After any failed record attempt, the run first checks whether 2 is recorded and whether the cursor table exists. The check is one statement in a fresh short transaction, under the record's lock timeout and the throttle's statement timeout.
The statement timeout still covers the COMMIT. Under synchronous replication a COMMIT waits for the standby with its xid running and its locks held, which #738 rules out for long. PostgreSQL treats a cancelled sync-rep wait as a local commit with a warning, so this exact case shows up as a lost reply, which the check covers. A comment by New gated test |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b4a8ab6018
ℹ️ 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".
… as unknown, not finished (Codex on #746) Every read of the share-hash cursor took any 42P01 for the cursor dropped since its look-up, by the transaction that records 2, and read it as nothing pending. But the read can miss another relation it needs: self-check's reads the fence from qbit_prism_schema_capabilities, so a database with its cursor beside a missing capability table, a damaged one self-check should diagnose, read as one whose backfill had finished, and self-check omitted both the field and the warning. Now a 42P01 reads as nothing pending only if the cursor is gone when it is looked up again, in one short statement. Otherwise the read's own error goes on, and self-check reports the backfill as unknown with it. Both readers of the cursor, self-check's and the one every start and migrate makes, go through that one place. The record of 2 has no such shortcut: its re-check after a failed attempt reads the catalog and the migration history, and a failure there stops the run. self-check's backfill test in ledger_postgres renames the capability table beside a pending cursor and requires state unknown with the missing relation named, and the warning. A gated lib test drops the cursor between its look-up and its read, through a test-only fault the record test's hook now shares, and requires both readers to read nothing pending. The lib tests move to share_hashes/postgres_tests.rs. Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5829a63919
ℹ️ 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".
Set VERSION and [workspace.package].version to 3.0.0-rc.5: rc.4 plus #737's fixes in #742 (fatal-state clear accepts a tip that only grew, takes --timeout-seconds, and runs the integrity report under its own statement timeout) and #744 (migration 026: the report computes each set once); the deferred share-hash backfill in #743 and #746 (migrate --defer-share-hashes, then the throttled backfill-share-hashes after go-live); #745 (migrate --offline-indexes, which composes with --defer-share-hashes); the cutover tooling merged after rc.4's tag (#728, #732, #736, #740); and #747, a test-only fix for #724. Both Cargo.lock files move only their workspace-member entries. doc/release-notes-3.0.0-rc.5.md, dated 2026-10-08, covers: - the changes, with the report's estimated 57 to 29 s since 026, the migrate --defer-share-hashes command measured on the pair at 5 min 06 s (539d6c9, before #745), backfill-share-hashes' throttle, record of 2 and safe rerun, the evidence scripts' changes, and the offline index builds' estimated gain; - upgrading: migrate is needed again (a binary-only upgrade refuses "missing migration(s) 26", and this export refuses a database without 026), the cutover's migrate step with both flags, and finishing the backfill after go-live under #738's snapshot rule, with self-check only at low share rates. Rolling back to rc.4 at fence 2 goes only by finishing the backfill first or from the pre-migrate backup or physical copy, and each rc.4 refusal is quoted where it applies: a start meets the cursor first and says to run migrate, which rc.4's migrate refuses. The rules still in force: #737's statement timeout for rc.4's tools, 026 or not, #738's snapshot rule, and fatal-state clear --timeout-seconds, whose bound ends before the commit; - the same evidence set as rc.4's, with each PR's merge SHA, the pair's serving evidence carried, and the rehearsal's full measurements left to the cutover's go/no-go record; - the known issues: rc.4's, minus #737's F1, F2, F4 and F5, plus #737's open part, #738 (its fix planned for rc.6), #739, #741, #731 and #734, with #582 closed and #712 and #724 updated. docs/prism-rust-migration.md now says how earlier candidates refuse a database at fence 2: a start with the backfill's own refusal, whose advice to run migrate holds only for this release, and their migrate, or a start with PRISM_POSTGRES_INIT_SCHEMA=1, with the fence. The development-line notes name 3.0.0-rc.5, and they and the 3.0.0 notes link all five candidates' notes. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
PR-A1 (#743, merged) lets
qbit-prism-server migrate --defer-share-hashestake migration 002's share-hash backfill out of the W1 cutover's outage. It maps the recent range, raises the fence toshare_hash_backfill_pending = 2, and the database serves with the rest of the legacy ledger unmapped. This PR adds the way to finish that backfill safely while frontends serve, and the evidence, self-check and docs around it:qbit-prism-server backfill-share-hashes [--max-batch 5000] [--statement-timeout-ms 2000] [--duty-cycle 0.5]maps the rest in throttled batches, checks for a double credit, and records 2. It refuses a database that isn't at fence 2, and says what to run instead. On a database whose backfill has finished it maps nothing and succeeds ("already_complete": true), so a retry after a lost reply is safe.migrateon a fence-2 database now takes the same throttled path, at the defaults (review finding A1-F1), with or without 3.x.x: let migrate --offline-indexes build 013's and 024's indexes with a plain parallel CREATE INDEX in one transaction when no instance is live #745's--offline-indexes, which changes only how 013 and 024 build. rc.4's batching (up to 50kshare_seq, up to the pool's 15 s per statement, back to back) stays only for the fence-1 backfill that runs before anything serves.--statement-timeout-msis capped at 5,000, and the transaction that records 2 waits at most 2 s for a lock an attempt, then backs off and tries again for about ten minutes before it stops cleanly.share_hashesdeferred. The capability check now compares the values startup accepts, not only the names.self-checkreports the backfill in a non-fatalshare_hash_backfillfield, with a warning line:"state": "pending"with the cursor, or"state": "unknown"with the error when it can't be read, never taken for done.backfill-share-hashessection, an evidence section, and a go-live runbook step inprism-ledger-ops.md.This is PR-A2 of rc.5 (
rc5-plan-u3.md§A.1, A2-a to A2-d), on 3.x.x at c62ac57: #743, migration 026 (#744), C1's fatal-state and self-check changes (#742), B'smigrate --offline-indexes(#745) and #747 are all in the base. Since #743,share-archive detachanddroprefuse every partition while the backfill is pending. Here that refusal, andrestore's, namebackfill-share-hashesas the remedy, and the docs say archiving waits until 2 is recorded. #743'san_archive_ready_native_partition_stays_attached_until_2_is_recordedpins that remedy, so its assertion is updated. The export'srequired_versionsline, with 026, is untouched.Design
The throttle (
share_hashes.rs)pub struct Throttle { max_batch, statement_timeout, duty_cycle, record_attempts, record_backoff }, re-exported asledger::ShareHashThrottle.share_seq, 2 s, 0.5, and the record's 20 attempts from a 2 s backoff.Throttle::check_max_batch(1 to 50,000, rc.4'sBATCH_MAX),check_statement_timeout_ms(1 to 5,000 ms,MAX_STATEMENT_TIMEOUT_MS: no statement may hold a snapshot on the serving primary longer, 3.x.x: every share append UPDATEs the qbit_prism_cluster singleton (ledger_clock_ms), so any snapshot held on the primary bloats it and saturates ORDER_LOCK in ~20 s at 400 shares/s; derive the clock from append-only state (rc.5) #738) andcheck_duty_cycle(0.01 to 1; NaN is refused).Throttle::newand the CLI's value parsers call the same three.with_record_attempts(attempts, backoff)shortens the record's patience for a test or a rehearsal.throttled()):BEGIN, thenSELECT set_config('statement_timeout', <ms>, true), then 002's batch statement and the cursor update, thenCOMMIT. The setting is transaction-local, so the pool's timeout comes back with the next transaction. No snapshot outlives one statement, and between batches the connection is idle.[min(1000, max_batch), max_batch]. It starts atmin(10_000, max_batch). A batch that outlasts the timeout is rolled back and retried at half its size, as today. At the floor, a timeout stops the run, witheven a batch of <n> share_seq, the smallest, outlasted its <ms> ms statement timeout, so run it with a smaller --max-batch, or else a larger --statement-timeout-ms, at most 5000. The double-credit check's chunks say the same. Plainmigrate's error namesbackfill-share-hashesfor that, sincemigratetakes no throttle flags.took * (1 - d) / doutside any transaction, timed from beforeBEGINto afterCOMMIT. It rests after a cancelled attempt too. It skips the rest after the last batch.percent(of this run's range) andbatch_seqs;seqs_per_secondandremaining_sare over the whole run, rests included, so the ETA holds.One finish path for both commands
apply(plainmigrate, every connect) takes the runners' lock, then callsrun_to_end(connection, backfill, &Throttle::default(), metrics). It runs as anOnlineMigration::ShareHashesstep, which 3.x.x: let migrate --offline-indexes build 013's and 024's indexes with a plain parallel CREATE INDEX in one transaction when no instance is live #745's step loop dispatches the same way in both index modes.finish(backfill-share-hashes) takes the runners' lock, runsserving_or_finished, then callsrun_to_end(connection, Finish, throttle, metrics).run_to_endis A1'sapplybody, moved without changes except that it passesserving.then_some(throttle)tomap_batchesandthrottletorefuse_double_credit, records 2 throughrecord_while_servingwhile frontends serve, and returnsOption<Finished>.backfill-share-hashesgets A1's checks unchanged: the fence and claim re-check under the lock, the F5conversion_bound_coversprecondition before any batch, the frozen end, the double-credit refusal, and the record step.serving_or_finished, under the lock: no cursor with 2 recorded means the backfill has finished, andfinishreturnsFinished { mapped: 0, range: None }(already_complete()). No cursor without 2 is refused (dropped by hand). Fence 1 means "does not permit serving", namingmigrate --defer-share-hashesand plainmigrate. No fence (pre-3.x.x: fence earlier native builds off a database whose 002 share-hash backfill is pending (#582 follow-up) #669) names plainmigrate. 3 or more is a newer release's.Recording 2 while frontends serve
The record is the one transaction that waits on other sessions' locks: the migration lock, which every migrating start takes, and the cursor table's, which
DROP TABLEtakes over every reader of the cursor, an evidence export's included. Unbounded, it would hold a snapshot, then an xid, on the serving primary for as long as anything held either one (#738). Sorecord_while_servingruns it in attempts (record_serving_once):BEGIN, thenset_config('statement_timeout', <throttle's>, true)andset_config('lock_timeout', '2000', true).lock_timeoutcoverspg_advisory_xact_lock(MIGRATION_LOCK)too, which waits in the lock manager as every heavyweight lock does.refuse_newer_fence,check_frozen_end(the cursorFOR UPDATE), thenrecord_2(drop the cursor, delete the fence, insert 2),COMMIT.refusing to wait any longer to record migration 2: something held MIGRATION_LOCK or the share-hash cursor through 20 attempts over about 10 minutes. Every batch committed and no native share repeats a legacy header; 2 is not recorded, and the cursor and the fence stay as they are. Run qbit-prism-server backfill-share-hashes again once it is released, .... A rerun goes straight to the double-credit check and the record.statement_timeoutandlock_timeoutat 0 and waits, as rc.4's and 013's and 017's records do.refuse_newer_fenceandrecord_2are shared by both paths.The double-credit check under the throttle
A1's
refuse_double_creditchunks[end_seq, last]. Now each statement, the initialmax(share_seq)included, runs in athrottled()transaction. Chunks use the throttle's sizing and halving, and rest by the duty cycle between them. The chunk statement and A1's correctness argument are unchanged.The CLI (
tools.rs)Command::BackfillShareHashes:throttle_flag(Throttle::check_*), parses each flag and holds it to the throttle's own check, so a bad throttle (--statement-timeout-ms 5001included) exits 2 before anything connects.PRISM_DATABASE_URLalone (url_from_env). It runsLedger::connect_operator(url, false), the start gate asmigratepasses it, with no registration. Then it runsLedger::backfill_share_hashes(&throttle)on a detached connection, as the online runners do, so the session lock ends with it.{"mapped", "next_seq", "end_seq", "seqs", "elapsed_ms", "recorded": true, "already_complete": false}. On a database whose backfill had finished:{"mapped": 0, "next_seq": null, "end_seq": null, "seqs": 0, "recorded": true, "already_complete": true}, exit 0.finishlogs that it is taking the runners' lock, so a run queued behind amigrateisn't silent.migrate --defer-share-hashesoutput, the start gate's WARN, and themigrate --helptext now namebackfill-share-hashesas the way to finish.Self-check
self-checksamples the backfill beside the heartbeats, the audit completeness and the submission hold, apart from #742's bounded integrity report. So the field is reported even when the node or a local check fails.Ledger::inspect_share_hash_backfill(url): one read-only connection under one 5 s deadline, which bounds the whole read, the connect included; the server's statement and lock timeouts are the same 5 s. One error text:reading migration 2's share-hash backfill took more than 5 seconds.share_hashes::pendingreads the cursor and its fence in one statement, throughcursor_row, whichprogressshares: the relkind check, the read, and a 42P01 (the table dropped by a concurrent record of 2) taken as nothing pending, in one place. The recent range's columns are read throughto_jsonb(row), sodeferred_atand a cursor without those columns are tolerated.share_hash_backfill: {"state": "pending", fence, start_seq, next_seq, end_seq, remaining_seqs, recent_min_height, recent_start_seq, started_at, updated_at}, or{"state": "unknown", "error": ...}when the read fails. A connection or protocol failure's text can carry the URL's parts, so it readsthe database could not be read; a database error or the deadline is reported as itself.WARNING:line for either: the cursor and the remedy, or that the backfill could not be read and how to read the cursor by hand.skip_serializing_if), soqbit.prism.self-check.v2's shape is unchanged once 2 is recorded. qbit-tools must tolerate the field while a backfill is pending or unreadable.remaining_seqsisend_seq - next_seq, an upper bound on the legacy rows left. An exact count would read the whole remaining range on the primary.Evidence export (
scripts/prism-recovery-evidence.sql)required_versionsline (C2's) is untouched.understood constant jsonb := '{…, "share_hash_backfill_pending": 2}', the highest value startup accepts per capability. It refuses a name not in it, and a value outside1..=max, with startup's wording ("understands % 1 to % only").pg_class), never the cursor table. Every session of the parallel export runs the preamble, and a session that held the table's lock while it waited for the others would hold up the record of 2. The refusals:migrate --defer-share-hashesto permit serving and plainmigrateto finish;migratealone;share_hashes_deferredflag (\gset, set before the first export) means a native cursor exists. The preamble guarantees it is at fence 2.share_hashesstatement becomesFROM (… WHERE NOT :'share_hashes_deferred'::boolean) mapping ORDER BY header_hash COLLATE "C". The planner folds the constant, and the parallel cutter's range predicate still lands on the outer query.share_hashes_deferredrecord is read last, after the integrity report and before the completion marker, in the export's snapshot, once aDOblock has required the cursor's row. Its fields arestart_seq,next_seq,end_seq,recent_min_heightandrecent_start_seq, the last two throughto_jsonb; timestamps anddeferred_atare not evidence. So the export takes the cursor table's lock only at its end and commits right after. If 2 was recorded after the snapshot, the table is gone by then and the export fails: export again.Summarizer and parallel cutter
prism-recovery-evidence.py:share_hashesrows beside it, in either order;records.share_hashes.deferred(the cursor) and anote: share_hashes deferredline;record(), so--jobs Nstays byte-identical (tested).prism-recovery-evidence-parallel.py: the coordinator also readsshare_hashes_deferred. When it is set, the share hashes are one empty part, so no sampling and no empty sessions, and the note saysshare_hashes in 1 (deferred: …). The cut is unchanged: the cursor's record is in the tail part, which commits as soon as it has read it, and no other session reads the cursor table. The parallel export stays byte-identical to the serial one (tested, gated).Docs
docs/prism-rust-migration.md:backfill-share-hashesor plainmigrate, both throttled, and the record's bounded attempts;backfill-share-hashes" (when and how, the snapshot rule from 3.x.x: every share append UPDATEs the qbit_prism_cluster singleton (ledger_clock_ms), so any snapshot held on the primary bloats it and saturates ORDER_LOCK in ~20 s at 400 shares/s; derive the clock from append-only state (rc.5) #738, the throttle table with the 5,000 ms cap, what it refuses,already_complete, how to watch it, interrupting and resuming);jq 'del(.records.share_hashes)', and the legacy-mapping query to run on a paused standby once 2 is recorded);docs/prism-ledger-ops.md: a new runbook section, "Finish a deferred share-hash backfill after go-live" (check, with"state"; choose the throttle; run; watch with the cursor, theorder_lock_holdandshare_ackseries andpg_stat_activity; stop and resume; the end, with the record's retries andalready_complete; afterwards), and the evidence comparison in the one-way migration runbook.The recovery test helpers
tests/support/recovery.rs'sparallel_exportandsummarize_withnow refuse an export script edited after the test binary was built:scripts/prism-recovery-evidence.sql changed after this test binary was built: the serial export runs the copy built in, the parallel exporter and the summarizer the file. Rebuild and rerun. See "The deferred-export failure in the local full suite" below.ensure_same_rowsnow prints the first differing line of both exports.Tests
Local, on a private PostgreSQL 16 cluster (fsync,
full_page_writesandsynchronous_commitat their defaults),PRISM_TEST_REQUIRE_INTEGRATION=1,--test-threads=4, a fresh database per binary, on the final tree, rebased on 3.x.x at 2d103c3.ledger_postgresran last, after the test fix below; that fix touched only its own module, and the other binaries ran on the tree before it:cargo fmt --all -- --check: clean.cargo clippy --workspace --all-targets -- -D warnings: clean.compileall,check_gate_env_reads.py,check_toolchain_pin.py,check_prism_settings.py,check_deleted_test_map.pyandcheck_prism_pool_acquires.py: all pass. The pool-acquire map gains three sites,share_hashes.rs::throttled#1::connection .begin(),share_hashes.rs::record_serving_once#1::connection .begin()andmigration.rs::backfill_share_hashes#1::self .acquire(), andapply#1's.begin()is renamedrun_to_end#1.tests.test_prism_recovery_evidence,_jobs,_parallel,test_check_prism_pool_acquires,test_check_gate_manifest,test_check_e2e_scenarios,test_check_prism_settings,test_check_deleted_test_map,test_check_gate_env_reads,test_run_python_test_shard,test_run_rust_test_shard,test_prism_legacy_import_admission_gate,test_mainnet_compose_contract). The skips aretest_mainnet_compose_contract, with no docker CLI here, andtest_prism_legacy_import_admission_gate.RealSchemaTests, which needs a database URL and the server binary.--lib: 692 passed, 0 failed, 2 ignored.--test ledger_postgres, the whole binary: 250/250, including all 36share_hash_backfilltests (10 new), 3.x.x: let migrate --offline-indexes build 013's and 024's indexes with a plain parallel CREATE INDEX in one transaction when no instance is live #745'smigrate_defer_share_hashes_with_offline_indexes_permits_serving_in_one_runamong them. The first run on the rebased tree failed two of A2's own tests: the cap refused the CLI test's--statement-timeout-ms 60000, now 5000; and the record test's 2 s statement timeout raced its 2 s lock timeout, so it now runs under the cap's 5 s, where only the lock timeout can cut a wait.plain_migrate_maps_a_deferred_backfill_at_the_default_throttlenow runs plainmigratein both index modes. Rerun whole after the fix: 250/250.--test config_cli: 30/30.--test migration_rollback: 13 passed, 2 ignored.self_check_cli6/6,audit_completeness3/3,pool_fee_guard8/8,postgres_failover3/3 (it includesoffer_standby_flush.rs).live_regtest(live_migration_lifecycle.rs) needs the pinned qbitd and runs weekly, not per PR.PRISM_TEST_GATE_MANIFEST): all 405 gated tests thattest/prism-gated-tests.txtlists for these binaries executed (243, and 162 lib). None was skipped or failed, and none executed unlisted. The list gains the 11 below.New gated tests, all in
ledger_postgres::share_hash_backfillunless named otherwise:backfill_share_hashes_maps_the_rest_while_frontends_append_and_records_2. It runs the real binary, at--statement-timeout-ms 5000, while a frontend appends: one batch is held on a legacy header while natives are appended. The legacy mapping ends up as the whole backfill's, the natives keep their own headers, the end stays frozen, and 2 is recorded. It checks the JSON output ("already_complete": false), thatinspect_share_hash_backfillreads the cursor before and nothing after, and that a second run succeeds with{"recorded": true, "already_complete": true, "mapped": 0, "seqs": 0}.backfill_share_hashes_refuses_to_record_2_over_a_native_share_repeating_a_legacy_header. A1's double-credit refusal is still made through the new command, with the cursor at(end, end), the fence at 2 and 2 unrecorded.backfill_share_hashes_refuses_a_backfill_that_does_not_permit_serving. The binary at fence 1 is refused by the start gate, naming bothmigrateremedies, and maps nothing. Under the lock, with the fence edited after the gate, it refuses at 1, with no fence, and at 3. A missing 017 conversion bound is refused before any batch. A finished database has nothing to map:already_complete(),mapped0 and no range.backfill_share_hashes_runs_each_batch_under_its_statement_timeout_and_rests_between_batches. A test trigger on the cursor logs every batch'scurrent_setting('statement_timeout')and time, and a statement trigger makes each mapping statement take 150 ms. Every batch ran under1500ms, covered at most 5,000share_seq, and started at least 0.5 s after the last (duty 0.25: the rest is at least 450 ms).a_batch_past_the_throttles_statement_timeout_is_retried_at_half_its_size. A trigger holds every mapping statement for 1 s: 4,000, then 2,000, then 1,000 time out at 300 ms, and the run stops with the "smallest … smaller--max-batch, or else a larger--statement-timeout-ms, at most 5000" error, the cursor unmoved. Then only the first two attempts are slowed: the first committed batch is 1,000, none exceeds 4,000, and 2 is recorded.plain_migrate_maps_a_deferred_backfill_at_the_default_throttle(A1-F1). With the same triggers, plainmigrate's batches all ran under2s, at most 5,000share_seqeach, at least 0.25 s apart, once with concurrent index builds and once with--offline-indexes(3.x.x: let migrate --offline-indexes build 013's and 024's indexes with a plain parallel CREATE INDEX in one transaction when no instance is live #745).the_double_credit_check_runs_under_the_throttles_statement_timeout(note 2 from A1). Every batch is done, and a test holdsACCESS EXCLUSIVEonqbit_share_ledger. The check's first read is cancelled at the throttle's 300 ms, as a statement timeout, in under 4 s, not at the pool's 5 s lock timeout. The run stops before recording 2 and namesbackfill-share-hashes.the_record_of_2_waits_out_a_reader_of_the_cursor_in_short_attempts(review finding 1). Under the cap's 5 s statement timeout, so that only the 2 s lock timeout can cut a wait short of 4 s. An open transaction that read the cursor stands in for an export. The record'sDROP TABLEis seen waiting in at least two distinct attempts inpg_stat_activity, none older than 4 s, with the cursor and the history unchanged. Once the reader commits, the next attempt records 2, within a 60 s bound: nothing hangs.the_record_of_2_stops_cleanly_behind_a_held_migration_lock_and_records_once_released(review finding 2). Under the same 5 s statement timeout, a transaction holdsMIGRATION_LOCK. A run allowed three attempts stops after at least 6 s withrefusing to wait any longer … through 3 attempts,Run qbit-prism-server backfill-share-hashes again once it is releasedandcanceling statement due to lock timeout, leaving the cursor at its end, the fence at 2 and 2 unrecorded. A patient rerun is seen waiting on the advisory lock in at least two attempts, none older than 4 s, and records 2 once the lock is released.self_check_reports_a_deferred_backfill_without_failing_on_it. The realself-checkagainst an unreachable node reports the field ("state": "pending") and the warning, and fails only on the node. Both are gone once 2 is recorded. With the cursor replaced by a view, so that the read fails, it reports{"state": "unknown", "error": …}and its warning, and still fails only on the node.migration_rollback::the_evidence_export_defers_share_hashes_while_the_backfill_permits_serving. A 2.x source with heights spread so that the recent range is a quarter of the ledger goes throughmigrate --defer-share-hashes.--jobs 3are byte-identical, with "share_hashes in 1 (deferred…)".share_hashesis{count 0, sha256 of nothing, deferred: the cursor}, with the note. Every other record equals the source's.migrate --defer-share-hashesand plainmigrate. With the fence removed, as a build before 3.x.x: fence earlier native builds off a database whose 002 share-hash backfill is pending (#582 follow-up) #669 left it, the hint names plainmigratealone.backfill-share-hashes, the whole summary equals the source's.Unit and CLI:
share_hashes::tests::a_throttle_keeps_batches_within_its_size_and_rests_by_its_duty_cycle: the defaults, the clamp, the floor below rc.4's, the rest math, every refused value (5,001 ms and 600,000 ms included), and eachcheck_*bound.share_hashes::tests::the_record_of_2_backs_off_to_thirty_seconds_for_about_ten_minutes: backoffs 2, 4, 8, 16, 30, 30 s; 2 s lock timeout; 9 to 11 minutes in all at the defaults;with_record_attempts's arithmetic and bounds.migration::tests::recovery_evidence_understands_the_capabilities_startup_understands: the export'sunderstoodmap equalsNATIVE_CAPABILITIES, names and values (fence 2 included), and the export checks against that map alone. Extended for A1-F6.tools::configuration_tests::backfill_share_hashes_parses_its_throttle(5,000 ms accepted, 5,001 refused),config_cli::backfill_share_hashes_refuses_a_bad_throttle_before_connecting(exit 2, "1 to 5000 milliseconds",--helpshows the three knobs and defaults), andbackfill-share-hashesadded todatabase_only_cli_commands_reach_postgres_without_reading_seeds.self_check_cli: the three reports for an unreachable database now carry{"state": "unknown", "error": "the database could not be read"}.Mutations
Each mutation was applied to the committed tree, its tests run, and reverted with
git checkout;git status --porcelainwas empty after each.Review round, at the final tree:
lock_timeout0, its statement timeout keptthe_record_of_2_waits_out_a_reader_of_the_cursor_in_short_attempts,the_record_of_2_stops_cleanly_behind_a_held_migration_lock_and_records_once_releasedstatement timeout, notlock timeoutstatement_timeoutandlock_timeoutboth 0DROP TABLE qbit_prism_share_hash_backfillwaiting, not 2: one that waits without a lock timeout is never seen again"; "the record waited for the migration lock without a bound"--statement-timeout-msa_throttle_keeps_batches_within_its_size_and_rests_by_its_duty_cycle,backfill_share_hashes_parses_its_throttle,config_cli::backfill_share_hashes_refuses_a_bad_throttle_before_connecting--statement-timeout-ms 5001was accepted; the command went on to connectNone)self_check_cli's three unreachable-database reports,self_check_reports_a_deferred_backfill_without_failing_on_itshare_hash_backfillbackfill-share-hasheson a recorded database fails againbackfill_share_hashes_refuses_a_backfill_that_does_not_permit_serving,backfill_share_hashes_maps_the_rest_while_frontends_append_and_records_2First round, run at that round's tree (8e560459, on #743's first commit). The review round reworked some of these lines (M1's
refuse_unless_servingis nowserving_or_finished), and its own mutations above cover what changed:refuse_unless_servingaccepts any fencebackfill_share_hashes_refuses_a_backfill_that_does_not_permit_serving…runs_each_batch_under_its_statement_timeout…,plain_migrate_maps_…,a_batch_past_…1min; the always-slow run succeeded…runs_each_batch_under_its_statement_timeout_and_rests…,plain_migrate_maps_…a_batch_past_the_throttles_statement_timeout_is_retried_at_half_its_sizemigrateat rc.4-like settings (50,000, 15 s, duty 1) instead of the defaultsplain_migrate_maps_a_deferred_backfill_at_the_default_throttleshare_seqbatches under15sBEGINthe_double_credit_check_runs_under_the_throttles_statement_timeoutmigration_rollback::the_evidence_export_defers_…recovery_evidence_understands_the_capabilities_startup_understandsNATIVE_CAPABILITIESself_check_reports_a_deferred_backfill_without_failing_on_itshare_hash_backfill--duty-cyclenot checked by clapconfig_cli::backfill_share_hashes_refuses_a_bad_throttle_before_connectingshare_hashesrows beside a deferraltest_a_share_hash_deferral_is_refused_beside_rows_twice_or_late(now…_or_after_completion)test_a_pending_share_hash_backfill_exports_its_cursor_once_and_the_hashes_in_one_partThe local full suite
At this PR's head
fa7b9ada(lib and 85 test binaries,live_regtestexcluded, PostgreSQL 16, 4 threads, 35 min): 2,009 passed, 0 failed.Earlier, the parent's local full suite at c1896662, the first round's commit, on this host: 1,987 passed, 6 failed.
The deferred-export failure (
migration_rollback::the_evidence_export_defers_share_hashes_while_the_backfill_permits_serving,printed 238168 bytes, the serial export 238168, first differing at line Some(409)) was a build/run skew in the test harness, not the export. The serial export runsrecovery::SCRIPT, the SQL compiled into the test binary (include_str!). The parallel exporter readsscripts/prism-recovery-evidence.sqlfrom disk when it runs. This review round's fix moved the deferral record in that file while the suite ran (its compile phase was over). In c1896662's layout, 0-based line 409 is theshare_hashes_deferredrecord, the first line of the tail, followed by threeactive_carrylines,integrityandcomplete. In the edited file it followsintegrity. So the two exports held the same lines in a different order, the same bytes, first differing there.active_carry.--test-threads=1undertaskset -c 0,1, in each layout, c1896662's and the final one. The database didn't change between the two exports, and the export is byte-comparable.parallel_exportandsummarize_withrefuse the skew by name before anything runs (checked: 3 of 3 runs of the skewed build stop at the message). At the final tree, 20 of 20 more passed the same way.The other five are the host-load class (
canceling statement due to lock timeout×3,deadline has elapsed,proxy connection task failed: Broken pipe, in a lib run that took 657 s against about 300 s unloaded). Each rerun alone,--test-threads=1, in a fresh database, at the final tree:--libcoordinator::candidate_lease_tests::a_forward_database_clock_step_keeps_the_holders_lease_through_its_landing--libledger::candidates::park_tests::advanced_state_is_not_parked_by_a_stale_decode--libledger::connect::acquire::job_tests::postgres_job_checkouts_start_on_first_poll_and_recover--libledger::connect::acquire::tests::postgres_checkout_boundaries_and_callers--test compact_runtime_e2eissued_expiry_during_sql_wait_does_not_publish_or_renew_original_identityNone touches the share-hash code. The four lib tests also passed in this round's 4-thread
--libgate.Review
Findings A1 deferred to this PR
migrateon fence 2 ran rc.4's unthrottled batches beside serving frontends): fixed. One path,run_to_end, with the defaultThrottle;plain_migrate_maps_a_deferred_backfill_at_the_default_throttlepins it.capability_value <> 1and any cursor; the capability test compared names only): fixed as above, with the value comparison in the unit test.deferred_atis tolerated, being read by name, never exported. (2) The throttle governs the chunked double-credit check. (3)backfill-share-hashesrunsconversion_bound_coversbefore any batch, through the sharedrun_to_end, and a test covers it. (4) and (5) need nothing here./code-review highof c1896662: all ten fixedcount(*)of the cursor in every session, the coordinator's included, holding the table's lock until each committed. A record'sDROP TABLEqueued behind the coordinator, a part queued behind theDROP, and the coordinator waited in Python for that part. Fixed on both sides. The export reads only the catalog in the preamble and the cursor last, in the tail part, which commits right after. The record waits at most 2 s a lock an attempt and retries (2 below). So the export holds the cursor's lock for no longer than the end of its tail part, and nothing else in it does. Test:the_record_of_2_waits_out_a_reader_of_the_cursor_in_short_attempts.statement_timeoutandlock_timeoutat 0. It now runs with a transaction-local 2 slock_timeoutand the throttle's statement timeout. On 55P03 or 57014 it rolls back, backs off from 2 s doubling to 30 s, logs each wait, and stops after 20 attempts (about ten minutes) namingMIGRATION_LOCKor the cursor, the minutes, andbackfill-share-hashesto rerun. The fence-1 path is unchanged. The docs' "brief transaction at the end" now describe the attempts. Tests:the_record_of_2_stops_cleanly_behind_a_held_migration_lock_and_records_once_releasedand the backoff unit test.--statement-timeout-msis capped at 5,000 ms (MAX_STATEMENT_TIMEOUT_MS). A timed-out smallest batch or chunk says to run with a smaller--max-batch, or else a larger--statement-timeout-ms, at most 5000. Tests: the throttle unit test, the CLI parser test, andconfig_cli.{"state": "unknown", "error": …}and a warning; the field is absent only when the read succeeded and nothing is pending. Tests:self_check_reports_a_deferred_backfill_without_failing_on_itand threeself_check_clireports.migrate's fence-2 error namesqbit-prism-server backfill-share-hasheswith a smaller--max-batchor a larger--statement-timeout-msup to the cap, and no longer impliesmigratetakes them.migrate --defer-share-hashesto serve or plainmigrateto finish; no fence names plainmigratealone. Test: the deferred-export test, both refusals.backfill-share-hasheson a recorded database exits 0 with{"recorded": true, "mapped": 0, "already_complete": true}(and a null range,seqs0). Tests and docs updated.inspect_share_hash_backfillhas one timeout, in one place, with one error text: the 5 s deadline bounds the whole read, the connect included, and sets the server's timeouts.pending()reads the cursor once, with its fence, throughcursor_row, where the relkind check and the 42P01 handling now live, shared withprogress().check_max_batch,check_statement_timeout_msandcheck_duty_cycle, called byThrottle::newand by the CLI's one generic value parser.Codex on #746: a record attempt that committed before it failed
The P2: an attempt can commit and still fail, its COMMIT's reply lost or cut short, and the retry then met the cursor that commit had dropped and reported a finished backfill as failed. Fixed in a second commit:
record_state).an attempt to record migration 2 failed after its COMMIT: its reply was lost or cancelled, but 2 is recorded and the share-hash cursor is gone, so the backfill is doneand succeeds, reporting what it mapped, as any finished run does.backfill-share-hashes, which finds 2 recorded or records it.record_transaction's comment says so.ledger::migration::share_hashes::record_tests::a_record_attempt_that_committed_before_it_failed_finishes_the_backfill(gated, lib). A test-only fault hook, in the pattern of the candidate claims'faultsand keyed by schema, lets the first attempt commit and then return PostgreSQL's own 57014.backfill-share-hashes'sfinishreports the backfill done, with 2 recorded and the cursor and the fence gone. A unit test pins the four states the read can find. Mutation: without the re-check, the test fails withrelation "qbit_prism_share_hash_backfill" does not exist, the undefined-table error Codex described.-D warnings;--lib694 passed, 2 ignored;ledger_postgres share_hash_backfill::36/36;config_cli30/30; the Python checks (the pool-acquire site renamedrecord_transaction#1) and 396 unittests, 2 skipped; the gate manifest for those 199 gated tests, all executed.Codex on #746: a missing capability table read as a finished backfill
The second P2: every read of the cursor took any 42P01 for the cursor dropped since its look-up and read it as nothing pending, but
pending()also reads the fence fromqbit_prism_schema_capabilities. A cursor beside a missing capability table read as a finished backfill, andself-checkomitted both the field and the warning. Fixed in a third commit:cursor_rowlooks it up again, in one short statement. Otherwise the read's own error goes on, underreading migration 2's share-hash backfill cursor, andself-checkreports{"state": "unknown", "error": "...relation \"qbit_prism_schema_capabilities\" does not exist"}with its warning. Both readers,pending()(self-check) andprogress()(every start,migrateand the command), go through that one place. The record's re-check has no such shortcut.share_hash_backfill::self_check_reports_a_deferred_backfill_without_failing_on_itnow renames the capability table beside a pending cursor and requiresunknownwith the missing relation named, and the warning. The gated lib testpostgres_tests::a_cursor_dropped_after_its_look_up_reads_as_nothing_pendingdrops the cursor between its look-up and its read, through a test-only fault the record test's hook now shares, and requires both readers to read nothing pending. The lib tests move toshare_hashes/postgres_tests.rs.relation "qbit_prism_share_hash_backfill" does not exist.-D warnings;--lib695 passed, 2 ignored;ledger_postgres share_hash_backfill::36/36;self_check_cli6/6;config_cli30/30; the Python checks and 396 unittests, 2 skipped; the gate manifest for those 201 gated tests, all executed.Deviations
submission-hold showthrough at fence 2.share_hashes_deferred), not a hashed kind. So a complete export's summary is byte-identical to rc.4's, and only a pending one changes. The plan's NOTICE became the summarizer'snote:line: a psql NOTICE would print once per parallel session.migrate --defer-share-hashesand plainmigrate). The command's own fence check runs under the runners' lock and catches a fence changed after the gate.self-check's field is absent (skip_serializing_if) rather thannullwhen nothing is pending. That keeps every existing pinned report of a migrated database unchanged; a report of an unreadable database now carries"state": "unknown".share_seqa chunk at the defaults) rather than rc.4's 50,000. Its total time is governed by the duty cycle either way.Risks
share_seqbatch and as long again resting, so about 5,500share_seq/s: three to four hours for 65.9M shares. This is an estimate from the measured 83 to 94 µs a row, unmeasured beside live load. The run holds the runners' lock throughout, so amigratestarted meanwhile waits.order_lock_hold_seconds{holder="append"}and share ACK percentiles and stop on a rise.remote_apply). The batch is then committed locally, and the cursor commits with it, so a failover resumes from the standby's cursor, which is consistent. The record's attempts run under the same timeout: one cut that way has committed locally too, and a failover before the standby applied it leaves the standby's cursor at its end with 2 unrecorded, which a rerun records.MIGRATION_LOCKor a transaction left open on the cursor for ten minutes stops the run with 2 unrecorded; frontends keep serving, and the rerun is one command that goes straight to the record.records.share_hashes.deferredas "compare later", and tolerateshare_hash_backfillin self-check while a backfill is pending or unreadable.What the pair rehearsal should measure
One throttled-backfill hour beside live load, defaults first:
share_seqper second, from the progress lines and the cursor'supdated_at, and the projected total for 65.9M;qbit_prism_database_order_lock_hold_seconds{holder="append"}p50/p99, against the same hour without the backfill;qbit_prism_share_ack_seconds{result="accepted"}, against the same;max(age(backend_xmin))overpg_stat_activity(in transactions) and the oldestxact_start, sampled every second, the backfill's backend among them;--duty-cycle 0.25changes the first three, to calibrate the default;--jobs 8), the deferred summary, and thejq-filtered comparison with the source's.🤖 Generated with Claude Code