Skip to content

v3.0.0 feat: add prepared-window reference foundation - #327

Merged
djh58 merged 35 commits into
3.x.xfrom
djh58/prism-b1-window-reference
Sep 11, 2026
Merged

djh58 merged 35 commits into
3.x.xfrom
djh58/prism-b1-window-reference

Conversation

@djh58

@djh58 djh58 commented Sep 11, 2026 •

Copy link
Copy Markdown
Member

Summary

Prepared work still persists the payout window inline. This draft delivers the B273 schema and authenticated-reader foundation needed to replace that payload; it does not switch refresh, resume or submit to compact jobs and does not complete #273.

  • Add migration008 with immutable digest-keyed template/as-issued balance stores, typed window references, exact null-state checks and digest indexes. Existing job payloads, expiry and top-level issued extranonce1 are preserved.
  • Expose the design's WindowRef, ShareRange, WindowError, BalanceSource and Ledger::read_window. Read one repeatable-read primary snapshot in ascending 4096-row pages; preserve native digest semantics, original as-issued balances and truthful failures.
  • Add coherent revision/balance observation through Ledger::payout_state(). This helper does not decide eligibility. The approved lease bridges revision changes only while the balance digest is unchanged.
  • Keep cancelled partial-window cleanup and abandoned page results off runtime workers. Include the explicit late-cancellation measurement requested on 3.x.x: Reference the window from prepared work and job rows instead of copying it #273.
  • Integrate 008 with the landed membership runner and test actual 008/009 installation in both orders. Migration009 and A's candidate/audit implementations are unchanged.

The branch preserves history through additive base merges and is based on 3.x.x at d39cf621ce25fea4d5a1e86b02cf6c3c66949ce5. No VERSION/CHANGELOG change, deployment or cutover is included. Stop/drain-all development migration remains the documented policy.

Current dependencies

Upstream Checked state Remaining dependency
#313 Merged as 0af13ec9b405731ce4eb93fb473352c94972a730, included None; its original worktree was not edited.
#264 / #297 #264 closed; #297 head 406b27344f53d9d84b68004adcae05b2f0f46f88 merged as 82a543d36447ce66ee92de90b6295adc7969765e Design is available. The user's narrowed-contract signoff pins bed6ad8; all four original objections were answered.
#276 / #319 Merged as d39cf621ce25fea4d5a1e86b02cf6c3c66949ce5, included Combined runner and unchanged 009 are tested.
#265 / #325 #265 open; #325 open at ff74abb0da65f15ddcd25689328a075f7ab2a1b4 PR325 is canonical import/read work only. Actual builder-version export, slim candidate types/constructor, migration007 references and candidate enqueue/landing integration remain unavailable. Import itself is not a missing B prerequisite.
#321 Open at 798860c1a79a05a536a9512208f1960220ff4ef9 Supplies 006/source-schema startup checks, not 007 or candidate types. Reconcile its future runner with 008 when combined; no source-schema implementation is copied here.

The concrete A265 interface request is recorded in issue265.

The landed GC-first enqueue decision is recorded: A re-inserts authenticated as-issued balances under ORDER_LOCK, probes the prefix and still enqueues/alerts if it is unexpectedly absent. B still needs its concrete Rust inputs and typed retention references; this is not a renewed design objection.

Validation

Tested code at 125a4df1704d2bdeb6b8c6cf64a3a4e8d7570428, Rust 1.98.1, disposable PostgreSQL 16.14:

  • 236 passed: 144 library, 37 ledger, 1 migration rollback, 6 readiness, 1 Stratum admission, 22 Stratum protocol, 8 window oracle, 17 window reference. Three explicit qualifications were ignored in this run. Existing miner assertions remain intact; migration assertions require the full version set and exact original fields plus the seven new null columns.
  • All 14 regular B database cases recorded execution and passed the scoped manifest check. This is not a claim of full CI-manifest qualification.
  • Workspace/all-target Clippy with -D warnings, formatting, gate environment-read lint and diff checks passed. All-target cargo check also passed before the final PR319 merge; final all-target Clippy compiled the combined base.
  • Separately, at a6e3482, a 400k fixture was cancelled after 96 pages / 393,216 accumulated shares: abort-to-join 27 microseconds, maximum 1 ms timer gap 5.418 ms, sole database connection recovered. Command wall time 31.97 seconds and maximum RSS 380,977,152 bytes include build/fixture effects. The test forces and verifies a streaming plan; this is cleanup evidence, not production throughput or a full resume-deadline result.
  • Earlier foundation reader-only 400k/500k and issued-dependency evidence is preserved with commit/toolchain/method qualifiers in the report; it was not rerun as full runtime qualification here.

Incomplete runtime and review checklist

  • A265 shared AUDIT_BUILDER_VERSION, slim candidate/window/policy/CTV/signer/bootstrap/leased inputs, required suffix, parts-based landing, witness parser and migration007 retention references.
  • Compact Prepared/StoredPrepared, WorkLedger refresh/resume/submit wiring; exact original signed hashes; coherent revision-plus-balance eligibility and authority/expiry checks after every wait.
  • Atomic template/balance/prepared/child save and cold repair with immutable conflict checks and original child expiry.
  • B GC under SETTLEMENT_LOCK then ORDER_LOCK, bounded job deletion after a qualified expiry grace, candidate-aware retention, and a later orphan sweep even when no jobs expire; both GC/repair/enqueue lock orders.
  • One original 30-second deadline, permit ownership through blocking closure exit, bounded singleflight isolation, original bootstrap share and retained-generation memory qualification.
  • Real 400k refresh plus A-to-B signed-equality resume, 500k headroom, every refresh JSONB value under 1 MB, measured WAL against the 5 MB target, dedicated asynchronous standby, per-phase RSS/row reads, affected work and prompt replacement delivery on balance changes. No unmeasured success or cutover waiver is claimed.
  • Full deep-review and CI qualification. Medium code-review, thermo, Fable/Codex adversarial lanes and the GitHub bot loop have not run for this draft. Publication precedes that review by request; this remains a high-stakes incomplete change.

Details: integration plan and foundation evidence / exact A265 interface matrix.

djh58 and others added 30 commits September 11, 2026 10:54
Separate observed and published tip authority, retain original issued
worker context through replacement and reconnects, and preserve bounded
delivery-based grace without renewing expiry after awaited work.

Exercise real Coordinator decisions and socket interleavings, including
constant node-RPC load across 1, 32 and 128 clients.

Refs #280
# Conflicts:
#	crates/qbit-prism-server/src/coordinator.rs
Add the independently approved B273 schema and reader foundation on PR313, with typed reconstruction errors, immutable blob tables, per-version migrations, and PostgreSQL qualification. Runtime prepared/resume, candidate, atomic repair and GC integration remain gated on A265 and shared owner agreement.
# Conflicts:
#	crates/qbit-prism-server/src/ledger/connect.rs
#	crates/qbit-prism-server/tests/support/ledger_2x.rs
@djh58

djh58 commented Sep 11, 2026

Copy link
Copy Markdown
Member Author

@cursor review

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Bugbot reviewed your changes and found no new issues!

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit 125a4df. Configure here.

@djh58

djh58 commented Sep 11, 2026

Copy link
Copy Markdown
Member Author

Review status update: foundation commit 125a4df remains unchanged. Cursor Bugbot completed successfully with no new issues; hosted CI remains green. The medium review and Codex adversarial lane reported no actionable findings. Fable adversarial and thermo-nuclear maintainability lanes are now in progress through retained review sessions; this PR is awaiting those reports. Latest 3.x.x includes PR320 as 22bd1a2; its actual patch is alert/metric inventory work with no overlap in the foundation code paths, so no rebase or cosmetic push was made. Runtime #273 follow-up remains intentionally open and is not represented as completed here.

@kiwidream kiwidream left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@djh58, I read #327 at 125a4df against what #265's next PR (slice 3: migration 007, the slim candidate, the claim rebuild and the write off ORDER_LOCK) builds on. Summary: it matches the merged record, and slice 3 can build on it.

  • read_window follows the record's six "Read" steps: the REPEATABLE READ READ ONLY transaction; revision, then balances, then the empty-window return; the endpoint probe; ascending 4,096-row pages with the exact predicate; the count, then the streamed digest; no partial window.
  • It's awaitable from the claim, with per-page spawn_blocking and off-runtime drops.
  • The WindowRef and ShareRange wire form and the hex32 rules match the record exactly, and 007 will embed that type unchanged.
  • 008's six columns and CHECK are the record's SQL, so 007 will mirror them byte for byte on the outbox, with the same pg_constraint guard and a versions.contains(&7) block.
  • WindowError's variants match the record, and #327 merges cleanly with #325.

On Prepared.window: slice 3 will add it, computed once per non-cached refresh in refresh_once (off the runtime, joined with the bundle build, with the empty-window reference for an empty snapshot), set on resume, and cloned by submit. Your plan doc already has B's integration take "the issued digest … from the authenticated Prepared.window, computed once at refresh", while B's slim resumed jobs can't go ahead "without #265". If #273 had to add it first, each side would wait on the other. It's in B-owned coordinator.rs, so please review that part of slice 3.

Requests for #327 before it merges, or confirmations (each saves slice 3 from editing B-owned code or tests):

  1. Version asserts. Four gated tests assert the exact applied-migration list [2, 3, 4, 5, 8, 9]: tests/support/ledger_2x.rs:52-57, tests/support/session_sequence.rs:175, and tests/window_reference.rs:563 and :669. When 007 lands they fail. Could they assert a superset, or at least not fail on 7?
  2. WindowRef::from_snapshot(&Snapshot). Only the test helper builds one today (tests/window_reference.rs:177-190). Slice 3 needs it for Prepared.window. I'd add it in window.rs as a synchronous function that callers run in spawn_blocking, unless you'd rather add it here.
  3. The balance-snapshot writer. 008 has the qbit_prism_balance_snapshots table, but #327 has no writer: no encoder, no insert, no conflict check. The leased-candidate enqueue has to re-insert as-issued balances byte-identically with save_job. Can #327 (or #273) export one writer that takes the caller's transaction (sort, digest, compact JSON, ON CONFLICT DO NOTHING, compare on conflict), so both sides write the same bytes?
  4. Page and probe primitives on a caller's transaction. The page loop and the endpoint probe are inline in read_window on its own transaction, and WindowRead is private. Slice 3 needs the probe inside the enqueue transaction, and a paged fetch-and-map with the same predicate for landing's range re-read inside the landing transaction. Could you expose them as pub(super) functions taking &mut Transaction? Otherwise I'll add them in window.rs in slice 3 for your review.
  5. window_reads. There's no semaphore yet, and the record reads both ways ("read_window also takes a permit" versus "the caller acquires it"). Your code comment says callers own the permits. I propose slice 3 adds one window_reads semaphore next to build_slots, sized clamp(database_max_connections - 2, 1, build_workers) and shared by claim and resume, with the caller holding the permit. OK?
  6. JoinError becomes Decode. A panicked or cancelled blocking task surfaces as WindowError::Decode, which the claim alerts on as corruption. Either map it separately, or document that it happens.
  7. BalanceSnapshotMissing on a leased claim. The record's Claim column says n/a, but leased candidates rebuild with AsIssued. Slice 3 will treat it like Incomplete: retry_candidate with an alert, never abandon. Please confirm.
  8. Optional: add the fatal_error IS NULL guard to read_window's revision read, as payout_state() has.

What slice 3 delivers against your "Exact A265 dependencies" table, to be confirmed in slice 3's PR:

  • qbit_prism::AUDIT_BUILDER_VERSION: u16, with frozen vectors keyed by version.
  • The slim Candidate and a construction API that takes the original inputs, not an owned bundle: window, found_block, payout_policy, ctv{…}, audit_builder_version, signer_keys{…}, bootstrap_share, leased, the required coinbase_suffix_hex, payout_revision, job_id, deferred_share, and the block hash, digest and bytes. These are exported so B's slim resumed jobs can keep them.
  • Migration 007, with three proposals:
    • the six columns plus an index on window_prior_balances_sha256 for your garbage collection;
    • leased only as the JSON flag, with no SQL column;
    • the retention predicate is "window_anchor_ms IS NOT NULL": the terminal UPDATE NULLs all six columns, so a non-NULL anchor means exactly the non-terminal rows, pending ones included, whether claimed, retrying or unclaimed. Does that work for your GC join?
  • An enqueue method under ORDER_LOCK that takes the as-issued balances: it re-inserts them after a digest check, probes the share prefix, and enqueues with an alert even if the prefix is missing. Its signature goes up for your review in slice 3's PR.
  • The leased dispatch order from the record (submit the stored bytes first, rebuild with AsIssued, land before any terminal outcome). leased stays false until #273 sets it.
  • Parts-based claim and landing, plus codec::witness_merkle_leaves_from_block.

One question: are you OK with slice 3 stacking on djh58/prism-b1-window-reference before #327 merges? Or would you rather we wait for the merge?

