Skip to content

3.x.x: compute the carry-forward integrity report's mismatches and drift once each, as migration 026 (#737) - #744

Merged
RobertClarke merged 1 commit into
3.x.xfrom
RobertClarke/rc5-integrity-report-once
Oct 7, 2026
Merged

RobertClarke merged 1 commit into
3.x.xfrom
RobertClarke/rc5-integrity-report-once

Conversation

@RobertClarke

@RobertClarke RobertClarke commented Oct 7, 2026 •

Copy link
Copy Markdown
Member

Summary

#737's F4. qbit_carry_forward_integrity_report() as 001 defines it runs each of its two expensive sets twice: once to count it and once to list it. Migration 026 replaces it so each runs once. The report is evaluated as 001's is, by 001's own subqueries in 001's order.

  • Why. The report is CPU-bound. On a production-sized ledger (2,753,849 active carry rows, on a standby with replay paused), EXPLAIN ANALYZE put qbit_carry_forward_integrity_mismatches() at 20.29 s and qbit_carry_forward_current_drift() at 9.14 s, and the report took 57.42 s. self-check, fatal-state clear and the import admission gate all wait for it, and a clear holds its transaction open that long while the tip may move. work_mem doesn't help (1 GB: 54.98 s).
  • Estimated effect. About 57 s → about 29 s at production size. That is the sum of the two EXPLAIN ANALYZE parts, not a timed 026 run. Measured locally on 400,000 rows: 2.30 s → 1.21 s (below).

What 026 changes

migrations/026_carry_forward_integrity_report_once.sql runs CREATE OR REPLACE FUNCTION qbit_carry_forward_integrity_report():

  • 001's three subqueries are kept word for word: the checked_active_rows count and the two listings. The listings are the mismatch and drift jsonb_aggs with their per-row objects, ORDER BY clauses and COALESCE(…, '[]'). I checked this mechanically, as a whitespace-normalized substring match against 001's body.
  • Each is evaluated once, in WITH listed AS MATERIALIZED (…), in 001's order: the count, the validator's listing, then the drift listing. A run that fails stops where 001's does, after the same work. Traced with notice-raising wrappers: 001 calls validator, drift, drift, validator; 026 calls validator, drift.
  • Without MATERIALIZED, PostgreSQL inlines the CTE and copies each listing's subquery into every reference.
  • mismatch_count and current_drift_count are jsonb_array_length(...) of their listings. That is the same number 001's separate count(*) pass returns, under the same snapshot.

This deviates from the plan's SQL sketch (WITH mismatch AS MATERIALIZED (SELECT * FROM …), count(*) FROM mismatch), because that design doesn't evaluate the listing the way 001 does. See the next section.