@djh58

djh58 commented Sep 11, 2026

Copy link
Copy Markdown
Member Author

Thanks Alex—good to hear the foundation matches the record and supports slice 3.

Please go ahead and stack slice 3 on #327 at 125a4df; we’ll coordinate any foundation review fixes before merging the stack. Adding Prepared.window in your slice, with B reviewing the coordinator changes, makes sense to avoid the circular dependency.

We’re checking your eight points now and will reply with explicit ownership: what we’ll fix in #327 versus what you can add in slice 3. In particular, we’ll reconcile the migration assertions, shared balance writer/read primitives, and error handling before calling #327 merge-ready.

No further design sign-off is pending from me; the remaining work is technical integration and review.

@djh58

djh58 commented Sep 11, 2026

Copy link
Copy Markdown
Member Author

Review disposition for the foundation slice:

Fable and thermo independently identified one correctness issue: read_prior_balances was applying the shared bytewise sort used for semantic digesting to the legacy snapshot vector itself. That could change persisted prior_balances order; later order-sensitive comparisons could reject an otherwise identical older candidate and retry indefinitely under a non-C collation/order scenario. Commit 9d61574 removes that shared sort from read_prior_balances. check_balances now sorts a clone only for the semantic digest and returns the original vector order. It adds a real PostgreSQL regression with an intentionally unsorted as-issued persisted bundle, plus the focused unit assertion. This preserves base snapshot ordering while retaining canonical digest validation.

The second focused fix adds fatal_error IS NULL to read_window's revision read, matching payout_state(). A gated regression proves a fatal cluster cannot expose a payout revision.

Alex's eight points:

  1. Exact migration assertions stay exact. Slice3 must update them atomically to [2,3,4,5,7,8,9] when 007 lands; no superset or vacuous check.
  2. WindowRef::from_snapshot(&Snapshot) can be added in slice3 as a synchronous shared helper, invoked from the caller's blocking build.
  3. The canonical balance-snapshot writer is a required slice3/B integration seam: caller transaction, canonical sort/compact encoding, semantic digest, ON CONFLICT DO NOTHING, and byte comparison on conflict. Enqueue and save/repair must share it.
  4. Caller-transaction endpoint/page primitives are slice3 work. They must preserve the existing predicate, keyset order, 4096 page bound, and digest/count checks.
  5. A shared caller-owned window_reads semaphore for claim and resume is compatible with the foundation; capacity may use clamp(database_max_connections - 2, 1, build_workers) and must cover the entire read/blocking handoff.
  6. Mapping every JoinError to Decode is a runtime taxonomy issue. Slice3 should distinguish cancellation/task failure from corruption or document and handle it so cancellation cannot trigger a corruption/abandon path.
  7. BalanceSnapshotMissing on a leased claim should remain recoverable: alert and retry, never abandon or infer credit semantics.
  8. The fatal guard is now fixed in 9d61574.

The proposed 007 GC predicate window_anchor_ms IS NOT NULL is acceptable if terminal updates NULL all six window columns atomically. It preserves pending/claimed/retrying/unclaimed candidate references without inventing a SQL leased column; the balance-digest index is appropriate for the later GC join and orphan sweep.

Prepared.window should remain slice3-owned in coordinator.rs: compute once per non-cached refresh, set on resume, and clone on submit. Slice3 may stack on djh58/prism-b1-window-reference pinned at 9d61574 before #327 merges, with B review of those coordinator changes. Runtime #273 remains open and no new credit semantics are accepted by this disposition.

@djh58

djh58 commented Sep 11, 2026

Copy link
Copy Markdown
Member Author

Focused delta verification for 9d61574 is complete locally: window-reference 19 passed, ledger 37 passed, library 144 passed; 16 gated window cases executed, manifest proof passed, Clippy/format/gate-env/diff checks passed. Hosted checks for this new commit are still pending; no new full review battery is being requested.

@djh58

djh58 commented Sep 11, 2026

Copy link
Copy Markdown
Member Author

Closeout verifier follow-up: commit 63e1770 is pushed on top of 9d61574. The unsorted PostgreSQL fixture now stores the z-order entry before the a-order entry. Negative control with the old check_balances behavior (sorting the returned vector) failed the exact test with exit 101; restored fixed behavior passed the full window-reference binary: 19 passed, 2 ignored, with all 16 gated cases executed and manifest proof passing. Formatting and diff checks pass. The foundation report now states precisely that digest validation sorts a clone while returning source order unchanged. No runtime #273 scope or credit semantics changed; Alex’s items 1–7 remain slice3 work, and fatal guarding plus legacy-order preservation are complete.

@djh58

djh58 commented Sep 11, 2026

Copy link
Copy Markdown
Member Author

CI harness correction pushed as b11cbbb. Run 34643574101 showed a real live_regtest::highdiff_tests::observability_grace_counter_moves_only_after_real_durable_credit failure (readiness timeout), then set -e stopped the workspace step before later required suites ran; the strict manifest correctly reported 71/107 distinct tests and named the missing migrations/oracle/window-reference/etc. identities. The workflow now marks each required test invocation outcome, continues through all three invocations so every gated test gets a decision, runs the unchanged strict manifest proof, and fails if either any invocation failed or the manifest has missing/skipped/failed/unexpected identities. No required test or expected identity was removed.

@djh58

djh58 commented Sep 11, 2026

Copy link
Copy Markdown
Member Author

CI diagnosis update: I reverted b11cbbb in ef8b6c9; the continue-on-error workflow change is not a solution and is no longer part of this PR.

The first failure in job 103408888617 / run 34643574101 is the live test highdiff_tests::observability_grace_counter_moves_only_after_real_durable_credit, which timed out waiting for qbitd HTTP readiness (127.0.0.1:37103/healthz). The later manifest failure (71 distinct executions vs 107 expected) is a consequence of the cargo step exiting at that failed test before later gated invocations; the manifest proof itself was not weakened.

I reproduced the exact focused test twice with the native disposable-PostgreSQL harness, pinned qbitd v1.0.0, and integration-required mode; both passed (~4.5s each), including the gate identity. PR329 merge 0ecc7d2 has no diff overlap with live_highdiff.rs or the qbitd readiness path (its changes are metrics/health inventory/docs), so there is no evidence of a PR-related code regression. Current conclusion is an intermittent readiness/startup failure pending CI rerun; no thresholds or tests were changed, and this PR is not merge-ready until the full required job is green.

@djh58
djh58 merged commit 096e9b6 into 3.x.x Sep 11, 2026
16 checks passed
Anatolie added a commit that referenced this pull request Sep 14, 2026
#327 added 008_prepared_window_reference.sql to the runner in connect.rs,
which this branch had moved into migrate_schema. Put 008 in
NATIVE_MIGRATIONS, so the scratch apply reserves what it creates, and in
REQUIRED_SCHEMA_VERSIONS, so the startup gate requires it; apply it after
006 and before 009. 007 is the only reserved number now. The pre-006
fixtures the tests undo from the current chain therefore model the database
today's 3.x.x leaves, at 2, 3, 4, 5, 8 and 9, and the messages and docs
name that set.
Anatolie added a commit that referenced this pull request Sep 14, 2026
…ns, gate startup (#321)

* 3.x.x: pin the migration source schema and gate startup on it

The migrator accepted any database that had a share ledger, tested the
outbox with a JSONB predicate that a #258 v2 row slips past, never read
qbit_prism_schema_capabilities, and skipped the schema version entirely
when PRISM_POSTGRES_INIT_SCHEMA=0, the native default. Its "frozen 2.x.x
schema" in the upgrade tests was include_str! of the live 001, which #244
already edits.

Freeze the 2.x.x release SQL as byte-exact fixtures taken from the
release commits (001 from v2.0.2, identical at v2.0.1 and v2.0.0; 002
from v2.0.2), pin their digests, pin the live 001's digest, and compare
the live 001 to the release statement for statement, since #244 changed
only its comments. Editing either live file fails the test with the
instruction the editor needs.

Migration 006 pins the accepted source states as data: fresh, pre-#258
(001 only), #258 applied (candidate_storage_version = 2 and every 002
object), partial 002 (refused, naming the missing object) and newer
(refused before any DDL). The inventory comes from the catalog, so the
drain predicate is built only from outbox columns that exist: the
storage_version and body_id clauses on a #258 source, the v1 form on a
pre-#258 one, where a fixed predicate errored instead of refusing. The
check reads rows, never the capability row, which only proves 002 ran.
The refusal names the blocking rows and the 2.x.x drain: the pinned
coordinator's submitter, or lab.prism.recover_pending_blocks from the
2.x.x image.

Every start now reads qbit_prism_schema_migrations and the capability
rows, with or without initialize, and refuses a schema other than
version 6 or a capability the binary does not understand, naming the
required version. A successful migration records the accepted source
state, its 2.x.x release and commit, the declared capability value and
the prior schema version in qbit_prism_migration_source; migrate prints
it, every start logs it, and a repeated migrate never rewrites it. 006
also declares candidate_storage_version = 1 on sources that had no
capability row and adds the outbox storage_version column so one claim
statement serves every source; the chunk tables are not carried.

The API database test hand-applies migrations up to 003 and then
connected without initialize, which the gate now refuses; it initializes.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01AauTYgQEqxzDE13xLjYTR9

* 3.x.x: park candidates the claim lane cannot decode

The claim lane returned the outbox row's candidate column alone. A #258
v2 row returns NULL with the claim token set, no CandidateClaim can be
built, the submit loop logs "candidate polling failed", and the row
re-enters the due lane at every lease expiry, forever.

Return storage_version and an Option<Value> candidate. A version 1 row
with a body is decoded as before. Any other row, a v2 body this server
does not import or a version it does not know, is parked inside the
claim transaction: the claim is released, last_error says why, and
next_attempt_at becomes infinity, so no lease expiry offers it again and
ordinary v1 work keeps flowing. The row stays pending with its body
untouched; resetting next_attempt_at re-offers it, which is how an
operator hands it back after draining it with the 2.x.x image. The edit
is deliberately small, since #265 reshapes candidate storage.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01AauTYgQEqxzDE13xLjYTR9

* Document the supported 2.x.x source schemas and the drain requirement

The migration guide names the minimum supported 2.x.x release (v2.0.1,
whose offline recovery command is part of the drain; v2.0.0 has the same
schema), the newest (v2.0.2), #258's rollback floor, the source-state
table the migrator pins, the drain requirement for v1 and v2 rows with
the 2.x.x commands, what qbit_prism_migration_source records, the
startup gate, and how a parked row is found and re-offered. The server
README points at it.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01AauTYgQEqxzDE13xLjYTR9

* 3.x.x: accept a newer schema at start and let capabilities fence formats

The startup gate refused any schema version other than the one this
binary migrates to. That silently withdrew the rollout the guide
promises, where compatible Rust releases drain and replace one frontend
at a time, because a release that adds a migration would have kept every
frontend on the previous release from starting once its migrate ran.

Refuse only a schema below the required version, as the issue asks. A
newer schema is accepted with a warning that names both versions: native
migrations are additive, and a release whose format an older binary must
not touch declares a capability, which require_known_capabilities still
refuses exactly as before. The guide's rollout paragraph is restored with
the order that makes it hold: the new release's migrate runs first,
frontends on the previous release keep starting while its migrations are
additive and it declares no capability they do not understand, and a
release that declares a new capability needs every frontend stopped
first. The startup-gate test now asserts that a start on the next schema
version succeeds and rewrites nothing.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01AauTYgQEqxzDE13xLjYTR9

* Record the migrator and schema freeze in the 3.x.x development-line note

The note listed how 002_candidate_bodies.sql is handled as frozen by a
pending issue. It is now carried byte-identical to v2.0.2 and
digest-pinned, never applied, and a #258 source is accepted after the
drain check while a partial or newer source is refused before any DDL.
The matching "not done yet" bullet is gone.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01AauTYgQEqxzDE13xLjYTR9

* 3.x.x: verify the frozen 001 schema after it has run, refusing drift transactionally

A database with no 002 objects was accepted as the pre-#258 source on the
strength of qbit_share_ledger existing. 001 is idempotent, but its IF NOT
EXISTS leaves an existing table, column, index or named constraint as it
is, so an older, partially applied or locally modified schema passed the
pin, was recorded as v2.0.1, and its incompatible definitions survived a
successful migration.

The migrator now applies 001 to the source as before and then, before
002_multi_instance.sql or any later native DDL touches those tables,
checks that what 001 left alone is the release definition. The expected
definitions are not a stored fingerprint: under a savepoint in the
migration transaction it creates a scratch schema, applies the same 001
there (plus 002_candidate_bodies.sql for a #258 source), reads every
table, column, constraint, index, trigger and function that produced,
and rolls the savepoint back, so the comparison is exact for the running
PostgreSQL version and nothing from the scratch apply survives. Each
object then needs an equivalent in the schema the migrator runs in:
column type, NOT NULL, default, identity, generated status and
collation; constraints per table by definition; index definitions and
validity; trigger definitions and enabled state; function arguments,
result, language, body, volatility and settings. Schema qualification,
column order, comments, auto-generated constraint names and the NOT
VALID mark 001 itself leaves on an upgraded table are ignored; extra
objects are kept and logged; a missing or different one fails the
migration, which rolls back whole, naming each object and what differs.
A migrate role without CREATE on the database is refused with the grant
it needs. The source-state table gains the "drifted 001" row in
SOURCE_STATES, migration 006's comment and the migration guide; the
migration record is unchanged.

Tests: a pre-#258 source with a dropped foreign key, a dropped NOT NULL,
a changed column type and a same-named index with a different
definition is refused naming all four and left untouched; a #258 source
with a replaced 002 function body and a disabled 002 trigger is refused;
an extra table, column and index, a 001 column moved to a different
physical position with its data, and a NOT VALID credit-policy CHECK
still migrate; a role without CREATE on the database is told the grant.
Replays of the real 0.1.2 -> 1.x -> 2.x history (every 001 revision in
order, then the frozen v2.0.2 file, with and without 002) all migrate.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01EVxRdWsnzBhrsgiEX2kvKR

* 3.x.x: register the source-schema gated tests in the gate manifest

The branch was rebased onto #322, which fails the prism-native-postgres
job for any gated test that executes without being listed in
test/prism-gated-tests.txt. None of the ten Postgres tests this PR adds
in tests/support/ledger_2x.rs were listed, so the job would have failed
on its manifest check. List them, sorted, and update the count the gate
guide quotes. The other #322 checks (formatting, clippy with -D warnings,
the gate env-read lint, the toolchain pin, version skew) already pass on
this branch and need no change.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_019mWgeEnsyHLZSiGaAj8bZi

* 3.x.x: compare release sequences in the source-schema check

The post-001 fingerprint read tables, columns, constraints, indexes,
triggers and functions, but never the sequences behind 001's bigserial
columns or its explicit qbit_audit_publication_sequence_seq. CREATE TABLE
IF NOT EXISTS leaves an existing sequence exactly as it is, so a lowered
MAXVALUE or a changed INCREMENT on qbit_share_ledger_share_seq_seq
survived the idempotent apply, compared equal to the frozen release, and
migrated; the next share inserts would then fail or take unexpected
identifiers.

The fingerprint now records every sequence of the schema from
pg_sequence: data type, start, increment, minimum, maximum, cache and
cycle. The value a sequence has reached (last_value, is_called) is the
source's data and is not read, so an advanced ledger still migrates and
keeps its position. A release sequence that is missing or whose structure
differs is drift, named in the refusal the way columns and functions
are, for example

  sequence qbit_share_ledger_share_seq_seq differs: maximum expected
  9223372036854775807, found 1000000

and an extra sequence is logged with the other extras.

Tests: the pre-#258 drift test also lowers the share sequence's maximum
and doubles the payout entry sequence's increment, and the refusal names
both and rolls back; the tolerated-differences test advances the share
sequence with setval and the first native share takes the next value; a
unit test covers the comparison. The real 0.1.2 -> 1.x -> 2.x histories
(every 001 revision in order, then the frozen v2.0.2 001, with and
without 002) all still migrate, and each leaves the same sequence
structure as a fresh apply. The migration guide and the 006 comment list
what is compared.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_019mWgeEnsyHLZSiGaAj8bZi

* 3.x.x: treat a database as fresh only when no release object exists

A database without qbit_share_ledger and without any 002 object was
classified as fresh on that evidence alone, and the post-001 comparison
was skipped for it. A selective restore or a hand-installed piece of the
schema, qbit_pool_blocks on its own for instance, therefore passed: 001's
CREATE ... IF NOT EXISTS kept whatever those objects held, the migration
recorded success, and the accounting code ran over a schema nobody had
checked.

The release definitions are now taken once, before any DDL touches the
source: the frozen release SQL (001, plus 002 for a #258 source) is
applied to a scratch schema under a savepoint and rolled back, and that
one fingerprint serves both checks. A database without qbit_share_ledger
is fresh only if it has no table, sequence, index, trigger or function
the release 001 creates. Otherwise it is the new source state
"partial 001", refused before any DDL and naming the objects present,
capped as the drift report is:

  refusing to migrate a partial 001 source before any DDL: the database
  has no qbit_share_ledger but holds 4 object(s) that the 2.x.x
  release's 001_share_ledger.sql creates (table qbit_pool_blocks; index
  ...), so it is neither an empty database nor a 2.x.x ledger, and
  001's IF NOT EXISTS would keep those objects whatever they hold.
  Nothing was changed. Restore the full pre-migration backup, or
  migrate into an empty database

Objects the release does not create, an operator's own table, do not
disqualify a fresh database and are logged as extras. The post-001
comparison now runs for every source state, fresh included, where it
passes trivially: 001 has just created everything.

SOURCE_STATES gains the partial 001 row after fresh. The rows are cited
by name through constants and looked up by name, never by position, and
a unit test checks every cited name is exactly one row, so reordering
the table cannot silently change a refusal again. The pinned-data test,
the 006 comment, the guide's table and the development-line note carry
the new row.

Tests (Postgres): a leftover 001 table, sequence or function alone,
each created from the frozen release definition, is refused as partial
001 naming it, with no native table, no scratch schema and the leftover
untouched; an empty database with only an operator's table still
migrates as fresh and keeps the table; a truly empty database migrates
as fresh. The real 0.1.2 -> 1.x -> 2.x history replays, with and without
002, still migrate. Both new gated tests are in the manifest.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_019mWgeEnsyHLZSiGaAj8bZi

* 3.x.x: recheck the outbox before 006 on a native schema an earlier build migrated

A database an earlier 3.x.x build brought to native schema 3, 4 or 5 went
straight to 004, 005 and 006 without the drain check, and that build's
v1-only predicate never counted a v2 row (`candidate ?& ...` is NULL for a
NULL body). A pending v2 candidate could therefore be carried into version 6
and parked by the claim lane instead of refusing the cutover, leaving a
possibly valid found block unsubmitted.

`migrate_schema` now runs the column-aware inventory and
`refuse_undrained_outbox` on a recorded version 3, 4 or 5 before 004, 005
and 006 run, so a refusal on that path is before any DDL as well. Native
pending rows carry the native payout_revision, bundle and block_hash fields
and are not counted; only a v2 body, a body_id, a storage_version other than
1, or a v1 body without those fields is refused. The refusal has its own
wording: it names the native schema version, names the rows the same way as
the 2.x.x refusal, and gives the remedy the guide backs, restoring the
pre-migration 2.x.x backup and draining there with the pinned image. The
2.x.x release is not supported against a native schema (its revert script
refuses one), so the message says not to point it at the database.

Postgres tests build the earlier build's schema 5 faithfully: the frozen
001 (and 002), the current migration, then 006 undone, deleting the version
6 row and dropping qbit_prism_migration_source, and on a pre-#258 source
also the storage_version column and the capability table 006 created. A
pending v2 row on the #258 simulation is refused naming the row, with
max(version) still 5 and no 006 object; a native pending candidate on either
simulation migrates to 6 and is still claimable; an undrained 2.x.x v1 row on
the pre-#258 simulation exercises the v1-only form of the predicate. The
guide's drain text and the 006 comment describe the check; the gated-test
manifest and its documented count are updated.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01QuEYH8xHQRo7C4SnexM3cP

* 3.x.x: compare table and sequence persistence in the source-schema check

The release-schema fingerprint recorded a table by name and compared its
columns, constraints and indexes, so a release table an operator had
changed to UNLOGGED compared equal to the logged table the scratch apply
creates, and the migration accepted a ledger or outbox whose rows
PostgreSQL truncates after a crash.

The fingerprint now records pg_class.relpersistence for every table and
every sequence (PostgreSQL 15 and later have unlogged sequences, and a
sequence owned by an unlogged table is unlogged with it). A mismatch is
drift, named the way the other differences are: `table
qbit_share_ledger differs: expected logged, found UNLOGGED`, and for a
sequence the persistence joins its other properties. Extra objects are
unaffected.

A Postgres test makes qbit_payout_carry_forward UNLOGGED on a pre-#258
source: it holds the carried balances and has no foreign key in either
direction, so SET UNLOGGED is accepted as it is, and the sequence behind
its bigserial column follows the table. The migration is refused naming
the table and its sequence, rolls back with the relations still unlogged
and no native table, and accepts the same source once it is logged again.
(qbit_audit_publication_sequence_seq is not used for this: 001's own guard
already refuses that sequence when it is not logged.) A unit test covers
the comparison for tables, sequences and a temporary table. Replays of the
real 0.1.2 -> 1.x -> 2.x schema history, with and without 002, still
migrate: no revision creates an unlogged relation. The guide's
release-schema paragraph, its drifted 001 row and the comment in migration
006 name persistence; the gated-test manifest and its count are updated.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01QuEYH8xHQRo7C4SnexM3cP

* 3.x.x: compare constraint validation, exempting only the release's own NOT VALID check

The source-schema check stripped NOT VALID from every constraint definition
before comparing, so a foreign key or CHECK an operator had dropped and
re-added NOT VALID compared equal to the validated release constraint, and
a source whose rows were never checked against it, orphaned outbox rows or
invalid accounting rows for instance, still migrated.

The blanket strip is replaced by a pinned exemption list, NOT_VALID_EXEMPT:
the constraints the frozen release 001 itself adds NOT VALID on an upgraded
table and never validates. Today that is qbit_share_ledger_credit_policy_check
alone (001 adds it NOT VALID to a qbit_share_ledger upgraded from before the
column existed; a fresh apply creates it validated inside CREATE TABLE). An
exempt constraint is accepted in either state on either side. Every other
constraint is compared by pg_constraint.convalidated as well as by
definition: a release constraint that is NOT VALID in the source is drift,
`constraint qbit_block_candidate_outbox_share_id_fkey on
qbit_block_candidate_outbox is NOT VALID; the release validates it`. The
definition without its NOT VALID suffix is still the lookup key, so an
unvalidated constraint finds its release counterpart and is named.

A test parses the frozen 001 and 002 fixtures for constraints added NOT
VALID and not validated later in the same file (plain statements and the
format() form alike) and asserts the set equals NOT_VALID_EXEMPT, so the
list cannot drift from the release. A Postgres test drops and re-adds the
outbox share_id foreign key and a carry-forward CHECK NOT VALID: the
migration is refused naming both, rolls back with nothing validated, and
accepts the source once they are validated. The existing tolerated-
differences case, with the credit-policy check NOT VALID, still migrates.
Unit tests cover the comparison and the exemption. Replays of the real
0.1.2 -> 1.x -> 2.x schema history, with and without 002, still migrate:
the only constraint a genuine history leaves NOT VALID is the exempt one.
The guide's release-schema paragraph, its drifted 001 row and the comment
in migration 006 describe the rule; the gated-test manifest and its count
are updated.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01QuEYH8xHQRo7C4SnexM3cP

* 3.x.x: require every schema migration at start, 009 included

and may land after 009, and the rebase moved its 009 step into
migrate_schema with the rest of the chain. The startup gate still compared
max(version) with 6, which a database at 2, 3, 4, 5 and 9 passes without
006, and its "newer than required" warning would have fired on every start
once 009 was in the chain.

REQUIRED_SCHEMA_VERSIONS names 2, 3, 4, 5, 6 and 9. A start refuses a
database missing any of them, naming the gap, and warns only about
migrations this binary does not know. The pre-006 outbox refusal names the
applied set instead of a high-water mark; prior_schema_version in the
source record stays the highest migration recorded.

Tests: a database at 2, 3, 4, 5 and 9 applies 006 on the next migrate and
leaves 009 as it found it; a start without PRISM_POSTGRES_INIT_SCHEMA on
that database is refused naming 6; the newest-migration case now undoes
009. #319's read-only pre-009 connect test is removed, since the gate
refuses that database by design, and the gate manifest follows.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* 3.x.x: refuse unknown capabilities before 004 to 006 run on a native schema

On a database an earlier 3.x.x build migrated to native schema 3, 4 or
5, migrate_schema ran the drain check and then applied 004, 005 and 006
without reading the capability rows, so a database a newer release wrote
(candidate_storage_version = 3, or a capability this binary does not
know) was altered and recorded at 6, and only Ledger::connect refused
it, after the commit. Every native path now takes the inventory first
and refuses those rows before any DDL, on a database already at 6 too,
before 009; the 006 record reuses the same rows instead of reading them
again, and the recorded versions are read in order so the refusal names
them deterministically. A pre-006 test on a #258 source covers both
refusals and the migration once the row is gone; the migration guide and
the 006 comment describe the order.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* 3.x.x: compare row-level security and policies in the source-schema check

The release-schema fingerprint read a table's name, persistence and columns
only, so a release table with row-level security enabled or forced, or a
policy on it, compared equal to the frozen release. For a migrate role that
does not bypass row-level security, a policy hiding pending rows (or forced
security with no policy) makes the drain check see an empty outbox, so the
migration commits with legacy candidates stranded where the native claim
lane never sees them. The fingerprint now reads relrowsecurity and
relforcerowsecurity from pg_class and every policy from pg_policy (command,
permissive or restrictive, roles, USING and WITH CHECK, rendered without
schema qualification), both for the scratch release apply and the source,
and the comparison refuses a release table whose flags differ or that
carries a policy the release does not have, naming the table, the flags
found and each policy. Policies on tables the release does not create are
not reported. A Postgres test migrates as a non-superuser owner role and
shows the row hidden, the refusal, the rollback, and the migration once
security is off and the row drained; the docs and the 006 header say what
is compared and why.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Quote the pre-006 outbox refusal as the migrator words it since 009 joined the chain

The guide's example still read "a native schema 5 database", the wording
from before the applied migrations were tracked as a set; the migrator
names the recorded set ("a native database at schema migrations 2, 3, 4,
5, 9") since the startup gate stopped comparing a high-water mark.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* 3.x.x: refuse a 2.x.x or empty source that already holds a native object or column

Codex P1 on #321: a source that already contains an object a native
migration creates (a qbit_prism_cluster(singleton boolean PRIMARY KEY),
for instance) passed the fresh and release checks as a harmless extra.
002's CREATE TABLE IF NOT EXISTS then kept it as it was, the migration
recorded its versions, and only after commit did writable() fail on the
missing fatal_error column, with every later migrate skipping the
recorded version. A column a native migration adds with ADD COLUMN IF
NOT EXISTS (002's claim columns on the outbox and the fanout artifacts,
003's canonical_audit_bytes and inactive_since, 006's storage_version on
a pre-#258 outbox) is the same bug: a source release table that already
has a column of that name keeps it whatever its type or default.

The scratch apply release_fingerprint runs now continues, after the
release SQL, with the native migrations in the order migrate_schema
applies them (NATIVE_MIGRATIONS, pinned to REQUIRED_SCHEMA_VERSIONS by a
unit test) and fingerprints the scratch schema again. The second reading
minus the first is the reserved set (ReservedObjects): every table,
sequence, index, trigger and function a native migration creates and the
release does not, and, per release table, every column the native chain
adds to it. qbit_prism_schema_migrations, the migrator's own, is never
in it, and an object or column in both readings (the capability table on
a #258 source, the outbox's storage_version there, which the release 002
added; on a pre-#258 source 006 adds it, so it is reserved) stays
governed by the release checks. Reserved columns are kept in their own
field: objects_present also serves the partial-001 check, where a
present table already refuses and listing its columns would be noise, so
only require_no_native_collision looks at them. On the 2.x.x path,
before any DDL, the source is fingerprinted once, require_fresh_source
(now synchronous, on that reading) runs on a fresh source, and a source
that already has a reserved object or column is refused as the new
"native collision" state, naming each (capped by named_objects; a column
as column <table>.<column>), saying nothing was changed, and telling the
operator to restore the backup or check and remove the objects; nothing
is dropped and no DROP is suggested. release_objects_present is renamed
objects_present.

The migrator applies each native migration from NATIVE_MIGRATIONS, so
the scratch apply and the real one cannot drift apart. SOURCE_STATES,
its pinned-table test, the comment in 006 and the guide's table carry
the new row; the guide shows the refusal and names the column case.

Tests, against PostgreSQL 16: an empty database with a stray
qbit_prism_cluster is refused naming it, with no migrator table and the
stray table unaltered, and migrates as fresh once the table is removed;
a pre-#258 and a #258 source with a stray native table, function and
sequence are refused naming all three, unchanged, and migrate once they
are removed; a pre-#258 and a #258 source with a stray claim_token
integer on the outbox are refused naming column
qbit_block_candidate_outbox.claim_token, unchanged (the column keeps its
type), and migrate once it is dropped, after which 002 adds the text
column it wanted. The unit test on the reserved set pins the column
derivation, including storage_version reserved on a pre-#258 outbox and
not on a #258 one. The api_database fixture, which hand-applies 001 to
003 and then lets connect bring the schema forward, now records versions
2 and 3 the way the migrator does: native objects with no record are the
collision this commit refuses.

The genuine 0.1.2 -> 1.x -> 2.x history replays (the 12 distinct 001
revisions reachable from the release tags, main, 2.x.x and 3.x.x,
applied in order into one database and each on its own, then the frozen
v2.0.2 001, with and without 002, then migrate: 26 runs) are all
accepted, so no real history contains a native object or column.

The new Postgres tests are registered in test/prism-gated-tests.txt, and
the "N today" count in docs/prism-integration-test-gate.md, which had
fallen behind the manifest at an earlier rebase, is set to the
manifest's id count, 114.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* 3.x.x: fold migration 008 into the native chain after rebasing on 3.x.x

#327 added 008_prepared_window_reference.sql to the runner in connect.rs,
which this branch had moved into migrate_schema. Put 008 in
NATIVE_MIGRATIONS, so the scratch apply reserves what it creates, and in
REQUIRED_SCHEMA_VERSIONS, so the startup gate requires it; apply it after
006 and before 009. 007 is the only reserved number now. The pre-006
fixtures the tests undo from the current chain therefore model the database
today's 3.x.x leaves, at 2, 3, 4, 5, 8 and 9, and the messages and docs
name that set.

* 3.x.x: refuse a native record with 3 and not 2 before any DDL

Every native build has recorded 2 and 3 in the one transaction that
applied them, so a record with 3 and not 2 was edited or restored
selectively. migrate_schema's native path applied the rest of the chain
above it and only the startup gate then refused the gap, at every start,
and no later migrate could repair it: 002 is not re-run on a database at 3,
and recording it unseen would vouch for objects the run never checked.
Refuse the record before any DDL, naming the remedy; a start without
initialize keeps refusing the gap.

* 3.x.x: require the capability declaration once migration 006 is recorded

require_known_capabilities accepted a database at 6 whose capability table
or candidate_storage_version row was gone, as if absence were the legacy
state it was before 006; after a selective restore or a deletion the
database could no longer say which release wrote it and the connect gate
let it through. 006 created both and nothing native removes them, so
require them at connect once require_schema_version has established 6,
naming the remedy, and refuse the same database on the migrate path before
008 or 009 run above the missing declaration.

* 3.x.x: compare the enforcement triggers of release constraints

The trigger reading skipped every internal trigger and the constraint
comparison looked at the definition and convalidated only, so a release
foreign key whose referential triggers a superuser had disabled (ALTER
TABLE ... DISABLE TRIGGER ALL during a bulk load, say) compared equal: no
new row was checked against it, 001 never re-enables a trigger it did not
create, and the native ledger could go on accumulating orphaned rows. Read
the enabled state of each internal trigger that enforces a constraint into
its definition, on both tables of a foreign key, and refuse a release
constraint whose states differ from the scratch apply, naming them.

* 3.x.x: refuse inheritance involving a release table

The table reading never looked at pg_inherits, so a child created with
INHERITS (qbit_share_ledger) was an extra ordinary table, accepted with a
warning, while PostgreSQL includes its rows in every query of the ledger,
the unqualified share reads included, without the release constraints ever
checking them. Read each table's parents and children into its definition
and refuse a release table that has either, naming them; a release table
attached as a partition of or inheriting from another table is drift the
same way, and inheritance among the operator's own tables stays theirs.

* 3.x.x: count a reserved name held by a relation of any kind as a collision

The index reading left every index backing a primary, unique or exclusion
constraint to the constraint comparison, and the collision check looked up
reserved index names in that reading only, so an operator table whose
unique constraint was named qbit_prism_candidate_claim_idx owned that name
unseen: 002's CREATE INDEX IF NOT EXISTS would skip the outbox index it
meant to create, record the migration anyway, and leave candidate polling
to scan the outbox. IF NOT EXISTS looks at the name alone, for a view or a
composite type as much as for such an index, so read every relation of the
kinds no other map models into the fingerprint, reserve the native ones the
release lacks, and count a reserved table, sequence or index name held by
any of them, naming what holds it. An index backing a constraint of an
expected table goes with that table and is not named twice.

* 3.x.x: refuse extra user triggers on release tables

The release-schema check classified a user trigger the release does not
create on a release table as a tolerated extra, so require_release_schema
logged it and migrated over it. Such a trigger can be valid for the
legacy writer and incompatible with the native one: a guard that rejects
writer_epoch = 0 lets the 2.x.x writer's leased epochs through and fails
every native share insert, which writes epoch 0, and a trigger can just
as well rewrite what the migrator and the native writers put in the
accounting tables. Report a found user trigger on a release table whose
(table, name) the release lacks as drift, naming the trigger, its table
and its definition, and whether the release has no trigger on that table
or simply does not create this one, so the migration refuses
transactionally and the database is unchanged. Triggers on tables the
release does not create stay the operator's own; the expected-trigger
definition and enabled-state comparison and the enforcement-trigger
check of release constraints are unchanged.

Regression: a comparator unit test for both reasons, a missing release
trigger and an operator table's trigger; and a two_x PostgreSQL test on
the frozen pre-#258 and #258 sources that shows the guard accepting a
legacy epoch and refusing epoch 0, the refusal naming the trigger and
rolling back with the trigger, the legacy rows and no native table or
version in place, then the same source migrating once the operator
drops the guard, with the operator table's trigger kept and firing and
the native writers inserting their epoch-0 shares.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01N2if7arQVKaZ1yMupJiprr

* fix: reject extra constraints on migration source tables

* fix: reject unsatisfied extra migration source columns

* fix: reject extra indexes that affect native writes

* fix: update rustls to address RUSTSEC-2026-0285

* fix: reject executable expressions on extra source columns

* fix: fingerprint table rewrite rules before migration

* fix: reject incoming foreign keys from extra source tables

* fix: validate storage version before native migration 006

* fix: reject domain-typed extra migration columns

* fix: reject migration sources resolved outside the current schema

* fix: reject all extra indexes on release tables

* fix: validate source metadata before later native migrations

* fix: reject preexisting source metadata before migration 006

* fix: reject row security on capability metadata

* fix: separate legacy source versions from native capabilities

* fix: reject outbox row security before native migration drain

* fix: validate migration history before trusting version records

* fix: require an ordinary table for capability declarations

* fix: bind the capability declaration to the current schema

The connect-time gate probed qbit_prism_schema_capabilities with an
unqualified to_regclass, which follows search_path. When the migrated
schema had lost its capability table, the probe could resolve a later
schema's table, and its version-1 row cleared a database whose own
declaration was gone, while require_migration_history had bound the
history to current_schema(). Migrate was already safe through
require_source_schema_resolution; connect was not.

read_capabilities now looks the visible relation up in the catalog and
refuses one outside current_schema(), naming both schemas, before any
row is read. Both callers share the path: the connect gate drops its
separate probe and the migrate inventory reads through the same
function. A new gated test drops the migrated schema's declaration,
declares version 1 in a later schema on search_path, and asserts that
connect and migrate both refuse it, that the loss is still named as a
loss without the later schema, and that the restored declaration is
read with the later schema still present.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* fix: bind migration provenance to the verified schema

* fix: reject object collisions in native migration gaps

---------

Co-authored-by: Claude Fable 5.1 <[email protected]>
kiwidream added a commit that referenced this pull request Oct 27, 2026
* docs: design record for WindowRef and Ledger::read_window (#297)

* docs: design record for WindowRef and Ledger::read_window (#264)

Add docs/prism-coordinator-refactor/window-ref.md, the design record that
#265 (migration 007) and #273 (migration 008) implement against, and link
it from the directory README.

The record specifies:
- WindowRef { anchor_ms, prior_balances_digest, shares: Option<ShareRange> }
- the six window_* columns and their three-state CHECK
- Ledger::read_window: one REPEATABLE READ READ ONLY transaction,
  mandatory ascending keyset paging, a streaming digest, typed errors and
  never a partial window
- per-caller revision fences that keep today's observe_candidate rule for
  claims
- the non-window bundle inputs a rebuild stores instead of reading config
- the upgrade procedure, retention floor and expected cost at 400k shares
- the borrowed qbit-prism parts API merged in #296

It went through two adversarial reviews.

Part of #261.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs: hex-serialize WindowRef digests and clamp the resume timeout (#264)

Two fixes to the WindowRef design record after review:

- A derived Serialize writes a [u8; 32] as a JSON array of 32 integers, not
  the lowercase 64-hex string the payload and column contract requires. Both
  digest fields now carry #[serde(with = "hex32")], a small adapter in
  ledger/window.rs that writes lowercase hex and reads exactly 64 lowercase
  hex characters. The server's hex dependency has no serde feature.
- The proposed resume timeout, initial_job_timeout_seconds minus 5 s, is
  zero or negative for any setting at or below 5 s, which validation allows.
  It is now outer - min(5 s, outer / 2), computed from the Duration the
  caller already builds: 25 s at the 30 s default, always positive, strictly
  shorter than the outer timeout, and free of Duration underflow.

Part of #261.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs: bootstrap resumes use stored policy inputs (#264)

An empty-window resume rebuilt each miner's bootstrap bundle through
Coordinator::build_bundle. That function reads config.ctv_enabled,
payout_policy, ctv_direct_floor and ctv_config, so after a config or
fingerprint reset a resumed job could get a different signed bundle under
the same job ID. That is the drift the stored-inputs invariant forbids.

The record now has the per-miner bootstrap rebuild call the borrowing
builders directly. It takes its own build_slots permit after the
single-flight entry's permit is released. Its inputs are the synthetic
share build_bundle fabricates today, the template, anchor, payout_policy
and ctv stored in StoredPrepared, and the balances and revision read_window
returned. #273's must-not row now forbids build_bundle for any resume
rebuild.

Part of #261.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs: readable imported audits and a race-free upgrade order (#264)

Two fixes to the WindowRef design record after review.

Imported legacy audits: #265 stores canonical_audit_bytes and no inline
body. Only audit_canonical_bytes reads those bytes today. Ledger::audit_bundle
returns just the JSON column, so backfill-ctv would stop on imported rows,
and the bundle endpoint's fallback reads only body_uri. The record now
requires the same PR to make both readers decode the stored canonical
bytes first, digest-checked and under spawn_blocking. Leaving an imported
audit readable only through body_uri is now forbidden.

Upgrade order: a zero pending count taken while the pre-007 frontends still
run proves nothing, because a block can be found before they stop. The
count is now taken after every frontend is stopped. A non-zero count means
restarting the pre-007 frontends to drain and repeating, and 007's refusal
remains the backstop.

Part of #261.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs: one owned window per Prepared and the established lock order (#264)

Two fixes to the WindowRef design record after review.

Window ownership: Prepared and JobContext would have held an owned
AuditBundle beside the Snapshot. into_bundle takes the share Vec by value,
and two Arcs don't share storage, so every resume would keep a second
window: about 0.75 GB per 400k rebuild instead of 0.5 GB. Both structs now
hold Arc<Snapshot>, the only owned window, next to Arc<AuditBundleBody>.
Canonical bytes and verification come from the parts functions, and an
owned bundle is assembled only at claim.

Lock order: the D6 prune now takes SETTLEMENT_LOCK and then ORDER_LOCK,
the order every existing dual-lock site uses, so it can't form an
advisory-lock cycle with a refresh snapshot or a candidate finalization.

Part of #261.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs: version the audit builder behind durable references (#264)

Stored inputs reproduce a bundle only under the builder that first built
it. If a release changes builder output, a pending candidate that survived
the upgrade would rebuild into a different bundle than its coinbase commits
to, and fail on every retry or land changed audit data.

qbit-prism gains AUDIT_BUILDER_VERSION, which both the 007 candidate and
008's StoredPrepared store. A rebuild checks it before read_window: a
mismatched candidate is retried with an alert and never rebuilt with the
current builder, and a mismatched job is a cache miss. A release that
bumps the constant ships a migration step that refuses while pending
outbox rows carry another version; they drain through the 007 procedure.
Keeping frozen old builders is recorded as the rejected alternative.

Part of #261.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs: pin the signing keys behind durable references (#264)

The bundle embeds both public keys and their signatures, so a rebuild
reproduces the original bytes only under the original keys. Rotating a
key takes an operator resetting the cluster fingerprint, and a candidate
still pending across that reset would be re-signed into bytes its
coinbase does not commit to.

Both documents now store signer_keys, the two public keys the building
frontend signed with. A rebuild checks them next to the builder version,
before read_window, and never re-signs a mismatch with the local keys.
#265 extends configure to refuse a new fingerprint while a pending outbox
row stores other keys, so the operator drains with the old keys first.
Keeping retired seeds online to reproduce old signatures is recorded as
the rejected alternative.

Part of #261.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs: reuse the refresh-time WindowRef at submit (#264)

Submit built the candidate's reference from the prepared Snapshot, which
re-hashes and re-serializes the whole 233 to 260 MB window whenever a
block is found. That puts 0.7 to 1.4 s of digest CPU on the
latency-critical share path, on top of the once-per-refresh cost the
cost table budgets. refresh_once already computes the identical
reference, so Prepared now keeps it as window: WindowRef. Submit clones
that small value into the candidate, a resume takes it from
StoredPrepared, and re-digesting at submit is a must-not for #265.

Part of #261.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs: sort rebuilt prior balances canonically (#264)

prior_balances_digest sorts internally, but AuditBundle.prior_balances
serializes in vector order. read_prior_balances has no outer ORDER BY,
and SQL doesn't guarantee the function's internal order through a table
expression. Balances returned in a different order at claim or resume
would pass the digest check and still change the canonical bundle.

read_prior_balances now sorts with the digest's comparator (order_key,
recipient_id, p2mr_program_hex, byte order). Refresh and every rebuild
share that function, so the builder gets the same vector. A SQL ORDER BY
alone would follow the database collation, not the digest's byte order.
A #265 unit test requires permutations to give identical bytes.

Part of #261.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs: finish recovered claims from landed digest columns (#264)

A claim that finds its block's audit already landed finished through
materialize_audit_row. That function reads the whole range unpaged,
serializes and clones it on the async runtime, and builds an owned
AuditBundle: two share arrays at 400k on the submit loop, which the
cooperative 60 s deadline cannot interrupt.

The recovery branch now checks the landed row's columns alone, as
today's landing does for an existing audit. share_snapshot_sha256 must
equal window_snapshot_sha256, found_block_bits must match the header,
and the claim then finishes. materialize_audit_row on the submit loop is
a #265 must-not. If that path ever needs the body, #267's paged,
parts-based reader becomes a prerequisite.

Part of #261.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs: re-pin the WindowRef record to 3.x.x after #283 (#264)

#283 landed through #300: the 2.x.x tip merge and the split of ledger.rs
into candidates, jobs, window and connect submodules. The record's code
citations were pinned to 1398bbc, and many pointed into the old ledger.rs.
Every citation now resolves at 3.x.x 41a2afd: 76 of 252 changed, and all
247 cited line numbers were checked against that tree.

"Where the code lives" now describes what #300 landed. ledger/window.rs
exists under workstream B and already holds share_from_row and
read_prior_balances, and SELECT_SHARE stays in the module root. The only
question left for Anatolie is whether read_range moves out of A-owned
ledger/audit.rs.

Two review fixes in the landed-audit recovery path. A retried claim
authenticates the landed audit against the block it found: the landed
coinbase must match block_hex, and the root of the landed commitment
leaves must equal the coinbase's witness reserved value. For an empty
window, the snapshot comparison uses the digest of [bootstrap_share],
because window_snapshot_sha256 is NULL there.

Part of #261.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs: keep pool connections free during window rebuilds (#264)

build_slots bounds concurrent rebuilds at build_workers, but that doesn't
protect the database pool. PRISM_DATABASE_MAX_CONNECTIONS may be as low as
4, build_workers may exceed it, and share appends and candidate-lease
heartbeats share the pool with a 15 s acquire timeout. Rebuilds of
distinct jobs could hold every connection for their whole multi-page
reads, and a heartbeat that fails to get a connection drops recoverable
claim work.

read_window now also takes a permit from a window_reads semaphore sized
clamp(database_max_connections - 2, 1, build_workers). The caller takes it
after build_slots and releases it before the rebuild, so two connections
always stay free. Calling read_window without that permit is a must-not
for #265 and #273. A dedicated pool was rejected because it would exceed
the configured connection budget.

Part of #261.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs: continue to submission after recognizing a landed audit (#264)

The recovery path finished a claim as soon as it authenticated a landed
audit. But an inactive block lands before the lease renewal and
submitblock, so an earlier claim can land and lose its lease before it
submits. Finishing then would abandon a valid found block that was never
submitted.

A recognized landed audit now means landing is done. The claim skips
read_window, the rebuild and land_candidate, and continues through
today's observe, renew and submitblock flow, finishing only where today's
code does: an active block, or an inactive one whose revision or parent
moved. Finishing a claim only because its audit landed is a #265
must-not.

Part of #261.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs: reserve in-flight windows and scope the claim deadline (#264)

Two review fixes.

The retention floor covered written references only. Ledger::snapshot
releases its locks when its first transaction commits, and the scan, the
bundle and save_job follow with no row referencing the window yet. A prune
in that gap, after a fall in difficulty, could delete rows of the window
being built. D6 now adds a reservation. The snapshot's locked first
transaction inserts it, the refresh fills in the window start after the
scan, and save_job deletes it (publishing nothing if it expired or the
rows are gone). The prune skips while any reservation is unresolved and
otherwise keeps every reserved window. An age-based horizon was rejected
because a window's reach in time depends on hashrate.

The claim's 60 s timeout covered the whole call, including submitblock,
whose RPC timeout may be up to 86,400 s. It now covers read_window plus
the rebuild only, and the later steps keep their existing deadlines.

Part of #261.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs: answer djh58's four B contract points (#264)

djh58's review on #273 (comment 5624891010) raised four points against
the resume contract. The record now:

- lets B's published-identity and lease check decide resume eligibility
  instead of revision equality, and rebuilds eligible work with its
  as-issued balances from an immutable qbit_prism_balance_snapshots row
  keyed by prior_balances_digest;
- keeps reconstruction failures (Incomplete, digest mismatch, decode,
  database, expiry) distinct from missing work, under one end-to-end
  deadline, the caller's existing initial_job_timeout_seconds, with no
  inner timeout;
- names both share digests, the native snapshot_sha256 and #274's
  canonical_digest_hex, amends #274's reuse instruction, and adds a cost
  model for a sliding window;
- moves the template out of the prepared payload into an immutable
  qbit_prism_templates row, keeping #273's 1 MB criterion whole-value, and
  moves #265's block_hex into a bytea column.

It also records the permit-ownership and coalesced-waiter rules from the
same review.

Part of #261.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs: add the balance source to read_window and authenticate block bytes (#264)

The resume contract needs as-issued balances, but read_window's declared
API had no way to ask for them, and the read algorithm always used the
current set. Implemented literally, it would have returned
PriorBalancesChanged for the published work it was meant to rebuild.
read_window now takes a BalanceSource. Current reads the current view as
before. AsIssued reads the qbit_prism_balance_snapshots row keyed by the
reference's digest, sorts it with the digest's comparator and verifies it.
A missing row is the new BalanceSnapshotMissing, and a mismatching one is
Decode. Claims pass Current, and resumes of published work pass AsIssued.

Moving block_hex to a bytea column took it out of candidate_sha256. The
candidate JSON now keeps block_sha256. Claim decode checks it and that the
block header hashes to block_hash before any witness derivation, landing
or submission.

Part of #261.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs: prune externalized templates and balance snapshots with their jobs (#264)

Moving each full template into an immutable qbit_prism_templates row left
no cleanup for those rows. Templates change on every new transaction set
and at every reanchor, so each is a new, possibly multi-megabyte row, and
prune_expired_jobs deletes only job rows. The balance snapshots had the
same gap.

prune_expired_jobs becomes one transaction under SETTLEMENT_LOCK, the lock
save_job holds while it inserts the template, the balance snapshot and the
job row. It deletes the expired batch, then the template and balance rows
that batch referenced and no remaining job row references, in two
statements, because a data-modifying CTE's NOT EXISTS would still see the
deleted jobs. The job row gains an indexed template_sha256. Balance
snapshots follow job rows only, since claims read the current balances.

Part of #261.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs: keep the issued revision on resume and ratchet D6's horizon (#264)

Two review fixes.

A resumed Snapshot now keeps StoredPrepared.payout_revision, the revision
the job was issued with. read_window's current revision is only B's
eligibility input and the claim's probe hint. The job wire and any
candidate take their revision from the snapshot, so a block found on R0
work carries R0, and observe_candidate takes the superseded path instead
of retrying PriorBalancesChanged forever.

A D6 horizon computed from today's difficulty fails when difficulty rises
after a prune: Ledger::snapshot stops when rows run out, so it would
publish an underweight window. D6 now needs a ratcheted horizon kept at a
durable maximum difficulty in qbit_prism_cluster. It must also record the
share_seq it deleted below, so snapshot fails when its scan reaches that
floor before the requested weight.

Part of #261.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs: drop rebuilt windows from resumed jobs once the coinbase is built (#264)

build_workers bounds how many rebuilds run at once, not how many rebuilt
windows stay resident. Each resumed JobContext kept its Prepared, with
Arc<Snapshot> and Arc<AuditBundleBody>, and a session keeps up to 64 jobs
per connection. Sequential resumes of different jobs could therefore pin
about 0.5 GB each, and the stated k x 0.5 GB peak didn't hold.

Once the rebuild has produced the job's coinbase, a resumed Prepared keeps
only what submit reads: the WindowRef, the snapshot scalars, the template,
the fee and the body's non-window fields. Submit reads nothing else, and
the whole-bundle clone into the candidate goes with #265. Snapshot.shares
and reward_manifest.shares are dropped before the job reaches the session,
so windows exist only inside rebuilds.

Part of #261.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs: stop old signers before a reset and fence writes on the fingerprint (#264)

configure's one-time pending-row check could pass while an old-key
frontend was still running. That frontend could then find a block and
enqueue a candidate with the old signer_keys, which no new-key frontend
can rebuild, and enqueue is not fenced by the fingerprint today.

A rotation now follows the 007 order: drain, stop every old-key frontend,
then check that nothing is pending, reset and start the new frontends.
#265 and #273 also re-read config_fingerprint FOR SHARE inside every
enqueue and save_job transaction and refuse writes under a foreign
fingerprint. FOR SHARE conflicts with configure's FOR UPDATE, so a write
and a reset cannot interleave, and a procedure violation fails loudly
instead of leaving rows nobody can rebuild.

Part of #261.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs: keep every stored input in slim resumed jobs (#264)

The slim resumed Prepared kept the WindowRef, the snapshot scalars, the
template, the fee and the body's non-window fields, but not the stored
payout_policy and nested ctv. A candidate found on that job must persist
those exact inputs, and neither the fee nor the coinbase manifest can
recover them, so submit would have had to read local configuration.

The slim form now keeps the decoded StoredPrepared itself: payout_policy,
the whole ctv, audit_builder_version, signer_keys, coinbase_suffix,
template_sha256, the WindowRef and the snapshot scalars, all O(1). For an
empty window it also keeps the miner's own bootstrap_share. Only the
window is dropped. Dropping a stored input before enqueue is a #273
must-not.

Part of #261.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs: let the published-work lease reach submission (#264)

Keeping R0 on a resumed snapshot doesn't help if its found block never
reaches observe_candidate. Today submit rejects work whose frontend or job
revision differs from the ledger's, apart from parent-stale work inside
the stale grace. That grace work is credited as a share, but a candidate
is enqueued only when the work isn't stale, so its block is dropped.

B8's lease now decides those submit checks the way it decides resume
eligibility. Work the lease covers is not stale because the revision
changed, and a block found on it is enqueued as a candidate carrying R0,
with its as-issued window and inputs. observe_candidate then decides at
claim whether it lands. Work outside the lease keeps today's handling.

Part of #261.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs: submit leased candidates first and clear terminal block bytes (#264)

Two review fixes.

A candidate enqueued from leased R0 work still met the unchanged claim
fence, which would finish it as superseded before submitblock and discard
the block. The candidate now records a leased flag. A leased candidate
skips the pre-submit supersession checks and the pre-submit landing,
renews its lease, calls submitblock, and only then meets
observe_candidate. Whether an active leased block lands is B8's rule with
#289.

Moving block_hex into the block_bytes bytea column meant the terminal
UPDATE no longer removed the block. It now NULLs block_bytes too, so the
outbox doesn't keep every finished block forever.

Part of #261.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs: correct claim-flow line citations to 3.x.x 41a2afd (#264)

The landed-audit continuation and leased-candidate paragraphs cited
coordinator.rs claim-flow lines read from a later 3.x.x, where #308 had
shifted them by five. They now point at the record's pin, 41a2afd:
the post-rebuild observe at :1039, the active branch at :1040-1048, the
inactive supersession at :1050-1063, the landing at :1067-1069, the
post-land check at :1070-1080, the lease renewal and submitblock at
:1084-1092, and the post-submit observe at :1095.

Part of #261.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs: submit leased candidates before any rebuild (#264)

A leased candidate skipped the pre-submit fences, but the #265 claim
rebuild still called read_window with BalanceSource::Current before
them. For an R0 candidate that returns PriorBalancesChanged and retries
forever, so the block never reached submitblock.

A leased candidate now submits before any rebuild, because submitblock
needs only the stored block. If the block is active, its audit rebuild
uses BalanceSource::AsIssued. A non-terminal leased outbox row therefore
keeps its balance snapshot. The prune checks for such rows and takes
SETTLEMENT_LOCK then ORDER_LOCK, so it cannot interleave with a leased
enqueue.

Part of #261.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs: release rebuilt windows off the runtime; hold the lease to unchanged balances (#264)

Two review fixes.

Freeing a completed rebuild's last Arc<Snapshot> and Arc<AuditBundleBody>
drops about 0.5 GB on whichever Tokio worker releases it, which can stall
lease heartbeats and share processing. The rebuild's spawn_blocking closure
now builds the coinbase and the slim resumed form and drops the window
there. Every other release of a rebuilt window goes through
spawn_blocking(drop).

An active leased block rebuilt with R0's balances could not land, because
landing requires the current balances. Until B8 and #289 define how such a
block lands, the lease covers only revision changes that leave
prior_balances_digest unchanged, and a balance change ends it at once. An
active leased block then lands through today's path, and the open
question asks djh58 and #289 for the full rule.

Part of #261.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs: land first-time claims from parts; sweep orphaned balance snapshots (#264)

Two review fixes.

A first-time landing assembled the rebuilt window into an AuditBundle, then
cloned it, serialized it whole for the stored body and the canonical length,
and re-read the range unpaged, all on a Tokio worker. At 400k shares that is
several half-gigabyte representations on the runtime. CandidateClaim now
holds the parts. Landing verifies, serializes and digests them in one
spawn_blocking closure before its transaction opens. It keeps the range
fence, but as a paged re-read. #267 is not a prerequisite.

The balance-snapshot prune only considered digests from the expired batch,
so a snapshot kept alive by a leased candidate could never be reclaimed once
its job had gone. Snapshots now get their own statement over every row with
no remaining reference.

Part of #261.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs: keep the bootstrap share in local jobs; correct local window residency (#264)

Three review fixes.

An empty-window local job held its only full AcceptedShare in
JobContext.bundle. Once JobContext holds a body, that share would be gone
and submit could not fill Candidate.bootstrap_share. JobContext now keeps
the synthetic share beside the body.

The record claimed the local frontend keeps one full window. Retired local
jobs keep their generation's Prepared for Stratum's retention period, as they
do today. The record now says so. Bounding that is logged as a #273
acceptance note.

The landing bind still copies the stored body into SQLx's argument buffer on
the runtime. The record now names that copy. Measuring it is logged as a
#265 acceptance note.

Part of #261.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs: keep null-response leased candidates pending; carry empty-window balances (#264)

Two review fixes.

The record finished an inactive leased candidate as superseded after
submission. Today's wrapper treats a null submitblock result on an inactive
block as unresolved, because it can still be a known side-chain block, and
retries with the candidate intact. Leased candidates now keep that outcome,
so a block that becomes active later still has its audit inputs.

For an empty window, resume waiters build their own bootstrap bundles from
the as-issued balances. The single-flight entry now carries those balances
until every waiter has built, instead of only the rebuilding caller holding
them.

Part of #261.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs: land a submitted leased candidate before any terminal outcome (#264)

After a null submitblock result on an inactive leased block, the retry
resubmitted before landing. A node can then answer "duplicate", which the
string branch treats as terminal, clearing the unlanded audit inputs.
Today's flow avoids that by landing an inactive block before its RPC, so a
late acceptance stays reconcilable.

A leased candidate still submits first, so delivery never waits on a
rebuild. It then rebuilds with AsIssued and lands at the observed
revision before any terminal outcome, whether or not the block is active,
and only then takes today's three outcomes.

Part of #261.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs: re-establish candidate references inside the enqueue transaction (#264)

Taking locks in order stops a prune and an enqueue from interleaving, but
it doesn't decide which runs first. A submission that passed its expiry
check could lose to a prune that deleted the job row and its balance
snapshot, and then enqueue a leased candidate pointing at missing data.

Enqueue now re-inserts a leased candidate's balance snapshot from the
as-issued balances the job carries (the slim resumed form keeps them),
and probes the window's first share row, both inside its ORDER_LOCK
transaction. Shares can't be written back, so an expired job row now holds
the retention floor until the prune deletes it, and the prune waits a grace
past expiry. A failed probe still publishes the candidate, with an alert.

Part of #261.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>

* 3.x.x: make Prism session sequence wrap-safe (#319)

* fix(prism): reserve session extranonces safely across sequence wrap

* fix(prism): fence stopped session owners by process incarnation

* fix(prism): drain session guards before shutdown cleanup

* fix(prism): scope migration readiness to mining startup

* test(prism): build complete legacy schema for read-only connect

* fix(tests): route integration databases through test gate

* test(prism): register all gated session coverage

* fix(tests): adapt fixtures to shared session backend

* 3.x.x: Generate native metric inventory and migrate deployed alerts (#320)

* docs(prism): generate metric inventory and migrate deployed alerts

* fix(prism): preserve the network-wide connected client alert floor

* fix(prism): evaluate standby lag from observed durable WAL progress

* fix(prism): delete provisioned native rules when gates disable them

* fix(prism): alert on invalid synchronous standby configuration

* docs(prism): record local review evidence and prepare PR draft

* fix(prism): reject stale alert and metric metadata

* fix(prism): alert when public scrape fails

* fix(prism): preserve native failure and paging alerts

* fix(prism): preserve native alert tuning overrides

* Revert "fix(prism): preserve native alert tuning overrides"

This reverts commit 31b26812ef133a6cfb7e76deefb11e50a2bf306e.

* fix(prism): preserve configurable alert tuning

* fix(prism): render tuning dwells as JSON

* fix(prism): validate rendered alert dwell overrides

* 3.x.x: finish native health contract evidence (#329)

* docs(prism): pin intentional legacy health differences

* docs(prism): correct legacy max blocks semantics

* style(prism): format health snapshot assertions

* v3.0.0 feat: add prepared-window reference foundation (#327)

* fix: preserve PRISM issued-work and stale-grace semantics

Separate observed and published tip authority, retain original issued
worker context through replacement and reconnects, and preserve bounded
delivery-based grace without renewing expiry after awaited work.

Exercise real Coordinator decisions and socket interleavings, including
constant node-RPC load across 1, 32 and 128 clients.

Refs #280

* docs: reference PRISM miner parity settings

Co-Authored-By: OpenAI Codex <[email protected]>

* fix(prism): bind share admission to one published payout view

* fix(prism): verify changed block notifications with fresh chain state

* docs(prism): record B8 review regressions and rebased qualification

* test(prism): adapt merged admission fixture to stale grace contract

* fix(prism): classify retained capacity by current published tip

* fix(prism): retain prepared dependencies for issued work

* test(prism): verify issued job dependency persistence

* fix(prism): keep sessions alive while retained work is usable

* docs(prism): record timer coverage and final qualification procedure

* docs: point D2 credit explanation to miner submit module

* test: align candidate lease tip fixture with coordinator state

* fix: integrate miner parity with native metrics registry

* fix: integrate miner parity with metrics registry API

* ci: run issued job dependency acceptance explicitly

* test: keep miner parity fixture publication reachable

* test: complete JSONB gate fixture config

* docs: specify prepared window reference integration plan

* test: restore D2 coordinator coverage

* feat(prism): add window reference schema and authenticated reader

Add the independently approved B273 schema and reader foundation on PR313, with typed reconstruction errors, immutable blob tables, per-version migrations, and PostgreSQL qualification. Runtime prepared/resume, candidate, atomic repair and GC integration remain gated on A265 and shared owner agreement.

* feat(prism): add coherent payout state for lease eligibility

* Keep cancelled window cleanup off runtime workers and qualify current base

* Qualify landed 008 and 009 migration orders on current base

* Preserve legacy balance order and reject fatal window reads

* Prove legacy balance order preservation in PostgreSQL

* Run all gated suites before manifest proof

* Revert "Run all gated suites before manifest proof"

This reverts commit b11cbbb183927db9b51daf6bf0176a09c4afc0b8.

---------

Co-authored-by: OpenAI Codex <[email protected]>

* 3.x.x: store imported legacy audits as canonical bytes and decode them on read (#325)

* 3.x.x: store imported legacy audits as canonical bytes and decode them on read

The legacy-audit import wrote the parsed bundle back into the
audit_bundle JSONB column. That value holds two copies of the payout
window (shares and reward_manifest.shares), so at 400k shares it
crosses PostgreSQL's JSONB container limit. The import now stores
only canonical_audit_bytes and the non-share metadata. It keeps its
idempotency and optimistic guards, verifies off the runtime, and drops
the parsed window before the write transaction opens. Rows that
already hold an inline body keep it unchanged, because the
body-present CHECK needs one of audit_bundle and body_uri.
found_block_bits stays as stored: no audit body carries the compact
bits.

A shared decode_canonical_audit_body helper checks the stored bytes
against audit_bundle_sha256 and parses them with
parse_audit_bundle_value. It returns the logical body the import used
to store inline, and all of that work runs under spawn_blocking.
Ledger::audit_bundle serves native snapshot rows first, then imported
canonical bytes, then inline bodies, so backfill-ctv works on imported
rows. The bundle endpoint serves imported bytes before any body_uri
fallback, on the same public pool. A digest mismatch or undecodable
bytes refuses the row, even when the legacy file still exists. The
settlement-artifacts audit link now also accepts stored canonical
bytes, so it does not decode a whole body just to show a link.

The JSONB ceiling gate drops its import-phase known violation, and the
measurement and capacity-readiness docs now count three
window-carrying writes.

Part of #265.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* 3.x.x: load only the served audit body and bound imported-audit decodes

The bundle queries now project no inline audit_bundle for a row whose
canonical bytes supersede it, the same rule Ledger::audit_bundle uses,
and report whether canonical bytes exist so bundle() skips the bytes
query for rows without them. The flag is removed before responding.

Imported-audit decodes run after their read connection is released, so
ApiState now carries a semaphore sized from the same read concurrency as
the public read pool. bundle() takes an owned permit inside the
request's existing deadline and moves it into the blocking decode, so a
dropped request cannot free it before the decode ends. Ledger::audit_bundle
takes no permit and releases its fetched row before decoding.

The decode refuses body-ref and v2 envelope schemas, since canonical
bytes are always a flat bundle. The storage-sizing doc describes the
canonical-bytes import, and the measurement doc gains a post-#265 note.

Tests pin the pre-change row shape (inline body, canonical bytes and
body_uri, no snapshot), bound the decode across a dropped request, and
refuse a digest-valid body-ref envelope.

Part of #265.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>

* 3.x.x: add deterministic HA readiness probe harness (#331)

* test: add deterministic HA readiness probe harness

* test: qualify readiness probe timing

* test: preserve probe state in jsonl harness

* test: harden readiness probe input boundaries

* test: reject overlapping readiness probes

* docs: use generic HA readiness contract wording

* test: classify malformed probe durations as failures

* 3.x.x: reconcile share-commit deadlines instead of dropping the append (#333)

* ledger: let append callers veto COMMIT at the last moment

append_at_revision_gated takes a non-optional pre-commit hook. It runs at
most once, after every statement including persist_candidate has
succeeded, while ORDER_LOCK is held and immediately before COMMIT. A false
return rolls the transaction back explicitly and fails with the typed
CommitGateClosed error, so COMMIT is never sent. append and
append_at_revision keep their signatures and pass no hook.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* metrics: count late share confirmations and unknown outcomes

A share whose commit is confirmed after the acknowledgement deadline is
still accepted, and a commit whose outcome cannot be established is no
longer reported as a clean rejection. Both need their own signal.

Add the late_confirmed_shares_total family, recorded through
record_late_confirmation and zero-registered like the other counters, and
the ledger-outcome-unknown reject reason. Without the new reason, an
unknown outcome would fold into internal-error.

PrismShareAppendFailures paged on any ledger-confirmation-failed, so it
now matches the unknown reason too and keeps its low-volume total-write-
failure coverage. The deployment patch is regenerated from the reviewed
snapshot, and a scenario covers the new reason alone.

Document the narrowed meaning of ledger-confirmation-failed, the new
reason, the statement-timeout guard, and the block-only acknowledgement
bound.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* coordinator: reconcile share-commit deadlines instead of dropping the append (#324)

submit wrapped the whole persistence future in a timeout and dropped it
when the deadline fired, answering ledger-confirmation-failed. If COMMIT
had already been flushed, sqlx drained the reply and reused the
connection, so the share was committed and credited without an
acknowledgement. A load harness reproduced that: 164 such rejections, two
of them committed rows. The block-only path committed its candidate
first, so its timeout always led to a later credit with no
acknowledgement.

Run the append in a task behind a one-shot commit gate. At the deadline
the acknowledgement path either closes the gate, which proves COMMIT was
never sent and aborts the doomed append, or finds the commit already in
flight and awaits its reply for share_commit_grace. Only a server error
of severity ERROR is a definite rejection; every other error, and a
commit that outlasts the grace, is answered ledger-outcome-unknown and
logged with its eventual outcome. A confirmation whose commit took at
least the effective statement_timeout is also unknown, because a
cancelled synchronous-replication wait commits only locally.

An append carrying a found-block candidate is never refused, since that
would discard the block; it waits for block_only_ack_timeout instead.
Block-only proofs always finish their enqueue and then follow the
candidate's disposition within the same bound, and poll errors after the
enqueue never become a rejection.

The new bounds are Config fields rather than environment variables, and
statement_timeout is read from the session the ledger pool actually uses.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* coordinator: bound the block-only enqueue wait and time COMMIT in the task

Review feedback on PR #333.

enqueue_candidate_once was awaited directly, outside the bound that covers
every other step of a block-only submission, so a degraded database could
hold the acknowledgement open well past block_only_ack_timeout. Wait for it
in a task until the bound instead. The enqueue still runs to completion,
because cutting it off could strand a COMMIT that was already sent, but the
miner is answered ledger-outcome-unknown on time and the enqueue's eventual
outcome is logged.

The synchronous-replication guard compared statement_timeout against a
COMMIT duration measured when the coordinator classified the finished task.
Scheduler delay after a successful COMMIT therefore counted as database
time and could turn a durable accepted share into an unknown one. Measure
the duration inside the append task, where COMMIT actually finishes.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* metrics: count a late confirmation from when the append finished

Review feedback on PR #333.

late_confirmed_shares_total was decided by reading the clock while the
acknowledgement was being processed, which can be arbitrarily later than the
append itself. A coordinator task scheduled late therefore counted an
on-time confirmation as a late one. Decide it from the instant the append
finished, which the task already reports, and record it where that instant
is known.

The help text also claimed every counted share was confirmed within the
grace period. That was never true of a share-pass submission carrying a
found-block candidate: those are deliberately never refused, so they can be
confirmed later still, up to the block-only bound, and they are counted.
Say what the counter measures instead, and spell the found-block case out
in the metrics documentation.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>

* perf(metrics): remove allocations from closed-label event recording (#344)

* 3.x.x: add bounded PostgreSQL WAL qualification helper (#330)

* test(prism): add bounded PostgreSQL WAL measurement helper

* fix(prism): harden WAL qualification failure semantics

* fix(prism): harden WAL helper validation and outcomes

* fix(prism): sanitize WAL helper connection inputs

* test(prism): cover WAL helper outcomes and scope

* fix(prism): preserve WAL operation outcome uncertainty

* fix(prism): bound WAL measurement subprocesses

* fix(prism): complete WAL helper diagnostics and test coverage

* test(prism): repair WAL helper test layout

* test(prism): stabilize WAL diagnostic mocks

* 3.x.x: Measure the share-append throughput floor against PostgreSQL (#323)

* 3.x.x: measure the share-append throughput floor against PostgreSQL

test/test-prism-postgres-throughput.sh measured `cargo run -- benchmark`, a
CPU-only run of the audit builder with no database at all, and the 2.x.x
report it replaced measured one bulk INSERT ... SELECT ... FROM
generate_series. Neither says anything about the path a share actually takes.
Every native share append is one transaction that takes the cluster-wide
ORDER_LOCK advisory lock, checks writability, bumps the single-row ledger
clock and writes two rows, so share appends are serialized cluster-wide, and
nobody had measured that with more than one writer.

tests/throughput_floor.rs seeds a payout window with the #264 fixture
generator and then appends through Ledger::append at 1, 2 and 4 concurrent
appenders, each appender holding its own Ledger with its own pool and its own
instance_id, as separate production frontends do. A connection outside every
appender pool samples pg_locks for backends queued behind ORDER_LOCK while a
level runs, and the report says how many waiters it saw and for how long --
labelled throughout as sampled estimates, with the episode count a lower
bound, because a wait shorter than the 10 ms interval can be missed entirely.
A sampler that fails reports null and the error, never zero.

The report is qbit.prism.postgres-throughput.v2, a deliberately new schema
name: its numbers must never be read against v1's bulk-insert rate. It is
written before the floor is asserted, so a run that fails the floor still
leaves its evidence behind. Every QBIT_PRISM_* input is validated at entry,
before a connection is opened: nan, inf, a negative or an empty floor are
configuration errors rather than extreme floors, and a window size that does
not divide the fixture's window weight would not produce the window it claims
to.

CI_MIN_SHARES_PER_SEC is provisional -- 25% of the slowest level rate measured
in a debug build on the writer's host. Debug is the right base because CI runs
this test in debug, and the wide margin is honest about the fact that nothing
has calibrated it on the 2-vCPU runner yet.

Part of #271

Co-Authored-By: Claude Opus 5 <[email protected]>

* 3.x.x: point the throughput script and target at the share-append floor

test-prism-postgres-throughput ran `cargo run -- benchmark`, which measures
the audit builder's CPU cost and never opens a database, so the target named
after PostgreSQL throughput was not measuring PostgreSQL at all. It now runs
the full-size share-append floor: the ignored throughput_floor test, in
release, against PRISM_TEST_DATABASE_URL when one is set and otherwise through
prism-native-tests.sh, which initdb's a disposable cluster on a random
loopback port and removes it on exit.

The builder benchmark has not gone anywhere and is still worth running; the
script says so, and gives the exact command, because it answers a different
question rather than a worse version of this one.

`set -e` is suspended around the test so the report path is printed on a red
run too -- the test writes the report before it asserts the floor, so a run
that fails the floor is exactly the run whose report someone wants to read --
and the test's exit status is re-raised immediately afterwards. Every
QBIT_PRISM_* variable reaches the test process unchanged; the script reads
none of them except to say where the report landed.

Part of #271

Co-Authored-By: Claude Opus 5 <[email protected]>

* 3.x.x: resolve pg_stat_statements by schema, not by search path

The pg_stat_statements probe was `to_regclass('pg_stat_statements')`, and the
read and the reset named the view unqualified. Every connection in this run
carries `options=-csearch_path=<run schema>`, which replaces the search path
rather than prepending to it, so `public` is not on it. On a server with the
extension installed in `public` the probe therefore returned NULL and the
report said "unavailable" about a view that was sitting right there -- an
EP-OBSERVABILITY failure of exactly the kind the rest of this file is careful
about, because it reads as "this server cannot tell us" when the truth was
"this query looked in the wrong place".

The extension's schema is now resolved from pg_extension and the server's own
quote_ident, and both the reset and the read qualify with it. Verified against
PostgreSQL 16.15 with `shared_preload_libraries=pg_stat_statements` and the
extension created in public: the block now reports 2000 calls per level, and
its total_exec_time corroborates the sampler closely -- 4254 ms against a
sampled 3.97-4.31 waiter-seconds at two appenders, and 17387 ms against a
sampled 16.9-17.3 at four. Two independent methods agreeing to within a few
percent is worth more than either alone, which is the whole reason the block
is there.

Part of #271

Co-Authored-By: Claude Opus 5 <[email protected]>

* 3.x.x: attribute ORDER_LOCK waits to the run that caused them

The adversarial review found that the per-run schema isolates the tables but
not the lock. ORDER_LOCK is a PostgreSQL advisory lock and an advisory lock is
scoped to the database, so any other backend appending shares into the same
database serialises against this run's appenders, and the sampler -- filtered
only by database -- counted those foreign waits as this level's. Measured on a
quiet server against the same server with one other appending process, the
rates fell 40-57% and nothing in the report said why. A run like that either
fails a calibrated floor for a reason that is not the append path, or, once the
margin narrows, passes on a number describing two workloads.

Every connection this run opens now carries a per-run application_name,
`throughput-<uuid>`, pushed through the URL -- which is the only thing
Ledger::connect is handed, so the seeding ledger, every appender ledger and the
sampler all announce themselves without any production code knowing this test
exists. sqlx 0.8 parses the parameter out of the URL and sends it in the
startup packet, but the run does not take that on trust: it reads
current_setting('application_name') back on its first connection and refuses to
measure anything if the server disagrees, because a silently ignored parameter
would make every foreign backend look like ours and every contaminated run look
clean.

The sampler then reports this run's waiters as before, and foreign_waiters_max
and foreign_backends_seen beside them. A foreign backend counts whether it was
waiting on the lock or holding it: either way it is serialising against these
appends. A backend whose pg_stat_activity row this role may not read counts as
foreign, which is the safe direction. A level during which any foreign backend
was seen is marked contaminated, in the level, at the top of the report and in
the floor's failure message; it is still measured and still gated, because the
rate is what the appends really achieved, but the report now says plainly that
the number describes a shared database and must not be carried forward.

contaminated is null, not false, when the sampler could not look. "Nobody
checked" is not "nothing was there", and the same reasoning fixes the smaller
version of that bug next door: a level that ended before the sampler completed
a poll used to emit mean_waiters 0.0, max_waiters 0 and
estimated_waiter_seconds 0.0, which reads as "nobody ever waited". Those are
null now, samples stays 0, and the error says the level ended first.

The sampler's shutdown and its interval are fixed together. It tested the stop
flag only at the top of its loop and then blocked in sleep(interval), so every
level burned up to a whole interval of dead time after its appends had
finished -- 65 seconds of wall clock for 0.43 seconds of measurement at a
20-second interval. The flag is now paired with a Notify signalled alongside
it, so the sleep is interruptible and a level ends when the appends end;
notify_one stores the permit, so the signal cannot be lost in the window
between a poll and a sleep. The interval itself is bounded to 1..=1000 ms at
entry, before any connection, with a message saying that an interval coarser
than a second cannot resolve a lock wait that lasts milliseconds.

Two other gaps the review left open. A run that dies connecting, seeding or
appending now writes a report anyway -- identity, configuration, the full error
chain, passed_minimum false and an empty results array -- so the newest file on
disk belongs to this run rather than to some earlier one; a failure to write it
is attached to the original error as context and never replaces it. And the
default report path is per test, target/prism-postgres-throughput-<test>.json,
with a "test" field in the JSON to match, because the two floor tests run in
parallel threads under --include-ignored and the survivor of a shared path was
whichever finished last, unlabelled. QBIT_PRISM_THROUGHPUT_REPORT is still the
explicit override.

Cancellation is documented rather than fixed: SIGINT kills the process before
the schema drop runs, and handling it properly needs a signal handler, which
means a dependency this test may not add. The module docs now say so and give
the query that finds and drops the leftovers, next to the standing requirement
that this run wants a database nothing else is appending to.

Part of #271

Co-Authored-By: Claude Opus 5 <[email protected]>

* 3.x.x: make the throughput script point at a report that exists

Two things the script got wrong, both of which send a reader looking for
evidence that is not there.

It printed the report path unconditionally, after the status had been
captured. On the fallback path with PRISM_TEST_DATABASE_URL unset and no local
server binaries, the run dies before the test starts and writes nothing, yet
the script still announced a file. It now prints the path only when the file is
actually on disk, and otherwise says that no report was written and where it
would have been. The exit status is unchanged either way.

It also pointed at the old shared default path. The test writes
target/prism-postgres-throughput-<test name>.json now, one per test, so the
script derives its path from the test it runs rather than from a constant that
has moved.

The header gains the two warnings the test itself carries. ORDER_LOCK is
database-wide, not schema-wide, so this must run against a database nothing
else is appending to; a run that shares one is marked contaminated and its
number describes two workloads. And a cancelled run leaves its
prism_throughput_<uuid> schema behind, so the header gives the query that finds
the leftovers and the statement that drops them -- unnecessary on a disposable
cluster, which is thrown away whole, and that is the reason to prefer one.

Part of #271

Co-Authored-By: Claude Opus 5 <[email protected]>

* 3.x.x: print the floor's per-level rates where CI can see them

The floor test prints its rates with println!, and libtest throws away the
captured output of a passing test. CI keeps no report artifact either, so a
green prism-native-postgres run recorded nothing about how far above the floor
it was, and the provisional CI_MIN_SHARES_PER_SEC could not be calibrated from
CI at all.

After the report is written, the test now emits one summary line through
std::io::stderr() directly, which the test harness does not capture: the test
name, build profile, window, shares per level, the rate at each appender
count, the floor, the verdict and the contamination flag. Every CI log then
carries the margin the floor is set from. A failed write is ignored, because
the report file already holds everything the line summarises.

Part of #271

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* 3.x.x: move the throughput floor onto the shared integration gate

#322 replaced every test's private copy of the database guard with one
shared gate, qbit-prism-test-gate, and made the prism-native-postgres job
prove that each gated test executed against test/prism-gated-tests.txt.
The floor still carried its own copy of the old guard, which the new
check_gate_env_reads lint rejects, and it was not on the list, so the proof
step would have failed the moment the test ran.

The floor now asks the gate for its database URL, so it follows the same
decision table as every other gated test and records its decision in the
execution manifest. share_append_throughput_floor joins the list; the
full-size test is not selected in CI and stays off it.

Part of #271

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* 3.x.x: set the CI throughput floor from the CI runner's own numbers

CI_MIN_SHARES_PER_SEC was a provisional 71 shares/s, a quarter of what an
8-vCPU devbox managed, because nothing had measured the runner that enforces
it. Four runs of prism-native-postgres on blacksmith-2vcpu-ubuntu-2404, read
from the summary line the test now writes, put the slowest level of each run
at 1,290, 847, 1,242 and 1,200 shares/s (debug build, the job's PostgreSQL 16
service, a 20k-share window and 2,000 appends per level).

The floor is now 250, about 30% of the slowest level seen. Runs on that
runner differ by about a third, so the margin keeps a noisy run green, while a
3-4x collapse of the append path still fails the build. The report's source
label no longer calls the constant provisional.

Part of #271

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* 3.x.x: run the floor the disposable-cluster path was skipping

Four findings from the review of this PR, all in the paths that are hardest to exercise by hand.

The wrapper script passed cargo_args beginning with 'test' to prism-native-tests.sh, which runs 'cargo test "$@"' itself, so the second word became a test-name filter. With --exact alongside it the disposable-cluster path selected nothing, printed nothing and exited 0: the script that exists to measure the floor measured nothing whenever PRISM_TEST_DATABASE_URL was unset. The array now carries only the arguments, and the direct call adds 'test' itself.

The full-size test is selected by name, so a missing database must fail it rather than skip it; it now takes the gate's required entry point, and the CI-sized test keeps the skipping one. Resetting pg_stat_statements cleared the whole server's counters, including other databases; each level now reports the difference of two reads instead, and says so where the numbers are. The level clock started after the barrier opened, so an appender the runtime resumed first could work outside the measured window and inflate the rate; it starts before.

Part of #271

* 3.x.x: scope the lock statistics to this database and stop announcing stale reports

Two findings from review, both about a number that looks right and is not.

`pg_stat_statements` is server-wide. The level's advisory-lock figures
were the difference of two reads filtered only by query text, so an
advisory lock taken in any other database on the same server landed in
the level's count. A lock in another database cannot contend with this
run -- an advisory lock is scoped to its database -- so the level was
correctly marked uncontaminated while its lock figures described someone
else's work. Filter on `dbid`, and say so in the report's caveat.

Measured on a PostgreSQL 16 with `pg_stat_statements` loaded, over a
level during which another database took 3,000 advisory locks: the old
query attributed 3,000 calls to the level, the filtered one attributes 0.
With the fix and a concurrent foreign load of about 24,000 locks, each
level reports exactly 300 calls for 300 appended shares -- one lock per
share, which is what the append path takes.

The wrapper announced any file at the report path as this run's evidence,
so a run that died during compilation or cluster setup pointed the reader
at a previous run's report while returning a failure. The earlier file is
now moved aside before the run, which makes the report's presence
afterwards proof that this run wrote it, and it is put back if this run
wrote nothing. Deleting it instead would have destroyed the previous
run's data on a run that produced none of its own.

Timestamps were tried first and rejected: a warm build and a small window
can finish inside one filesystem timestamp tick, and a fresh report then
compares as no newer than the moment the run started, which reports a
good run as stale.

Verified end to end through the wrapper against a real PostgreSQL 16, and
for all three announcement cases: a failed run with an earlier report
present, a successful run that writes one, and no report at all.

Part of #271

---------

Co-authored-by: Claude Opus 5 <[email protected]>

* 3.x.x: list the new reject reason in the metric exposition fixture (#348)

`3.x.x` has been red since #344 landed. Two pull requests collided
semantically while each was green on its own:

- #333 (e13051cf) added `ledger-outcome-unknown` to `RejectReason`, so
  `/metrics` now emits one more `qbit_prism_rejections_total` series;
- #344 (037b04e4) added `event_exposition_matches_the_pre_allocation_change_byte_for_byte`,
  whose fixture was captured at 2914a629, before that reason existed.

Neither branch could see the problem, because it only appears in the
merged tree. The whole difference is one line, so the fixture gains it.

The comment above the assertion is refreshed at the same time: it claimed
provenance the fixture no longer had, and it now says what the pin
implies -- adding a value to a closed label set has to be recorded here.

Verified on this branch: the four metrics_allocation tests pass, and the
failure reproduces on a6fe3fd9 without this change.

Part of #338

* v3.0.0 fix: record cancelled collector pool acquisitions (#345)

* fix: record cancelled collector pool acquisitions

* docs: align collector cancellation timing contract

* docs: qualify cancelled collector waits in alert contracts

* test(metrics): include approved unknown ledger outcome in fixture

PR #333 intentionally added the ledger-outcome-unknown rejection label and a producer contract test. Add exactly that sample to the older exposition fixture from #344, retaining the byte-for-byte equality assertion and leaving runtime behavior unchanged.

(cherry picked from commit 4e5b4c41e980a3ebd956f39d5ed4d4676083d04e)

* build: update rustls to 0.23.45 for RUSTSEC-2026-0285 (#354)

rustls 0.23.44 accepted TLS 1.3 handshake messages sent at the wrong
encryption level when they followed a key-changing message in the same
record, instead of terminating the connection as RFC 8446 section 5.1
requires. The transcript stays authenticated, so a network-position
attacker cannot alter or complete a handshake; the effect is that a peer
can send handshake messages in plaintext that should have been encrypted
without rustls rejecting the connection. It is the same bug as Go's
CVE-2025-61730.

The advisory names 0.23.45 as the fix. This is a lockfile-only change:
`cargo update -p rustls`, no manifest or source change.

The advisory database picked this up today, so the dependency audit now
fails on 3.x.x and on every open pull request.

* 3.x.x: Normalize stored audit bodies so they stop growing with the window (#353)

* 3.x.x: add PrismRewardManifestHeader and a checked reward-manifest rebuild (#267)

A native audit row is about to stop storing `reward_manifest.shares`. The
counted window is a pure fold over `(shares, found_block)`, so the row only
needs the manifest header; `restore_reward_manifest` reruns the fold and
returns its window only after proving the rebuilt header is identical to the
stored one, failing as the existing `reward_manifest` audit mismatch
otherwise. There is no unchecked variant.

`PrismRewardManifestHeader` denies unknown fields, so a legacy manifest that
still carries `shares` can never be read as a header; and the full manifest
still requires `shares`, so an older reader meeting a normalized row fails
explicitly instead of serving an empty window.

Tests prove the rebuilt bundle is byte-identical to the original (both
schemas, credit_policy included), that one changed field in a rebuilt share
moves the canonical sha256, that a tampered header is refused by name, and
that neither shape can be mistaken for the other.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LXvnfUC8CvPxskAXLgd1xx

* 3.x.x: store native audit bodies without reward_manifest.shares and verify the range before the settlement lock (#267)

The landed native audit body kept `reward_manifest.shares`, one record per
counted share, so it grew with the payout window: about 235 MB in one JSONB
value at the production window, 88% of PostgreSQL's container limit. The
landing write now removes that copy alongside the top-level `shares`; the
stored body is O(distinct miners and payout accounts). Nothing else is added
or removed, `audit_body_byte_len` stays the full canonical artifact length,
and the GIN-indexed leaf arrays stay in the body.

Reads branch on the stored shape. A body whose `reward_manifest` has no
`shares` key is decoded as `PrismRewardManifestHeader` and its window rebuilt
through `restore_reward_manifest`, which refuses a header the fold does not
reproduce; a body that still has the key (landed before this change) is
served exactly as before. Both arms then run the unchanged canonical digest
check, so a rebuilt body is proven byte-identical, not merely equivalent.
Imported rows never enter this path. The snapshot digest, the rebuild and the
canonical hash run on one blocking thread, and the public API hands that job
the same permit imported decodes hold, so a dropped request cannot free the
limit before the rebuild ends.

The durable-range proof no longer runs inside the settlement transaction.
`verify_durable_range` runs before the lock, page by page (4096 rows, the
window reader's page), decoding and comparing each page on a blocking thread
against the same positions of the candidate window: same predicate, same
ordering, same full equality, same bootstrap exemption, same error text, and
the first mismatched page fails the landing. An already-landed block skips it
and takes the existing-row digest path as before. Under the lock the snapshot
now only counts the same anchored predicate and fails the landing if the count
differs from the window.

The JSONB ceiling gate's landing entry is deleted: that write no longer
crosses the threshold. Gated tests prove the stored shape and identical served
bytes, that a tampered stored header is refused by name, that pre-change
native rows still serve identical bytes, and that imported rows serve from
their canonical bytes even with a poisoned inline body. An ignored harness
measures the stored body, the settlement-lock hold and the landing peak RSS
at a configurable window size.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LXvnfUC8CvPxskAXLgd1xx

* 3.x.x: document the measured native audit body before and after normalization (#267)

State the measured stored bytes per block at 20,000 and 100,000 shares before
and after `reward_manifest.shares` left the stored body,…
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.

2 participants