Plumbing follows 025 (#710):

  • REQUIRED_SCHEMA_VERSIONS and NATIVE_MIGRATIONS gain 26.
  • migrate_schema runs 026 under if !versions.contains(&26) || !versions.contains(&3) and records 26 only when it is missing. So 026 runs again whenever 001 just ran, as 025 runs again after 011. 001 runs only without 3, and a recorded history without 3 is refused before any DDL (migration.rs ~2886). For now the second clause therefore only ever fires on a fresh or 2.x.x source, where 26 is missing anyway (see Review).
  • ONLINE_MIGRATIONS is untouched.
  • scripts/prism-recovery-evidence.sql's required_versions gains 26.
  • The 29 version pins and ALL_VERSIONS: [i32; 25] gain 26.
  • ledger_2x::undo_006 deletes 26 beside 25 and restores 001's report by hand. That restore is still needed: a record that keeps 3 never runs 001 again. A comment says so. Its validator_001() became function_001(name), used for both the validator and the report.

No capability and no quiesce proof. rc.4's require_schema_version accepts an unknown recorded migration with a warning, and 026 declares nothing. So rc.4 frontends keep starting beside it and read the same report.

Equivalence evidence

ORDER BY uniqueness.

  • Drift: encode(p2mr_program,'hex') is unique per row. Drift is a full join of two per-program aggregates on the program; p2mr_program is NOT NULL in both qbit_payout_carry_forward and qbit_payout_carry_forward_current, and hex is injective.
  • Mismatches: (block_height, carry_forward_seq) is not unique since 011's as-issued rule, which 025 keeps. Every finding without a carry row has a NULL seq, so all of one height's such findings tie: block, manifest-account, evidence_missing, payout_entry_* and payout_entry_unexpected findings. A manifest that names one account twice also yields two findings with the same non-NULL seq (reproduced: seq 11 twice, duplicate_evidence and duplicate_evidence,gross_amount).

001's order for tied rows is plan-dependent, so no tiebreak was added.

  • In 001, the mismatch jsonb_agg reads the validator's own sort, (block_height, carry_forward_seq NULLS LAST, payout_order_key, miner_id), as presorted (PG16 presorted aggregate; no second Sort in the plan). Tied findings therefore come out in the validator's order.
  • That order leaves ties of its own: one account's evidence, payout and manifest findings, two marked blocks at one height, NULL order keys. Those come out in whatever order the plan and sort leave them.
  • 001's output for the same rows differs between work_mem 4MB and 64kB.
  • So 026 can promise the same evaluation as 001, not a fixed order. 026 keeps the same listing subqueries, so ties come out as 001's own evaluation leaves them.

Why the per-set CTE design fails.

  • Rows read back from a CTE carry no sort order in PG16, so the planner adds Sort (block_height, carry_forward_seq) over the CTE scan.
  • In memory, that sort leaves presorted input as it is. Once it spills, its merge can reorder a tie group larger than one run.
  • With one marked block naming 1,000 miners and none of their evidence (2,000 findings tied at one height), at work_mem 64kB, 001 and the per-set design differed at 1,405 of 2,000 positions, in one statement and one snapshot. At 4MB they agreed. 026 matched 001 in both cases, at 8df472ab and with this round's reordered body.

Plans. The listing subtrees of 026's plan are node-for-node 001's (EXPLAIN VERBOSE diff; only alias numbering differs). Each set function is called once per 026 report and twice per 001 report (counted with sequence-bumping wrappers).

Other states compared on a scratch database, reordered body: the tie fixture with 16 NULL-seq findings at one height and 20 mismatches in all, the duplicated manifest account, and the 2,000 tied findings at 64kB and 4MB. All equal as jsonb and as text.

Flag for review: tied mismatch findings have no deterministic order in 001 itself, beyond the validator's four keys. That is harmless today: self-check, clear and the gate refuse any mismatch, and the evidence summarizer refuses any NULL-seq finding and drops the list from the summary. A tiebreak would change 001's output, so it's left to you.

Tests

New gated tests (in test/prism-gated-tests.txt):

  • offer_lifecycle::integrity_report_026_equals_001_on_clean_mismatch_and_drift_fixtures. 001's report is installed beside 026's (cut from the frozen 001 like validator_011()), and both run in one statement, each evaluated once. They must be equal jsonb and text on:

    • no carry rows, then clean rows;
    • legacy breaks, two at one height;
    • an as-issued block whose four findings tie at its height;
    • drift of each shape;
    • 2,000 tied findings at the default work_mem and at 64kB, in a transaction.

    It also counts each set run once per 026 report and twice per 001 report. With both sets made to raise, it checks that 001's report and 026's both fail in the validator.

  • offer_lifecycle::migration_026_is_recorded_once_and_survives_remigrate. On a v2.0.2 fix: bound candidate replay and audit finalization #258 source with 11 undone, 26 is recorded once. The report's catalog row (xmin, prosrc) survives a migrate that runs 011 and 025 again and one with nothing to do. A record without 26 over 001's report gets 026 once, and a later migrate leaves it. A record with 26 but not 3 is refused before any DDL ("… without migration 3"), and the report's source is still 026's, catalog row untouched.

Mutation checks:

  • The per-set CTE body (round 1): the equivalence test failed at the 64kB step, after passing every earlier one.
  • This round's order fix: with 026's body as at 8df472ab (drift listing first, count outside the CTE), the equivalence test failed at the new order check, after passing every earlier step. 001's report failed in the validator; 026's failed with qbit_carry_forward_current_drift failed.
  • This round's re-run clause: with it dropped (026 again only when 26 is missing), migration_026_is_recorded_once_and_survives_remigrate still passes, as it must. The record with 26 but not 3 is refused before any DDL, so no migrate reaches 026's guard right after 001 with 26 recorded. Today no test can tell the clause apart.

Gates for this round (host rules: heavy.sh, 4 test threads, fresh database per run):

Gate Result
cargo fmt --all --check clean
cargo clippy --locked --workspace --all-targets -- -D warnings clean
cargo test --locked -p qbit-prism-server --no-fail-fast --lib --test offer_lifecycle --test ledger_postgres --test migration_rollback -- --test-threads=4 lib 678 passed, 0 failed, 2 ignored; ledger_postgres (the only binary that includes ledger_2x.rs, so undo_006) 210 passed; migration_rollback 12 passed, 2 ignored; offer_lifecycle 26 passed
check_prism_pool_acquires.py, check_prism_settings.py, check_deleted_test_map.py, check_gate_env_reads.py all pass
python3 -m unittest tests.test_prism_recovery_evidence_parallel tests.test_prism_recovery_evidence 26 passed

Full suite at 8df472ab (the previous revision of this commit; this round changed 026's evaluation order, migrate's 026 guard, tests and docs, and CI re-runs everything):

Run at 8df472ab Result
Full PostgreSQL suite (--lib + 85 tests/*.rs binaries but live_regtest, --test-threads=4) 86 binaries: 1,949 passed, 0 failed, 28 ignored (about 34 min). The lib binary was 678 passed, 2 ignored. The gate manifest has 812 executed, none skipped or failed, and none outside test/prism-gated-tests.txt.
The two live_regtest tests that check the report (real_two_server_mining_failover_audit_and_reorg, real_ctv_maturity_broadcast_and_confirmation, pinned qbitd 1.0.0) 2 passed
python3 -m unittest tests.test_prism_legacy_import_admission_gate with a server binary built from the branch 38 passed, including both RealSchemaTests: PASS carry-forward integrity (mismatch 0, drift 0) on a schema migrated through 026
Recovery-evidence Python tests (…_parallel, …, …_jobs) 26 + 14 passed

Not run locally: the rest of live_regtest, and the 13 #[ignore] database contracts CI's shard runner selects with --ignored (issued_job_dependency, observability_database, compact_runtime_scale, one stratum_admission_postgres test). None of them reads the report.

Timing

PG16, work_mem 4MB, a scratch fixture of 400,000 clean legacy carry rows (2,000 blocks × 200 of 4,000 programs), host load about 6. Three alternating rounds, measured on the 8df472ab body; this round's reorder changes no work:

round 1 round 2 round 3
001's report 2.19 s 2.30 s 2.36 s
026's report 1.20 s 1.21 s 1.24 s

The validator alone took 0.74 s and the drift check 0.32 s, so 001 is about two of each and 026 about one. At production size, about 29 s is an estimate from N1's EXPLAIN ANALYZE parts (20.29 s + 9.14 s); no 026 run was timed there.

Docs

  • docs/prism-rust-migration.md:
    • a 026 paragraph after 025's: the estimated time, evaluation like 001's, and the re-run rule;
    • the gate section's report time is now "about a minute before 026, an estimated half minute since";
    • the startup gate no longer says "migrations 2 through 18"; it requires every native migration the release ships and points at REQUIRED_SCHEMA_VERSIONS;
    • the rehearsal's migration-transaction list gains 026.
  • docs/prism-ledger-ops.md: a 026 note after 025's bullets, covering the estimated time and the same evaluation as 001.
  • No rc.5 release-notes draft exists in the repo, so none was created.

Review

A /code-review high of 8df472ab found no correctness bug. Of its hardening and doc findings:

Fixed:

  • Re-run 026 whenever 001 (re)defines the report in the same run, as 025 after 011.
    • The change: migrate_schema now runs 026 under !versions.contains(&26) || !versions.contains(&3), the clause by which 025's guard knows 011 ran, and records 26 only when it is missing.
    • The premise: the reported scenario ("a record with 26 but not 3 takes the 2.x path, reruns 001, then skips 026") can't happen today. migrate_schema refuses a recorded history without 3 before any DDL. I checked with the binary: the migrate exited 1 with "refusing a non-native qbit_prism_schema_migrations before any DDL … without migration 3", and the report's md5 and the record were unchanged. So 001 runs only on a fresh or 2.x.x source, where 26 is missing anyway. The new clause is the explicit 025-style dependency and keeps 026 after 001 if that refusal is ever relaxed.
    • The test: a record with 26 but not 3 is refused and keeps 026's report.
    • The mutation: dropping the re-run clause can't make that test fail, because the refusal comes first. (run: the test passed without it.)
    • undo_006: its manual restore of 001's report stays: the record it builds keeps 3, so no migrate reruns 001 there. A comment says so.
  • Evaluation order. The CTE runs the count, then the validator's listing, then the drift listing, as 001 does. I also moved the count in, because the CTE is evaluated before the outer projection: with only the listings swapped, the validator would run before the count. The equivalence tests pass, and a report whose sets both fail now fails in the validator, as 001's does (the 8df472ab order fails the new check with qbit_carry_forward_current_drift failed).
  • Docs. The about-29 s and "about half a minute" figures are marked as estimates from the two EXPLAIN ANALYZE parts (20.29 s + 9.14 s), not a timed 026 run. The tie-order claim is narrowed to "evaluated the same way as 001, by the same listing subqueries". Places: docs/prism-rust-migration.md ~104 and ~657, docs/prism-ledger-ops.md ~1299, 026's header and the commit message.
  • Startup gate paragraph (docs/prism-rust-migration.md ~576): instead of "migrations 2 through 18", it now requires every native migration the release ships, from 2 on, and points at REQUIRED_SCHEMA_VERSIONS, so it can't go stale.

Declined:

  • The admission gate script's header comment ("about a minute"). The script is pinned by sha256 in qbit-tools (#1238/#1251), so a comment-only change forces a repin for no behaviour change. It goes in the rc.5 release notes instead.
  • An OFFSET 0 subquery instead of the MATERIALIZED CTE. The CTE's tuplestore holds one row. It spills only with very many findings, which every caller refuses anyway. The CTE form is what the equivalence test pins.
  • A shared cut_function test helper. It's a test-only refactor, not worth the churn now.
  • The rc.4 → rc.5 upgrade note ("run migrate; binary-only no longer works"). It belongs in the rc.5 bump PR's release notes, which the parent will write.

🤖 Generated with Claude Code

…ift once each, as migration 026 (#737)

001's qbit_carry_forward_integrity_report() counts
qbit_carry_forward_integrity_mismatches() and
qbit_carry_forward_current_drift() in two scalar subqueries and lists
them in two more, so each runs twice. Both are CPU-bound. On union's
restored ledger, 2,753,849 active carry rows on a standby with replay
paused, EXPLAIN ANALYZE put the validator at 20.29 s and the drift
check at 9.14 s, and the report took 57.42 s. self-check, fatal-state
clear and the import admission gate all wait for it, and a clear holds
its transaction open that long while the chain tip may move.

Migration 026 replaces the report in place. It keeps 001's subqueries
word for word, the active row count and the two listings, and
evaluates each once in a MATERIALIZED CTE, in 001's order: the count,
the validator, then the drift check, so a run that fails stops where
001's does. Each set's count is its listing's length. Running each
check once is estimated at about 29 s at production size, the sum of
the two parts, not a timed run; on a fixture of 400,000 clean carry
rows the report took 1.2 s instead of 2.3 s.

The report feeds the recovery evidence's source and migrated summaries
and the admission gate, so it must be evaluated as 001's is. Listing a
materialized copy of each set, the first plan, is not. 001's mismatch
order, block height then carry_forward_seq, ties for every finding
without a carry row, whose seq is NULL, and a manifest that names an
account twice repeats a seq. 001 lists tied findings in the order the
validator's own sort leaves them, since its aggregate reads that sort
as presorted. Rows read back from a CTE are sorted again, and once that
sort spills it can reorder ties: with 2,000 findings at one height and
work_mem at 64kB, that design and 001 differed at 1,405 of 2,000
positions. 001's own order of ties changes with work_mem, so no
tiebreak is added.

026 is applied in the migration transaction with no capability and no
shutdown proof, as 025 is, and an earlier binary accepts the unknown
migration with a warning and reads the same report. migrate runs 026
again whenever it runs 001, as it runs 025 again after 011. 001 runs
only without 3, and a recorded history without 3 is refused before any
DDL, so for now that is only a fresh or 2.x.x source, where 26 is
missing anyway.

Two gated tests cover it. One checks the report against 001's,
installed beside it, on empty, clean, legacy-break, as-issued and drift
fixtures and on the 2,000 tied findings at the default and the smallest
work_mem. It counts one run of each set per report, checks that a
report whose sets both fail fails in the validator, as 001's does, and
fails against the per-set CTE design. The other checks that 26 is
recorded once, survives a migrate that runs 011 and 025 again and one
with nothing to do, and is applied once to the record an earlier build
left, and that a record with 26 but not 3 is refused with 026's report
kept. ledger_2x's undo_006 restores 001's report with its version, and
every version pin gains 26.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 7, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-07T21:29:54.718206Z c82e716 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@RobertClarke
RobertClarke merged commit 1a4e353 into 3.x.x Oct 7, 2026
39 checks passed
@RobertClarke
RobertClarke deleted the RobertClarke/rc5-integrity-report-once branch October 7, 2026 21:57
RobertClarke added a commit that referenced this pull request Oct 8, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant