Repository navigation
3.x.x: store imported legacy audits as canonical bytes and decode them on read - #325
Conversation
…m 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]>
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 92a23fe8f9
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
3.x.x now proves that every gated test executed and that the executed set matches test/prism-gated-tests.txt. This branch's four new imported-audit tests are gated, so they join the list. Part of #265. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ff74abb0da
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
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]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f9bb901967
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
Slice 1 (#325) merged after this stack branched, and its tests in tests/support/ledger_2x.rs still built the pre-007 candidate: they read block.bundle from a Candidate and called candidate_with_bundle without a window reference or settlement inputs. The rebase merged them cleanly and the tree then failed to compile. The three helpers now take the TestCandidate the constructors return, so they reach the bundle beside the slim candidate, and land_confirmed attaches the claim's parts the way the other ledger tests do. The three constructor calls pass the window reference the bundle was built on, and the settlement inputs for the CTV case. No assertion changes. Part of #265.
Slice 1 (#325) merged after this stack branched, and its tests in tests/support/ledger_2x.rs still built the pre-007 candidate: they read block.bundle from a Candidate and called candidate_with_bundle without a window reference or settlement inputs. The rebase merged them cleanly and the tree then failed to compile. The three helpers now take the TestCandidate the constructors return, so they reach the bundle beside the slim candidate, and land_confirmed attaches the claim's parts the way the other ledger tests do. The three constructor calls pass the window reference the bundle was built on, and the settlement inputs for the CTV case. No assertion changes. Part of #265.
Slice 1 (#325) merged after this stack branched, and its tests in tests/support/ledger_2x.rs still built the pre-007 candidate: they read block.bundle from a Candidate and called candidate_with_bundle without a window reference or settlement inputs. The rebase merged them cleanly and the tree then failed to compile. The three helpers now take the TestCandidate the constructors return, so they reach the bundle beside the slim candidate, and land_confirmed attaches the claim's parts the way the other ledger tests do. The three constructor calls pass the window reference the bundle was built on, and the settlement inputs for the CTV case. No assertion changes. Part of #265.
#355 landed deadline and single-execution coverage against the candidate that still carried an assembled bundle, and against `configure` before it took the frontend's signing keys. Adapted, the same way #325's and #267's suites were: a `TestCandidate` pairs the stored candidate with the bundle a landing still needs, claims attach their parts through `with_bundle`, and the conflicting claim that is never landed carries none. `ledger_deadline_atomicity` builds its candidate from a bundle rather than a snapshot, so its window reference is derived from that bundle: the anchor and prior-balances digest it already records, and the range and digest of the shares it carries. Its signer keys come from the public keys that actually signed it, rather than from a local pair, so the stored inputs describe the bundle.
Slice 1 (#325) merged after this stack branched, and its tests in tests/support/ledger_2x.rs still built the pre-007 candidate: they read block.bundle from a Candidate and called candidate_with_bundle without a window reference or settlement inputs. The rebase merged them cleanly and the tree then failed to compile. The three helpers now take the TestCandidate the constructors return, so they reach the bundle beside the slim candidate, and land_confirmed attaches the claim's parts the way the other ledger tests do. The three constructor calls pass the window reference the bundle was built on, and the settlement inputs for the CTV case. No assertion changes. Part of #265.
#355 landed deadline and single-execution coverage against the candidate that still carried an assembled bundle, and against `configure` before it took the frontend's signing keys. Adapted, the same way #325's and #267's suites were: a `TestCandidate` pairs the stored candidate with the bundle a landing still needs, claims attach their parts through `with_bundle`, and the conflicting claim that is never landed carries none. `ledger_deadline_atomicity` builds its candidate from a bundle rather than a snapshot, so its window reference is derived from that bundle: the anchor and prior-balances digest it already records, and the range and digest of the shares it carries. Its signer keys come from the public keys that actually signed it, rather than from a local pair, so the stored inputs describe the bundle.
Slice 1 (#325) merged after this stack branched, and its tests in tests/support/ledger_2x.rs still built the pre-007 candidate: they read block.bundle from a Candidate and called candidate_with_bundle without a window reference or settlement inputs. The rebase merged them cleanly and the tree then failed to compile. The three helpers now take the TestCandidate the constructors return, so they reach the bundle beside the slim candidate, and land_confirmed attaches the claim's parts the way the other ledger tests do. The three constructor calls pass the window reference the bundle was built on, and the settlement inputs for the CTV case. No assertion changes. Part of #265.
#355 landed deadline and single-execution coverage against the candidate that still carried an assembled bundle, and against `configure` before it took the frontend's signing keys. Adapted, the same way #325's and #267's suites were: a `TestCandidate` pairs the stored candidate with the bundle a landing still needs, claims attach their parts through `with_bundle`, and the conflicting claim that is never landed carries none. `ledger_deadline_atomicity` builds its candidate from a bundle rather than a snapshot, so its window reference is derived from that bundle: the anchor and prior-balances digest it already records, and the range and digest of the shares it carries. Its signer keys come from the public keys that actually signed it, rather than from a local pair, so the stored inputs describe the bundle.
#359) * 3.x.x: add migration 007 and refuse pre-007 candidate outbox rows Migration 007 mirrors 008 onto qbit_block_candidate_outbox: the same six window-reference columns, and a three-state CHECK whose body is identical to 008's apart from the table and constraint names. It also adds block_bytes, the nullable bytea the block moves into so the candidate document stays small, and a partial index on window_prior_balances_sha256 for the balance-snapshot GC. Nothing writes any of them yet; this is additive schema only. The runner applies 007 by membership, in its own block between 5 and 8, so it assumes neither 006 nor 008 has run. Before any DDL it refuses while the outbox still holds a pending row in a pre-007 shape: a native inline candidate, a NULL candidate, or storage_version other than 1 on the 2.x.x schemas that have that column, which is checked for first so the predicate does not error on a native schema. The refusal names every offending block_hash and the drain procedure, and the whole migration transaction rolls back, so a refused start leaves the schema untouched. The applied set is now [2, 3, 4, 5, 7, 8, 9], and the four exact migration assertions move with it rather than being weakened to a superset. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: retain the cluster fingerprint configure pinned or verified The candidate enqueue and save_job must fence against a fingerprint reset by re-reading qbit_prism_cluster.config_fingerprint FOR SHARE in their own transaction and refusing a write that is not this frontend's own. That needs the value configure settled at startup, so Ledger keeps it in a shared OnceLock, set only once the pin or the match has committed, and exposes it read-only through config_fingerprint(). configure keeps its signature and its mismatch refusal, and a refused call retains nothing. The rotation refusal in configure, and the writer fence itself, belong to the enqueue change and are not here. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: share the window reference, balance writer and page primitives WindowRef::from_snapshot is the synchronous reference builder both writers need: anchor_ms copied, the semantic balances digest, and for a non-empty snapshot the first and last share_seq, the length, and the share array's SHA-256 streamed through the existing DigestWriter, so the 233 to 260 MB serialized window at 400,000 shares is never built and the digest equals the one qbit_prism_audit_snapshots already stores. An empty snapshot gives the empty-window reference. Callers run it inside their own spawn_blocking. put_balance_snapshot is the one canonical writer of qbit_prism_balance_snapshots, on the caller's transaction: the sort by (order_key, recipient_id, p2mr_program_hex), the semantic digest that keys the row, and compact JSON of the sorted set, all off the runtime, then INSERT ... ON CONFLICT DO NOTHING. On a conflict it reads the stored bytes back and compares them with its own, because these rows are immutable and can only disagree through corruption. The enqueue and save_job and its repair all write through it. read_prior_balances and the current-balance read still keep their SQL order; the writer's sort defines the stored encoding, which is the order read_window(..., AsIssued) returns. probe_share_rows and read_range_paged are read_window's endpoint probe and page loop, lifted onto a caller's connection so the enqueue probe and the landing re-read share one implementation. The predicate, the ascending keyset order, the 4096-row page bound and the per-page count bound are unchanged, and read_window now calls them, with its signature and behaviour unchanged. The paged reader takes the caller's state and a per-page consumer, both of which travel to the blocking thread with the rows, so the landing re-read can compare each page with its slice of a vector it already holds without any whole-window work on the runtime; a dropped read still releases the accumulated state on a blocking thread. read_window_with_permit holds the caller's window_reads permit across the whole read. The permit is moved into a BlockingDrop declared before the read starts, so a cancellation releases it on a blocking thread after the page state queued its own release there, and never with the future; a return releases it inline, before the caller's rebuild. WindowError::TaskFailed separates a cancelled or panicking blocking hand-off from corruption. Every hand-off maps a JoinError to it instead of to Decode, so a cancellation is a retryable failure with its own alert and never takes the abandon path. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: derive the witness merkle leaves from an assembled block A claim rebuilds from stored inputs, and the witness leaves are the one builder input that scales with the block, so they are re-derived rather than stored: one 64-hex string per transaction beside the candidate would grow the document with the block. witness_merkle_leaves_from_block skips the 80-byte header, reads the compact-size transaction count, walks past the coinbase and returns double_sha256 of every remaining transaction's full serialized bytes. That is sound because assemble_submission appends the template's transactions verbatim after the coinbase, so the result equals witness_merkle_leaves_hex(&transactions_from_template(template)) for the block built from that template, with or without segwit transactions. The segwit-aware walk is strip_witness_transaction's own, factored into a helper that also reports where the transaction ends, which is what a block walker needs; strip_witness_transaction keeps its trailing-byte check and its output. A truncated block, trailing bytes, a zero count and a count that disagrees with the transactions present are all errors, never a partial list of leaves. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: version the audit builders and key the CC5 goldens by it A stored window reference reproduces its bundle only under the builder that first built it. The schema strings do not capture that, because the share shape chooses them rather than the builder logic, so qbit-prism gains AUDIT_BUILDER_VERSION, starting at 1. A candidate and a prepared job store it, and a rebuild refuses a reference at another version instead of rebuilding it with the current builder. The bump rule is on the constant: any change that alters canonical_audit_bundle_bytes for the same inputs bumps it in the same commit. The CC5 golden test now selects its expected digests from a table keyed by the constant, and fails when no entry exists, so a new output is recorded as a new entry beside the old one and review sees both. Version 1 holds the existing literals, unchanged. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: cover 007, the fingerprint and the window primitives on PostgreSQL Ten gated database cases, all listed in test/prism-gated-tests.txt. They go in a new file rather than the shared 2.x.x support module, which another open change appends to. Migration 007: a frozen 2.x.x schema carrying only terminal outbox rows upgrades with every row and field intact and the seven new columns NULL; each of the three pre-007 pending shapes is refused by name, with nothing from 007 applied and no version 7 row, and the same binary starts once the row is drained; a database at [2, 3, 4, 5, 8, 9] applies 007 and only 007, leaving every other version's applied_at untouched; the CHECK accepts exactly the three states across all 64 null combinations and rejects a short or uppercase digest, a zero or out-of-range count and a zero sequence; and the retention index is the partial one on window_prior_balances_sha256. config_fingerprint() returns what configure pinned or verified, is shared by clones, and stays empty after a refused configure. from_snapshot's streamed digest equals sha256(serde_json::to_vec) and the snapshot_sha256 landing writes for the same window. The balance writer stores the canonical sort, is idempotent under any permutation, errors rather than accepting a different encoding of the same digest, and read_window(..., AsIssued) hands back the stored order. The probe misses a missing endpoint, the paged reader compares 4,999 rows page by page with a vector held inside the caller's transaction, and a row the predicate skips inside a range is Incomplete with no partial window. The permit case builds a runtime with one blocking thread, occupies it, and cancels a reader parked mid-page on a database gate: no permit is available while the cleanup is queued, and one is once it has run. A failed blocking hand-off surfaces as TaskFailed, never as Decode. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: carry the window reference on prepared work, behind a read permit `Prepared` gains `window: WindowRef`, computed once per non-cached refresh beside `build_bundle` under `tokio::join!`, so submit can clone it instead of re-digesting the window on the share path when a block is found. An empty snapshot gets the empty-window reference on the runtime thread; a resume computes it inside the blocking decode it already runs. `Coordinator` gains the `window_reads` semaphore, sized `clamp(database_max_connections - 2, 1, build_workers)`, and the one entry point callers use: it takes an owned permit after the caller's `build_slots` permit and hands it to `Ledger::read_window_with_permit`, which holds it across the whole read, including the off-runtime cleanup a cancellation leaves behind, and releases it before the rebuild. `Ledger::read_window` is awaited on the runtime, never wrapped in `spawn_blocking`; the test with a single blocking thread pins that. The four gated `window_ref_tests` are listed in the manifest. Part of #265 Co-Authored-By: Claude Fable 5.1 <[email protected]> * 3.x.x: switch the candidate outbox to the window reference `Candidate` drops the embedded `AuditBundle` for `window: WindowRef` and every builder input except the window: `found_block`, `payout_policy`, the nested `ctv` triple (whose presence selects the CTV builder), the stored `bootstrap_share` of an empty window, `audit_builder_version`, `signer_keys`, a `leased` flag and the now-required `coinbase_suffix_hex`. The block leaves the document for the `block_bytes` column, authenticated by `block_sha256`, which `candidate_sha256` covers. The write serializes, digests and checks the candidate before the append or enqueue transaction opens; under `ORDER_LOCK` the transaction re-reads `config_fingerprint FOR SHARE` and refuses a value the writer did not pin, re-inserts a `leased` candidate's as-issued balance snapshot through the shared writer, probes the window's first row (an absent row alerts and still publishes), and inserts only the prepared bytes with the six typed columns. Submit builds the slim candidate from `Prepared.window`, the `BundleInputs` captured where `build_bundle` read configuration, and the job's own bootstrap share; it clones no bundle and reads no config. The claim's `UPDATE … RETURNING` returns the columns and the block, and the decode, off the runtime, checks the document against them, the digest, `sha256(block_bytes)`, the header hash, the required fields and the two reference invariants. A pending row with a NULL anchor is a hard error naming the pre-007 frontend; an inline document is never decoded. Before any read the claim retries, with an alert naming both values, a stored builder version or signer pair that is not this binary's; a landed audit is authenticated against the block (coinbase, audit root as the witness reserved value, share snapshot, bits) and the claim then skips the rebuild and landing and continues to observe, renew and submit. Otherwise it takes `build_slots`, then `window_reads` inside one 60 s deadline around the awaited `read_window(Current)` and the borrowing builder run directly in `spawn_blocking`, and keeps `Arc<AuditBundleBody>` and the shares as `ClaimParts`. `Incomplete`, `SnapshotDigestMismatch`, `Decode`, `BalanceSnapshotMissing`, `TaskFailed` and the deadline retry with their own alerts; `PriorBalancesChanged` finishes only a block `observe_candidate` proves inactive and superseded; `Database` propagates. A `leased` candidate submits from `block_bytes` first, then rebuilds `AsIssued` and lands before any terminal outcome. Rebuilt parts are released off the runtime on every path. Landing takes the parts and does all whole-window work in one blocking closure: `verify_audit_parts`, the raw body, the counted canonical bytes, the leaves and accounts, and the share snapshot digest, which must equal the reference's. The balance fence compares the current set and the parts' through the semantic digest, so an as-issued set compares equal in any order. `persist_audit_snapshot` re-reads the range with the paged reader inside the landing transaction, page against slice on the blocking thread; `read_range` stays for the API. The terminal UPDATE NULLs the six window columns and `block_bytes` with `candidate`. `configure` refuses to pin a fingerprint onto a reset one while a pending row stores other signer keys, and the startup gate requires 007 with 009. The JSONB gate drops its enqueue entry, and every helper that built a candidate builds the slim one, handing the ledger-level landings the bundle's parts through `CandidateClaim::with_bundle`. Part of #265 Co-Authored-By: Claude Fable 5.1 <[email protected]> * 3.x.x: cover the candidate switch on PostgreSQL Ledger-level, in `candidate_window_switch`: a two-page window enqueues a document with no array and no share row, under 1 MB, whose six typed columns equal its reference and whose block is stored as bytes; the writer fence refuses a reset or different fingerprint in the same transaction, share included; a missing window prefix row alerts and still publishes, and its read then meets `Incomplete`; a `leased` enqueue re-inserts the as-issued balance snapshot in the writer's canonical order, writes none when not leased, and refuses balances that do not hash to the reference; every preparation failure is refused without waiting for `ORDER_LOCK`; every column, digest, block, header, NULL-anchor, missing-field, invariant and inline-document disagreement is refused at claim; landing refuses parts that are not the referenced window and a claim without parts; the terminal UPDATE NULLs the six columns and the block for submitted and abandoned rows; the landed-audit authentication rejects a forged coinbase, root, snapshot or bits; and `configure` refuses a rotation over a foreign-signed pending candidate. Coordinator-level, in `window_switch_tests` behind a fake node: a stored builder version or signer pair that is not this binary's retries, naming both values, while the build slot is held; a landed audit is authenticated and the claim continues to `submitblock` without a build slot, and a forged landed coinbase or root is refused with the row left pending; `Incomplete`, a digest mismatch, changed balances on a current block and the rebuild deadline all retry with an alert and release their permits; `classify_window_error` keeps `TaskFailed` apart from corruption and propagates `Database`; the read, rebuild and landing complete while `ORDER_LOCK` is held, with one build worker; a `leased` candidate submits first, then lands from `AsIssued`, and finishes submitted, abandoned with the node's reason, or pending when its balance snapshot is missing; and `OffRuntime` releases on a blocking thread, on cancellation too. The fifteen gated tests are listed in the manifest. Part of #265 Co-Authored-By: Claude Fable 5.1 <[email protected]> * 3.x.x: migrate the imported-audit tests to the slim candidate Slice 1 (#325) merged after this stack branched, and its tests in tests/support/ledger_2x.rs still built the pre-007 candidate: they read block.bundle from a Candidate and called candidate_with_bundle without a window reference or settlement inputs. The rebase merged them cleanly and the tree then failed to compile. The three helpers now take the TestCandidate the constructors return, so they reach the bundle beside the slim candidate, and land_confirmed attaches the claim's parts the way the other ledger tests do. The three constructor calls pass the window reference the bundle was built on, and the settlement inputs for the CTV case. No assertion changes. Part of #265. * 3.x.x: qualify lease renewal and the claim's canonical bytes at scale Incident 1: a candidate whose window holds N shares is claimed and processed under the short lease, and every renewal is read back from claim_expires_at. The largest gap stays below interval + 2 x timeout, the lease never lapses, and a successor ledger cannot take the claim. The bundle a claim rebuilds through the window-read entry point and the borrowing builder has the canonical bytes refresh built for the same job, and the landed audit carries that bundle's digest. Both run at PRISM_WINDOW_QUALIFY_SHARES (20,000 by default); the 400,000-share variants are ignored and run on a larger host. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: measure ACK latency and ORDER_LOCK hold across window sizes Incident 2: two frontends on one database submit ordinary shares at a fixed rate while one of them solves a block on an N-share window and its own submit loop claims, rebuilds, lands and submits it. The solving share's ACK and the bystander's p99 stay within max(2 x baseline p99 + 50 ms, 250 ms), every ACK is well under the share-commit timeout, and the block is enqueued exactly once. Latency is the in-process MiningBackend::submit wall clock; the socket-level harness (#271) does not exist yet. A pg_locks sampler on its own connection measures how long a solving append holds ORDER_LOCK at two window sizes with no other traffic: the larger size stays within a fixed slack of the smaller, and the candidate document is the same size at both and under 1 MiB. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: hold the JSONB gate's enqueue to a window-free row under 1 MiB At every measured size the enqueue must be accepted and every JSONB value it writes, the outbox candidate document included, must stay under 1,048,576 bytes. At the reduced sizes the enqueue, claim and landing phases must all run. The ratchet and its expected values are unchanged. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: make the window-read permit test actually wait before it looks The delay that gives an unpermitted read time to finish was an empty async block, so the check that the read had not finished ran at once and passed whether or not the entry point took a permit. It now sleeps 500 ms inside a 5 s bound, and fails when the permit acquisition is removed from the entry point. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: rebuild a CTV candidate from its stored settlement inputs No host-runnable test reached the CTV branch of the claim rebuild. A CTV-enabled frontend now claims a candidate whose stored direct floor differs from its configuration, and builds a different coinbase than the configured floor would, and the claim must land that candidate's own audit and submit it. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: pin the SQL order of the current-balance reads Nothing defended the ruling that the current-balance path keeps its SQL order: every fixture's balances already arrived in byte-wise canonical order. The carry table's text columns now take an ICU collation, under which the SQL order and the canonical sort disagree, and the snapshot and the current-balance window read must both return the SQL order. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: record what incident 2 must also assert once #324 is in the base After #324 a slow solve is acknowledged late rather than refused, so acceptance proves nothing and the latency percentiles stay the assertion. The doc comment and a TODO at the outcome checks name the counter and outcome to assert at rebase. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: assert incident 2's late-confirm counter now that #324 is in the base W3c wrote the qualification tests against a base that predated #324 and left a marked place for the assertions that only make sense once the commit gate is there. The base now carries it, so apply them: incident 2 asserts `qbit_prism_late_confirmed_shares_total` is zero on both frontends and that no acknowledgement, the block-solving share included, is `ledger-outcome-unknown`. Acceptance alone is no longer proof. #324 gives a share-pass append carrying a candidate its own `block_only_ack_timeout`, so a slow solve is never refused at the share deadline; it is answered late, or answered unknown. Either would have satisfied the acceptance checks with the serialization stall still present. Also set #324's two new `Config` fields in the qualification fixture. * 3.x.x: pin a refused candidate as a definite rejection, not an unknown outcome #324 decides what a miner is told when a block-only enqueue fails: `enqueue_failed_before_commit` answers a provably uncommitted failure with `ledger-confirmation-failed`, and anything else with `ledger-outcome-unknown`, which asks an operator to go and follow the outbox row. Slice 3 added the checks that guard the reference: the block's length, its header hash, its digest against `block_sha256`, the coinbase suffix, the reference invariants, and a leased candidate's balances. All of them are raised by `prepare_candidate` before the enqueue takes a connection, so none carries an `sqlx::Error` and all classify as definite today. That is a property of where the checks sit, not something the classifier knows about them, so it is pinned here rather than left to hold by accident: a corrupt candidate must never send a miner chasing a row that was never written. Verified by mutation: classifying a non-sqlx failure as unknown fails this test. * 3.x.x: say why the full-size qualification variants cannot reach 400k yet Their ignore reasons blamed RAM and the host. The real limit is #273: the job payload still holds three copies of the window (2 x AcceptedShare + 1 x CountedShare), so publishing a job for a 400,000-share window needs about 670 MiB and PostgreSQL refuses the write above its 256 MiB jsonb object limit. Every full-size variant fails at fixture set-up, before it measures anything. The count must also divide the window weight exactly, so the largest usable size today is 125,000, where all four variants pass in release: incident 1 50 renewals, max gap 118.25 ms against a 700 ms bound incident 2 phase-A p99 2.60 ms, phase-B p99 95.79 ms, bound 250 ms lock hold median 0.75 ms at 5,000 against 1.32 ms at 125,000 canonical refresh and claim rebuild both 139,040,610 B, same sha256 The candidate document stays flat at 1103 B and 1107 B, which is the property this slice exists to establish. * 3.x.x: migrate the audit-body normalization tests to the slim candidate #267 landed its own test file against the candidate that still carried an assembled bundle. This slice replaced that with a window reference, so the file keeps a `TestCandidate` pairing the stored candidate with the bundle a test still needs, as `tests/ledger_postgres.rs` does, and attaches the claim's parts through `with_bundle`. One case needed more than a shape change. The four negative cases hand the claim a window the ledger does not hold and require the durable-range proof to be what refuses it. A candidate now commits to a snapshot digest, so a reference taken from the unaltered snapshot would be refused earlier, at the reference check, and the proof under test would never run. `window_ref_for` therefore derives each altered window's reference from that window, leaving the proof as the only thing that can notice, which is what #267 wrote them to prove. * 3.x.x: pin the durable-range proof outside the settlement lock #267 moved the full-equality proof of a candidate's window out of the settlement transaction so the lock is not held for a window-sized read. This slice made that read paged, so it does not occupy a runtime thread either. Reconciling the two is the step that can quietly undo the first: keep this slice's `persist_audit_snapshot` through the rebase and the full read goes back under the lock. The landing stays correct, every other test still passes, and only the lock hold grows, so nothing in the suite can tell. Measured at 100,000 shares on #267's branch that was a 34% longer hold. The guard is deterministic and needs no large window. A second connection holds `SETTLEMENT_LOCK`, so the landing blocks on it once its proof has run. While it waits, one share's `ntime` is altered: full equality sees that, a count over the same anchored predicate cannot. The landing must then succeed, which it can only do if it had already read and compared the shares before taking the lock. Accepted history is immutable and a trigger enforces it, so the test lifts that trigger for the single statement, inside its own disposable schema, and puts it straight back. Verified by mutation: restoring the in-transaction range read fails this test with "the landing read share payloads under the settlement lock". * 3.x.x: serialise the coordinator test modules that share the ledger's locks The ledger's advisory locks are cluster-wide constants, not schema-scoped, so two coordinator test modules running in parallel contend for ORDER_LOCK even though each works in its own throwaway schema. Every module held a lock of its own, which serialised it against itself and left cross-module waits to `lock_timeout`, 5 s by default. #324's reconciliation tests hold ORDER_LOCK for up to about 1.5 s, and this slice adds three more modules that open a ledger. Once enough of them ran at once those waits stacked past the timeout: a full `--lib` run failed with "canceling statement due to lock timeout" in `candidate_lease_tests` and `window_switch_tests`, and passed on the next run. A suite that fails for a reason unrelated to what it tests is worse than a slow one. All seven modules now take one shared lock. The run goes from about 35 s to about 62 s, and three consecutive runs pass where the flake had reproduced. * 3.x.x: add migration 007 and refuse pre-007 candidate outbox rows Migration 007 mirrors 008 onto qbit_block_candidate_outbox: the same six window-reference columns, and a three-state CHECK whose body is identical to 008's apart from the table and constraint names. It also adds block_bytes, the nullable bytea the block moves into so the candidate document stays small, and a partial index on window_prior_balances_sha256 for the balance-snapshot GC. Nothing writes any of them yet; this is additive schema only. The runner applies 007 by membership, in its own block between 5 and 8, so it assumes neither 006 nor 008 has run. Before any DDL it refuses while the outbox still holds a pending row in a pre-007 shape: a native inline candidate, a NULL candidate, or storage_version other than 1 on the 2.x.x schemas that have that column, which is checked for first so the predicate does not error on a native schema. The refusal names every offending block_hash and the drain procedure, and the whole migration transaction rolls back, so a refused start leaves the schema untouched. The applied set is now [2, 3, 4, 5, 7, 8, 9], and the four exact migration assertions move with it rather than being weakened to a superset. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: retain the cluster fingerprint configure pinned or verified The candidate enqueue and save_job must fence against a fingerprint reset by re-reading qbit_prism_cluster.config_fingerprint FOR SHARE in their own transaction and refusing a write that is not this frontend's own. That needs the value configure settled at startup, so Ledger keeps it in a shared OnceLock, set only once the pin or the match has committed, and exposes it read-only through config_fingerprint(). configure keeps its signature and its mismatch refusal, and a refused call retains nothing. The rotation refusal in configure, and the writer fence itself, belong to the enqueue change and are not here. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: share the window reference, balance writer and page primitives WindowRef::from_snapshot is the synchronous reference builder both writers need: anchor_ms copied, the semantic balances digest, and for a non-empty snapshot the first and last share_seq, the length, and the share array's SHA-256 streamed through the existing DigestWriter, so the 233 to 260 MB serialized window at 400,000 shares is never built and the digest equals the one qbit_prism_audit_snapshots already stores. An empty snapshot gives the empty-window reference. Callers run it inside their own spawn_blocking. put_balance_snapshot is the one canonical writer of qbit_prism_balance_snapshots, on the caller's transaction: the sort by (order_key, recipient_id, p2mr_program_hex), the semantic digest that keys the row, and compact JSON of the sorted set, all off the runtime, then INSERT ... ON CONFLICT DO NOTHING. On a conflict it reads the stored bytes back and compares them with its own, because these rows are immutable and can only disagree through corruption. The enqueue and save_job and its repair all write through it. read_prior_balances and the current-balance read still keep their SQL order; the writer's sort defines the stored encoding, which is the order read_window(..., AsIssued) returns. probe_share_rows and read_range_paged are read_window's endpoint probe and page loop, lifted onto a caller's connection so the enqueue probe and the landing re-read share one implementation. The predicate, the ascending keyset order, the 4096-row page bound and the per-page count bound are unchanged, and read_window now calls them, with its signature and behaviour unchanged. The paged reader takes the caller's state and a per-page consumer, both of which travel to the blocking thread with the rows, so the landing re-read can compare each page with its slice of a vector it already holds without any whole-window work on the runtime; a dropped read still releases the accumulated state on a blocking thread. read_window_with_permit holds the caller's window_reads permit across the whole read. The permit is moved into a BlockingDrop declared before the read starts, so a cancellation releases it on a blocking thread after the page state queued its own release there, and never with the future; a return releases it inline, before the caller's rebuild. WindowError::TaskFailed separates a cancelled or panicking blocking hand-off from corruption. Every hand-off maps a JoinError to it instead of to Decode, so a cancellation is a retryable failure with its own alert and never takes the abandon path. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: derive the witness merkle leaves from an assembled block A claim rebuilds from stored inputs, and the witness leaves are the one builder input that scales with the block, so they are re-derived rather than stored: one 64-hex string per transaction beside the candidate would grow the document with the block. witness_merkle_leaves_from_block skips the 80-byte header, reads the compact-size transaction count, walks past the coinbase and returns double_sha256 of every remaining transaction's full serialized bytes. That is sound because assemble_submission appends the template's transactions verbatim after the coinbase, so the result equals witness_merkle_leaves_hex(&transactions_from_template(template)) for the block built from that template, with or without segwit transactions. The segwit-aware walk is strip_witness_transaction's own, factored into a helper that also reports where the transaction ends, which is what a block walker needs; strip_witness_transaction keeps its trailing-byte check and its output. A truncated block, trailing bytes, a zero count and a count that disagrees with the transactions present are all errors, never a partial list of leaves. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: version the audit builders and key the CC5 goldens by it A stored window reference reproduces its bundle only under the builder that first built it. The schema strings do not capture that, because the share shape chooses them rather than the builder logic, so qbit-prism gains AUDIT_BUILDER_VERSION, starting at 1. A candidate and a prepared job store it, and a rebuild refuses a reference at another version instead of rebuilding it with the current builder. The bump rule is on the constant: any change that alters canonical_audit_bundle_bytes for the same inputs bumps it in the same commit. The CC5 golden test now selects its expected digests from a table keyed by the constant, and fails when no entry exists, so a new output is recorded as a new entry beside the old one and review sees both. Version 1 holds the existing literals, unchanged. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: cover 007, the fingerprint and the window primitives on PostgreSQL Ten gated database cases, all listed in test/prism-gated-tests.txt. They go in a new file rather than the shared 2.x.x support module, which another open change appends to. Migration 007: a frozen 2.x.x schema carrying only terminal outbox rows upgrades with every row and field intact and the seven new columns NULL; each of the three pre-007 pending shapes is refused by name, with nothing from 007 applied and no version 7 row, and the same binary starts once the row is drained; a database at [2, 3, 4, 5, 8, 9] applies 007 and only 007, leaving every other version's applied_at untouched; the CHECK accepts exactly the three states across all 64 null combinations and rejects a short or uppercase digest, a zero or out-of-range count and a zero sequence; and the retention index is the partial one on window_prior_balances_sha256. config_fingerprint() returns what configure pinned or verified, is shared by clones, and stays empty after a refused configure. from_snapshot's streamed digest equals sha256(serde_json::to_vec) and the snapshot_sha256 landing writes for the same window. The balance writer stores the canonical sort, is idempotent under any permutation, errors rather than accepting a different encoding of the same digest, and read_window(..., AsIssued) hands back the stored order. The probe misses a missing endpoint, the paged reader compares 4,999 rows page by page with a vector held inside the caller's transaction, and a row the predicate skips inside a range is Incomplete with no partial window. The permit case builds a runtime with one blocking thread, occupies it, and cancels a reader parked mid-page on a database gate: no permit is available while the cleanup is queued, and one is once it has run. A failed blocking hand-off surfaces as TaskFailed, never as Decode. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: carry the window reference on prepared work, behind a read permit `Prepared` gains `window: WindowRef`, computed once per non-cached refresh beside `build_bundle` under `tokio::join!`, so submit can clone it instead of re-digesting the window on the share path when a block is found. An empty snapshot gets the empty-window reference on the runtime thread; a resume computes it inside the blocking decode it already runs. `Coordinator` gains the `window_reads` semaphore, sized `clamp(database_max_connections - 2, 1, build_workers)`, and the one entry point callers use: it takes an owned permit after the caller's `build_slots` permit and hands it to `Ledger::read_window_with_permit`, which holds it across the whole read, including the off-runtime cleanup a cancellation leaves behind, and releases it before the rebuild. `Ledger::read_window` is awaited on the runtime, never wrapped in `spawn_blocking`; the test with a single blocking thread pins that. The four gated `window_ref_tests` are listed in the manifest. Part of #265 Co-Authored-By: Claude Fable 5.1 <[email protected]> * 3.x.x: switch the candidate outbox to the window reference `Candidate` drops the embedded `AuditBundle` for `window: WindowRef` and every builder input except the window: `found_block`, `payout_policy`, the nested `ctv` triple (whose presence selects the CTV builder), the stored `bootstrap_share` of an empty window, `audit_builder_version`, `signer_keys`, a `leased` flag and the now-required `coinbase_suffix_hex`. The block leaves the document for the `block_bytes` column, authenticated by `block_sha256`, which `candidate_sha256` covers. The write serializes, digests and checks the candidate before the append or enqueue transaction opens; under `ORDER_LOCK` the transaction re-reads `config_fingerprint FOR SHARE` and refuses a value the writer did not pin, re-inserts a `leased` candidate's as-issued balance snapshot through the shared writer, probes the window's first row (an absent row alerts and still publishes), and inserts only the prepared bytes with the six typed columns. Submit builds the slim candidate from `Prepared.window`, the `BundleInputs` captured where `build_bundle` read configuration, and the job's own bootstrap share; it clones no bundle and reads no config. The claim's `UPDATE … RETURNING` returns the columns and the block, and the decode, off the runtime, checks the document against them, the digest, `sha256(block_bytes)`, the header hash, the required fields and the two reference invariants. A pending row with a NULL anchor is a hard error naming the pre-007 frontend; an inline document is never decoded. Before any read the claim retries, with an alert naming both values, a stored builder version or signer pair that is not this binary's; a landed audit is authenticated against the block (coinbase, audit root as the witness reserved value, share snapshot, bits) and the claim then skips the rebuild and landing and continues to observe, renew and submit. Otherwise it takes `build_slots`, then `window_reads` inside one 60 s deadline around the awaited `read_window(Current)` and the borrowing builder run directly in `spawn_blocking`, and keeps `Arc<AuditBundleBody>` and the shares as `ClaimParts`. `Incomplete`, `SnapshotDigestMismatch`, `Decode`, `BalanceSnapshotMissing`, `TaskFailed` and the deadline retry with their own alerts; `PriorBalancesChanged` finishes only a block `observe_candidate` proves inactive and superseded; `Database` propagates. A `leased` candidate submits from `block_bytes` first, then rebuilds `AsIssued` and lands before any terminal outcome. Rebuilt parts are released off the runtime on every path. Landing takes the parts and does all whole-window work in one blocking closure: `verify_audit_parts`, the raw body, the counted canonical bytes, the leaves and accounts, and the share snapshot digest, which must equal the reference's. The balance fence compares the current set and the parts' through the semantic digest, so an as-issued set compares equal in any order. `persist_audit_snapshot` re-reads the range with the paged reader inside the landing transaction, page against slice on the blocking thread; `read_range` stays for the API. The terminal UPDATE NULLs the six window columns and `block_bytes` with `candidate`. `configure` refuses to pin a fingerprint onto a reset one while a pending row stores other signer keys, and the startup gate requires 007 with 009. The JSONB gate drops its enqueue entry, and every helper that built a candidate builds the slim one, handing the ledger-level landings the bundle's parts through `CandidateClaim::with_bundle`. Part of #265 Co-Authored-By: Claude Fable 5.1 <[email protected]> * 3.x.x: cover the candidate switch on PostgreSQL Ledger-level, in `candidate_window_switch`: a two-page window enqueues a document with no array and no share row, under 1 MB, whose six typed columns equal its reference and whose block is stored as bytes; the writer fence refuses a reset or different fingerprint in the same transaction, share included; a missing window prefix row alerts and still publishes, and its read then meets `Incomplete`; a `leased` enqueue re-inserts the as-issued balance snapshot in the writer's canonical order, writes none when not leased, and refuses balances that do not hash to the reference; every preparation failure is refused without waiting for `ORDER_LOCK`; every column, digest, block, header, NULL-anchor, missing-field, invariant and inline-document disagreement is refused at claim; landing refuses parts that are not the referenced window and a claim without parts; the terminal UPDATE NULLs the six columns and the block for submitted and abandoned rows; the landed-audit authentication rejects a forged coinbase, root, snapshot or bits; and `configure` refuses a rotation over a foreign-signed pending candidate. Coordinator-level, in `window_switch_tests` behind a fake node: a stored builder version or signer pair that is not this binary's retries, naming both values, while the build slot is held; a landed audit is authenticated and the claim continues to `submitblock` without a build slot, and a forged landed coinbase or root is refused with the row left pending; `Incomplete`, a digest mismatch, changed balances on a current block and the rebuild deadline all retry with an alert and release their permits; `classify_window_error` keeps `TaskFailed` apart from corruption and propagates `Database`; the read, rebuild and landing complete while `ORDER_LOCK` is held, with one build worker; a `leased` candidate submits first, then lands from `AsIssued`, and finishes submitted, abandoned with the node's reason, or pending when its balance snapshot is missing; and `OffRuntime` releases on a blocking thread, on cancellation too. The fifteen gated tests are listed in the manifest. Part of #265 Co-Authored-By: Claude Fable 5.1 <[email protected]> * 3.x.x: migrate the imported-audit tests to the slim candidate Slice 1 (#325) merged after this stack branched, and its tests in tests/support/ledger_2x.rs still built the pre-007 candidate: they read block.bundle from a Candidate and called candidate_with_bundle without a window reference or settlement inputs. The rebase merged them cleanly and the tree then failed to compile. The three helpers now take the TestCandidate the constructors return, so they reach the bundle beside the slim candidate, and land_confirmed attaches the claim's parts the way the other ledger tests do. The three constructor calls pass the window reference the bundle was built on, and the settlement inputs for the CTV case. No assertion changes. Part of #265. * 3.x.x: qualify lease renewal and the claim's canonical bytes at scale Incident 1: a candidate whose window holds N shares is claimed and processed under the short lease, and every renewal is read back from claim_expires_at. The largest gap stays below interval + 2 x timeout, the lease never lapses, and a successor ledger cannot take the claim. The bundle a claim rebuilds through the window-read entry point and the borrowing builder has the canonical bytes refresh built for the same job, and the landed audit carries that bundle's digest. Both run at PRISM_WINDOW_QUALIFY_SHARES (20,000 by default); the 400,000-share variants are ignored and run on a larger host. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: measure ACK latency and ORDER_LOCK hold across window sizes Incident 2: two frontends on one database submit ordinary shares at a fixed rate while one of them solves a block on an N-share window and its own submit loop claims, rebuilds, lands and submits it. The solving share's ACK and the bystander's p99 stay within max(2 x baseline p99 + 50 ms, 250 ms), every ACK is well under the share-commit timeout, and the block is enqueued exactly once. Latency is the in-process MiningBackend::submit wall clock; the socket-level harness (#271) does not exist yet. A pg_locks sampler on its own connection measures how long a solving append holds ORDER_LOCK at two window sizes with no other traffic: the larger size stays within a fixed slack of the smaller, and the candidate document is the same size at both and under 1 MiB. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: hold the JSONB gate's enqueue to a window-free row under 1 MiB At every measured size the enqueue must be accepted and every JSONB value it writes, the outbox candidate document included, must stay under 1,048,576 bytes. At the reduced sizes the enqueue, claim and landing phases must all run. The ratchet and its expected values are unchanged. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: make the window-read permit test actually wait before it looks The delay that gives an unpermitted read time to finish was an empty async block, so the check that the read had not finished ran at once and passed whether or not the entry point took a permit. It now sleeps 500 ms inside a 5 s bound, and fails when the permit acquisition is removed from the entry point. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: rebuild a CTV candidate from its stored settlement inputs No host-runnable test reached the CTV branch of the claim rebuild. A CTV-enabled frontend now claims a candidate whose stored direct floor differs from its configuration, and builds a different coinbase than the configured floor would, and the claim must land that candidate's own audit and submit it. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: pin the SQL order of the current-balance reads Nothing defended the ruling that the current-balance path keeps its SQL order: every fixture's balances already arrived in byte-wise canonical order. The carry table's text columns now take an ICU collation, under which the SQL order and the canonical sort disagree, and the snapshot and the current-balance window read must both return the SQL order. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: record what incident 2 must also assert once #324 is in the base After #324 a slow solve is acknowledged late rather than refused, so acceptance proves nothing and the latency percentiles stay the assertion. The doc comment and a TODO at the outcome checks name the counter and outcome to assert at rebase. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: assert incident 2's late-confirm counter now that #324 is in the base W3c wrote the qualification tests against a base that predated #324 and left a marked place for the assertions that only make sense once the commit gate is there. The base now carries it, so apply them: incident 2 asserts `qbit_prism_late_confirmed_shares_total` is zero on both frontends and that no acknowledgement, the block-solving share included, is `ledger-outcome-unknown`. Acceptance alone is no longer proof. #324 gives a share-pass append carrying a candidate its own `block_only_ack_timeout`, so a slow solve is never refused at the share deadline; it is answered late, or answered unknown. Either would have satisfied the acceptance checks with the serialization stall still present. Also set #324's two new `Config` fields in the qualification fixture. * 3.x.x: pin a refused candidate as a definite rejection, not an unknown outcome #324 decides what a miner is told when a block-only enqueue fails: `enqueue_failed_before_commit` answers a provably uncommitted failure with `ledger-confirmation-failed`, and anything else with `ledger-outcome-unknown`, which asks an operator to go and follow the outbox row. Slice 3 added the checks that guard the reference: the block's length, its header hash, its digest against `block_sha256`, the coinbase suffix, the reference invariants, and a leased candidate's balances. All of them are raised by `prepare_candidate` before the enqueue takes a connection, so none carries an `sqlx::Error` and all classify as definite today. That is a property of where the checks sit, not something the classifier knows about them, so it is pinned here rather than left to hold by accident: a corrupt candidate must never send a miner chasing a row that was never written. Verified by mutation: classifying a non-sqlx failure as unknown fails this test. * 3.x.x: say why the full-size qualification variants cannot reach 400k yet Their ignore reasons blamed RAM and the host. The real limit is #273: the job payload still holds three copies of the window (2 x AcceptedShare + 1 x CountedShare), so publishing a job for a 400,000-share window needs about 670 MiB and PostgreSQL refuses the write above its 256 MiB jsonb object limit. Every full-size variant fails at fixture set-up, before it measures anything. The count must also divide the window weight exactly, so the largest usable size today is 125,000, where all four variants pass in release: incident 1 50 renewals, max gap 118.25 ms against a 700 ms bound incident 2 phase-A p99 2.60 ms, phase-B p99 95.79 ms, bound 250 ms lock hold median 0.75 ms at 5,000 against 1.32 ms at 125,000 canonical refresh and claim rebuild both 139,040,610 B, same sha256 The candidate document stays flat at 1103 B and 1107 B, which is the property this slice exists to establish. * 3.x.x: migrate the audit-body normalization tests to the slim candidate #267 landed its own test file against the candidate that still carried an assembled bundle. This slice replaced that with a window reference, so the file keeps a `TestCandidate` pairing the stored candidate with the bundle a test still needs, as `tests/ledger_postgres.rs` does, and attaches the claim's parts through `with_bundle`. One case needed more than a shape change. The four negative cases hand the claim a window the ledger does not hold and require the durable-range proof to be what refuses it. A candidate now commits to a snapshot digest, so a reference taken from the unaltered snapshot would be refused earlier, at the reference check, and the proof under test would never run. `window_ref_for` therefore derives each altered window's reference from that window, leaving the proof as the only thing that can notice, which is what #267 wrote them to prove. * 3.x.x: pin the durable-range proof outside the settlement lock #267 moved the full-equality proof of a candidate's window out of the settlement transaction so the lock is not held for a window-sized read. This slice made that read paged, so it does not occupy a runtime thread either. Reconciling the two is the step that can quietly undo the first: keep this slice's `persist_audit_snapshot` through the rebase and the full read goes back under the lock. The landing stays correct, every other test still passes, and only the lock hold grows, so nothing in the suite can tell. Measured at 100,000 shares on #267's branch that was a 34% longer hold. The guard is deterministic and needs no large window. A second connection holds `SETTLEMENT_LOCK`, so the landing blocks on it once its proof has run. While it waits, one share's `ntime` is altered: full equality sees that, a count over the same anchored predicate cannot. The landing must then succeed, which it can only do if it had already read and compared the shares before taking the lock. Accepted history is immutable and a trigger enforces it, so the test lifts that trigger for the single statement, inside its own disposable schema, and puts it straight back. Verified by mutation: restoring the in-transaction range read fails this test with "the landing read share payloads under the settlement lock". * 3.x.x: serialise the coordinator test modules that share the ledger's locks The ledger's advisory locks are cluster-wide constants, not schema-scoped, so two coordinator test modules running in parallel contend for ORDER_LOCK even though each works in its own throwaway schema. Every module held a lock of its own, which serialised it against itself and left cross-module waits to `lock_timeout`, 5 s by default. #324's reconciliation tests hold ORDER_LOCK for up to about 1.5 s, and this slice adds three more modules that open a ledger. Once enough of them ran at once those waits stacked past the timeout: a full `--lib` run failed with "canceling statement due to lock timeout" in `candidate_lease_tests` and `window_switch_tests`, and passed on the next run. A suite that fails for a reason unrelated to what it tests is worse than a slow one. All seven modules now take one shared lock. The run goes from about 35 s to about 62 s, and three consecutive runs pass where the flake had reproduced. * 3.x.x: pass the signer keys #334's wait-metrics tests now need `Ledger::configure` takes the frontend's signing keys since this slice, so the fingerprint contention tests #334 added call it with a fixed pair. That suite measures advisory-lock and pool-acquire waits, not signing, so the only thing the keys have to be is the same on every call. * feat: add compact prepared storage and immutable template blobs * Validate compact prepared endpoints and document caller contracts * 3.x.x: add migration 007 and refuse pre-007 candidate outbox rows Migration 007 mirrors 008 onto qbit_block_candidate_outbox: the same six window-reference columns, and a three-state CHECK whose body is identical to 008's apart from the table and constraint names. It also adds block_bytes, the nullable bytea the block moves into so the candidate document stays small, and a partial index on window_prior_balances_sha256 for the balance-snapshot GC. Nothing writes any of them yet; this is additive schema only. The runner applies 007 by membership, in its own block between 5 and 8, so it assumes neither 006 nor 008 has run. Before any DDL it refuses while the outbox still holds a pending row in a pre-007 shape: a native inline candidate, a NULL candidate, or storage_version other than 1 on the 2.x.x schemas that have that column, which is checked for first so the predicate does not error on a native schema. The refusal names every offending block_hash and the drain procedure, and the whole migration transaction rolls back, so a refused start leaves the schema untouched. The applied set is now [2, 3, 4, 5, 7, 8, 9], and the four exact migration assertions move with it rather than being weakened to a superset. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: retain the cluster fingerprint configure pinned or verified The candidate enqueue and save_job must fence against a fingerprint reset by re-reading qbit_prism_cluster.config_fingerprint FOR SHARE in their own transaction and refusing a write that is not this frontend's own. That needs the value configure settled at startup, so Ledger keeps it in a shared OnceLock, set only once the pin or the match has committed, and exposes it read-only through config_fingerprint(). configure keeps its signature and its mismatch refusal, and a refused call retains nothing. The rotation refusal in configure, and the writer fence itself, belong to the enqueue change and are not here. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: share the window reference, balance writer and page primitives WindowRef::from_snapshot is the synchronous reference builder both writers need: anchor_ms copied, the semantic balances digest, and for a non-empty snapshot the first and last share_seq, the length, and the share array's SHA-256 streamed through the existing DigestWriter, so the 233 to 260 MB serialized window at 400,000 shares is never built and the digest equals the one qbit_prism_audit_snapshots already stores. An empty snapshot gives the empty-window reference. Callers run it inside their own spawn_blocking. put_balance_snapshot is the one canonical writer of qbit_prism_balance_snapshots, on the caller's transaction: the sort by (order_key, recipient_id, p2mr_program_hex), the semantic digest that keys the row, and compact JSON of the sorted set, all off the runtime, then INSERT ... ON CONFLICT DO NOTHING. On a conflict it reads the stored bytes back and compares them with its own, because these rows are immutable and can only disagree through corruption. The enqueue and save_job and its repair all write through it. read_prior_balances and the current-balance read still keep their SQL order; the writer's sort defines the stored encoding, which is the order read_window(..., AsIssued) returns. probe_share_rows and read_range_paged are read_window's endpoint probe and page loop, lifted onto a caller's connection so the enqueue probe and the landing re-read share one implementation. The predicate, the ascending keyset order, the 4096-row page bound and the per-page count bound are unchanged, and read_window now calls them, with its signature and behaviour unchanged. The paged reader takes the caller's state and a per-page consumer, both of which travel to the blocking thread with the rows, so the landing re-read can compare each page with its slice of a vector it already holds without any whole-window work on the runtime; a dropped read still releases the accumulated state on a blocking thread. read_window_with_permit holds the caller's window_reads permit across the whole read. The permit is moved into a BlockingDrop declared before the read starts, so a cancellation releases it on a blocking thread after the page state queued its own release there, and never with the future; a return releases it inline, before the caller's rebuild. WindowError::TaskFailed separates a cancelled or panicking blocking hand-off from corruption. Every hand-off maps a JoinError to it instead of to Decode, so a cancellation is a retryable failure with its own alert and never takes the abandon path. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: derive the witness merkle leaves from an assembled block A claim rebuilds from stored inputs, and the witness leaves are the one builder input that scales with the block, so they are re-derived rather than stored: one 64-hex string per transaction beside the candidate would grow the document with the block. witness_merkle_leaves_from_block skips the 80-byte header, reads the compact-size transaction count, walks past the coinbase and returns double_sha256 of every remaining transaction's full serialized bytes. That is sound because assemble_submission appends the template's transactions verbatim after the coinbase, so the result equals witness_merkle_leaves_hex(&transactions_from_template(template)) for the block built from that template, with or without segwit transactions. The segwit-aware walk is strip_witness_transaction's own, factored into a helper that also reports where the transaction ends, which is what a block walker needs; strip_witness_transaction keeps its trailing-byte check and its output. A truncated block, trailing bytes, a zero count and a count that disagrees with the transactions present are all errors, never a partial list of leaves. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: version the audit builders and key the CC5 goldens by it A stored window reference reproduces its bundle only under the builder that first built it. The schema strings do not capture that, because the share shape chooses them rather than the builder logic, so qbit-prism gains AUDIT_BUILDER_VERSION, starting at 1. A candidate and a prepared job store it, and a rebuild refuses a reference at another version instead of rebuilding it with the current builder. The bump rule is on the constant: any change that alters canonical_audit_bundle_bytes for the same inputs bumps it in the same commit. The CC5 golden test now selects its expected digests from a table keyed by the constant, and fails when no entry exists, so a new output is recorded as a new entry beside the old one and review sees both. Version 1 holds the existing literals, unchanged. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: cover 007, the fingerprint and the window primitives on PostgreSQL Ten gated database cases, all listed in test/prism-gated-tests.txt. They go in a new file rather than the shared 2.x.x support module, which another open change appends to. Migration 007: a frozen 2.x.x schema carrying only terminal outbox rows upgrades with every row and field intact and the seven new columns NULL; each of the three pre-007 pending shapes is refused by name, with nothing from 007 applied and no version 7 row, and the same binary starts once the row is drained; a database at [2, 3, 4, 5, 8, 9] applies 007 and only 007, leaving every other version's applied_at untouched; the CHECK accepts exactly the three states across all 64 null combinations and rejects a short or uppercase digest, a zero or out-of-range count and a zero sequence; and the retention index is the partial one on window_prior_balances_sha256. config_fingerprint() returns what configure pinned or verified, is shared by clones, and stays empty after a refused configure. from_snapshot's streamed digest equals sha256(serde_json::to_vec) and the snapshot_sha256 landing writes for the same window. The balance writer stores the canonical sort, is idempotent under any permutation, errors rather than accepting a different encoding of the same digest, and read_window(..., AsIssued) hands back the stored order. The probe misses a missing endpoint, the paged reader compares 4,999 rows page by page with a vector held inside the caller's transaction, and a row the predicate skips inside a range is Incomplete with no partial window. The permit case builds a runtime with one blocking thread, occupies it, and cancels a reader parked mid-page on a database gate: no permit is available while the cleanup is queued, and one is once it has run. A failed blocking hand-off surfaces as TaskFailed, never as Decode. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: carry the window reference on prepared work, behind a read permit `Prepared` gains `window: WindowRef`, computed once per non-cached refresh beside `build_bundle` under `tokio::join!`, so submit can clone it instead of re-digesting the window on the share path when a block is found. An empty snapshot gets the empty-window reference on the runtime thread; a resume computes it inside the blocking decode it already runs. `Coordinator` gains the `window_reads` semaphore, sized `clamp(database_max_connections - 2, 1, build_workers)`, and the one entry point callers use: it takes an owned permit after the caller's `build_slots` permit and hands it to `Ledger::read_window_with_permit`, which holds it across the whole read, including the off-runtime cleanup a cancellation leaves behind, and releases it before the rebuild. `Ledger::read_window` is awaited on the runtime, never wrapped in `spawn_blocking`; the test with a single blocking thread pins that. The four gated `window_ref_tests` are listed in the manifest. Part of #265 Co-Authored-By: Claude Fable 5.1 <[email protected]> * 3.x.x: switch the candidate outbox to the window reference `Candidate` drops the embedded `AuditBundle` for `window: WindowRef` and every builder input except the window: `found_block`, `payout_policy`, the nested `ctv` triple (whose presence selects the CTV builder), the stored `bootstrap_share` of an empty window, `audit_builder_version`, `signer_keys`, a `leased` flag and the now-required `coinbase_suffix_hex`. The block leaves the document for the `block_bytes` column, authenticated by `block_sha256`, which `candidate_sha256` covers. The write serializes, digests and checks the candidate before the append or enqueue transaction opens; under `ORDER_LOCK` the transaction re-reads `config_fingerprint FOR SHARE` and refuses a value the writer did not pin, re-inserts a `leased` candidate's as-issued balance snapshot through the shared writer, probes the window's first row (an absent row alerts and still publishes), and inserts only the prepared bytes with the six typed columns. Submit builds the slim candidate from `Prepared.window`, the `BundleInputs` captured where `build_bundle` read configuration, and the job's own bootstrap share; it clones no bundle and reads no config. The claim's `UPDATE … RETURNING` returns the columns and the block, and the decode, off the runtime, checks the document against them, the digest, `sha256(block_bytes)`, the header hash, the required fields and the two reference invariants. A pending row with a NULL anchor is a hard error naming the pre-007 frontend; an inline document is never decoded. Before any read the claim retries, with an alert naming both values, a stored builder version or signer pair that is not this binary's; a landed audit is authenticated against the block (coinbase, audit root as the witness reserved value, s…
…write off the ordering lock (#350) * 3.x.x: add migration 007 and refuse pre-007 candidate outbox rows Migration 007 mirrors 008 onto qbit_block_candidate_outbox: the same six window-reference columns, and a three-state CHECK whose body is identical to 008's apart from the table and constraint names. It also adds block_bytes, the nullable bytea the block moves into so the candidate document stays small, and a partial index on window_prior_balances_sha256 for the balance-snapshot GC. Nothing writes any of them yet; this is additive schema only. The runner applies 007 by membership, in its own block between 5 and 8, so it assumes neither 006 nor 008 has run. Before any DDL it refuses while the outbox still holds a pending row in a pre-007 shape: a native inline candidate, a NULL candidate, or storage_version other than 1 on the 2.x.x schemas that have that column, which is checked for first so the predicate does not error on a native schema. The refusal names every offending block_hash and the drain procedure, and the whole migration transaction rolls back, so a refused start leaves the schema untouched. The applied set is now [2, 3, 4, 5, 7, 8, 9], and the four exact migration assertions move with it rather than being weakened to a superset. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: retain the cluster fingerprint configure pinned or verified The candidate enqueue and save_job must fence against a fingerprint reset by re-reading qbit_prism_cluster.config_fingerprint FOR SHARE in their own transaction and refusing a write that is not this frontend's own. That needs the value configure settled at startup, so Ledger keeps it in a shared OnceLock, set only once the pin or the match has committed, and exposes it read-only through config_fingerprint(). configure keeps its signature and its mismatch refusal, and a refused call retains nothing. The rotation refusal in configure, and the writer fence itself, belong to the enqueue change and are not here. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: share the window reference, balance writer and page primitives WindowRef::from_snapshot is the synchronous reference builder both writers need: anchor_ms copied, the semantic balances digest, and for a non-empty snapshot the first and last share_seq, the length, and the share array's SHA-256 streamed through the existing DigestWriter, so the 233 to 260 MB serialized window at 400,000 shares is never built and the digest equals the one qbit_prism_audit_snapshots already stores. An empty snapshot gives the empty-window reference. Callers run it inside their own spawn_blocking. put_balance_snapshot is the one canonical writer of qbit_prism_balance_snapshots, on the caller's transaction: the sort by (order_key, recipient_id, p2mr_program_hex), the semantic digest that keys the row, and compact JSON of the sorted set, all off the runtime, then INSERT ... ON CONFLICT DO NOTHING. On a conflict it reads the stored bytes back and compares them with its own, because these rows are immutable and can only disagree through corruption. The enqueue and save_job and its repair all write through it. read_prior_balances and the current-balance read still keep their SQL order; the writer's sort defines the stored encoding, which is the order read_window(..., AsIssued) returns. probe_share_rows and read_range_paged are read_window's endpoint probe and page loop, lifted onto a caller's connection so the enqueue probe and the landing re-read share one implementation. The predicate, the ascending keyset order, the 4096-row page bound and the per-page count bound are unchanged, and read_window now calls them, with its signature and behaviour unchanged. The paged reader takes the caller's state and a per-page consumer, both of which travel to the blocking thread with the rows, so the landing re-read can compare each page with its slice of a vector it already holds without any whole-window work on the runtime; a dropped read still releases the accumulated state on a blocking thread. read_window_with_permit holds the caller's window_reads permit across the whole read. The permit is moved into a BlockingDrop declared before the read starts, so a cancellation releases it on a blocking thread after the page state queued its own release there, and never with the future; a return releases it inline, before the caller's rebuild. WindowError::TaskFailed separates a cancelled or panicking blocking hand-off from corruption. Every hand-off maps a JoinError to it instead of to Decode, so a cancellation is a retryable failure with its own alert and never takes the abandon path. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: derive the witness merkle leaves from an assembled block A claim rebuilds from stored inputs, and the witness leaves are the one builder input that scales with the block, so they are re-derived rather than stored: one 64-hex string per transaction beside the candidate would grow the document with the block. witness_merkle_leaves_from_block skips the 80-byte header, reads the compact-size transaction count, walks past the coinbase and returns double_sha256 of every remaining transaction's full serialized bytes. That is sound because assemble_submission appends the template's transactions verbatim after the coinbase, so the result equals witness_merkle_leaves_hex(&transactions_from_template(template)) for the block built from that template, with or without segwit transactions. The segwit-aware walk is strip_witness_transaction's own, factored into a helper that also reports where the transaction ends, which is what a block walker needs; strip_witness_transaction keeps its trailing-byte check and its output. A truncated block, trailing bytes, a zero count and a count that disagrees with the transactions present are all errors, never a partial list of leaves. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: version the audit builders and key the CC5 goldens by it A stored window reference reproduces its bundle only under the builder that first built it. The schema strings do not capture that, because the share shape chooses them rather than the builder logic, so qbit-prism gains AUDIT_BUILDER_VERSION, starting at 1. A candidate and a prepared job store it, and a rebuild refuses a reference at another version instead of rebuilding it with the current builder. The bump rule is on the constant: any change that alters canonical_audit_bundle_bytes for the same inputs bumps it in the same commit. The CC5 golden test now selects its expected digests from a table keyed by the constant, and fails when no entry exists, so a new output is recorded as a new entry beside the old one and review sees both. Version 1 holds the existing literals, unchanged. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: cover 007, the fingerprint and the window primitives on PostgreSQL Ten gated database cases, all listed in test/prism-gated-tests.txt. They go in a new file rather than the shared 2.x.x support module, which another open change appends to. Migration 007: a frozen 2.x.x schema carrying only terminal outbox rows upgrades with every row and field intact and the seven new columns NULL; each of the three pre-007 pending shapes is refused by name, with nothing from 007 applied and no version 7 row, and the same binary starts once the row is drained; a database at [2, 3, 4, 5, 8, 9] applies 007 and only 007, leaving every other version's applied_at untouched; the CHECK accepts exactly the three states across all 64 null combinations and rejects a short or uppercase digest, a zero or out-of-range count and a zero sequence; and the retention index is the partial one on window_prior_balances_sha256. config_fingerprint() returns what configure pinned or verified, is shared by clones, and stays empty after a refused configure. from_snapshot's streamed digest equals sha256(serde_json::to_vec) and the snapshot_sha256 landing writes for the same window. The balance writer stores the canonical sort, is idempotent under any permutation, errors rather than accepting a different encoding of the same digest, and read_window(..., AsIssued) hands back the stored order. The probe misses a missing endpoint, the paged reader compares 4,999 rows page by page with a vector held inside the caller's transaction, and a row the predicate skips inside a range is Incomplete with no partial window. The permit case builds a runtime with one blocking thread, occupies it, and cancels a reader parked mid-page on a database gate: no permit is available while the cleanup is queued, and one is once it has run. A failed blocking hand-off surfaces as TaskFailed, never as Decode. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: carry the window reference on prepared work, behind a read permit `Prepared` gains `window: WindowRef`, computed once per non-cached refresh beside `build_bundle` under `tokio::join!`, so submit can clone it instead of re-digesting the window on the share path when a block is found. An empty snapshot gets the empty-window reference on the runtime thread; a resume computes it inside the blocking decode it already runs. `Coordinator` gains the `window_reads` semaphore, sized `clamp(database_max_connections - 2, 1, build_workers)`, and the one entry point callers use: it takes an owned permit after the caller's `build_slots` permit and hands it to `Ledger::read_window_with_permit`, which holds it across the whole read, including the off-runtime cleanup a cancellation leaves behind, and releases it before the rebuild. `Ledger::read_window` is awaited on the runtime, never wrapped in `spawn_blocking`; the test with a single blocking thread pins that. The four gated `window_ref_tests` are listed in the manifest. Part of #265 Co-Authored-By: Claude Fable 5.1 <[email protected]> * 3.x.x: switch the candidate outbox to the window reference `Candidate` drops the embedded `AuditBundle` for `window: WindowRef` and every builder input except the window: `found_block`, `payout_policy`, the nested `ctv` triple (whose presence selects the CTV builder), the stored `bootstrap_share` of an empty window, `audit_builder_version`, `signer_keys`, a `leased` flag and the now-required `coinbase_suffix_hex`. The block leaves the document for the `block_bytes` column, authenticated by `block_sha256`, which `candidate_sha256` covers. The write serializes, digests and checks the candidate before the append or enqueue transaction opens; under `ORDER_LOCK` the transaction re-reads `config_fingerprint FOR SHARE` and refuses a value the writer did not pin, re-inserts a `leased` candidate's as-issued balance snapshot through the shared writer, probes the window's first row (an absent row alerts and still publishes), and inserts only the prepared bytes with the six typed columns. Submit builds the slim candidate from `Prepared.window`, the `BundleInputs` captured where `build_bundle` read configuration, and the job's own bootstrap share; it clones no bundle and reads no config. The claim's `UPDATE … RETURNING` returns the columns and the block, and the decode, off the runtime, checks the document against them, the digest, `sha256(block_bytes)`, the header hash, the required fields and the two reference invariants. A pending row with a NULL anchor is a hard error naming the pre-007 frontend; an inline document is never decoded. Before any read the claim retries, with an alert naming both values, a stored builder version or signer pair that is not this binary's; a landed audit is authenticated against the block (coinbase, audit root as the witness reserved value, share snapshot, bits) and the claim then skips the rebuild and landing and continues to observe, renew and submit. Otherwise it takes `build_slots`, then `window_reads` inside one 60 s deadline around the awaited `read_window(Current)` and the borrowing builder run directly in `spawn_blocking`, and keeps `Arc<AuditBundleBody>` and the shares as `ClaimParts`. `Incomplete`, `SnapshotDigestMismatch`, `Decode`, `BalanceSnapshotMissing`, `TaskFailed` and the deadline retry with their own alerts; `PriorBalancesChanged` finishes only a block `observe_candidate` proves inactive and superseded; `Database` propagates. A `leased` candidate submits from `block_bytes` first, then rebuilds `AsIssued` and lands before any terminal outcome. Rebuilt parts are released off the runtime on every path. Landing takes the parts and does all whole-window work in one blocking closure: `verify_audit_parts`, the raw body, the counted canonical bytes, the leaves and accounts, and the share snapshot digest, which must equal the reference's. The balance fence compares the current set and the parts' through the semantic digest, so an as-issued set compares equal in any order. `persist_audit_snapshot` re-reads the range with the paged reader inside the landing transaction, page against slice on the blocking thread; `read_range` stays for the API. The terminal UPDATE NULLs the six window columns and `block_bytes` with `candidate`. `configure` refuses to pin a fingerprint onto a reset one while a pending row stores other signer keys, and the startup gate requires 007 with 009. The JSONB gate drops its enqueue entry, and every helper that built a candidate builds the slim one, handing the ledger-level landings the bundle's parts through `CandidateClaim::with_bundle`. Part of #265 Co-Authored-By: Claude Fable 5.1 <[email protected]> * 3.x.x: cover the candidate switch on PostgreSQL Ledger-level, in `candidate_window_switch`: a two-page window enqueues a document with no array and no share row, under 1 MB, whose six typed columns equal its reference and whose block is stored as bytes; the writer fence refuses a reset or different fingerprint in the same transaction, share included; a missing window prefix row alerts and still publishes, and its read then meets `Incomplete`; a `leased` enqueue re-inserts the as-issued balance snapshot in the writer's canonical order, writes none when not leased, and refuses balances that do not hash to the reference; every preparation failure is refused without waiting for `ORDER_LOCK`; every column, digest, block, header, NULL-anchor, missing-field, invariant and inline-document disagreement is refused at claim; landing refuses parts that are not the referenced window and a claim without parts; the terminal UPDATE NULLs the six columns and the block for submitted and abandoned rows; the landed-audit authentication rejects a forged coinbase, root, snapshot or bits; and `configure` refuses a rotation over a foreign-signed pending candidate. Coordinator-level, in `window_switch_tests` behind a fake node: a stored builder version or signer pair that is not this binary's retries, naming both values, while the build slot is held; a landed audit is authenticated and the claim continues to `submitblock` without a build slot, and a forged landed coinbase or root is refused with the row left pending; `Incomplete`, a digest mismatch, changed balances on a current block and the rebuild deadline all retry with an alert and release their permits; `classify_window_error` keeps `TaskFailed` apart from corruption and propagates `Database`; the read, rebuild and landing complete while `ORDER_LOCK` is held, with one build worker; a `leased` candidate submits first, then lands from `AsIssued`, and finishes submitted, abandoned with the node's reason, or pending when its balance snapshot is missing; and `OffRuntime` releases on a blocking thread, on cancellation too. The fifteen gated tests are listed in the manifest. Part of #265 Co-Authored-By: Claude Fable 5.1 <[email protected]> * 3.x.x: migrate the imported-audit tests to the slim candidate Slice 1 (#325) merged after this stack branched, and its tests in tests/support/ledger_2x.rs still built the pre-007 candidate: they read block.bundle from a Candidate and called candidate_with_bundle without a window reference or settlement inputs. The rebase merged them cleanly and the tree then failed to compile. The three helpers now take the TestCandidate the constructors return, so they reach the bundle beside the slim candidate, and land_confirmed attaches the claim's parts the way the other ledger tests do. The three constructor calls pass the window reference the bundle was built on, and the settlement inputs for the CTV case. No assertion changes. Part of #265. * 3.x.x: qualify lease renewal and the claim's canonical bytes at scale Incident 1: a candidate whose window holds N shares is claimed and processed under the short lease, and every renewal is read back from claim_expires_at. The largest gap stays below interval + 2 x timeout, the lease never lapses, and a successor ledger cannot take the claim. The bundle a claim rebuilds through the window-read entry point and the borrowing builder has the canonical bytes refresh built for the same job, and the landed audit carries that bundle's digest. Both run at PRISM_WINDOW_QUALIFY_SHARES (20,000 by default); the 400,000-share variants are ignored and run on a larger host. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: measure ACK latency and ORDER_LOCK hold across window sizes Incident 2: two frontends on one database submit ordinary shares at a fixed rate while one of them solves a block on an N-share window and its own submit loop claims, rebuilds, lands and submits it. The solving share's ACK and the bystander's p99 stay within max(2 x baseline p99 + 50 ms, 250 ms), every ACK is well under the share-commit timeout, and the block is enqueued exactly once. Latency is the in-process MiningBackend::submit wall clock; the socket-level harness (#271) does not exist yet. A pg_locks sampler on its own connection measures how long a solving append holds ORDER_LOCK at two window sizes with no other traffic: the larger size stays within a fixed slack of the smaller, and the candidate document is the same size at both and under 1 MiB. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: hold the JSONB gate's enqueue to a window-free row under 1 MiB At every measured size the enqueue must be accepted and every JSONB value it writes, the outbox candidate document included, must stay under 1,048,576 bytes. At the reduced sizes the enqueue, claim and landing phases must all run. The ratchet and its expected values are unchanged. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: make the window-read permit test actually wait before it looks The delay that gives an unpermitted read time to finish was an empty async block, so the check that the read had not finished ran at once and passed whether or not the entry point took a permit. It now sleeps 500 ms inside a 5 s bound, and fails when the permit acquisition is removed from the entry point. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: rebuild a CTV candidate from its stored settlement inputs No host-runnable test reached the CTV branch of the claim rebuild. A CTV-enabled frontend now claims a candidate whose stored direct floor differs from its configuration, and builds a different coinbase than the configured floor would, and the claim must land that candidate's own audit and submit it. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: pin the SQL order of the current-balance reads Nothing defended the ruling that the current-balance path keeps its SQL order: every fixture's balances already arrived in byte-wise canonical order. The carry table's text columns now take an ICU collation, under which the SQL order and the canonical sort disagree, and the snapshot and the current-balance window read must both return the SQL order. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: record what incident 2 must also assert once #324 is in the base After #324 a slow solve is acknowledged late rather than refused, so acceptance proves nothing and the latency percentiles stay the assertion. The doc comment and a TODO at the outcome checks name the counter and outcome to assert at rebase. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: assert incident 2's late-confirm counter now that #324 is in the base W3c wrote the qualification tests against a base that predated #324 and left a marked place for the assertions that only make sense once the commit gate is there. The base now carries it, so apply them: incident 2 asserts `qbit_prism_late_confirmed_shares_total` is zero on both frontends and that no acknowledgement, the block-solving share included, is `ledger-outcome-unknown`. Acceptance alone is no longer proof. #324 gives a share-pass append carrying a candidate its own `block_only_ack_timeout`, so a slow solve is never refused at the share deadline; it is answered late, or answered unknown. Either would have satisfied the acceptance checks with the serialization stall still present. Also set #324's two new `Config` fields in the qualification fixture. * 3.x.x: pin a refused candidate as a definite rejection, not an unknown outcome #324 decides what a miner is told when a block-only enqueue fails: `enqueue_failed_before_commit` answers a provably uncommitted failure with `ledger-confirmation-failed`, and anything else with `ledger-outcome-unknown`, which asks an operator to go and follow the outbox row. Slice 3 added the checks that guard the reference: the block's length, its header hash, its digest against `block_sha256`, the coinbase suffix, the reference invariants, and a leased candidate's balances. All of them are raised by `prepare_candidate` before the enqueue takes a connection, so none carries an `sqlx::Error` and all classify as definite today. That is a property of where the checks sit, not something the classifier knows about them, so it is pinned here rather than left to hold by accident: a corrupt candidate must never send a miner chasing a row that was never written. Verified by mutation: classifying a non-sqlx failure as unknown fails this test. * 3.x.x: say why the full-size qualification variants cannot reach 400k yet Their ignore reasons blamed RAM and the host. The real limit is #273: the job payload still holds three copies of the window (2 x AcceptedShare + 1 x CountedShare), so publishing a job for a 400,000-share window needs about 670 MiB and PostgreSQL refuses the write above its 256 MiB jsonb object limit. Every full-size variant fails at fixture set-up, before it measures anything. The count must also divide the window weight exactly, so the largest usable size today is 125,000, where all four variants pass in release: incident 1 50 renewals, max gap 118.25 ms against a 700 ms bound incident 2 phase-A p99 2.60 ms, phase-B p99 95.79 ms, bound 250 ms lock hold median 0.75 ms at 5,000 against 1.32 ms at 125,000 canonical refresh and claim rebuild both 139,040,610 B, same sha256 The candidate document stays flat at 1103 B and 1107 B, which is the property this slice exists to establish. * 3.x.x: migrate the audit-body normalization tests to the slim candidate #267 landed its own test file against the candidate that still carried an assembled bundle. This slice replaced that with a window reference, so the file keeps a `TestCandidate` pairing the stored candidate with the bundle a test still needs, as `tests/ledger_postgres.rs` does, and attaches the claim's parts through `with_bundle`. One case needed more than a shape change. The four negative cases hand the claim a window the ledger does not hold and require the durable-range proof to be what refuses it. A candidate now commits to a snapshot digest, so a reference taken from the unaltered snapshot would be refused earlier, at the reference check, and the proof under test would never run. `window_ref_for` therefore derives each altered window's reference from that window, leaving the proof as the only thing that can notice, which is what #267 wrote them to prove. * 3.x.x: pin the durable-range proof outside the settlement lock #267 moved the full-equality proof of a candidate's window out of the settlement transaction so the lock is not held for a window-sized read. This slice made that read paged, so it does not occupy a runtime thread either. Reconciling the two is the step that can quietly undo the first: keep this slice's `persist_audit_snapshot` through the rebase and the full read goes back under the lock. The landing stays correct, every other test still passes, and only the lock hold grows, so nothing in the suite can tell. Measured at 100,000 shares on #267's branch that was a 34% longer hold. The guard is deterministic and needs no large window. A second connection holds `SETTLEMENT_LOCK`, so the landing blocks on it once its proof has run. While it waits, one share's `ntime` is altered: full equality sees that, a count over the same anchored predicate cannot. The landing must then succeed, which it can only do if it had already read and compared the shares before taking the lock. Accepted history is immutable and a trigger enforces it, so the test lifts that trigger for the single statement, inside its own disposable schema, and puts it straight back. Verified by mutation: restoring the in-transaction range read fails this test with "the landing read share payloads under the settlement lock". * 3.x.x: serialise the coordinator test modules that share the ledger's locks The ledger's advisory locks are cluster-wide constants, not schema-scoped, so two coordinator test modules running in parallel contend for ORDER_LOCK even though each works in its own throwaway schema. Every module held a lock of its own, which serialised it against itself and left cross-module waits to `lock_timeout`, 5 s by default. #324's reconciliation tests hold ORDER_LOCK for up to about 1.5 s, and this slice adds three more modules that open a ledger. Once enough of them ran at once those waits stacked past the timeout: a full `--lib` run failed with "canceling statement due to lock timeout" in `candidate_lease_tests` and `window_switch_tests`, and passed on the next run. A suite that fails for a reason unrelated to what it tests is worse than a slow one. All seven modules now take one shared lock. The run goes from about 35 s to about 62 s, and three consecutive runs pass where the flake had reproduced. * 3.x.x: pass the signer keys #334's wait-metrics tests now need `Ledger::configure` takes the frontend's signing keys since this slice, so the fingerprint contention tests #334 added call it with a fixed pair. That suite measures advisory-lock and pool-acquire waits, not signing, so the only thing the keys have to be is the same on every call. * 3.x.x: resume a job's bundle only while the current inputs still describe it A resumed job reuses the bundle it was issued with, but captures its inputs from this frontend's configuration now. Before this slice that was harmless: the candidate carried the assembled bundle, and landing used it directly. Now the candidate stores the inputs and the claim rebuilds the audit from them, so an old bundle labelled with today's configuration rebuilds to a coinbase the block does not commit to. The claim fails its comparison before `submitblock` and retries until the job expires, which can lose a found block. The stored bundle is now reused only when the captured inputs still describe it, comparing what the bundle itself records about how it was built: the payout policy, and the public keys that actually signed its coinbase manifest and its ledger attestation. A difference is a cache miss, so the bundle is rebuilt rather than mislabelled. Both directions are covered, since over-tightening would silently defeat the job cache and rebuild on every resume: unchanged inputs must still describe the bundle, and a payout-policy change, a full signer rotation and a rotation of either key alone must each refuse it. Known residue, recorded in the doc comment: a bundle records neither the CTV settlement inputs nor `audit_builder_version`, so a change to either between issue and resume is still undetectable here. Closing that needs the issued job to store its inputs, which is #273's format. * 3.x.x: migrate #355's ledger tests to the slim candidate #355 landed deadline and single-execution coverage against the candidate that still carried an assembled bundle, and against `configure` before it took the frontend's signing keys. Adapted, the same way #325's and #267's suites were: a `TestCandidate` pairs the stored candidate with the bundle a landing still needs, claims attach their parts through `with_bundle`, and the conflicting claim that is never landed carries none. `ledger_deadline_atomicity` builds its candidate from a bundle rather than a snapshot, so its window reference is derived from that bundle: the anchor and prior-balances digest it already records, and the range and digest of the shares it carries. Its signer keys come from the public keys that actually signed it, rather than from a local pair, so the stored inputs describe the bundle. * 3.x.x: make the landed-audit forgery always alter the row, and migrate #360's fixture The forged-coinbase case placed a literal '0' at a fixed offset. Whenever the digit already held that value the forgery changed nothing, so the claim was right to accept it and the case failed only by luck. The coinbase varies per run, because the bundle's anchor comes from the ledger clock, so this passed repeatedly and then failed once as "the forgery was accepted" — an alarming message for a case that was in fact a no-op. A security check that can quietly become vacuous is worse than one that is absent. The digit is now flipped to a value it does not currently hold, and the row is read back either side of the statement so a forgery that altered nothing fails the case for that reason instead. Also passes the signer keys #360's `tests/support/fatal_state.rs` now needs, since `configure` takes them in this slice. * 3.x.x: drop the pre-#362 path for the heartbeat SQL gated test #362 moved `live_instance_tests` from `tools` to `ledger::instances`. Merging the gated-test manifest during the rebase kept both paths, because a rename upstream looks like one id removed and another added, and a union keeps the removed one. The old `tools::` path then never executed and the gate refused the run: "194 distinct gated tests executed, below the minimum of 195". The manifest is a superset of the base's ids, and every id this branch adds over the base resolves to a test function that exists in the tree. * v3.0.0 feat: add compact prepared storage and immutable template blobs (#359) * 3.x.x: add migration 007 and refuse pre-007 candidate outbox rows Migration 007 mirrors 008 onto qbit_block_candidate_outbox: the same six window-reference columns, and a three-state CHECK whose body is identical to 008's apart from the table and constraint names. It also adds block_bytes, the nullable bytea the block moves into so the candidate document stays small, and a partial index on window_prior_balances_sha256 for the balance-snapshot GC. Nothing writes any of them yet; this is additive schema only. The runner applies 007 by membership, in its own block between 5 and 8, so it assumes neither 006 nor 008 has run. Before any DDL it refuses while the outbox still holds a pending row in a pre-007 shape: a native inline candidate, a NULL candidate, or storage_version other than 1 on the 2.x.x schemas that have that column, which is checked for first so the predicate does not error on a native schema. The refusal names every offending block_hash and the drain procedure, and the whole migration transaction rolls back, so a refused start leaves the schema untouched. The applied set is now [2, 3, 4, 5, 7, 8, 9], and the four exact migration assertions move with it rather than being weakened to a superset. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: retain the cluster fingerprint configure pinned or verified The candidate enqueue and save_job must fence against a fingerprint reset by re-reading qbit_prism_cluster.config_fingerprint FOR SHARE in their own transaction and refusing a write that is not this frontend's own. That needs the value configure settled at startup, so Ledger keeps it in a shared OnceLock, set only once the pin or the match has committed, and exposes it read-only through config_fingerprint(). configure keeps its signature and its mismatch refusal, and a refused call retains nothing. The rotation refusal in configure, and the writer fence itself, belong to the enqueue change and are not here. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: share the window reference, balance writer and page primitives WindowRef::from_snapshot is the synchronous reference builder both writers need: anchor_ms copied, the semantic balances digest, and for a non-empty snapshot the first and last share_seq, the length, and the share array's SHA-256 streamed through the existing DigestWriter, so the 233 to 260 MB serialized window at 400,000 shares is never built and the digest equals the one qbit_prism_audit_snapshots already stores. An empty snapshot gives the empty-window reference. Callers run it inside their own spawn_blocking. put_balance_snapshot is the one canonical writer of qbit_prism_balance_snapshots, on the caller's transaction: the sort by (order_key, recipient_id, p2mr_program_hex), the semantic digest that keys the row, and compact JSON of the sorted set, all off the runtime, then INSERT ... ON CONFLICT DO NOTHING. On a conflict it reads the stored bytes back and compares them with its own, because these rows are immutable and can only disagree through corruption. The enqueue and save_job and its repair all write through it. read_prior_balances and the current-balance read still keep their SQL order; the writer's sort defines the stored encoding, which is the order read_window(..., AsIssued) returns. probe_share_rows and read_range_paged are read_window's endpoint probe and page loop, lifted onto a caller's connection so the enqueue probe and the landing re-read share one implementation. The predicate, the ascending keyset order, the 4096-row page bound and the per-page count bound are unchanged, and read_window now calls them, with its signature and behaviour unchanged. The paged reader takes the caller's state and a per-page consumer, both of which travel to the blocking thread with the rows, so the landing re-read can compare each page with its slice of a vector it already holds without any whole-window work on the runtime; a dropped read still releases the accumulated state on a blocking thread. read_window_with_permit holds the caller's window_reads permit across the whole read. The permit is moved into a BlockingDrop declared before the read starts, so a cancellation releases it on a blocking thread after the page state queued its own release there, and never with the future; a return releases it inline, before the caller's rebuild. WindowError::TaskFailed separates a cancelled or panicking blocking hand-off from corruption. Every hand-off maps a JoinError to it instead of to Decode, so a cancellation is a retryable failure with its own alert and never takes the abandon path. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: derive the witness merkle leaves from an assembled block A claim rebuilds from stored inputs, and the witness leaves are the one builder input that scales with the block, so they are re-derived rather than stored: one 64-hex string per transaction beside the candidate would grow the document with the block. witness_merkle_leaves_from_block skips the 80-byte header, reads the compact-size transaction count, walks past the coinbase and returns double_sha256 of every remaining transaction's full serialized bytes. That is sound because assemble_submission appends the template's transactions verbatim after the coinbase, so the result equals witness_merkle_leaves_hex(&transactions_from_template(template)) for the block built from that template, with or without segwit transactions. The segwit-aware walk is strip_witness_transaction's own, factored into a helper that also reports where the transaction ends, which is what a block walker needs; strip_witness_transaction keeps its trailing-byte check and its output. A truncated block, trailing bytes, a zero count and a count that disagrees with the transactions present are all errors, never a partial list of leaves. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: version the audit builders and key the CC5 goldens by it A stored window reference reproduces its bundle only under the builder that first built it. The schema strings do not capture that, because the share shape chooses them rather than the builder logic, so qbit-prism gains AUDIT_BUILDER_VERSION, starting at 1. A candidate and a prepared job store it, and a rebuild refuses a reference at another version instead of rebuilding it with the current builder. The bump rule is on the constant: any change that alters canonical_audit_bundle_bytes for the same inputs bumps it in the same commit. The CC5 golden test now selects its expected digests from a table keyed by the constant, and fails when no entry exists, so a new output is recorded as a new entry beside the old one and review sees both. Version 1 holds the existing literals, unchanged. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: cover 007, the fingerprint and the window primitives on PostgreSQL Ten gated database cases, all listed in test/prism-gated-tests.txt. They go in a new file rather than the shared 2.x.x support module, which another open change appends to. Migration 007: a frozen 2.x.x schema carrying only terminal outbox rows upgrades with every row and field intact and the seven new columns NULL; each of the three pre-007 pending shapes is refused by name, with nothing from 007 applied and no version 7 row, and the same binary starts once the row is drained; a database at [2, 3, 4, 5, 8, 9] applies 007 and only 007, leaving every other version's applied_at untouched; the CHECK accepts exactly the three states across all 64 null combinations and rejects a short or uppercase digest, a zero or out-of-range count and a zero sequence; and the retention index is the partial one on window_prior_balances_sha256. config_fingerprint() returns what configure pinned or verified, is shared by clones, and stays empty after a refused configure. from_snapshot's streamed digest equals sha256(serde_json::to_vec) and the snapshot_sha256 landing writes for the same window. The balance writer stores the canonical sort, is idempotent under any permutation, errors rather than accepting a different encoding of the same digest, and read_window(..., AsIssued) hands back the stored order. The probe misses a missing endpoint, the paged reader compares 4,999 rows page by page with a vector held inside the caller's transaction, and a row the predicate skips inside a range is Incomplete with no partial window. The permit case builds a runtime with one blocking thread, occupies it, and cancels a reader parked mid-page on a database gate: no permit is available while the cleanup is queued, and one is once it has run. A failed blocking hand-off surfaces as TaskFailed, never as Decode. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: carry the window reference on prepared work, behind a read permit `Prepared` gains `window: WindowRef`, computed once per non-cached refresh beside `build_bundle` under `tokio::join!`, so submit can clone it instead of re-digesting the window on the share path when a block is found. An empty snapshot gets the empty-window reference on the runtime thread; a resume computes it inside the blocking decode it already runs. `Coordinator` gains the `window_reads` semaphore, sized `clamp(database_max_connections - 2, 1, build_workers)`, and the one entry point callers use: it takes an owned permit after the caller's `build_slots` permit and hands it to `Ledger::read_window_with_permit`, which holds it across the whole read, including the off-runtime cleanup a cancellation leaves behind, and releases it before the rebuild. `Ledger::read_window` is awaited on the runtime, never wrapped in `spawn_blocking`; the test with a single blocking thread pins that. The four gated `window_ref_tests` are listed in the manifest. Part of #265 Co-Authored-By: Claude Fable 5.1 <[email protected]> * 3.x.x: switch the candidate outbox to the window reference `Candidate` drops the embedded `AuditBundle` for `window: WindowRef` and every builder input except the window: `found_block`, `payout_policy`, the nested `ctv` triple (whose presence selects the CTV builder), the stored `bootstrap_share` of an empty window, `audit_builder_version`, `signer_keys`, a `leased` flag and the now-required `coinbase_suffix_hex`. The block leaves the document for the `block_bytes` column, authenticated by `block_sha256`, which `candidate_sha256` covers. The write serializes, digests and checks the candidate before the append or enqueue transaction opens; under `ORDER_LOCK` the transaction re-reads `config_fingerprint FOR SHARE` and refuses a value the writer did not pin, re-inserts a `leased` candidate's as-issued balance snapshot through the shared writer, probes the window's first row (an absent row alerts and still publishes), and inserts only the prepared bytes with the six typed columns. Submit builds the slim candidate from `Prepared.window`, the `BundleInputs` captured where `build_bundle` read configuration, and the job's own bootstrap share; it clones no bundle and reads no config. The claim's `UPDATE … RETURNING` returns the columns and the block, and the decode, off the runtime, checks the document against them, the digest, `sha256(block_bytes)`, the header hash, the required fields and the two reference invariants. A pending row with a NULL anchor is a hard error naming the pre-007 frontend; an inline document is never decoded. Before any read the claim retries, with an alert naming both values, a stored builder version or signer pair that is not this binary's; a landed audit is authenticated against the block (coinbase, audit root as the witness reserved value, share snapshot, bits) and the claim then skips the rebuild and landing and continues to observe, renew and submit. Otherwise it takes `build_slots`, then `window_reads` inside one 60 s deadline around the awaited `read_window(Current)` and the borrowing builder run directly in `spawn_blocking`, and keeps `Arc<AuditBundleBody>` and the shares as `ClaimParts`. `Incomplete`, `SnapshotDigestMismatch`, `Decode`, `BalanceSnapshotMissing`, `TaskFailed` and the deadline retry with their own alerts; `PriorBalancesChanged` finishes only a block `observe_candidate` proves inactive and superseded; `Database` propagates. A `leased` candidate submits from `block_bytes` first, then rebuilds `AsIssued` and lands before any terminal outcome. Rebuilt parts are released off the runtime on every path. Landing takes the parts and does all whole-window work in one blocking closure: `verify_audit_parts`, the raw body, the counted canonical bytes, the leaves and accounts, and the share snapshot digest, which must equal the reference's. The balance fence compares the current set and the parts' through the semantic digest, so an as-issued set compares equal in any order. `persist_audit_snapshot` re-reads the range with the paged reader inside the landing transaction, page against slice on the blocking thread; `read_range` stays for the API. The terminal UPDATE NULLs the six window columns and `block_bytes` with `candidate`. `configure` refuses to pin a fingerprint onto a reset one while a pending row stores other signer keys, and the startup gate requires 007 with 009. The JSONB gate drops its enqueue entry, and every helper that built a candidate builds the slim one, handing the ledger-level landings the bundle's parts through `CandidateClaim::with_bundle`. Part of #265 Co-Authored-By: Claude Fable 5.1 <[email protected]> * 3.x.x: cover the candidate switch on PostgreSQL Ledger-level, in `candidate_window_switch`: a two-page window enqueues a document with no array and no share row, under 1 MB, whose six typed columns equal its reference and whose block is stored as bytes; the writer fence refuses a reset or different fingerprint in the same transaction, share included; a missing window prefix row alerts and still publishes, and its read then meets `Incomplete`; a `leased` enqueue re-inserts the as-issued balance snapshot in the writer's canonical order, writes none when not leased, and refuses balances that do not hash to the reference; every preparation failure is refused without waiting for `ORDER_LOCK`; every column, digest, block, header, NULL-anchor, missing-field, invariant and inline-document disagreement is refused at claim; landing refuses parts that are not the referenced window and a claim without parts; the terminal UPDATE NULLs the six columns and the block for submitted and abandoned rows; the landed-audit authentication rejects a forged coinbase, root, snapshot or bits; and `configure` refuses a rotation over a foreign-signed pending candidate. Coordinator-level, in `window_switch_tests` behind a fake node: a stored builder version or signer pair that is not this binary's retries, naming both values, while the build slot is held; a landed audit is authenticated and the claim continues to `submitblock` without a build slot, and a forged landed coinbase or root is refused with the row left pending; `Incomplete`, a digest mismatch, changed balances on a current block and the rebuild deadline all retry with an alert and release their permits; `classify_window_error` keeps `TaskFailed` apart from corruption and propagates `Database`; the read, rebuild and landing complete while `ORDER_LOCK` is held, with one build worker; a `leased` candidate submits first, then lands from `AsIssued`, and finishes submitted, abandoned with the node's reason, or pending when its balance snapshot is missing; and `OffRuntime` releases on a blocking thread, on cancellation too. The fifteen gated tests are listed in the manifest. Part of #265 Co-Authored-By: Claude Fable 5.1 <[email protected]> * 3.x.x: migrate the imported-audit tests to the slim candidate Slice 1 (#325) merged after this stack branched, and its tests in tests/support/ledger_2x.rs still built the pre-007 candidate: they read block.bundle from a Candidate and called candidate_with_bundle without a window reference or settlement inputs. The rebase merged them cleanly and the tree then failed to compile. The three helpers now take the TestCandidate the constructors return, so they reach the bundle beside the slim candidate, and land_confirmed attaches the claim's parts the way the other ledger tests do. The three constructor calls pass the window reference the bundle was built on, and the settlement inputs for the CTV case. No assertion changes. Part of #265. * 3.x.x: qualify lease renewal and the claim's canonical bytes at scale Incident 1: a candidate whose window holds N shares is claimed and processed under the short lease, and every renewal is read back from claim_expires_at. The largest gap stays below interval + 2 x timeout, the lease never lapses, and a successor ledger cannot take the claim. The bundle a claim rebuilds through the window-read entry point and the borrowing builder has the canonical bytes refresh built for the same job, and the landed audit carries that bundle's digest. Both run at PRISM_WINDOW_QUALIFY_SHARES (20,000 by default); the 400,000-share variants are ignored and run on a larger host. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: measure ACK latency and ORDER_LOCK hold across window sizes Incident 2: two frontends on one database submit ordinary shares at a fixed rate while one of them solves a block on an N-share window and its own submit loop claims, rebuilds, lands and submits it. The solving share's ACK and the bystander's p99 stay within max(2 x baseline p99 + 50 ms, 250 ms), every ACK is well under the share-commit timeout, and the block is enqueued exactly once. Latency is the in-process MiningBackend::submit wall clock; the socket-level harness (#271) does not exist yet. A pg_locks sampler on its own connection measures how long a solving append holds ORDER_LOCK at two window sizes with no other traffic: the larger size stays within a fixed slack of the smaller, and the candidate document is the same size at both and under 1 MiB. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: hold the JSONB gate's enqueue to a window-free row under 1 MiB At every measured size the enqueue must be accepted and every JSONB value it writes, the outbox candidate document included, must stay under 1,048,576 bytes. At the reduced sizes the enqueue, claim and landing phases must all run. The ratchet and its expected values are unchanged. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: make the window-read permit test actually wait before it looks The delay that gives an unpermitted read time to finish was an empty async block, so the check that the read had not finished ran at once and passed whether or not the entry point took a permit. It now sleeps 500 ms inside a 5 s bound, and fails when the permit acquisition is removed from the entry point. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: rebuild a CTV candidate from its stored settlement inputs No host-runnable test reached the CTV branch of the claim rebuild. A CTV-enabled frontend now claims a candidate whose stored direct floor differs from its configuration, and builds a different coinbase than the configured floor would, and the claim must land that candidate's own audit and submit it. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: pin the SQL order of the current-balance reads Nothing defended the ruling that the current-balance path keeps its SQL order: every fixture's balances already arrived in byte-wise canonical order. The carry table's text columns now take an ICU collation, under which the SQL order and the canonical sort disagree, and the snapshot and the current-balance window read must both return the SQL order. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: record what incident 2 must also assert once #324 is in the base After #324 a slow solve is acknowledged late rather than refused, so acceptance proves nothing and the latency percentiles stay the assertion. The doc comment and a TODO at the outcome checks name the counter and outcome to assert at rebase. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: assert incident 2's late-confirm counter now that #324 is in the base W3c wrote the qualification tests against a base that predated #324 and left a marked place for the assertions that only make sense once the commit gate is there. The base now carries it, so apply them: incident 2 asserts `qbit_prism_late_confirmed_shares_total` is zero on both frontends and that no acknowledgement, the block-solving share included, is `ledger-outcome-unknown`. Acceptance alone is no longer proof. #324 gives a share-pass append carrying a candidate its own `block_only_ack_timeout`, so a slow solve is never refused at the share deadline; it is answered late, or answered unknown. Either would have satisfied the acceptance checks with the serialization stall still present. Also set #324's two new `Config` fields in the qualification fixture. * 3.x.x: pin a refused candidate as a definite rejection, not an unknown outcome #324 decides what a miner is told when a block-only enqueue fails: `enqueue_failed_before_commit` answers a provably uncommitted failure with `ledger-confirmation-failed`, and anything else with `ledger-outcome-unknown`, which asks an operator to go and follow the outbox row. Slice 3 added the checks that guard the reference: the block's length, its header hash, its digest against `block_sha256`, the coinbase suffix, the reference invariants, and a leased candidate's balances. All of them are raised by `prepare_candidate` before the enqueue takes a connection, so none carries an `sqlx::Error` and all classify as definite today. That is a property of where the checks sit, not something the classifier knows about them, so it is pinned here rather than left to hold by accident: a corrupt candidate must never send a miner chasing a row that was never written. Verified by mutation: classifying a non-sqlx failure as unknown fails this test. * 3.x.x: say why the full-size qualification variants cannot reach 400k yet Their ignore reasons blamed RAM and the host. The real limit is #273: the job payload still holds three copies of the window (2 x AcceptedShare + 1 x CountedShare), so publishing a job for a 400,000-share window needs about 670 MiB and PostgreSQL refuses the write above its 256 MiB jsonb object limit. Every full-size variant fails at fixture set-up, before it measures anything. The count must also divide the window weight exactly, so the largest usable size today is 125,000, where all four variants pass in release: incident 1 50 renewals, max gap 118.25 ms against a 700 ms bound incident 2 phase-A p99 2.60 ms, phase-B p99 95.79 ms, bound 250 ms lock hold median 0.75 ms at 5,000 against 1.32 ms at 125,000 canonical refresh and claim rebuild both 139,040,610 B, same sha256 The candidate document stays flat at 1103 B and 1107 B, which is the property this slice exists to establish. * 3.x.x: migrate the audit-body normalization tests to the slim candidate #267 landed its own test file against the candidate that still carried an assembled bundle. This slice replaced that with a window reference, so the file keeps a `TestCandidate` pairing the stored candidate with the bundle a test still needs, as `tests/ledger_postgres.rs` does, and attaches the claim's parts through `with_bundle`. One case needed more than a shape change. The four negative cases hand the claim a window the ledger does not hold and require the durable-range proof to be what refuses it. A candidate now commits to a snapshot digest, so a reference taken from the unaltered snapshot would be refused earlier, at the reference check, and the proof under test would never run. `window_ref_for` therefore derives each altered window's reference from that window, leaving the proof as the only thing that can notice, which is what #267 wrote them to prove. * 3.x.x: pin the durable-range proof outside the settlement lock #267 moved the full-equality proof of a candidate's window out of the settlement transaction so the lock is not held for a window-sized read. This slice made that read paged, so it does not occupy a runtime thread either. Reconciling the two is the step that can quietly undo the first: keep this slice's `persist_audit_snapshot` through the rebase and the full read goes back under the lock. The landing stays correct, every other test still passes, and only the lock hold grows, so nothing in the suite can tell. Measured at 100,000 shares on #267's branch that was a 34% longer hold. The guard is deterministic and needs no large window. A second connection holds `SETTLEMENT_LOCK`, so the landing blocks on it once its proof has run. While it waits, one share's `ntime` is altered: full equality sees that, a count over the same anchored predicate cannot. The landing must then succeed, which it can only do if it had already read and compared the shares before taking the lock. Accepted history is immutable and a trigger enforces it, so the test lifts that trigger for the single statement, inside its own disposable schema, and puts it straight back. Verified by mutation: restoring the in-transaction range read fails this test with "the landing read share payloads under the settlement lock". * 3.x.x: serialise the coordinator test modules that share the ledger's locks The ledger's advisory locks are cluster-wide constants, not schema-scoped, so two coordinator test modules running in parallel contend for ORDER_LOCK even though each works in its own throwaway schema. Every module held a lock of its own, which serialised it against itself and left cross-module waits to `lock_timeout`, 5 s by default. #324's reconciliation tests hold ORDER_LOCK for up to about 1.5 s, and this slice adds three more modules that open a ledger. Once enough of them ran at once those waits stacked past the timeout: a full `--lib` run failed with "canceling statement due to lock timeout" in `candidate_lease_tests` and `window_switch_tests`, and passed on the next run. A suite that fails for a reason unrelated to what it tests is worse than a slow one. All seven modules now take one shared lock. The run goes from about 35 s to about 62 s, and three consecutive runs pass where the flake had reproduced. * 3.x.x: add migration 007 and refuse pre-007 candidate outbox rows Migration 007 mirrors 008 onto qbit_block_candidate_outbox: the same six window-reference columns, and a three-state CHECK whose body is identical to 008's apart from the table and constraint names. It also adds block_bytes, the nullable bytea the block moves into so the candidate document stays small, and a partial index on window_prior_balances_sha256 for the balance-snapshot GC. Nothing writes any of them yet; this is additive schema only. The runner applies 007 by membership, in its own block between 5 and 8, so it assumes neither 006 nor 008 has run. Before any DDL it refuses while the outbox still holds a pending row in a pre-007 shape: a native inline candidate, a NULL candidate, or storage_version other than 1 on the 2.x.x schemas that have that column, which is checked for first so the predicate does not error on a native schema. The refusal names every offending block_hash and the drain procedure, and the whole migration transaction rolls back, so a refused start leaves the schema untouched. The applied set is now [2, 3, 4, 5, 7, 8, 9], and the four exact migration assertions move with it rather than being weakened to a superset. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: retain the cluster fingerprint configure pinned or verified The candidate enqueue and save_job must fence against a fingerprint reset by re-reading qbit_prism_cluster.config_fingerprint FOR SHARE in their own transaction and refusing a write that is not this frontend's own. That needs the value configure settled at startup, so Ledger keeps it in a shared OnceLock, set only once the pin or the match has committed, and exposes it read-only through config_fingerprint(). configure keeps its signature and its mismatch refusal, and a refused call retains nothing. The rotation refusal in configure, and the writer fence itself, belong to the enqueue change and are not here. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: share the window reference, balance writer and page primitives WindowRef::from_snapshot is the synchronous reference builder both writers need: anchor_ms copied, the semantic balances digest, and for a non-empty snapshot the first and last share_seq, the length, and the share array's SHA-256 streamed through the existing DigestWriter, so the 233 to 260 MB serialized window at 400,000 shares is never built and the digest equals the one qbit_prism_audit_snapshots already stores. An empty snapshot gives the empty-window reference. Callers run it inside their own spawn_blocking. put_balance_snapshot is the one canonical writer of qbit_prism_balance_snapshots, on the caller's transaction: the sort by (order_key, recipient_id, p2mr_program_hex), the semantic digest that keys the row, and compact JSON of the sorted set, all off the runtime, then INSERT ... ON CONFLICT DO NOTHING. On a conflict it reads the stored bytes back and compares them with its own, because these rows are immutable and can only disagree through corruption. The enqueue and save_job and its repair all write through it. read_prior_balances and the current-balance read still keep their SQL order; the writer's sort defines the stored encoding, which is the order read_window(..., AsIssued) returns. probe_share_rows and read_range_paged are read_window's endpoint probe and page loop, lifted onto a caller's connection so the enqueue probe and the landing re-read share one implementation. The predicate, the ascending keyset order, the 4096-row page bound and the per-page count bound are unchanged, and read_window now calls them, with its signature and behaviour unchanged. The paged reader takes the caller's state and a per-page consumer, both of which travel to the blocking thread with the rows, so the landing re-read can compare each page with its slice of a vector it already holds without any whole-window work on the runtime; a dropped read still releases the accumulated state on a blocking thread. read_window_with_permit holds the caller's window_reads permit across the whole read. The permit is moved into a BlockingDrop declared before the read starts, so a cancellation releases it on a blocking thread after the page state queued its own release there, and never with the future; a return releases it inline, before the caller's rebuild. WindowError::TaskFailed separates a cancelled or panicking blocking hand-off from corruption. Every hand-off maps a JoinError to it instead of to Decode, so a cancellation is a retryable failure with its own alert and never takes the abandon path. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: derive the witness merkle leaves from an assembled block A claim rebuilds from stored inputs, and the witness leaves are the one builder input that scales with the block, so they are re-derived rather than stored: one 64-hex string per transaction beside the candidate would grow the document with the block. witness_merkle_leaves_from_block skips the 80-byte header, reads the compact-size transaction count, walks past the coinbase and returns double_sha256 of every remaining transaction's full serialized bytes. That is sound because assemble_submission appends the template's transactions verbatim after the coinbase, so the result equals witness_merkle_leaves_hex(&transactions_from_template(template)) for the block built from that template, with or without segwit transactions. The segwit-aware walk is strip_witness_transaction's own, factored into a helper that also reports where the transaction ends, which is what a block walker needs; strip_witness_transaction keeps its trailing-byte check and its output. A truncated block, trailing bytes, a zero count and a count that disagrees with the transactions present are all errors, never a partial list of leaves. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: version the audit builders and key the CC5 goldens by it A stored window reference reproduces its bundle only under the builder that first built it. The schema strings do not capture that, because the share shape chooses them rather than the builder logic, so qbit-prism gains AUDIT_BUILDER_VERSION, starting at 1. A candidate and a prepared job store it, and a rebuild refuses a reference at another version instead of rebuilding it with the current builder. The bump rule is on the constant: any change that alters canonical_audit_bundle_bytes for the same inputs bumps it in the same commit. The CC5 golden test now selects its expected digests from a table keyed by the constant, and fails when no entry exists, so a new output is recorded as a new entry beside the old one and review sees both. Version 1 holds the existing literals, unchanged. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: cover 007, the fingerprint and the window primitives on PostgreSQL Ten gated database cases, all listed in test/prism-gated-tests.txt. They go in a new file rather than the shared 2.x.x support module, which another open change appends to. Migration 007: a frozen 2.x.x schema carrying only terminal outbox rows upgrades with every row and field intact and the seven new columns NULL; each of the three pre-007 pending shapes is refused by name, with nothing from 007 applied and no version 7 row, and the same binary starts once the row is drained; a database at [2, 3, 4, 5, 8, 9] applies 007 and only 007, leaving every other version's applied_at untouched; the CHECK accepts exactly the three states across all 64 null combinations and rejects a short or uppercase digest, a zero or out-of-range count and a zero sequence; and the retention index is the partial one on window_prior_balances_sha256. config_fingerprint() returns what configure pinned or verified, is shared by clones,…
* 3.x.x: add migration 007 and refuse pre-007 candidate outbox rows Migration 007 mirrors 008 onto qbit_block_candidate_outbox: the same six window-reference columns, and a three-state CHECK whose body is identical to 008's apart from the table and constraint names. It also adds block_bytes, the nullable bytea the block moves into so the candidate document stays small, and a partial index on window_prior_balances_sha256 for the balance-snapshot GC. Nothing writes any of them yet; this is additive schema only. The runner applies 007 by membership, in its own block between 5 and 8, so it assumes neither 006 nor 008 has run. Before any DDL it refuses while the outbox still holds a pending row in a pre-007 shape: a native inline candidate, a NULL candidate, or storage_version other than 1 on the 2.x.x schemas that have that column, which is checked for first so the predicate does not error on a native schema. The refusal names every offending block_hash and the drain procedure, and the whole migration transaction rolls back, so a refused start leaves the schema untouched. The applied set is now [2, 3, 4, 5, 7, 8, 9], and the four exact migration assertions move with it rather than being weakened to a superset. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: retain the cluster fingerprint configure pinned or verified The candidate enqueue and save_job must fence against a fingerprint reset by re-reading qbit_prism_cluster.config_fingerprint FOR SHARE in their own transaction and refusing a write that is not this frontend's own. That needs the value configure settled at startup, so Ledger keeps it in a shared OnceLock, set only once the pin or the match has committed, and exposes it read-only through config_fingerprint(). configure keeps its signature and its mismatch refusal, and a refused call retains nothing. The rotation refusal in configure, and the writer fence itself, belong to the enqueue change and are not here. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: share the window reference, balance writer and page primitives WindowRef::from_snapshot is the synchronous reference builder both writers need: anchor_ms copied, the semantic balances digest, and for a non-empty snapshot the first and last share_seq, the length, and the share array's SHA-256 streamed through the existing DigestWriter, so the 233 to 260 MB serialized window at 400,000 shares is never built and the digest equals the one qbit_prism_audit_snapshots already stores. An empty snapshot gives the empty-window reference. Callers run it inside their own spawn_blocking. put_balance_snapshot is the one canonical writer of qbit_prism_balance_snapshots, on the caller's transaction: the sort by (order_key, recipient_id, p2mr_program_hex), the semantic digest that keys the row, and compact JSON of the sorted set, all off the runtime, then INSERT ... ON CONFLICT DO NOTHING. On a conflict it reads the stored bytes back and compares them with its own, because these rows are immutable and can only disagree through corruption. The enqueue and save_job and its repair all write through it. read_prior_balances and the current-balance read still keep their SQL order; the writer's sort defines the stored encoding, which is the order read_window(..., AsIssued) returns. probe_share_rows and read_range_paged are read_window's endpoint probe and page loop, lifted onto a caller's connection so the enqueue probe and the landing re-read share one implementation. The predicate, the ascending keyset order, the 4096-row page bound and the per-page count bound are unchanged, and read_window now calls them, with its signature and behaviour unchanged. The paged reader takes the caller's state and a per-page consumer, both of which travel to the blocking thread with the rows, so the landing re-read can compare each page with its slice of a vector it already holds without any whole-window work on the runtime; a dropped read still releases the accumulated state on a blocking thread. read_window_with_permit holds the caller's window_reads permit across the whole read. The permit is moved into a BlockingDrop declared before the read starts, so a cancellation releases it on a blocking thread after the page state queued its own release there, and never with the future; a return releases it inline, before the caller's rebuild. WindowError::TaskFailed separates a cancelled or panicking blocking hand-off from corruption. Every hand-off maps a JoinError to it instead of to Decode, so a cancellation is a retryable failure with its own alert and never takes the abandon path. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: derive the witness merkle leaves from an assembled block A claim rebuilds from stored inputs, and the witness leaves are the one builder input that scales with the block, so they are re-derived rather than stored: one 64-hex string per transaction beside the candidate would grow the document with the block. witness_merkle_leaves_from_block skips the 80-byte header, reads the compact-size transaction count, walks past the coinbase and returns double_sha256 of every remaining transaction's full serialized bytes. That is sound because assemble_submission appends the template's transactions verbatim after the coinbase, so the result equals witness_merkle_leaves_hex(&transactions_from_template(template)) for the block built from that template, with or without segwit transactions. The segwit-aware walk is strip_witness_transaction's own, factored into a helper that also reports where the transaction ends, which is what a block walker needs; strip_witness_transaction keeps its trailing-byte check and its output. A truncated block, trailing bytes, a zero count and a count that disagrees with the transactions present are all errors, never a partial list of leaves. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: version the audit builders and key the CC5 goldens by it A stored window reference reproduces its bundle only under the builder that first built it. The schema strings do not capture that, because the share shape chooses them rather than the builder logic, so qbit-prism gains AUDIT_BUILDER_VERSION, starting at 1. A candidate and a prepared job store it, and a rebuild refuses a reference at another version instead of rebuilding it with the current builder. The bump rule is on the constant: any change that alters canonical_audit_bundle_bytes for the same inputs bumps it in the same commit. The CC5 golden test now selects its expected digests from a table keyed by the constant, and fails when no entry exists, so a new output is recorded as a new entry beside the old one and review sees both. Version 1 holds the existing literals, unchanged. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: cover 007, the fingerprint and the window primitives on PostgreSQL Ten gated database cases, all listed in test/prism-gated-tests.txt. They go in a new file rather than the shared 2.x.x support module, which another open change appends to. Migration 007: a frozen 2.x.x schema carrying only terminal outbox rows upgrades with every row and field intact and the seven new columns NULL; each of the three pre-007 pending shapes is refused by name, with nothing from 007 applied and no version 7 row, and the same binary starts once the row is drained; a database at [2, 3, 4, 5, 8, 9] applies 007 and only 007, leaving every other version's applied_at untouched; the CHECK accepts exactly the three states across all 64 null combinations and rejects a short or uppercase digest, a zero or out-of-range count and a zero sequence; and the retention index is the partial one on window_prior_balances_sha256. config_fingerprint() returns what configure pinned or verified, is shared by clones, and stays empty after a refused configure. from_snapshot's streamed digest equals sha256(serde_json::to_vec) and the snapshot_sha256 landing writes for the same window. The balance writer stores the canonical sort, is idempotent under any permutation, errors rather than accepting a different encoding of the same digest, and read_window(..., AsIssued) hands back the stored order. The probe misses a missing endpoint, the paged reader compares 4,999 rows page by page with a vector held inside the caller's transaction, and a row the predicate skips inside a range is Incomplete with no partial window. The permit case builds a runtime with one blocking thread, occupies it, and cancels a reader parked mid-page on a database gate: no permit is available while the cleanup is queued, and one is once it has run. A failed blocking hand-off surfaces as TaskFailed, never as Decode. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: carry the window reference on prepared work, behind a read permit `Prepared` gains `window: WindowRef`, computed once per non-cached refresh beside `build_bundle` under `tokio::join!`, so submit can clone it instead of re-digesting the window on the share path when a block is found. An empty snapshot gets the empty-window reference on the runtime thread; a resume computes it inside the blocking decode it already runs. `Coordinator` gains the `window_reads` semaphore, sized `clamp(database_max_connections - 2, 1, build_workers)`, and the one entry point callers use: it takes an owned permit after the caller's `build_slots` permit and hands it to `Ledger::read_window_with_permit`, which holds it across the whole read, including the off-runtime cleanup a cancellation leaves behind, and releases it before the rebuild. `Ledger::read_window` is awaited on the runtime, never wrapped in `spawn_blocking`; the test with a single blocking thread pins that. The four gated `window_ref_tests` are listed in the manifest. Part of #265 Co-Authored-By: Claude Fable 5.1 <[email protected]> * 3.x.x: switch the candidate outbox to the window reference `Candidate` drops the embedded `AuditBundle` for `window: WindowRef` and every builder input except the window: `found_block`, `payout_policy`, the nested `ctv` triple (whose presence selects the CTV builder), the stored `bootstrap_share` of an empty window, `audit_builder_version`, `signer_keys`, a `leased` flag and the now-required `coinbase_suffix_hex`. The block leaves the document for the `block_bytes` column, authenticated by `block_sha256`, which `candidate_sha256` covers. The write serializes, digests and checks the candidate before the append or enqueue transaction opens; under `ORDER_LOCK` the transaction re-reads `config_fingerprint FOR SHARE` and refuses a value the writer did not pin, re-inserts a `leased` candidate's as-issued balance snapshot through the shared writer, probes the window's first row (an absent row alerts and still publishes), and inserts only the prepared bytes with the six typed columns. Submit builds the slim candidate from `Prepared.window`, the `BundleInputs` captured where `build_bundle` read configuration, and the job's own bootstrap share; it clones no bundle and reads no config. The claim's `UPDATE … RETURNING` returns the columns and the block, and the decode, off the runtime, checks the document against them, the digest, `sha256(block_bytes)`, the header hash, the required fields and the two reference invariants. A pending row with a NULL anchor is a hard error naming the pre-007 frontend; an inline document is never decoded. Before any read the claim retries, with an alert naming both values, a stored builder version or signer pair that is not this binary's; a landed audit is authenticated against the block (coinbase, audit root as the witness reserved value, share snapshot, bits) and the claim then skips the rebuild and landing and continues to observe, renew and submit. Otherwise it takes `build_slots`, then `window_reads` inside one 60 s deadline around the awaited `read_window(Current)` and the borrowing builder run directly in `spawn_blocking`, and keeps `Arc<AuditBundleBody>` and the shares as `ClaimParts`. `Incomplete`, `SnapshotDigestMismatch`, `Decode`, `BalanceSnapshotMissing`, `TaskFailed` and the deadline retry with their own alerts; `PriorBalancesChanged` finishes only a block `observe_candidate` proves inactive and superseded; `Database` propagates. A `leased` candidate submits from `block_bytes` first, then rebuilds `AsIssued` and lands before any terminal outcome. Rebuilt parts are released off the runtime on every path. Landing takes the parts and does all whole-window work in one blocking closure: `verify_audit_parts`, the raw body, the counted canonical bytes, the leaves and accounts, and the share snapshot digest, which must equal the reference's. The balance fence compares the current set and the parts' through the semantic digest, so an as-issued set compares equal in any order. `persist_audit_snapshot` re-reads the range with the paged reader inside the landing transaction, page against slice on the blocking thread; `read_range` stays for the API. The terminal UPDATE NULLs the six window columns and `block_bytes` with `candidate`. `configure` refuses to pin a fingerprint onto a reset one while a pending row stores other signer keys, and the startup gate requires 007 with 009. The JSONB gate drops its enqueue entry, and every helper that built a candidate builds the slim one, handing the ledger-level landings the bundle's parts through `CandidateClaim::with_bundle`. Part of #265 Co-Authored-By: Claude Fable 5.1 <[email protected]> * 3.x.x: cover the candidate switch on PostgreSQL Ledger-level, in `candidate_window_switch`: a two-page window enqueues a document with no array and no share row, under 1 MB, whose six typed columns equal its reference and whose block is stored as bytes; the writer fence refuses a reset or different fingerprint in the same transaction, share included; a missing window prefix row alerts and still publishes, and its read then meets `Incomplete`; a `leased` enqueue re-inserts the as-issued balance snapshot in the writer's canonical order, writes none when not leased, and refuses balances that do not hash to the reference; every preparation failure is refused without waiting for `ORDER_LOCK`; every column, digest, block, header, NULL-anchor, missing-field, invariant and inline-document disagreement is refused at claim; landing refuses parts that are not the referenced window and a claim without parts; the terminal UPDATE NULLs the six columns and the block for submitted and abandoned rows; the landed-audit authentication rejects a forged coinbase, root, snapshot or bits; and `configure` refuses a rotation over a foreign-signed pending candidate. Coordinator-level, in `window_switch_tests` behind a fake node: a stored builder version or signer pair that is not this binary's retries, naming both values, while the build slot is held; a landed audit is authenticated and the claim continues to `submitblock` without a build slot, and a forged landed coinbase or root is refused with the row left pending; `Incomplete`, a digest mismatch, changed balances on a current block and the rebuild deadline all retry with an alert and release their permits; `classify_window_error` keeps `TaskFailed` apart from corruption and propagates `Database`; the read, rebuild and landing complete while `ORDER_LOCK` is held, with one build worker; a `leased` candidate submits first, then lands from `AsIssued`, and finishes submitted, abandoned with the node's reason, or pending when its balance snapshot is missing; and `OffRuntime` releases on a blocking thread, on cancellation too. The fifteen gated tests are listed in the manifest. Part of #265 Co-Authored-By: Claude Fable 5.1 <[email protected]> * 3.x.x: migrate the imported-audit tests to the slim candidate Slice 1 (#325) merged after this stack branched, and its tests in tests/support/ledger_2x.rs still built the pre-007 candidate: they read block.bundle from a Candidate and called candidate_with_bundle without a window reference or settlement inputs. The rebase merged them cleanly and the tree then failed to compile. The three helpers now take the TestCandidate the constructors return, so they reach the bundle beside the slim candidate, and land_confirmed attaches the claim's parts the way the other ledger tests do. The three constructor calls pass the window reference the bundle was built on, and the settlement inputs for the CTV case. No assertion changes. Part of #265. * 3.x.x: qualify lease renewal and the claim's canonical bytes at scale Incident 1: a candidate whose window holds N shares is claimed and processed under the short lease, and every renewal is read back from claim_expires_at. The largest gap stays below interval + 2 x timeout, the lease never lapses, and a successor ledger cannot take the claim. The bundle a claim rebuilds through the window-read entry point and the borrowing builder has the canonical bytes refresh built for the same job, and the landed audit carries that bundle's digest. Both run at PRISM_WINDOW_QUALIFY_SHARES (20,000 by default); the 400,000-share variants are ignored and run on a larger host. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: measure ACK latency and ORDER_LOCK hold across window sizes Incident 2: two frontends on one database submit ordinary shares at a fixed rate while one of them solves a block on an N-share window and its own submit loop claims, rebuilds, lands and submits it. The solving share's ACK and the bystander's p99 stay within max(2 x baseline p99 + 50 ms, 250 ms), every ACK is well under the share-commit timeout, and the block is enqueued exactly once. Latency is the in-process MiningBackend::submit wall clock; the socket-level harness (#271) does not exist yet. A pg_locks sampler on its own connection measures how long a solving append holds ORDER_LOCK at two window sizes with no other traffic: the larger size stays within a fixed slack of the smaller, and the candidate document is the same size at both and under 1 MiB. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: hold the JSONB gate's enqueue to a window-free row under 1 MiB At every measured size the enqueue must be accepted and every JSONB value it writes, the outbox candidate document included, must stay under 1,048,576 bytes. At the reduced sizes the enqueue, claim and landing phases must all run. The ratchet and its expected values are unchanged. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: make the window-read permit test actually wait before it looks The delay that gives an unpermitted read time to finish was an empty async block, so the check that the read had not finished ran at once and passed whether or not the entry point took a permit. It now sleeps 500 ms inside a 5 s bound, and fails when the permit acquisition is removed from the entry point. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: rebuild a CTV candidate from its stored settlement inputs No host-runnable test reached the CTV branch of the claim rebuild. A CTV-enabled frontend now claims a candidate whose stored direct floor differs from its configuration, and builds a different coinbase than the configured floor would, and the claim must land that candidate's own audit and submit it. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: pin the SQL order of the current-balance reads Nothing defended the ruling that the current-balance path keeps its SQL order: every fixture's balances already arrived in byte-wise canonical order. The carry table's text columns now take an ICU collation, under which the SQL order and the canonical sort disagree, and the snapshot and the current-balance window read must both return the SQL order. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: record what incident 2 must also assert once #324 is in the base After #324 a slow solve is acknowledged late rather than refused, so acceptance proves nothing and the latency percentiles stay the assertion. The doc comment and a TODO at the outcome checks name the counter and outcome to assert at rebase. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: assert incident 2's late-confirm counter now that #324 is in the base W3c wrote the qualification tests against a base that predated #324 and left a marked place for the assertions that only make sense once the commit gate is there. The base now carries it, so apply them: incident 2 asserts `qbit_prism_late_confirmed_shares_total` is zero on both frontends and that no acknowledgement, the block-solving share included, is `ledger-outcome-unknown`. Acceptance alone is no longer proof. #324 gives a share-pass append carrying a candidate its own `block_only_ack_timeout`, so a slow solve is never refused at the share deadline; it is answered late, or answered unknown. Either would have satisfied the acceptance checks with the serialization stall still present. Also set #324's two new `Config` fields in the qualification fixture. * 3.x.x: pin a refused candidate as a definite rejection, not an unknown outcome #324 decides what a miner is told when a block-only enqueue fails: `enqueue_failed_before_commit` answers a provably uncommitted failure with `ledger-confirmation-failed`, and anything else with `ledger-outcome-unknown`, which asks an operator to go and follow the outbox row. Slice 3 added the checks that guard the reference: the block's length, its header hash, its digest against `block_sha256`, the coinbase suffix, the reference invariants, and a leased candidate's balances. All of them are raised by `prepare_candidate` before the enqueue takes a connection, so none carries an `sqlx::Error` and all classify as definite today. That is a property of where the checks sit, not something the classifier knows about them, so it is pinned here rather than left to hold by accident: a corrupt candidate must never send a miner chasing a row that was never written. Verified by mutation: classifying a non-sqlx failure as unknown fails this test. * 3.x.x: say why the full-size qualification variants cannot reach 400k yet Their ignore reasons blamed RAM and the host. The real limit is #273: the job payload still holds three copies of the window (2 x AcceptedShare + 1 x CountedShare), so publishing a job for a 400,000-share window needs about 670 MiB and PostgreSQL refuses the write above its 256 MiB jsonb object limit. Every full-size variant fails at fixture set-up, before it measures anything. The count must also divide the window weight exactly, so the largest usable size today is 125,000, where all four variants pass in release: incident 1 50 renewals, max gap 118.25 ms against a 700 ms bound incident 2 phase-A p99 2.60 ms, phase-B p99 95.79 ms, bound 250 ms lock hold median 0.75 ms at 5,000 against 1.32 ms at 125,000 canonical refresh and claim rebuild both 139,040,610 B, same sha256 The candidate document stays flat at 1103 B and 1107 B, which is the property this slice exists to establish. * 3.x.x: migrate the audit-body normalization tests to the slim candidate #267 landed its own test file against the candidate that still carried an assembled bundle. This slice replaced that with a window reference, so the file keeps a `TestCandidate` pairing the stored candidate with the bundle a test still needs, as `tests/ledger_postgres.rs` does, and attaches the claim's parts through `with_bundle`. One case needed more than a shape change. The four negative cases hand the claim a window the ledger does not hold and require the durable-range proof to be what refuses it. A candidate now commits to a snapshot digest, so a reference taken from the unaltered snapshot would be refused earlier, at the reference check, and the proof under test would never run. `window_ref_for` therefore derives each altered window's reference from that window, leaving the proof as the only thing that can notice, which is what #267 wrote them to prove. * 3.x.x: pin the durable-range proof outside the settlement lock #267 moved the full-equality proof of a candidate's window out of the settlement transaction so the lock is not held for a window-sized read. This slice made that read paged, so it does not occupy a runtime thread either. Reconciling the two is the step that can quietly undo the first: keep this slice's `persist_audit_snapshot` through the rebase and the full read goes back under the lock. The landing stays correct, every other test still passes, and only the lock hold grows, so nothing in the suite can tell. Measured at 100,000 shares on #267's branch that was a 34% longer hold. The guard is deterministic and needs no large window. A second connection holds `SETTLEMENT_LOCK`, so the landing blocks on it once its proof has run. While it waits, one share's `ntime` is altered: full equality sees that, a count over the same anchored predicate cannot. The landing must then succeed, which it can only do if it had already read and compared the shares before taking the lock. Accepted history is immutable and a trigger enforces it, so the test lifts that trigger for the single statement, inside its own disposable schema, and puts it straight back. Verified by mutation: restoring the in-transaction range read fails this test with "the landing read share payloads under the settlement lock". * 3.x.x: serialise the coordinator test modules that share the ledger's locks The ledger's advisory locks are cluster-wide constants, not schema-scoped, so two coordinator test modules running in parallel contend for ORDER_LOCK even though each works in its own throwaway schema. Every module held a lock of its own, which serialised it against itself and left cross-module waits to `lock_timeout`, 5 s by default. #324's reconciliation tests hold ORDER_LOCK for up to about 1.5 s, and this slice adds three more modules that open a ledger. Once enough of them ran at once those waits stacked past the timeout: a full `--lib` run failed with "canceling statement due to lock timeout" in `candidate_lease_tests` and `window_switch_tests`, and passed on the next run. A suite that fails for a reason unrelated to what it tests is worse than a slow one. All seven modules now take one shared lock. The run goes from about 35 s to about 62 s, and three consecutive runs pass where the flake had reproduced. * 3.x.x: add migration 007 and refuse pre-007 candidate outbox rows Migration 007 mirrors 008 onto qbit_block_candidate_outbox: the same six window-reference columns, and a three-state CHECK whose body is identical to 008's apart from the table and constraint names. It also adds block_bytes, the nullable bytea the block moves into so the candidate document stays small, and a partial index on window_prior_balances_sha256 for the balance-snapshot GC. Nothing writes any of them yet; this is additive schema only. The runner applies 007 by membership, in its own block between 5 and 8, so it assumes neither 006 nor 008 has run. Before any DDL it refuses while the outbox still holds a pending row in a pre-007 shape: a native inline candidate, a NULL candidate, or storage_version other than 1 on the 2.x.x schemas that have that column, which is checked for first so the predicate does not error on a native schema. The refusal names every offending block_hash and the drain procedure, and the whole migration transaction rolls back, so a refused start leaves the schema untouched. The applied set is now [2, 3, 4, 5, 7, 8, 9], and the four exact migration assertions move with it rather than being weakened to a superset. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: retain the cluster fingerprint configure pinned or verified The candidate enqueue and save_job must fence against a fingerprint reset by re-reading qbit_prism_cluster.config_fingerprint FOR SHARE in their own transaction and refusing a write that is not this frontend's own. That needs the value configure settled at startup, so Ledger keeps it in a shared OnceLock, set only once the pin or the match has committed, and exposes it read-only through config_fingerprint(). configure keeps its signature and its mismatch refusal, and a refused call retains nothing. The rotation refusal in configure, and the writer fence itself, belong to the enqueue change and are not here. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: share the window reference, balance writer and page primitives WindowRef::from_snapshot is the synchronous reference builder both writers need: anchor_ms copied, the semantic balances digest, and for a non-empty snapshot the first and last share_seq, the length, and the share array's SHA-256 streamed through the existing DigestWriter, so the 233 to 260 MB serialized window at 400,000 shares is never built and the digest equals the one qbit_prism_audit_snapshots already stores. An empty snapshot gives the empty-window reference. Callers run it inside their own spawn_blocking. put_balance_snapshot is the one canonical writer of qbit_prism_balance_snapshots, on the caller's transaction: the sort by (order_key, recipient_id, p2mr_program_hex), the semantic digest that keys the row, and compact JSON of the sorted set, all off the runtime, then INSERT ... ON CONFLICT DO NOTHING. On a conflict it reads the stored bytes back and compares them with its own, because these rows are immutable and can only disagree through corruption. The enqueue and save_job and its repair all write through it. read_prior_balances and the current-balance read still keep their SQL order; the writer's sort defines the stored encoding, which is the order read_window(..., AsIssued) returns. probe_share_rows and read_range_paged are read_window's endpoint probe and page loop, lifted onto a caller's connection so the enqueue probe and the landing re-read share one implementation. The predicate, the ascending keyset order, the 4096-row page bound and the per-page count bound are unchanged, and read_window now calls them, with its signature and behaviour unchanged. The paged reader takes the caller's state and a per-page consumer, both of which travel to the blocking thread with the rows, so the landing re-read can compare each page with its slice of a vector it already holds without any whole-window work on the runtime; a dropped read still releases the accumulated state on a blocking thread. read_window_with_permit holds the caller's window_reads permit across the whole read. The permit is moved into a BlockingDrop declared before the read starts, so a cancellation releases it on a blocking thread after the page state queued its own release there, and never with the future; a return releases it inline, before the caller's rebuild. WindowError::TaskFailed separates a cancelled or panicking blocking hand-off from corruption. Every hand-off maps a JoinError to it instead of to Decode, so a cancellation is a retryable failure with its own alert and never takes the abandon path. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: derive the witness merkle leaves from an assembled block A claim rebuilds from stored inputs, and the witness leaves are the one builder input that scales with the block, so they are re-derived rather than stored: one 64-hex string per transaction beside the candidate would grow the document with the block. witness_merkle_leaves_from_block skips the 80-byte header, reads the compact-size transaction count, walks past the coinbase and returns double_sha256 of every remaining transaction's full serialized bytes. That is sound because assemble_submission appends the template's transactions verbatim after the coinbase, so the result equals witness_merkle_leaves_hex(&transactions_from_template(template)) for the block built from that template, with or without segwit transactions. The segwit-aware walk is strip_witness_transaction's own, factored into a helper that also reports where the transaction ends, which is what a block walker needs; strip_witness_transaction keeps its trailing-byte check and its output. A truncated block, trailing bytes, a zero count and a count that disagrees with the transactions present are all errors, never a partial list of leaves. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: version the audit builders and key the CC5 goldens by it A stored window reference reproduces its bundle only under the builder that first built it. The schema strings do not capture that, because the share shape chooses them rather than the builder logic, so qbit-prism gains AUDIT_BUILDER_VERSION, starting at 1. A candidate and a prepared job store it, and a rebuild refuses a reference at another version instead of rebuilding it with the current builder. The bump rule is on the constant: any change that alters canonical_audit_bundle_bytes for the same inputs bumps it in the same commit. The CC5 golden test now selects its expected digests from a table keyed by the constant, and fails when no entry exists, so a new output is recorded as a new entry beside the old one and review sees both. Version 1 holds the existing literals, unchanged. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: cover 007, the fingerprint and the window primitives on PostgreSQL Ten gated database cases, all listed in test/prism-gated-tests.txt. They go in a new file rather than the shared 2.x.x support module, which another open change appends to. Migration 007: a frozen 2.x.x schema carrying only terminal outbox rows upgrades with every row and field intact and the seven new columns NULL; each of the three pre-007 pending shapes is refused by name, with nothing from 007 applied and no version 7 row, and the same binary starts once the row is drained; a database at [2, 3, 4, 5, 8, 9] applies 007 and only 007, leaving every other version's applied_at untouched; the CHECK accepts exactly the three states across all 64 null combinations and rejects a short or uppercase digest, a zero or out-of-range count and a zero sequence; and the retention index is the partial one on window_prior_balances_sha256. config_fingerprint() returns what configure pinned or verified, is shared by clones, and stays empty after a refused configure. from_snapshot's streamed digest equals sha256(serde_json::to_vec) and the snapshot_sha256 landing writes for the same window. The balance writer stores the canonical sort, is idempotent under any permutation, errors rather than accepting a different encoding of the same digest, and read_window(..., AsIssued) hands back the stored order. The probe misses a missing endpoint, the paged reader compares 4,999 rows page by page with a vector held inside the caller's transaction, and a row the predicate skips inside a range is Incomplete with no partial window. The permit case builds a runtime with one blocking thread, occupies it, and cancels a reader parked mid-page on a database gate: no permit is available while the cleanup is queued, and one is once it has run. A failed blocking hand-off surfaces as TaskFailed, never as Decode. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: carry the window reference on prepared work, behind a read permit `Prepared` gains `window: WindowRef`, computed once per non-cached refresh beside `build_bundle` under `tokio::join!`, so submit can clone it instead of re-digesting the window on the share path when a block is found. An empty snapshot gets the empty-window reference on the runtime thread; a resume computes it inside the blocking decode it already runs. `Coordinator` gains the `window_reads` semaphore, sized `clamp(database_max_connections - 2, 1, build_workers)`, and the one entry point callers use: it takes an owned permit after the caller's `build_slots` permit and hands it to `Ledger::read_window_with_permit`, which holds it across the whole read, including the off-runtime cleanup a cancellation leaves behind, and releases it before the rebuild. `Ledger::read_window` is awaited on the runtime, never wrapped in `spawn_blocking`; the test with a single blocking thread pins that. The four gated `window_ref_tests` are listed in the manifest. Part of #265 Co-Authored-By: Claude Fable 5.1 <[email protected]> * 3.x.x: switch the candidate outbox to the window reference `Candidate` drops the embedded `AuditBundle` for `window: WindowRef` and every builder input except the window: `found_block`, `payout_policy`, the nested `ctv` triple (whose presence selects the CTV builder), the stored `bootstrap_share` of an empty window, `audit_builder_version`, `signer_keys`, a `leased` flag and the now-required `coinbase_suffix_hex`. The block leaves the document for the `block_bytes` column, authenticated by `block_sha256`, which `candidate_sha256` covers. The write serializes, digests and checks the candidate before the append or enqueue transaction opens; under `ORDER_LOCK` the transaction re-reads `config_fingerprint FOR SHARE` and refuses a value the writer did not pin, re-inserts a `leased` candidate's as-issued balance snapshot through the shared writer, probes the window's first row (an absent row alerts and still publishes), and inserts only the prepared bytes with the six typed columns. Submit builds the slim candidate from `Prepared.window`, the `BundleInputs` captured where `build_bundle` read configuration, and the job's own bootstrap share; it clones no bundle and reads no config. The claim's `UPDATE … RETURNING` returns the columns and the block, and the decode, off the runtime, checks the document against them, the digest, `sha256(block_bytes)`, the header hash, the required fields and the two reference invariants. A pending row with a NULL anchor is a hard error naming the pre-007 frontend; an inline document is never decoded. Before any read the claim retries, with an alert naming both values, a stored builder version or signer pair that is not this binary's; a landed audit is authenticated against the block (coinbase, audit root as the witness reserved value, share snapshot, bits) and the claim then skips the rebuild and landing and continues to observe, renew and submit. Otherwise it takes `build_slots`, then `window_reads` inside one 60 s deadline around the awaited `read_window(Current)` and the borrowing builder run directly in `spawn_blocking`, and keeps `Arc<AuditBundleBody>` and the shares as `ClaimParts`. `Incomplete`, `SnapshotDigestMismatch`, `Decode`, `BalanceSnapshotMissing`, `TaskFailed` and the deadline retry with their own alerts; `PriorBalancesChanged` finishes only a block `observe_candidate` proves inactive and superseded; `Database` propagates. A `leased` candidate submits from `block_bytes` first, then rebuilds `AsIssued` and lands before any terminal outcome. Rebuilt parts are released off the runtime on every path. Landing takes the parts and does all whole-window work in one blocking closure: `verify_audit_parts`, the raw body, the counted canonical bytes, the leaves and accounts, and the share snapshot digest, which must equal the reference's. The balance fence compares the current set and the parts' through the semantic digest, so an as-issued set compares equal in any order. `persist_audit_snapshot` re-reads the range with the paged reader inside the landing transaction, page against slice on the blocking thread; `read_range` stays for the API. The terminal UPDATE NULLs the six window columns and `block_bytes` with `candidate`. `configure` refuses to pin a fingerprint onto a reset one while a pending row stores other signer keys, and the startup gate requires 007 with 009. The JSONB gate drops its enqueue entry, and every helper that built a candidate builds the slim one, handing the ledger-level landings the bundle's parts through `CandidateClaim::with_bundle`. Part of #265 Co-Authored-By: Claude Fable 5.1 <[email protected]> * 3.x.x: cover the candidate switch on PostgreSQL Ledger-level, in `candidate_window_switch`: a two-page window enqueues a document with no array and no share row, under 1 MB, whose six typed columns equal its reference and whose block is stored as bytes; the writer fence refuses a reset or different fingerprint in the same transaction, share included; a missing window prefix row alerts and still publishes, and its read then meets `Incomplete`; a `leased` enqueue re-inserts the as-issued balance snapshot in the writer's canonical order, writes none when not leased, and refuses balances that do not hash to the reference; every preparation failure is refused without waiting for `ORDER_LOCK`; every column, digest, block, header, NULL-anchor, missing-field, invariant and inline-document disagreement is refused at claim; landing refuses parts that are not the referenced window and a claim without parts; the terminal UPDATE NULLs the six columns and the block for submitted and abandoned rows; the landed-audit authentication rejects a forged coinbase, root, snapshot or bits; and `configure` refuses a rotation over a foreign-signed pending candidate. Coordinator-level, in `window_switch_tests` behind a fake node: a stored builder version or signer pair that is not this binary's retries, naming both values, while the build slot is held; a landed audit is authenticated and the claim continues to `submitblock` without a build slot, and a forged landed coinbase or root is refused with the row left pending; `Incomplete`, a digest mismatch, changed balances on a current block and the rebuild deadline all retry with an alert and release their permits; `classify_window_error` keeps `TaskFailed` apart from corruption and propagates `Database`; the read, rebuild and landing complete while `ORDER_LOCK` is held, with one build worker; a `leased` candidate submits first, then lands from `AsIssued`, and finishes submitted, abandoned with the node's reason, or pending when its balance snapshot is missing; and `OffRuntime` releases on a blocking thread, on cancellation too. The fifteen gated tests are listed in the manifest. Part of #265 Co-Authored-By: Claude Fable 5.1 <[email protected]> * 3.x.x: migrate the imported-audit tests to the slim candidate Slice 1 (#325) merged after this stack branched, and its tests in tests/support/ledger_2x.rs still built the pre-007 candidate: they read block.bundle from a Candidate and called candidate_with_bundle without a window reference or settlement inputs. The rebase merged them cleanly and the tree then failed to compile. The three helpers now take the TestCandidate the constructors return, so they reach the bundle beside the slim candidate, and land_confirmed attaches the claim's parts the way the other ledger tests do. The three constructor calls pass the window reference the bundle was built on, and the settlement inputs for the CTV case. No assertion changes. Part of #265. * 3.x.x: qualify lease renewal and the claim's canonical bytes at scale Incident 1: a candidate whose window holds N shares is claimed and processed under the short lease, and every renewal is read back from claim_expires_at. The largest gap stays below interval + 2 x timeout, the lease never lapses, and a successor ledger cannot take the claim. The bundle a claim rebuilds through the window-read entry point and the borrowing builder has the canonical bytes refresh built for the same job, and the landed audit carries that bundle's digest. Both run at PRISM_WINDOW_QUALIFY_SHARES (20,000 by default); the 400,000-share variants are ignored and run on a larger host. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: measure ACK latency and ORDER_LOCK hold across window sizes Incident 2: two frontends on one database submit ordinary shares at a fixed rate while one of them solves a block on an N-share window and its own submit loop claims, rebuilds, lands and submits it. The solving share's ACK and the bystander's p99 stay within max(2 x baseline p99 + 50 ms, 250 ms), every ACK is well under the share-commit timeout, and the block is enqueued exactly once. Latency is the in-process MiningBackend::submit wall clock; the socket-level harness (#271) does not exist yet. A pg_locks sampler on its own connection measures how long a solving append holds ORDER_LOCK at two window sizes with no other traffic: the larger size stays within a fixed slack of the smaller, and the candidate document is the same size at both and under 1 MiB. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: hold the JSONB gate's enqueue to a window-free row under 1 MiB At every measured size the enqueue must be accepted and every JSONB value it writes, the outbox candidate document included, must stay under 1,048,576 bytes. At the reduced sizes the enqueue, claim and landing phases must all run. The ratchet and its expected values are unchanged. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: make the window-read permit test actually wait before it looks The delay that gives an unpermitted read time to finish was an empty async block, so the check that the read had not finished ran at once and passed whether or not the entry point took a permit. It now sleeps 500 ms inside a 5 s bound, and fails when the permit acquisition is removed from the entry point. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: rebuild a CTV candidate from its stored settlement inputs No host-runnable test reached the CTV branch of the claim rebuild. A CTV-enabled frontend now claims a candidate whose stored direct floor differs from its configuration, and builds a different coinbase than the configured floor would, and the claim must land that candidate's own audit and submit it. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: pin the SQL order of the current-balance reads Nothing defended the ruling that the current-balance path keeps its SQL order: every fixture's balances already arrived in byte-wise canonical order. The carry table's text columns now take an ICU collation, under which the SQL order and the canonical sort disagree, and the snapshot and the current-balance window read must both return the SQL order. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: record what incident 2 must also assert once #324 is in the base After #324 a slow solve is acknowledged late rather than refused, so acceptance proves nothing and the latency percentiles stay the assertion. The doc comment and a TODO at the outcome checks name the counter and outcome to assert at rebase. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: assert incident 2's late-confirm counter now that #324 is in the base W3c wrote the qualification tests against a base that predated #324 and left a marked place for the assertions that only make sense once the commit gate is there. The base now carries it, so apply them: incident 2 asserts `qbit_prism_late_confirmed_shares_total` is zero on both frontends and that no acknowledgement, the block-solving share included, is `ledger-outcome-unknown`. Acceptance alone is no longer proof. #324 gives a share-pass append carrying a candidate its own `block_only_ack_timeout`, so a slow solve is never refused at the share deadline; it is answered late, or answered unknown. Either would have satisfied the acceptance checks with the serialization stall still present. Also set #324's two new `Config` fields in the qualification fixture. * 3.x.x: pin a refused candidate as a definite rejection, not an unknown outcome #324 decides what a miner is told when a block-only enqueue fails: `enqueue_failed_before_commit` answers a provably uncommitted failure with `ledger-confirmation-failed`, and anything else with `ledger-outcome-unknown`, which asks an operator to go and follow the outbox row. Slice 3 added the checks that guard the reference: the block's length, its header hash, its digest against `block_sha256`, the coinbase suffix, the reference invariants, and a leased candidate's balances. All of them are raised by `prepare_candidate` before the enqueue takes a connection, so none carries an `sqlx::Error` and all classify as definite today. That is a property of where the checks sit, not something the classifier knows about them, so it is pinned here rather than left to hold by accident: a corrupt candidate must never send a miner chasing a row that was never written. Verified by mutation: classifying a non-sqlx failure as unknown fails this test. * 3.x.x: say why the full-size qualification variants cannot reach 400k yet Their ignore reasons blamed RAM and the host. The real limit is #273: the job payload still holds three copies of the window (2 x AcceptedShare + 1 x CountedShare), so publishing a job for a 400,000-share window needs about 670 MiB and PostgreSQL refuses the write above its 256 MiB jsonb object limit. Every full-size variant fails at fixture set-up, before it measures anything. The count must also divide the window weight exactly, so the largest usable size today is 125,000, where all four variants pass in release: incident 1 50 renewals, max gap 118.25 ms against a 700 ms bound incident 2 phase-A p99 2.60 ms, phase-B p99 95.79 ms, bound 250 ms lock hold median 0.75 ms at 5,000 against 1.32 ms at 125,000 canonical refresh and claim rebuild both 139,040,610 B, same sha256 The candidate document stays flat at 1103 B and 1107 B, which is the property this slice exists to establish. * 3.x.x: migrate the audit-body normalization tests to the slim candidate #267 landed its own test file against the candidate that still carried an assembled bundle. This slice replaced that with a window reference, so the file keeps a `TestCandidate` pairing the stored candidate with the bundle a test still needs, as `tests/ledger_postgres.rs` does, and attaches the claim's parts through `with_bundle`. One case needed more than a shape change. The four negative cases hand the claim a window the ledger does not hold and require the durable-range proof to be what refuses it. A candidate now commits to a snapshot digest, so a reference taken from the unaltered snapshot would be refused earlier, at the reference check, and the proof under test would never run. `window_ref_for` therefore derives each altered window's reference from that window, leaving the proof as the only thing that can notice, which is what #267 wrote them to prove. * 3.x.x: pin the durable-range proof outside the settlement lock #267 moved the full-equality proof of a candidate's window out of the settlement transaction so the lock is not held for a window-sized read. This slice made that read paged, so it does not occupy a runtime thread either. Reconciling the two is the step that can quietly undo the first: keep this slice's `persist_audit_snapshot` through the rebase and the full read goes back under the lock. The landing stays correct, every other test still passes, and only the lock hold grows, so nothing in the suite can tell. Measured at 100,000 shares on #267's branch that was a 34% longer hold. The guard is deterministic and needs no large window. A second connection holds `SETTLEMENT_LOCK`, so the landing blocks on it once its proof has run. While it waits, one share's `ntime` is altered: full equality sees that, a count over the same anchored predicate cannot. The landing must then succeed, which it can only do if it had already read and compared the shares before taking the lock. Accepted history is immutable and a trigger enforces it, so the test lifts that trigger for the single statement, inside its own disposable schema, and puts it straight back. Verified by mutation: restoring the in-transaction range read fails this test with "the landing read share payloads under the settlement lock". * 3.x.x: serialise the coordinator test modules that share the ledger's locks The ledger's advisory locks are cluster-wide constants, not schema-scoped, so two coordinator test modules running in parallel contend for ORDER_LOCK even though each works in its own throwaway schema. Every module held a lock of its own, which serialised it against itself and left cross-module waits to `lock_timeout`, 5 s by default. #324's reconciliation tests hold ORDER_LOCK for up to about 1.5 s, and this slice adds three more modules that open a ledger. Once enough of them ran at once those waits stacked past the timeout: a full `--lib` run failed with "canceling statement due to lock timeout" in `candidate_lease_tests` and `window_switch_tests`, and passed on the next run. A suite that fails for a reason unrelated to what it tests is worse than a slow one. All seven modules now take one shared lock. The run goes from about 35 s to about 62 s, and three consecutive runs pass where the flake had reproduced. * 3.x.x: pass the signer keys #334's wait-metrics tests now need `Ledger::configure` takes the frontend's signing keys since this slice, so the fingerprint contention tests #334 added call it with a fixed pair. That suite measures advisory-lock and pool-acquire waits, not signing, so the only thing the keys have to be is the same on every call. * feat: add compact prepared storage and immutable template blobs * Validate compact prepared endpoints and document caller contracts * 3.x.x: add migration 007 and refuse pre-007 candidate outbox rows Migration 007 mirrors 008 onto qbit_block_candidate_outbox: the same six window-reference columns, and a three-state CHECK whose body is identical to 008's apart from the table and constraint names. It also adds block_bytes, the nullable bytea the block moves into so the candidate document stays small, and a partial index on window_prior_balances_sha256 for the balance-snapshot GC. Nothing writes any of them yet; this is additive schema only. The runner applies 007 by membership, in its own block between 5 and 8, so it assumes neither 006 nor 008 has run. Before any DDL it refuses while the outbox still holds a pending row in a pre-007 shape: a native inline candidate, a NULL candidate, or storage_version other than 1 on the 2.x.x schemas that have that column, which is checked for first so the predicate does not error on a native schema. The refusal names every offending block_hash and the drain procedure, and the whole migration transaction rolls back, so a refused start leaves the schema untouched. The applied set is now [2, 3, 4, 5, 7, 8, 9], and the four exact migration assertions move with it rather than being weakened to a superset. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: retain the cluster fingerprint configure pinned or verified The candidate enqueue and save_job must fence against a fingerprint reset by re-reading qbit_prism_cluster.config_fingerprint FOR SHARE in their own transaction and refusing a write that is not this frontend's own. That needs the value configure settled at startup, so Ledger keeps it in a shared OnceLock, set only once the pin or the match has committed, and exposes it read-only through config_fingerprint(). configure keeps its signature and its mismatch refusal, and a refused call retains nothing. The rotation refusal in configure, and the writer fence itself, belong to the enqueue change and are not here. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: share the window reference, balance writer and page primitives WindowRef::from_snapshot is the synchronous reference builder both writers need: anchor_ms copied, the semantic balances digest, and for a non-empty snapshot the first and last share_seq, the length, and the share array's SHA-256 streamed through the existing DigestWriter, so the 233 to 260 MB serialized window at 400,000 shares is never built and the digest equals the one qbit_prism_audit_snapshots already stores. An empty snapshot gives the empty-window reference. Callers run it inside their own spawn_blocking. put_balance_snapshot is the one canonical writer of qbit_prism_balance_snapshots, on the caller's transaction: the sort by (order_key, recipient_id, p2mr_program_hex), the semantic digest that keys the row, and compact JSON of the sorted set, all off the runtime, then INSERT ... ON CONFLICT DO NOTHING. On a conflict it reads the stored bytes back and compares them with its own, because these rows are immutable and can only disagree through corruption. The enqueue and save_job and its repair all write through it. read_prior_balances and the current-balance read still keep their SQL order; the writer's sort defines the stored encoding, which is the order read_window(..., AsIssued) returns. probe_share_rows and read_range_paged are read_window's endpoint probe and page loop, lifted onto a caller's connection so the enqueue probe and the landing re-read share one implementation. The predicate, the ascending keyset order, the 4096-row page bound and the per-page count bound are unchanged, and read_window now calls them, with its signature and behaviour unchanged. The paged reader takes the caller's state and a per-page consumer, both of which travel to the blocking thread with the rows, so the landing re-read can compare each page with its slice of a vector it already holds without any whole-window work on the runtime; a dropped read still releases the accumulated state on a blocking thread. read_window_with_permit holds the caller's window_reads permit across the whole read. The permit is moved into a BlockingDrop declared before the read starts, so a cancellation releases it on a blocking thread after the page state queued its own release there, and never with the future; a return releases it inline, before the caller's rebuild. WindowError::TaskFailed separates a cancelled or panicking blocking hand-off from corruption. Every hand-off maps a JoinError to it instead of to Decode, so a cancellation is a retryable failure with its own alert and never takes the abandon path. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: derive the witness merkle leaves from an assembled block A claim rebuilds from stored inputs, and the witness leaves are the one builder input that scales with the block, so they are re-derived rather than stored: one 64-hex string per transaction beside the candidate would grow the document with the block. witness_merkle_leaves_from_block skips the 80-byte header, reads the compact-size transaction count, walks past the coinbase and returns double_sha256 of every remaining transaction's full serialized bytes. That is sound because assemble_submission appends the template's transactions verbatim after the coinbase, so the result equals witness_merkle_leaves_hex(&transactions_from_template(template)) for the block built from that template, with or without segwit transactions. The segwit-aware walk is strip_witness_transaction's own, factored into a helper that also reports where the transaction ends, which is what a block walker needs; strip_witness_transaction keeps its trailing-byte check and its output. A truncated block, trailing bytes, a zero count and a count that disagrees with the transactions present are all errors, never a partial list of leaves. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: version the audit builders and key the CC5 goldens by it A stored window reference reproduces its bundle only under the builder that first built it. The schema strings do not capture that, because the share shape chooses them rather than the builder logic, so qbit-prism gains AUDIT_BUILDER_VERSION, starting at 1. A candidate and a prepared job store it, and a rebuild refuses a reference at another version instead of rebuilding it with the current builder. The bump rule is on the constant: any change that alters canonical_audit_bundle_bytes for the same inputs bumps it in the same commit. The CC5 golden test now selects its expected digests from a table keyed by the constant, and fails when no entry exists, so a new output is recorded as a new entry beside the old one and review sees both. Version 1 holds the existing literals, unchanged. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: cover 007, the fingerprint and the window primitives on PostgreSQL Ten gated database cases, all listed in test/prism-gated-tests.txt. They go in a new file rather than the shared 2.x.x support module, which another open change appends to. Migration 007: a frozen 2.x.x schema carrying only terminal outbox rows upgrades with every row and field intact and the seven new columns NULL; each of the three pre-007 pending shapes is refused by name, with nothing from 007 applied and no version 7 row, and the same binary starts once the row is drained; a database at [2, 3, 4, 5, 8, 9] applies 007 and only 007, leaving every other version's applied_at untouched; the CHECK accepts exactly the three states across all 64 null combinations and rejects a short or uppercase digest, a zero or out-of-range count and a zero sequence; and the retention index is the partial one on window_prior_balances_sha256. config_fingerprint() returns what configure pinned or verified, is shared by clones, and stays empty after a refused configure. from_snapshot's streamed digest equals sha256(serde_json::to_vec) and the snapshot_sha256 landing writes for the same window. The balance writer stores the canonical sort, is idempotent under any permutation, errors rather than accepting a different encoding of the same digest, and read_window(..., AsIssued) hands back the stored order. The probe misses a missing endpoint, the paged reader compares 4,999 rows page by page with a vector held inside the caller's transaction, and a row the predicate skips inside a range is Incomplete with no partial window. The permit case builds a runtime with one blocking thread, occupies it, and cancels a reader parked mid-page on a database gate: no permit is available while the cleanup is queued, and one is once it has run. A failed blocking hand-off surfaces as TaskFailed, never as Decode. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: carry the window reference on prepared work, behind a read permit `Prepared` gains `window: WindowRef`, computed once per non-cached refresh beside `build_bundle` under `tokio::join!`, so submit can clone it instead of re-digesting the window on the share path when a block is found. An empty snapshot gets the empty-window reference on the runtime thread; a resume computes it inside the blocking decode it already runs. `Coordinator` gains the `window_reads` semaphore, sized `clamp(database_max_connections - 2, 1, build_workers)`, and the one entry point callers use: it takes an owned permit after the caller's `build_slots` permit and hands it to `Ledger::read_window_with_permit`, which holds it across the whole read, including the off-runtime cleanup a cancellation leaves behind, and releases it before the rebuild. `Ledger::read_window` is awaited on the runtime, never wrapped in `spawn_blocking`; the test with a single blocking thread pins that. The four gated `window_ref_tests` are listed in the manifest. Part of #265 Co-Authored-By: Claude Fable 5.1 <[email protected]> * 3.x.x: switch the candidate outbox to the window reference `Candidate` drops the embedded `AuditBundle` for `window: WindowRef` and every builder input except the window: `found_block`, `payout_policy`, the nested `ctv` triple (whose presence selects the CTV builder), the stored `bootstrap_share` of an empty window, `audit_builder_version`, `signer_keys`, a `leased` flag and the now-required `coinbase_suffix_hex`. The block leaves the document for the `block_bytes` column, authenticated by `block_sha256`, which `candidate_sha256` covers. The write serializes, digests and checks the candidate before the append or enqueue transaction opens; under `ORDER_LOCK` the transaction re-reads `config_fingerprint FOR SHARE` and refuses a value the writer did not pin, re-inserts a `leased` candidate's as-issued balance snapshot through the shared writer, probes the window's first row (an absent row alerts and still publishes), and inserts only the prepared bytes with the six typed columns. Submit builds the slim candidate from `Prepared.window`, the `BundleInputs` captured where `build_bundle` read configuration, and the job's own bootstrap share; it clones no bundle and reads no config. The claim's `UPDATE … RETURNING` returns the columns and the block, and the decode, off the runtime, checks the document against them, the digest, `sha256(block_bytes)`, the header hash, the required fields and the two reference invariants. A pending row with a NULL anchor is a hard error naming the pre-007 frontend; an inline document is never decoded. Before any read the claim retries, with an alert naming both values, a stored builder version or signer pair that is not this binary's; a landed audit is authenticated against the block (coinbase, audit root as the witness reserved value, share snapshot, …
* 3.x.x: add migration 007 and refuse pre-007 candidate outbox rows Migration 007 mirrors 008 onto qbit_block_candidate_outbox: the same six window-reference columns, and a three-state CHECK whose body is identical to 008's apart from the table and constraint names. It also adds block_bytes, the nullable bytea the block moves into so the candidate document stays small, and a partial index on window_prior_balances_sha256 for the balance-snapshot GC. Nothing writes any of them yet; this is additive schema only. The runner applies 007 by membership, in its own block between 5 and 8, so it assumes neither 006 nor 008 has run. Before any DDL it refuses while the outbox still holds a pending row in a pre-007 shape: a native inline candidate, a NULL candidate, or storage_version other than 1 on the 2.x.x schemas that have that column, which is checked for first so the predicate does not error on a native schema. The refusal names every offending block_hash and the drain procedure, and the whole migration transaction rolls back, so a refused start leaves the schema untouched. The applied set is now [2, 3, 4, 5, 7, 8, 9], and the four exact migration assertions move with it rather than being weakened to a superset. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: retain the cluster fingerprint configure pinned or verified The candidate enqueue and save_job must fence against a fingerprint reset by re-reading qbit_prism_cluster.config_fingerprint FOR SHARE in their own transaction and refusing a write that is not this frontend's own. That needs the value configure settled at startup, so Ledger keeps it in a shared OnceLock, set only once the pin or the match has committed, and exposes it read-only through config_fingerprint(). configure keeps its signature and its mismatch refusal, and a refused call retains nothing. The rotation refusal in configure, and the writer fence itself, belong to the enqueue change and are not here. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: share the window reference, balance writer and page primitives WindowRef::from_snapshot is the synchronous reference builder both writers need: anchor_ms copied, the semantic balances digest, and for a non-empty snapshot the first and last share_seq, the length, and the share array's SHA-256 streamed through the existing DigestWriter, so the 233 to 260 MB serialized window at 400,000 shares is never built and the digest equals the one qbit_prism_audit_snapshots already stores. An empty snapshot gives the empty-window reference. Callers run it inside their own spawn_blocking. put_balance_snapshot is the one canonical writer of qbit_prism_balance_snapshots, on the caller's transaction: the sort by (order_key, recipient_id, p2mr_program_hex), the semantic digest that keys the row, and compact JSON of the sorted set, all off the runtime, then INSERT ... ON CONFLICT DO NOTHING. On a conflict it reads the stored bytes back and compares them with its own, because these rows are immutable and can only disagree through corruption. The enqueue and save_job and its repair all write through it. read_prior_balances and the current-balance read still keep their SQL order; the writer's sort defines the stored encoding, which is the order read_window(..., AsIssued) returns. probe_share_rows and read_range_paged are read_window's endpoint probe and page loop, lifted onto a caller's connection so the enqueue probe and the landing re-read share one implementation. The predicate, the ascending keyset order, the 4096-row page bound and the per-page count bound are unchanged, and read_window now calls them, with its signature and behaviour unchanged. The paged reader takes the caller's state and a per-page consumer, both of which travel to the blocking thread with the rows, so the landing re-read can compare each page with its slice of a vector it already holds without any whole-window work on the runtime; a dropped read still releases the accumulated state on a blocking thread. read_window_with_permit holds the caller's window_reads permit across the whole read. The permit is moved into a BlockingDrop declared before the read starts, so a cancellation releases it on a blocking thread after the page state queued its own release there, and never with the future; a return releases it inline, before the caller's rebuild. WindowError::TaskFailed separates a cancelled or panicking blocking hand-off from corruption. Every hand-off maps a JoinError to it instead of to Decode, so a cancellation is a retryable failure with its own alert and never takes the abandon path. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: derive the witness merkle leaves from an assembled block A claim rebuilds from stored inputs, and the witness leaves are the one builder input that scales with the block, so they are re-derived rather than stored: one 64-hex string per transaction beside the candidate would grow the document with the block. witness_merkle_leaves_from_block skips the 80-byte header, reads the compact-size transaction count, walks past the coinbase and returns double_sha256 of every remaining transaction's full serialized bytes. That is sound because assemble_submission appends the template's transactions verbatim after the coinbase, so the result equals witness_merkle_leaves_hex(&transactions_from_template(template)) for the block built from that template, with or without segwit transactions. The segwit-aware walk is strip_witness_transaction's own, factored into a helper that also reports where the transaction ends, which is what a block walker needs; strip_witness_transaction keeps its trailing-byte check and its output. A truncated block, trailing bytes, a zero count and a count that disagrees with the transactions present are all errors, never a partial list of leaves. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: version the audit builders and key the CC5 goldens by it A stored window reference reproduces its bundle only under the builder that first built it. The schema strings do not capture that, because the share shape chooses them rather than the builder logic, so qbit-prism gains AUDIT_BUILDER_VERSION, starting at 1. A candidate and a prepared job store it, and a rebuild refuses a reference at another version instead of rebuilding it with the current builder. The bump rule is on the constant: any change that alters canonical_audit_bundle_bytes for the same inputs bumps it in the same commit. The CC5 golden test now selects its expected digests from a table keyed by the constant, and fails when no entry exists, so a new output is recorded as a new entry beside the old one and review sees both. Version 1 holds the existing literals, unchanged. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: cover 007, the fingerprint and the window primitives on PostgreSQL Ten gated database cases, all listed in test/prism-gated-tests.txt. They go in a new file rather than the shared 2.x.x support module, which another open change appends to. Migration 007: a frozen 2.x.x schema carrying only terminal outbox rows upgrades with every row and field intact and the seven new columns NULL; each of the three pre-007 pending shapes is refused by name, with nothing from 007 applied and no version 7 row, and the same binary starts once the row is drained; a database at [2, 3, 4, 5, 8, 9] applies 007 and only 007, leaving every other version's applied_at untouched; the CHECK accepts exactly the three states across all 64 null combinations and rejects a short or uppercase digest, a zero or out-of-range count and a zero sequence; and the retention index is the partial one on window_prior_balances_sha256. config_fingerprint() returns what configure pinned or verified, is shared by clones, and stays empty after a refused configure. from_snapshot's streamed digest equals sha256(serde_json::to_vec) and the snapshot_sha256 landing writes for the same window. The balance writer stores the canonical sort, is idempotent under any permutation, errors rather than accepting a different encoding of the same digest, and read_window(..., AsIssued) hands back the stored order. The probe misses a missing endpoint, the paged reader compares 4,999 rows page by page with a vector held inside the caller's transaction, and a row the predicate skips inside a range is Incomplete with no partial window. The permit case builds a runtime with one blocking thread, occupies it, and cancels a reader parked mid-page on a database gate: no permit is available while the cleanup is queued, and one is once it has run. A failed blocking hand-off surfaces as TaskFailed, never as Decode. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: carry the window reference on prepared work, behind a read permit `Prepared` gains `window: WindowRef`, computed once per non-cached refresh beside `build_bundle` under `tokio::join!`, so submit can clone it instead of re-digesting the window on the share path when a block is found. An empty snapshot gets the empty-window reference on the runtime thread; a resume computes it inside the blocking decode it already runs. `Coordinator` gains the `window_reads` semaphore, sized `clamp(database_max_connections - 2, 1, build_workers)`, and the one entry point callers use: it takes an owned permit after the caller's `build_slots` permit and hands it to `Ledger::read_window_with_permit`, which holds it across the whole read, including the off-runtime cleanup a cancellation leaves behind, and releases it before the rebuild. `Ledger::read_window` is awaited on the runtime, never wrapped in `spawn_blocking`; the test with a single blocking thread pins that. The four gated `window_ref_tests` are listed in the manifest. Part of #265 Co-Authored-By: Claude Fable 5.1 <[email protected]> * 3.x.x: switch the candidate outbox to the window reference `Candidate` drops the embedded `AuditBundle` for `window: WindowRef` and every builder input except the window: `found_block`, `payout_policy`, the nested `ctv` triple (whose presence selects the CTV builder), the stored `bootstrap_share` of an empty window, `audit_builder_version`, `signer_keys`, a `leased` flag and the now-required `coinbase_suffix_hex`. The block leaves the document for the `block_bytes` column, authenticated by `block_sha256`, which `candidate_sha256` covers. The write serializes, digests and checks the candidate before the append or enqueue transaction opens; under `ORDER_LOCK` the transaction re-reads `config_fingerprint FOR SHARE` and refuses a value the writer did not pin, re-inserts a `leased` candidate's as-issued balance snapshot through the shared writer, probes the window's first row (an absent row alerts and still publishes), and inserts only the prepared bytes with the six typed columns. Submit builds the slim candidate from `Prepared.window`, the `BundleInputs` captured where `build_bundle` read configuration, and the job's own bootstrap share; it clones no bundle and reads no config. The claim's `UPDATE … RETURNING` returns the columns and the block, and the decode, off the runtime, checks the document against them, the digest, `sha256(block_bytes)`, the header hash, the required fields and the two reference invariants. A pending row with a NULL anchor is a hard error naming the pre-007 frontend; an inline document is never decoded. Before any read the claim retries, with an alert naming both values, a stored builder version or signer pair that is not this binary's; a landed audit is authenticated against the block (coinbase, audit root as the witness reserved value, share snapshot, bits) and the claim then skips the rebuild and landing and continues to observe, renew and submit. Otherwise it takes `build_slots`, then `window_reads` inside one 60 s deadline around the awaited `read_window(Current)` and the borrowing builder run directly in `spawn_blocking`, and keeps `Arc<AuditBundleBody>` and the shares as `ClaimParts`. `Incomplete`, `SnapshotDigestMismatch`, `Decode`, `BalanceSnapshotMissing`, `TaskFailed` and the deadline retry with their own alerts; `PriorBalancesChanged` finishes only a block `observe_candidate` proves inactive and superseded; `Database` propagates. A `leased` candidate submits from `block_bytes` first, then rebuilds `AsIssued` and lands before any terminal outcome. Rebuilt parts are released off the runtime on every path. Landing takes the parts and does all whole-window work in one blocking closure: `verify_audit_parts`, the raw body, the counted canonical bytes, the leaves and accounts, and the share snapshot digest, which must equal the reference's. The balance fence compares the current set and the parts' through the semantic digest, so an as-issued set compares equal in any order. `persist_audit_snapshot` re-reads the range with the paged reader inside the landing transaction, page against slice on the blocking thread; `read_range` stays for the API. The terminal UPDATE NULLs the six window columns and `block_bytes` with `candidate`. `configure` refuses to pin a fingerprint onto a reset one while a pending row stores other signer keys, and the startup gate requires 007 with 009. The JSONB gate drops its enqueue entry, and every helper that built a candidate builds the slim one, handing the ledger-level landings the bundle's parts through `CandidateClaim::with_bundle`. Part of #265 Co-Authored-By: Claude Fable 5.1 <[email protected]> * 3.x.x: cover the candidate switch on PostgreSQL Ledger-level, in `candidate_window_switch`: a two-page window enqueues a document with no array and no share row, under 1 MB, whose six typed columns equal its reference and whose block is stored as bytes; the writer fence refuses a reset or different fingerprint in the same transaction, share included; a missing window prefix row alerts and still publishes, and its read then meets `Incomplete`; a `leased` enqueue re-inserts the as-issued balance snapshot in the writer's canonical order, writes none when not leased, and refuses balances that do not hash to the reference; every preparation failure is refused without waiting for `ORDER_LOCK`; every column, digest, block, header, NULL-anchor, missing-field, invariant and inline-document disagreement is refused at claim; landing refuses parts that are not the referenced window and a claim without parts; the terminal UPDATE NULLs the six columns and the block for submitted and abandoned rows; the landed-audit authentication rejects a forged coinbase, root, snapshot or bits; and `configure` refuses a rotation over a foreign-signed pending candidate. Coordinator-level, in `window_switch_tests` behind a fake node: a stored builder version or signer pair that is not this binary's retries, naming both values, while the build slot is held; a landed audit is authenticated and the claim continues to `submitblock` without a build slot, and a forged landed coinbase or root is refused with the row left pending; `Incomplete`, a digest mismatch, changed balances on a current block and the rebuild deadline all retry with an alert and release their permits; `classify_window_error` keeps `TaskFailed` apart from corruption and propagates `Database`; the read, rebuild and landing complete while `ORDER_LOCK` is held, with one build worker; a `leased` candidate submits first, then lands from `AsIssued`, and finishes submitted, abandoned with the node's reason, or pending when its balance snapshot is missing; and `OffRuntime` releases on a blocking thread, on cancellation too. The fifteen gated tests are listed in the manifest. Part of #265 Co-Authored-By: Claude Fable 5.1 <[email protected]> * 3.x.x: migrate the imported-audit tests to the slim candidate Slice 1 (#325) merged after this stack branched, and its tests in tests/support/ledger_2x.rs still built the pre-007 candidate: they read block.bundle from a Candidate and called candidate_with_bundle without a window reference or settlement inputs. The rebase merged them cleanly and the tree then failed to compile. The three helpers now take the TestCandidate the constructors return, so they reach the bundle beside the slim candidate, and land_confirmed attaches the claim's parts the way the other ledger tests do. The three constructor calls pass the window reference the bundle was built on, and the settlement inputs for the CTV case. No assertion changes. Part of #265. * 3.x.x: qualify lease renewal and the claim's canonical bytes at scale Incident 1: a candidate whose window holds N shares is claimed and processed under the short lease, and every renewal is read back from claim_expires_at. The largest gap stays below interval + 2 x timeout, the lease never lapses, and a successor ledger cannot take the claim. The bundle a claim rebuilds through the window-read entry point and the borrowing builder has the canonical bytes refresh built for the same job, and the landed audit carries that bundle's digest. Both run at PRISM_WINDOW_QUALIFY_SHARES (20,000 by default); the 400,000-share variants are ignored and run on a larger host. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: measure ACK latency and ORDER_LOCK hold across window sizes Incident 2: two frontends on one database submit ordinary shares at a fixed rate while one of them solves a block on an N-share window and its own submit loop claims, rebuilds, lands and submits it. The solving share's ACK and the bystander's p99 stay within max(2 x baseline p99 + 50 ms, 250 ms), every ACK is well under the share-commit timeout, and the block is enqueued exactly once. Latency is the in-process MiningBackend::submit wall clock; the socket-level harness (#271) does not exist yet. A pg_locks sampler on its own connection measures how long a solving append holds ORDER_LOCK at two window sizes with no other traffic: the larger size stays within a fixed slack of the smaller, and the candidate document is the same size at both and under 1 MiB. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: hold the JSONB gate's enqueue to a window-free row under 1 MiB At every measured size the enqueue must be accepted and every JSONB value it writes, the outbox candidate document included, must stay under 1,048,576 bytes. At the reduced sizes the enqueue, claim and landing phases must all run. The ratchet and its expected values are unchanged. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: make the window-read permit test actually wait before it looks The delay that gives an unpermitted read time to finish was an empty async block, so the check that the read had not finished ran at once and passed whether or not the entry point took a permit. It now sleeps 500 ms inside a 5 s bound, and fails when the permit acquisition is removed from the entry point. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: rebuild a CTV candidate from its stored settlement inputs No host-runnable test reached the CTV branch of the claim rebuild. A CTV-enabled frontend now claims a candidate whose stored direct floor differs from its configuration, and builds a different coinbase than the configured floor would, and the claim must land that candidate's own audit and submit it. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: pin the SQL order of the current-balance reads Nothing defended the ruling that the current-balance path keeps its SQL order: every fixture's balances already arrived in byte-wise canonical order. The carry table's text columns now take an ICU collation, under which the SQL order and the canonical sort disagree, and the snapshot and the current-balance window read must both return the SQL order. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: record what incident 2 must also assert once #324 is in the base After #324 a slow solve is acknowledged late rather than refused, so acceptance proves nothing and the latency percentiles stay the assertion. The doc comment and a TODO at the outcome checks name the counter and outcome to assert at rebase. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: assert incident 2's late-confirm counter now that #324 is in the base W3c wrote the qualification tests against a base that predated #324 and left a marked place for the assertions that only make sense once the commit gate is there. The base now carries it, so apply them: incident 2 asserts `qbit_prism_late_confirmed_shares_total` is zero on both frontends and that no acknowledgement, the block-solving share included, is `ledger-outcome-unknown`. Acceptance alone is no longer proof. #324 gives a share-pass append carrying a candidate its own `block_only_ack_timeout`, so a slow solve is never refused at the share deadline; it is answered late, or answered unknown. Either would have satisfied the acceptance checks with the serialization stall still present. Also set #324's two new `Config` fields in the qualification fixture. * 3.x.x: pin a refused candidate as a definite rejection, not an unknown outcome #324 decides what a miner is told when a block-only enqueue fails: `enqueue_failed_before_commit` answers a provably uncommitted failure with `ledger-confirmation-failed`, and anything else with `ledger-outcome-unknown`, which asks an operator to go and follow the outbox row. Slice 3 added the checks that guard the reference: the block's length, its header hash, its digest against `block_sha256`, the coinbase suffix, the reference invariants, and a leased candidate's balances. All of them are raised by `prepare_candidate` before the enqueue takes a connection, so none carries an `sqlx::Error` and all classify as definite today. That is a property of where the checks sit, not something the classifier knows about them, so it is pinned here rather than left to hold by accident: a corrupt candidate must never send a miner chasing a row that was never written. Verified by mutation: classifying a non-sqlx failure as unknown fails this test. * 3.x.x: say why the full-size qualification variants cannot reach 400k yet Their ignore reasons blamed RAM and the host. The real limit is #273: the job payload still holds three copies of the window (2 x AcceptedShare + 1 x CountedShare), so publishing a job for a 400,000-share window needs about 670 MiB and PostgreSQL refuses the write above its 256 MiB jsonb object limit. Every full-size variant fails at fixture set-up, before it measures anything. The count must also divide the window weight exactly, so the largest usable size today is 125,000, where all four variants pass in release: incident 1 50 renewals, max gap 118.25 ms against a 700 ms bound incident 2 phase-A p99 2.60 ms, phase-B p99 95.79 ms, bound 250 ms lock hold median 0.75 ms at 5,000 against 1.32 ms at 125,000 canonical refresh and claim rebuild both 139,040,610 B, same sha256 The candidate document stays flat at 1103 B and 1107 B, which is the property this slice exists to establish. * 3.x.x: migrate the audit-body normalization tests to the slim candidate #267 landed its own test file against the candidate that still carried an assembled bundle. This slice replaced that with a window reference, so the file keeps a `TestCandidate` pairing the stored candidate with the bundle a test still needs, as `tests/ledger_postgres.rs` does, and attaches the claim's parts through `with_bundle`. One case needed more than a shape change. The four negative cases hand the claim a window the ledger does not hold and require the durable-range proof to be what refuses it. A candidate now commits to a snapshot digest, so a reference taken from the unaltered snapshot would be refused earlier, at the reference check, and the proof under test would never run. `window_ref_for` therefore derives each altered window's reference from that window, leaving the proof as the only thing that can notice, which is what #267 wrote them to prove. * 3.x.x: pin the durable-range proof outside the settlement lock #267 moved the full-equality proof of a candidate's window out of the settlement transaction so the lock is not held for a window-sized read. This slice made that read paged, so it does not occupy a runtime thread either. Reconciling the two is the step that can quietly undo the first: keep this slice's `persist_audit_snapshot` through the rebase and the full read goes back under the lock. The landing stays correct, every other test still passes, and only the lock hold grows, so nothing in the suite can tell. Measured at 100,000 shares on #267's branch that was a 34% longer hold. The guard is deterministic and needs no large window. A second connection holds `SETTLEMENT_LOCK`, so the landing blocks on it once its proof has run. While it waits, one share's `ntime` is altered: full equality sees that, a count over the same anchored predicate cannot. The landing must then succeed, which it can only do if it had already read and compared the shares before taking the lock. Accepted history is immutable and a trigger enforces it, so the test lifts that trigger for the single statement, inside its own disposable schema, and puts it straight back. Verified by mutation: restoring the in-transaction range read fails this test with "the landing read share payloads under the settlement lock". * 3.x.x: serialise the coordinator test modules that share the ledger's locks The ledger's advisory locks are cluster-wide constants, not schema-scoped, so two coordinator test modules running in parallel contend for ORDER_LOCK even though each works in its own throwaway schema. Every module held a lock of its own, which serialised it against itself and left cross-module waits to `lock_timeout`, 5 s by default. #324's reconciliation tests hold ORDER_LOCK for up to about 1.5 s, and this slice adds three more modules that open a ledger. Once enough of them ran at once those waits stacked past the timeout: a full `--lib` run failed with "canceling statement due to lock timeout" in `candidate_lease_tests` and `window_switch_tests`, and passed on the next run. A suite that fails for a reason unrelated to what it tests is worse than a slow one. All seven modules now take one shared lock. The run goes from about 35 s to about 62 s, and three consecutive runs pass where the flake had reproduced. * 3.x.x: pass the signer keys #334's wait-metrics tests now need `Ledger::configure` takes the frontend's signing keys since this slice, so the fingerprint contention tests #334 added call it with a fixed pair. That suite measures advisory-lock and pool-acquire waits, not signing, so the only thing the keys have to be is the same on every call. * 3.x.x: resume a job's bundle only while the current inputs still describe it A resumed job reuses the bundle it was issued with, but captures its inputs from this frontend's configuration now. Before this slice that was harmless: the candidate carried the assembled bundle, and landing used it directly. Now the candidate stores the inputs and the claim rebuilds the audit from them, so an old bundle labelled with today's configuration rebuilds to a coinbase the block does not commit to. The claim fails its comparison before `submitblock` and retries until the job expires, which can lose a found block. The stored bundle is now reused only when the captured inputs still describe it, comparing what the bundle itself records about how it was built: the payout policy, and the public keys that actually signed its coinbase manifest and its ledger attestation. A difference is a cache miss, so the bundle is rebuilt rather than mislabelled. Both directions are covered, since over-tightening would silently defeat the job cache and rebuild on every resume: unchanged inputs must still describe the bundle, and a payout-policy change, a full signer rotation and a rotation of either key alone must each refuse it. Known residue, recorded in the doc comment: a bundle records neither the CTV settlement inputs nor `audit_builder_version`, so a change to either between issue and resume is still undetectable here. Closing that needs the issued job to store its inputs, which is #273's format. * 3.x.x: migrate #355's ledger tests to the slim candidate #355 landed deadline and single-execution coverage against the candidate that still carried an assembled bundle, and against `configure` before it took the frontend's signing keys. Adapted, the same way #325's and #267's suites were: a `TestCandidate` pairs the stored candidate with the bundle a landing still needs, claims attach their parts through `with_bundle`, and the conflicting claim that is never landed carries none. `ledger_deadline_atomicity` builds its candidate from a bundle rather than a snapshot, so its window reference is derived from that bundle: the anchor and prior-balances digest it already records, and the range and digest of the shares it carries. Its signer keys come from the public keys that actually signed it, rather than from a local pair, so the stored inputs describe the bundle. * 3.x.x: make the landed-audit forgery always alter the row, and migrate #360's fixture The forged-coinbase case placed a literal '0' at a fixed offset. Whenever the digit already held that value the forgery changed nothing, so the claim was right to accept it and the case failed only by luck. The coinbase varies per run, because the bundle's anchor comes from the ledger clock, so this passed repeatedly and then failed once as "the forgery was accepted" — an alarming message for a case that was in fact a no-op. A security check that can quietly become vacuous is worse than one that is absent. The digit is now flipped to a value it does not currently hold, and the row is read back either side of the statement so a forgery that altered nothing fails the case for that reason instead. Also passes the signer keys #360's `tests/support/fatal_state.rs` now needs, since `configure` takes them in this slice. * 3.x.x: drop the pre-#362 path for the heartbeat SQL gated test #362 moved `live_instance_tests` from `tools` to `ledger::instances`. Merging the gated-test manifest during the rebase kept both paths, because a rename upstream looks like one id removed and another added, and a union keeps the removed one. The old `tools::` path then never executed and the gate refused the run: "194 distinct gated tests executed, below the minimum of 195". The manifest is a superset of the base's ids, and every id this branch adds over the base resolves to a test function that exists in the tree. * v3.0.0 feat: add compact prepared storage and immutable template blobs (#359) * 3.x.x: add migration 007 and refuse pre-007 candidate outbox rows Migration 007 mirrors 008 onto qbit_block_candidate_outbox: the same six window-reference columns, and a three-state CHECK whose body is identical to 008's apart from the table and constraint names. It also adds block_bytes, the nullable bytea the block moves into so the candidate document stays small, and a partial index on window_prior_balances_sha256 for the balance-snapshot GC. Nothing writes any of them yet; this is additive schema only. The runner applies 007 by membership, in its own block between 5 and 8, so it assumes neither 006 nor 008 has run. Before any DDL it refuses while the outbox still holds a pending row in a pre-007 shape: a native inline candidate, a NULL candidate, or storage_version other than 1 on the 2.x.x schemas that have that column, which is checked for first so the predicate does not error on a native schema. The refusal names every offending block_hash and the drain procedure, and the whole migration transaction rolls back, so a refused start leaves the schema untouched. The applied set is now [2, 3, 4, 5, 7, 8, 9], and the four exact migration assertions move with it rather than being weakened to a superset. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: retain the cluster fingerprint configure pinned or verified The candidate enqueue and save_job must fence against a fingerprint reset by re-reading qbit_prism_cluster.config_fingerprint FOR SHARE in their own transaction and refusing a write that is not this frontend's own. That needs the value configure settled at startup, so Ledger keeps it in a shared OnceLock, set only once the pin or the match has committed, and exposes it read-only through config_fingerprint(). configure keeps its signature and its mismatch refusal, and a refused call retains nothing. The rotation refusal in configure, and the writer fence itself, belong to the enqueue change and are not here. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: share the window reference, balance writer and page primitives WindowRef::from_snapshot is the synchronous reference builder both writers need: anchor_ms copied, the semantic balances digest, and for a non-empty snapshot the first and last share_seq, the length, and the share array's SHA-256 streamed through the existing DigestWriter, so the 233 to 260 MB serialized window at 400,000 shares is never built and the digest equals the one qbit_prism_audit_snapshots already stores. An empty snapshot gives the empty-window reference. Callers run it inside their own spawn_blocking. put_balance_snapshot is the one canonical writer of qbit_prism_balance_snapshots, on the caller's transaction: the sort by (order_key, recipient_id, p2mr_program_hex), the semantic digest that keys the row, and compact JSON of the sorted set, all off the runtime, then INSERT ... ON CONFLICT DO NOTHING. On a conflict it reads the stored bytes back and compares them with its own, because these rows are immutable and can only disagree through corruption. The enqueue and save_job and its repair all write through it. read_prior_balances and the current-balance read still keep their SQL order; the writer's sort defines the stored encoding, which is the order read_window(..., AsIssued) returns. probe_share_rows and read_range_paged are read_window's endpoint probe and page loop, lifted onto a caller's connection so the enqueue probe and the landing re-read share one implementation. The predicate, the ascending keyset order, the 4096-row page bound and the per-page count bound are unchanged, and read_window now calls them, with its signature and behaviour unchanged. The paged reader takes the caller's state and a per-page consumer, both of which travel to the blocking thread with the rows, so the landing re-read can compare each page with its slice of a vector it already holds without any whole-window work on the runtime; a dropped read still releases the accumulated state on a blocking thread. read_window_with_permit holds the caller's window_reads permit across the whole read. The permit is moved into a BlockingDrop declared before the read starts, so a cancellation releases it on a blocking thread after the page state queued its own release there, and never with the future; a return releases it inline, before the caller's rebuild. WindowError::TaskFailed separates a cancelled or panicking blocking hand-off from corruption. Every hand-off maps a JoinError to it instead of to Decode, so a cancellation is a retryable failure with its own alert and never takes the abandon path. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: derive the witness merkle leaves from an assembled block A claim rebuilds from stored inputs, and the witness leaves are the one builder input that scales with the block, so they are re-derived rather than stored: one 64-hex string per transaction beside the candidate would grow the document with the block. witness_merkle_leaves_from_block skips the 80-byte header, reads the compact-size transaction count, walks past the coinbase and returns double_sha256 of every remaining transaction's full serialized bytes. That is sound because assemble_submission appends the template's transactions verbatim after the coinbase, so the result equals witness_merkle_leaves_hex(&transactions_from_template(template)) for the block built from that template, with or without segwit transactions. The segwit-aware walk is strip_witness_transaction's own, factored into a helper that also reports where the transaction ends, which is what a block walker needs; strip_witness_transaction keeps its trailing-byte check and its output. A truncated block, trailing bytes, a zero count and a count that disagrees with the transactions present are all errors, never a partial list of leaves. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: version the audit builders and key the CC5 goldens by it A stored window reference reproduces its bundle only under the builder that first built it. The schema strings do not capture that, because the share shape chooses them rather than the builder logic, so qbit-prism gains AUDIT_BUILDER_VERSION, starting at 1. A candidate and a prepared job store it, and a rebuild refuses a reference at another version instead of rebuilding it with the current builder. The bump rule is on the constant: any change that alters canonical_audit_bundle_bytes for the same inputs bumps it in the same commit. The CC5 golden test now selects its expected digests from a table keyed by the constant, and fails when no entry exists, so a new output is recorded as a new entry beside the old one and review sees both. Version 1 holds the existing literals, unchanged. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: cover 007, the fingerprint and the window primitives on PostgreSQL Ten gated database cases, all listed in test/prism-gated-tests.txt. They go in a new file rather than the shared 2.x.x support module, which another open change appends to. Migration 007: a frozen 2.x.x schema carrying only terminal outbox rows upgrades with every row and field intact and the seven new columns NULL; each of the three pre-007 pending shapes is refused by name, with nothing from 007 applied and no version 7 row, and the same binary starts once the row is drained; a database at [2, 3, 4, 5, 8, 9] applies 007 and only 007, leaving every other version's applied_at untouched; the CHECK accepts exactly the three states across all 64 null combinations and rejects a short or uppercase digest, a zero or out-of-range count and a zero sequence; and the retention index is the partial one on window_prior_balances_sha256. config_fingerprint() returns what configure pinned or verified, is shared by clones, and stays empty after a refused configure. from_snapshot's streamed digest equals sha256(serde_json::to_vec) and the snapshot_sha256 landing writes for the same window. The balance writer stores the canonical sort, is idempotent under any permutation, errors rather than accepting a different encoding of the same digest, and read_window(..., AsIssued) hands back the stored order. The probe misses a missing endpoint, the paged reader compares 4,999 rows page by page with a vector held inside the caller's transaction, and a row the predicate skips inside a range is Incomplete with no partial window. The permit case builds a runtime with one blocking thread, occupies it, and cancels a reader parked mid-page on a database gate: no permit is available while the cleanup is queued, and one is once it has run. A failed blocking hand-off surfaces as TaskFailed, never as Decode. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: carry the window reference on prepared work, behind a read permit `Prepared` gains `window: WindowRef`, computed once per non-cached refresh beside `build_bundle` under `tokio::join!`, so submit can clone it instead of re-digesting the window on the share path when a block is found. An empty snapshot gets the empty-window reference on the runtime thread; a resume computes it inside the blocking decode it already runs. `Coordinator` gains the `window_reads` semaphore, sized `clamp(database_max_connections - 2, 1, build_workers)`, and the one entry point callers use: it takes an owned permit after the caller's `build_slots` permit and hands it to `Ledger::read_window_with_permit`, which holds it across the whole read, including the off-runtime cleanup a cancellation leaves behind, and releases it before the rebuild. `Ledger::read_window` is awaited on the runtime, never wrapped in `spawn_blocking`; the test with a single blocking thread pins that. The four gated `window_ref_tests` are listed in the manifest. Part of #265 Co-Authored-By: Claude Fable 5.1 <[email protected]> * 3.x.x: switch the candidate outbox to the window reference `Candidate` drops the embedded `AuditBundle` for `window: WindowRef` and every builder input except the window: `found_block`, `payout_policy`, the nested `ctv` triple (whose presence selects the CTV builder), the stored `bootstrap_share` of an empty window, `audit_builder_version`, `signer_keys`, a `leased` flag and the now-required `coinbase_suffix_hex`. The block leaves the document for the `block_bytes` column, authenticated by `block_sha256`, which `candidate_sha256` covers. The write serializes, digests and checks the candidate before the append or enqueue transaction opens; under `ORDER_LOCK` the transaction re-reads `config_fingerprint FOR SHARE` and refuses a value the writer did not pin, re-inserts a `leased` candidate's as-issued balance snapshot through the shared writer, probes the window's first row (an absent row alerts and still publishes), and inserts only the prepared bytes with the six typed columns. Submit builds the slim candidate from `Prepared.window`, the `BundleInputs` captured where `build_bundle` read configuration, and the job's own bootstrap share; it clones no bundle and reads no config. The claim's `UPDATE … RETURNING` returns the columns and the block, and the decode, off the runtime, checks the document against them, the digest, `sha256(block_bytes)`, the header hash, the required fields and the two reference invariants. A pending row with a NULL anchor is a hard error naming the pre-007 frontend; an inline document is never decoded. Before any read the claim retries, with an alert naming both values, a stored builder version or signer pair that is not this binary's; a landed audit is authenticated against the block (coinbase, audit root as the witness reserved value, share snapshot, bits) and the claim then skips the rebuild and landing and continues to observe, renew and submit. Otherwise it takes `build_slots`, then `window_reads` inside one 60 s deadline around the awaited `read_window(Current)` and the borrowing builder run directly in `spawn_blocking`, and keeps `Arc<AuditBundleBody>` and the shares as `ClaimParts`. `Incomplete`, `SnapshotDigestMismatch`, `Decode`, `BalanceSnapshotMissing`, `TaskFailed` and the deadline retry with their own alerts; `PriorBalancesChanged` finishes only a block `observe_candidate` proves inactive and superseded; `Database` propagates. A `leased` candidate submits from `block_bytes` first, then rebuilds `AsIssued` and lands before any terminal outcome. Rebuilt parts are released off the runtime on every path. Landing takes the parts and does all whole-window work in one blocking closure: `verify_audit_parts`, the raw body, the counted canonical bytes, the leaves and accounts, and the share snapshot digest, which must equal the reference's. The balance fence compares the current set and the parts' through the semantic digest, so an as-issued set compares equal in any order. `persist_audit_snapshot` re-reads the range with the paged reader inside the landing transaction, page against slice on the blocking thread; `read_range` stays for the API. The terminal UPDATE NULLs the six window columns and `block_bytes` with `candidate`. `configure` refuses to pin a fingerprint onto a reset one while a pending row stores other signer keys, and the startup gate requires 007 with 009. The JSONB gate drops its enqueue entry, and every helper that built a candidate builds the slim one, handing the ledger-level landings the bundle's parts through `CandidateClaim::with_bundle`. Part of #265 Co-Authored-By: Claude Fable 5.1 <[email protected]> * 3.x.x: cover the candidate switch on PostgreSQL Ledger-level, in `candidate_window_switch`: a two-page window enqueues a document with no array and no share row, under 1 MB, whose six typed columns equal its reference and whose block is stored as bytes; the writer fence refuses a reset or different fingerprint in the same transaction, share included; a missing window prefix row alerts and still publishes, and its read then meets `Incomplete`; a `leased` enqueue re-inserts the as-issued balance snapshot in the writer's canonical order, writes none when not leased, and refuses balances that do not hash to the reference; every preparation failure is refused without waiting for `ORDER_LOCK`; every column, digest, block, header, NULL-anchor, missing-field, invariant and inline-document disagreement is refused at claim; landing refuses parts that are not the referenced window and a claim without parts; the terminal UPDATE NULLs the six columns and the block for submitted and abandoned rows; the landed-audit authentication rejects a forged coinbase, root, snapshot or bits; and `configure` refuses a rotation over a foreign-signed pending candidate. Coordinator-level, in `window_switch_tests` behind a fake node: a stored builder version or signer pair that is not this binary's retries, naming both values, while the build slot is held; a landed audit is authenticated and the claim continues to `submitblock` without a build slot, and a forged landed coinbase or root is refused with the row left pending; `Incomplete`, a digest mismatch, changed balances on a current block and the rebuild deadline all retry with an alert and release their permits; `classify_window_error` keeps `TaskFailed` apart from corruption and propagates `Database`; the read, rebuild and landing complete while `ORDER_LOCK` is held, with one build worker; a `leased` candidate submits first, then lands from `AsIssued`, and finishes submitted, abandoned with the node's reason, or pending when its balance snapshot is missing; and `OffRuntime` releases on a blocking thread, on cancellation too. The fifteen gated tests are listed in the manifest. Part of #265 Co-Authored-By: Claude Fable 5.1 <[email protected]> * 3.x.x: migrate the imported-audit tests to the slim candidate Slice 1 (#325) merged after this stack branched, and its tests in tests/support/ledger_2x.rs still built the pre-007 candidate: they read block.bundle from a Candidate and called candidate_with_bundle without a window reference or settlement inputs. The rebase merged them cleanly and the tree then failed to compile. The three helpers now take the TestCandidate the constructors return, so they reach the bundle beside the slim candidate, and land_confirmed attaches the claim's parts the way the other ledger tests do. The three constructor calls pass the window reference the bundle was built on, and the settlement inputs for the CTV case. No assertion changes. Part of #265. * 3.x.x: qualify lease renewal and the claim's canonical bytes at scale Incident 1: a candidate whose window holds N shares is claimed and processed under the short lease, and every renewal is read back from claim_expires_at. The largest gap stays below interval + 2 x timeout, the lease never lapses, and a successor ledger cannot take the claim. The bundle a claim rebuilds through the window-read entry point and the borrowing builder has the canonical bytes refresh built for the same job, and the landed audit carries that bundle's digest. Both run at PRISM_WINDOW_QUALIFY_SHARES (20,000 by default); the 400,000-share variants are ignored and run on a larger host. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: measure ACK latency and ORDER_LOCK hold across window sizes Incident 2: two frontends on one database submit ordinary shares at a fixed rate while one of them solves a block on an N-share window and its own submit loop claims, rebuilds, lands and submits it. The solving share's ACK and the bystander's p99 stay within max(2 x baseline p99 + 50 ms, 250 ms), every ACK is well under the share-commit timeout, and the block is enqueued exactly once. Latency is the in-process MiningBackend::submit wall clock; the socket-level harness (#271) does not exist yet. A pg_locks sampler on its own connection measures how long a solving append holds ORDER_LOCK at two window sizes with no other traffic: the larger size stays within a fixed slack of the smaller, and the candidate document is the same size at both and under 1 MiB. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: hold the JSONB gate's enqueue to a window-free row under 1 MiB At every measured size the enqueue must be accepted and every JSONB value it writes, the outbox candidate document included, must stay under 1,048,576 bytes. At the reduced sizes the enqueue, claim and landing phases must all run. The ratchet and its expected values are unchanged. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: make the window-read permit test actually wait before it looks The delay that gives an unpermitted read time to finish was an empty async block, so the check that the read had not finished ran at once and passed whether or not the entry point took a permit. It now sleeps 500 ms inside a 5 s bound, and fails when the permit acquisition is removed from the entry point. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: rebuild a CTV candidate from its stored settlement inputs No host-runnable test reached the CTV branch of the claim rebuild. A CTV-enabled frontend now claims a candidate whose stored direct floor differs from its configuration, and builds a different coinbase than the configured floor would, and the claim must land that candidate's own audit and submit it. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: pin the SQL order of the current-balance reads Nothing defended the ruling that the current-balance path keeps its SQL order: every fixture's balances already arrived in byte-wise canonical order. The carry table's text columns now take an ICU collation, under which the SQL order and the canonical sort disagree, and the snapshot and the current-balance window read must both return the SQL order. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: record what incident 2 must also assert once #324 is in the base After #324 a slow solve is acknowledged late rather than refused, so acceptance proves nothing and the latency percentiles stay the assertion. The doc comment and a TODO at the outcome checks name the counter and outcome to assert at rebase. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: assert incident 2's late-confirm counter now that #324 is in the base W3c wrote the qualification tests against a base that predated #324 and left a marked place for the assertions that only make sense once the commit gate is there. The base now carries it, so apply them: incident 2 asserts `qbit_prism_late_confirmed_shares_total` is zero on both frontends and that no acknowledgement, the block-solving share included, is `ledger-outcome-unknown`. Acceptance alone is no longer proof. #324 gives a share-pass append carrying a candidate its own `block_only_ack_timeout`, so a slow solve is never refused at the share deadline; it is answered late, or answered unknown. Either would have satisfied the acceptance checks with the serialization stall still present. Also set #324's two new `Config` fields in the qualification fixture. * 3.x.x: pin a refused candidate as a definite rejection, not an unknown outcome #324 decides what a miner is told when a block-only enqueue fails: `enqueue_failed_before_commit` answers a provably uncommitted failure with `ledger-confirmation-failed`, and anything else with `ledger-outcome-unknown`, which asks an operator to go and follow the outbox row. Slice 3 added the checks that guard the reference: the block's length, its header hash, its digest against `block_sha256`, the coinbase suffix, the reference invariants, and a leased candidate's balances. All of them are raised by `prepare_candidate` before the enqueue takes a connection, so none carries an `sqlx::Error` and all classify as definite today. That is a property of where the checks sit, not something the classifier knows about them, so it is pinned here rather than left to hold by accident: a corrupt candidate must never send a miner chasing a row that was never written. Verified by mutation: classifying a non-sqlx failure as unknown fails this test. * 3.x.x: say why the full-size qualification variants cannot reach 400k yet Their ignore reasons blamed RAM and the host. The real limit is #273: the job payload still holds three copies of the window (2 x AcceptedShare + 1 x CountedShare), so publishing a job for a 400,000-share window needs about 670 MiB and PostgreSQL refuses the write above its 256 MiB jsonb object limit. Every full-size variant fails at fixture set-up, before it measures anything. The count must also divide the window weight exactly, so the largest usable size today is 125,000, where all four variants pass in release: incident 1 50 renewals, max gap 118.25 ms against a 700 ms bound incident 2 phase-A p99 2.60 ms, phase-B p99 95.79 ms, bound 250 ms lock hold median 0.75 ms at 5,000 against 1.32 ms at 125,000 canonical refresh and claim rebuild both 139,040,610 B, same sha256 The candidate document stays flat at 1103 B and 1107 B, which is the property this slice exists to establish. * 3.x.x: migrate the audit-body normalization tests to the slim candidate #267 landed its own test file against the candidate that still carried an assembled bundle. This slice replaced that with a window reference, so the file keeps a `TestCandidate` pairing the stored candidate with the bundle a test still needs, as `tests/ledger_postgres.rs` does, and attaches the claim's parts through `with_bundle`. One case needed more than a shape change. The four negative cases hand the claim a window the ledger does not hold and require the durable-range proof to be what refuses it. A candidate now commits to a snapshot digest, so a reference taken from the unaltered snapshot would be refused earlier, at the reference check, and the proof under test would never run. `window_ref_for` therefore derives each altered window's reference from that window, leaving the proof as the only thing that can notice, which is what #267 wrote them to prove. * 3.x.x: pin the durable-range proof outside the settlement lock #267 moved the full-equality proof of a candidate's window out of the settlement transaction so the lock is not held for a window-sized read. This slice made that read paged, so it does not occupy a runtime thread either. Reconciling the two is the step that can quietly undo the first: keep this slice's `persist_audit_snapshot` through the rebase and the full read goes back under the lock. The landing stays correct, every other test still passes, and only the lock hold grows, so nothing in the suite can tell. Measured at 100,000 shares on #267's branch that was a 34% longer hold. The guard is deterministic and needs no large window. A second connection holds `SETTLEMENT_LOCK`, so the landing blocks on it once its proof has run. While it waits, one share's `ntime` is altered: full equality sees that, a count over the same anchored predicate cannot. The landing must then succeed, which it can only do if it had already read and compared the shares before taking the lock. Accepted history is immutable and a trigger enforces it, so the test lifts that trigger for the single statement, inside its own disposable schema, and puts it straight back. Verified by mutation: restoring the in-transaction range read fails this test with "the landing read share payloads under the settlement lock". * 3.x.x: serialise the coordinator test modules that share the ledger's locks The ledger's advisory locks are cluster-wide constants, not schema-scoped, so two coordinator test modules running in parallel contend for ORDER_LOCK even though each works in its own throwaway schema. Every module held a lock of its own, which serialised it against itself and left cross-module waits to `lock_timeout`, 5 s by default. #324's reconciliation tests hold ORDER_LOCK for up to about 1.5 s, and this slice adds three more modules that open a ledger. Once enough of them ran at once those waits stacked past the timeout: a full `--lib` run failed with "canceling statement due to lock timeout" in `candidate_lease_tests` and `window_switch_tests`, and passed on the next run. A suite that fails for a reason unrelated to what it tests is worse than a slow one. All seven modules now take one shared lock. The run goes from about 35 s to about 62 s, and three consecutive runs pass where the flake had reproduced. * 3.x.x: add migration 007 and refuse pre-007 candidate outbox rows Migration 007 mirrors 008 onto qbit_block_candidate_outbox: the same six window-reference columns, and a three-state CHECK whose body is identical to 008's apart from the table and constraint names. It also adds block_bytes, the nullable bytea the block moves into so the candidate document stays small, and a partial index on window_prior_balances_sha256 for the balance-snapshot GC. Nothing writes any of them yet; this is additive schema only. The runner applies 007 by membership, in its own block between 5 and 8, so it assumes neither 006 nor 008 has run. Before any DDL it refuses while the outbox still holds a pending row in a pre-007 shape: a native inline candidate, a NULL candidate, or storage_version other than 1 on the 2.x.x schemas that have that column, which is checked for first so the predicate does not error on a native schema. The refusal names every offending block_hash and the drain procedure, and the whole migration transaction rolls back, so a refused start leaves the schema untouched. The applied set is now [2, 3, 4, 5, 7, 8, 9], and the four exact migration assertions move with it rather than being weakened to a superset. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: retain the cluster fingerprint configure pinned or verified The candidate enqueue and save_job must fence against a fingerprint reset by re-reading qbit_prism_cluster.config_fingerprint FOR SHARE in their own transaction and refusing a write that is not this frontend's own. That needs the value configure settled at startup, so Ledger keeps it in a shared OnceLock, set only once the pin or the match has committed, and exposes it read-only through config_fingerprint(). configure keeps its signature and its mismatch refusal, and a refused call retains nothing. The rotation refusal in configure, and the writer fence itself, belong to the enqueue change and are not here. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: share the window reference, balance writer and page primitives WindowRef::from_snapshot is the synchronous reference builder both writers need: anchor_ms copied, the semantic balances digest, and for a non-empty snapshot the first and last share_seq, the length, and the share array's SHA-256 streamed through the existing DigestWriter, so the 233 to 260 MB serialized window at 400,000 shares is never built and the digest equals the one qbit_prism_audit_snapshots already stores. An empty snapshot gives the empty-window reference. Callers run it inside their own spawn_blocking. put_balance_snapshot is the one canonical writer of qbit_prism_balance_snapshots, on the caller's transaction: the sort by (order_key, recipient_id, p2mr_program_hex), the semantic digest that keys the row, and compact JSON of the sorted set, all off the runtime, then INSERT ... ON CONFLICT DO NOTHING. On a conflict it reads the stored bytes back and compares them with its own, because these rows are immutable and can only disagree through corruption. The enqueue and save_job and its repair all write through it. read_prior_balances and the current-balance read still keep their SQL order; the writer's sort defines the stored encoding, which is the order read_window(..., AsIssued) returns. probe_share_rows and read_range_paged are read_window's endpoint probe and page loop, lifted onto a caller's connection so the enqueue probe and the landing re-read share one implementation. The predicate, the ascending keyset order, the 4096-row page bound and the per-page count bound are unchanged, and read_window now calls them, with its signature and behaviour unchanged. The paged reader takes the caller's state and a per-page consumer, both of which travel to the blocking thread with the rows, so the landing re-read can compare each page with its slice of a vector it already holds without any whole-window work on the runtime; a dropped read still releases the accumulated state on a blocking thread. read_window_with_permit holds the caller's window_reads permit across the whole read. The permit is moved into a BlockingDrop declared before the read starts, so a cancellation releases it on a blocking thread after the page state queued its own release there, and never with the future; a return releases it inline, before the caller's rebuild. WindowError::TaskFailed separates a cancelled or panicking blocking hand-off from corruption. Every hand-off maps a JoinError to it instead of to Decode, so a cancellation is a retryable failure with its own alert and never takes the abandon path. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: derive the witness merkle leaves from an assembled block A claim rebuilds from stored inputs, and the witness leaves are the one builder input that scales with the block, so they are re-derived rather than stored: one 64-hex string per transaction beside the candidate would grow the document with the block. witness_merkle_leaves_from_block skips the 80-byte header, reads the compact-size transaction count, walks past the coinbase and returns double_sha256 of every remaining transaction's full serialized bytes. That is sound because assemble_submission appends the template's transactions verbatim after the coinbase, so the result equals witness_merkle_leaves_hex(&transactions_from_template(template)) for the block built from that template, with or without segwit transactions. The segwit-aware walk is strip_witness_transaction's own, factored into a helper that also reports where the transaction ends, which is what a block walker needs; strip_witness_transaction keeps its trailing-byte check and its output. A truncated block, trailing bytes, a zero count and a count that disagrees with the transactions present are all errors, never a partial list of leaves. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: version the audit builders and key the CC5 goldens by it A stored window reference reproduces its bundle only under the builder that first built it. The schema strings do not capture that, because the share shape chooses them rather than the builder logic, so qbit-prism gains AUDIT_BUILDER_VERSION, starting at 1. A candidate and a prepared job store it, and a rebuild refuses a reference at another version instead of rebuilding it with the current builder. The bump rule is on the constant: any change that alters canonical_audit_bundle_bytes for the same inputs bumps it in the same commit. The CC5 golden test now selects its expected digests from a table keyed by the constant, and fails when no entry exists, so a new output is recorded as a new entry beside the old one and review sees both. Version 1 holds the existing literals, unchanged. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: cover 007, the fingerprint and the window primitives on PostgreSQL Ten gated database cases, all listed in test/prism-gated-tests.txt. They go in a new file rather than the shared 2.x.x support module, which another open change appends to. Migration 007: a frozen 2.x.x schema carrying only terminal outbox rows upgrades with every row and field intact and the seven new columns NULL; each of the three pre-007 pending shapes is refused by name, with nothing from 007 applied and no version 7 row, and the same binary starts once the row is drained; a database at [2, 3, 4, 5, 8, 9] applies 007 and only 007, leaving every other version's applied_at untouched; the CHECK accepts exactly the three states across all 64 null combinations and rejects a short or uppercase digest, a zero or out-of-range count and a zero sequence; and the retention index is the partial one on window_prior_balances_sha256. config_fingerprint() returns what configure pinned or verified, is shared by clones, and stays empty after a refused conf…
* 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,…
* 3.x.x: Reference the window from candidates and move the found-block write off the ordering lock (#350) * 3.x.x: add migration 007 and refuse pre-007 candidate outbox rows Migration 007 mirrors 008 onto qbit_block_candidate_outbox: the same six window-reference columns, and a three-state CHECK whose body is identical to 008's apart from the table and constraint names. It also adds block_bytes, the nullable bytea the block moves into so the candidate document stays small, and a partial index on window_prior_balances_sha256 for the balance-snapshot GC. Nothing writes any of them yet; this is additive schema only. The runner applies 007 by membership, in its own block between 5 and 8, so it assumes neither 006 nor 008 has run. Before any DDL it refuses while the outbox still holds a pending row in a pre-007 shape: a native inline candidate, a NULL candidate, or storage_version other than 1 on the 2.x.x schemas that have that column, which is checked for first so the predicate does not error on a native schema. The refusal names every offending block_hash and the drain procedure, and the whole migration transaction rolls back, so a refused start leaves the schema untouched. The applied set is now [2, 3, 4, 5, 7, 8, 9], and the four exact migration assertions move with it rather than being weakened to a superset. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: retain the cluster fingerprint configure pinned or verified The candidate enqueue and save_job must fence against a fingerprint reset by re-reading qbit_prism_cluster.config_fingerprint FOR SHARE in their own transaction and refusing a write that is not this frontend's own. That needs the value configure settled at startup, so Ledger keeps it in a shared OnceLock, set only once the pin or the match has committed, and exposes it read-only through config_fingerprint(). configure keeps its signature and its mismatch refusal, and a refused call retains nothing. The rotation refusal in configure, and the writer fence itself, belong to the enqueue change and are not here. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: share the window reference, balance writer and page primitives WindowRef::from_snapshot is the synchronous reference builder both writers need: anchor_ms copied, the semantic balances digest, and for a non-empty snapshot the first and last share_seq, the length, and the share array's SHA-256 streamed through the existing DigestWriter, so the 233 to 260 MB serialized window at 400,000 shares is never built and the digest equals the one qbit_prism_audit_snapshots already stores. An empty snapshot gives the empty-window reference. Callers run it inside their own spawn_blocking. put_balance_snapshot is the one canonical writer of qbit_prism_balance_snapshots, on the caller's transaction: the sort by (order_key, recipient_id, p2mr_program_hex), the semantic digest that keys the row, and compact JSON of the sorted set, all off the runtime, then INSERT ... ON CONFLICT DO NOTHING. On a conflict it reads the stored bytes back and compares them with its own, because these rows are immutable and can only disagree through corruption. The enqueue and save_job and its repair all write through it. read_prior_balances and the current-balance read still keep their SQL order; the writer's sort defines the stored encoding, which is the order read_window(..., AsIssued) returns. probe_share_rows and read_range_paged are read_window's endpoint probe and page loop, lifted onto a caller's connection so the enqueue probe and the landing re-read share one implementation. The predicate, the ascending keyset order, the 4096-row page bound and the per-page count bound are unchanged, and read_window now calls them, with its signature and behaviour unchanged. The paged reader takes the caller's state and a per-page consumer, both of which travel to the blocking thread with the rows, so the landing re-read can compare each page with its slice of a vector it already holds without any whole-window work on the runtime; a dropped read still releases the accumulated state on a blocking thread. read_window_with_permit holds the caller's window_reads permit across the whole read. The permit is moved into a BlockingDrop declared before the read starts, so a cancellation releases it on a blocking thread after the page state queued its own release there, and never with the future; a return releases it inline, before the caller's rebuild. WindowError::TaskFailed separates a cancelled or panicking blocking hand-off from corruption. Every hand-off maps a JoinError to it instead of to Decode, so a cancellation is a retryable failure with its own alert and never takes the abandon path. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: derive the witness merkle leaves from an assembled block A claim rebuilds from stored inputs, and the witness leaves are the one builder input that scales with the block, so they are re-derived rather than stored: one 64-hex string per transaction beside the candidate would grow the document with the block. witness_merkle_leaves_from_block skips the 80-byte header, reads the compact-size transaction count, walks past the coinbase and returns double_sha256 of every remaining transaction's full serialized bytes. That is sound because assemble_submission appends the template's transactions verbatim after the coinbase, so the result equals witness_merkle_leaves_hex(&transactions_from_template(template)) for the block built from that template, with or without segwit transactions. The segwit-aware walk is strip_witness_transaction's own, factored into a helper that also reports where the transaction ends, which is what a block walker needs; strip_witness_transaction keeps its trailing-byte check and its output. A truncated block, trailing bytes, a zero count and a count that disagrees with the transactions present are all errors, never a partial list of leaves. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: version the audit builders and key the CC5 goldens by it A stored window reference reproduces its bundle only under the builder that first built it. The schema strings do not capture that, because the share shape chooses them rather than the builder logic, so qbit-prism gains AUDIT_BUILDER_VERSION, starting at 1. A candidate and a prepared job store it, and a rebuild refuses a reference at another version instead of rebuilding it with the current builder. The bump rule is on the constant: any change that alters canonical_audit_bundle_bytes for the same inputs bumps it in the same commit. The CC5 golden test now selects its expected digests from a table keyed by the constant, and fails when no entry exists, so a new output is recorded as a new entry beside the old one and review sees both. Version 1 holds the existing literals, unchanged. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: cover 007, the fingerprint and the window primitives on PostgreSQL Ten gated database cases, all listed in test/prism-gated-tests.txt. They go in a new file rather than the shared 2.x.x support module, which another open change appends to. Migration 007: a frozen 2.x.x schema carrying only terminal outbox rows upgrades with every row and field intact and the seven new columns NULL; each of the three pre-007 pending shapes is refused by name, with nothing from 007 applied and no version 7 row, and the same binary starts once the row is drained; a database at [2, 3, 4, 5, 8, 9] applies 007 and only 007, leaving every other version's applied_at untouched; the CHECK accepts exactly the three states across all 64 null combinations and rejects a short or uppercase digest, a zero or out-of-range count and a zero sequence; and the retention index is the partial one on window_prior_balances_sha256. config_fingerprint() returns what configure pinned or verified, is shared by clones, and stays empty after a refused configure. from_snapshot's streamed digest equals sha256(serde_json::to_vec) and the snapshot_sha256 landing writes for the same window. The balance writer stores the canonical sort, is idempotent under any permutation, errors rather than accepting a different encoding of the same digest, and read_window(..., AsIssued) hands back the stored order. The probe misses a missing endpoint, the paged reader compares 4,999 rows page by page with a vector held inside the caller's transaction, and a row the predicate skips inside a range is Incomplete with no partial window. The permit case builds a runtime with one blocking thread, occupies it, and cancels a reader parked mid-page on a database gate: no permit is available while the cleanup is queued, and one is once it has run. A failed blocking hand-off surfaces as TaskFailed, never as Decode. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: carry the window reference on prepared work, behind a read permit `Prepared` gains `window: WindowRef`, computed once per non-cached refresh beside `build_bundle` under `tokio::join!`, so submit can clone it instead of re-digesting the window on the share path when a block is found. An empty snapshot gets the empty-window reference on the runtime thread; a resume computes it inside the blocking decode it already runs. `Coordinator` gains the `window_reads` semaphore, sized `clamp(database_max_connections - 2, 1, build_workers)`, and the one entry point callers use: it takes an owned permit after the caller's `build_slots` permit and hands it to `Ledger::read_window_with_permit`, which holds it across the whole read, including the off-runtime cleanup a cancellation leaves behind, and releases it before the rebuild. `Ledger::read_window` is awaited on the runtime, never wrapped in `spawn_blocking`; the test with a single blocking thread pins that. The four gated `window_ref_tests` are listed in the manifest. Part of #265 Co-Authored-By: Claude Fable 5.1 <[email protected]> * 3.x.x: switch the candidate outbox to the window reference `Candidate` drops the embedded `AuditBundle` for `window: WindowRef` and every builder input except the window: `found_block`, `payout_policy`, the nested `ctv` triple (whose presence selects the CTV builder), the stored `bootstrap_share` of an empty window, `audit_builder_version`, `signer_keys`, a `leased` flag and the now-required `coinbase_suffix_hex`. The block leaves the document for the `block_bytes` column, authenticated by `block_sha256`, which `candidate_sha256` covers. The write serializes, digests and checks the candidate before the append or enqueue transaction opens; under `ORDER_LOCK` the transaction re-reads `config_fingerprint FOR SHARE` and refuses a value the writer did not pin, re-inserts a `leased` candidate's as-issued balance snapshot through the shared writer, probes the window's first row (an absent row alerts and still publishes), and inserts only the prepared bytes with the six typed columns. Submit builds the slim candidate from `Prepared.window`, the `BundleInputs` captured where `build_bundle` read configuration, and the job's own bootstrap share; it clones no bundle and reads no config. The claim's `UPDATE … RETURNING` returns the columns and the block, and the decode, off the runtime, checks the document against them, the digest, `sha256(block_bytes)`, the header hash, the required fields and the two reference invariants. A pending row with a NULL anchor is a hard error naming the pre-007 frontend; an inline document is never decoded. Before any read the claim retries, with an alert naming both values, a stored builder version or signer pair that is not this binary's; a landed audit is authenticated against the block (coinbase, audit root as the witness reserved value, share snapshot, bits) and the claim then skips the rebuild and landing and continues to observe, renew and submit. Otherwise it takes `build_slots`, then `window_reads` inside one 60 s deadline around the awaited `read_window(Current)` and the borrowing builder run directly in `spawn_blocking`, and keeps `Arc<AuditBundleBody>` and the shares as `ClaimParts`. `Incomplete`, `SnapshotDigestMismatch`, `Decode`, `BalanceSnapshotMissing`, `TaskFailed` and the deadline retry with their own alerts; `PriorBalancesChanged` finishes only a block `observe_candidate` proves inactive and superseded; `Database` propagates. A `leased` candidate submits from `block_bytes` first, then rebuilds `AsIssued` and lands before any terminal outcome. Rebuilt parts are released off the runtime on every path. Landing takes the parts and does all whole-window work in one blocking closure: `verify_audit_parts`, the raw body, the counted canonical bytes, the leaves and accounts, and the share snapshot digest, which must equal the reference's. The balance fence compares the current set and the parts' through the semantic digest, so an as-issued set compares equal in any order. `persist_audit_snapshot` re-reads the range with the paged reader inside the landing transaction, page against slice on the blocking thread; `read_range` stays for the API. The terminal UPDATE NULLs the six window columns and `block_bytes` with `candidate`. `configure` refuses to pin a fingerprint onto a reset one while a pending row stores other signer keys, and the startup gate requires 007 with 009. The JSONB gate drops its enqueue entry, and every helper that built a candidate builds the slim one, handing the ledger-level landings the bundle's parts through `CandidateClaim::with_bundle`. Part of #265 Co-Authored-By: Claude Fable 5.1 <[email protected]> * 3.x.x: cover the candidate switch on PostgreSQL Ledger-level, in `candidate_window_switch`: a two-page window enqueues a document with no array and no share row, under 1 MB, whose six typed columns equal its reference and whose block is stored as bytes; the writer fence refuses a reset or different fingerprint in the same transaction, share included; a missing window prefix row alerts and still publishes, and its read then meets `Incomplete`; a `leased` enqueue re-inserts the as-issued balance snapshot in the writer's canonical order, writes none when not leased, and refuses balances that do not hash to the reference; every preparation failure is refused without waiting for `ORDER_LOCK`; every column, digest, block, header, NULL-anchor, missing-field, invariant and inline-document disagreement is refused at claim; landing refuses parts that are not the referenced window and a claim without parts; the terminal UPDATE NULLs the six columns and the block for submitted and abandoned rows; the landed-audit authentication rejects a forged coinbase, root, snapshot or bits; and `configure` refuses a rotation over a foreign-signed pending candidate. Coordinator-level, in `window_switch_tests` behind a fake node: a stored builder version or signer pair that is not this binary's retries, naming both values, while the build slot is held; a landed audit is authenticated and the claim continues to `submitblock` without a build slot, and a forged landed coinbase or root is refused with the row left pending; `Incomplete`, a digest mismatch, changed balances on a current block and the rebuild deadline all retry with an alert and release their permits; `classify_window_error` keeps `TaskFailed` apart from corruption and propagates `Database`; the read, rebuild and landing complete while `ORDER_LOCK` is held, with one build worker; a `leased` candidate submits first, then lands from `AsIssued`, and finishes submitted, abandoned with the node's reason, or pending when its balance snapshot is missing; and `OffRuntime` releases on a blocking thread, on cancellation too. The fifteen gated tests are listed in the manifest. Part of #265 Co-Authored-By: Claude Fable 5.1 <[email protected]> * 3.x.x: migrate the imported-audit tests to the slim candidate Slice 1 (#325) merged after this stack branched, and its tests in tests/support/ledger_2x.rs still built the pre-007 candidate: they read block.bundle from a Candidate and called candidate_with_bundle without a window reference or settlement inputs. The rebase merged them cleanly and the tree then failed to compile. The three helpers now take the TestCandidate the constructors return, so they reach the bundle beside the slim candidate, and land_confirmed attaches the claim's parts the way the other ledger tests do. The three constructor calls pass the window reference the bundle was built on, and the settlement inputs for the CTV case. No assertion changes. Part of #265. * 3.x.x: qualify lease renewal and the claim's canonical bytes at scale Incident 1: a candidate whose window holds N shares is claimed and processed under the short lease, and every renewal is read back from claim_expires_at. The largest gap stays below interval + 2 x timeout, the lease never lapses, and a successor ledger cannot take the claim. The bundle a claim rebuilds through the window-read entry point and the borrowing builder has the canonical bytes refresh built for the same job, and the landed audit carries that bundle's digest. Both run at PRISM_WINDOW_QUALIFY_SHARES (20,000 by default); the 400,000-share variants are ignored and run on a larger host. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: measure ACK latency and ORDER_LOCK hold across window sizes Incident 2: two frontends on one database submit ordinary shares at a fixed rate while one of them solves a block on an N-share window and its own submit loop claims, rebuilds, lands and submits it. The solving share's ACK and the bystander's p99 stay within max(2 x baseline p99 + 50 ms, 250 ms), every ACK is well under the share-commit timeout, and the block is enqueued exactly once. Latency is the in-process MiningBackend::submit wall clock; the socket-level harness (#271) does not exist yet. A pg_locks sampler on its own connection measures how long a solving append holds ORDER_LOCK at two window sizes with no other traffic: the larger size stays within a fixed slack of the smaller, and the candidate document is the same size at both and under 1 MiB. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: hold the JSONB gate's enqueue to a window-free row under 1 MiB At every measured size the enqueue must be accepted and every JSONB value it writes, the outbox candidate document included, must stay under 1,048,576 bytes. At the reduced sizes the enqueue, claim and landing phases must all run. The ratchet and its expected values are unchanged. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: make the window-read permit test actually wait before it looks The delay that gives an unpermitted read time to finish was an empty async block, so the check that the read had not finished ran at once and passed whether or not the entry point took a permit. It now sleeps 500 ms inside a 5 s bound, and fails when the permit acquisition is removed from the entry point. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: rebuild a CTV candidate from its stored settlement inputs No host-runnable test reached the CTV branch of the claim rebuild. A CTV-enabled frontend now claims a candidate whose stored direct floor differs from its configuration, and builds a different coinbase than the configured floor would, and the claim must land that candidate's own audit and submit it. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: pin the SQL order of the current-balance reads Nothing defended the ruling that the current-balance path keeps its SQL order: every fixture's balances already arrived in byte-wise canonical order. The carry table's text columns now take an ICU collation, under which the SQL order and the canonical sort disagree, and the snapshot and the current-balance window read must both return the SQL order. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: record what incident 2 must also assert once #324 is in the base After #324 a slow solve is acknowledged late rather than refused, so acceptance proves nothing and the latency percentiles stay the assertion. The doc comment and a TODO at the outcome checks name the counter and outcome to assert at rebase. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: assert incident 2's late-confirm counter now that #324 is in the base W3c wrote the qualification tests against a base that predated #324 and left a marked place for the assertions that only make sense once the commit gate is there. The base now carries it, so apply them: incident 2 asserts `qbit_prism_late_confirmed_shares_total` is zero on both frontends and that no acknowledgement, the block-solving share included, is `ledger-outcome-unknown`. Acceptance alone is no longer proof. #324 gives a share-pass append carrying a candidate its own `block_only_ack_timeout`, so a slow solve is never refused at the share deadline; it is answered late, or answered unknown. Either would have satisfied the acceptance checks with the serialization stall still present. Also set #324's two new `Config` fields in the qualification fixture. * 3.x.x: pin a refused candidate as a definite rejection, not an unknown outcome #324 decides what a miner is told when a block-only enqueue fails: `enqueue_failed_before_commit` answers a provably uncommitted failure with `ledger-confirmation-failed`, and anything else with `ledger-outcome-unknown`, which asks an operator to go and follow the outbox row. Slice 3 added the checks that guard the reference: the block's length, its header hash, its digest against `block_sha256`, the coinbase suffix, the reference invariants, and a leased candidate's balances. All of them are raised by `prepare_candidate` before the enqueue takes a connection, so none carries an `sqlx::Error` and all classify as definite today. That is a property of where the checks sit, not something the classifier knows about them, so it is pinned here rather than left to hold by accident: a corrupt candidate must never send a miner chasing a row that was never written. Verified by mutation: classifying a non-sqlx failure as unknown fails this test. * 3.x.x: say why the full-size qualification variants cannot reach 400k yet Their ignore reasons blamed RAM and the host. The real limit is #273: the job payload still holds three copies of the window (2 x AcceptedShare + 1 x CountedShare), so publishing a job for a 400,000-share window needs about 670 MiB and PostgreSQL refuses the write above its 256 MiB jsonb object limit. Every full-size variant fails at fixture set-up, before it measures anything. The count must also divide the window weight exactly, so the largest usable size today is 125,000, where all four variants pass in release: incident 1 50 renewals, max gap 118.25 ms against a 700 ms bound incident 2 phase-A p99 2.60 ms, phase-B p99 95.79 ms, bound 250 ms lock hold median 0.75 ms at 5,000 against 1.32 ms at 125,000 canonical refresh and claim rebuild both 139,040,610 B, same sha256 The candidate document stays flat at 1103 B and 1107 B, which is the property this slice exists to establish. * 3.x.x: migrate the audit-body normalization tests to the slim candidate #267 landed its own test file against the candidate that still carried an assembled bundle. This slice replaced that with a window reference, so the file keeps a `TestCandidate` pairing the stored candidate with the bundle a test still needs, as `tests/ledger_postgres.rs` does, and attaches the claim's parts through `with_bundle`. One case needed more than a shape change. The four negative cases hand the claim a window the ledger does not hold and require the durable-range proof to be what refuses it. A candidate now commits to a snapshot digest, so a reference taken from the unaltered snapshot would be refused earlier, at the reference check, and the proof under test would never run. `window_ref_for` therefore derives each altered window's reference from that window, leaving the proof as the only thing that can notice, which is what #267 wrote them to prove. * 3.x.x: pin the durable-range proof outside the settlement lock #267 moved the full-equality proof of a candidate's window out of the settlement transaction so the lock is not held for a window-sized read. This slice made that read paged, so it does not occupy a runtime thread either. Reconciling the two is the step that can quietly undo the first: keep this slice's `persist_audit_snapshot` through the rebase and the full read goes back under the lock. The landing stays correct, every other test still passes, and only the lock hold grows, so nothing in the suite can tell. Measured at 100,000 shares on #267's branch that was a 34% longer hold. The guard is deterministic and needs no large window. A second connection holds `SETTLEMENT_LOCK`, so the landing blocks on it once its proof has run. While it waits, one share's `ntime` is altered: full equality sees that, a count over the same anchored predicate cannot. The landing must then succeed, which it can only do if it had already read and compared the shares before taking the lock. Accepted history is immutable and a trigger enforces it, so the test lifts that trigger for the single statement, inside its own disposable schema, and puts it straight back. Verified by mutation: restoring the in-transaction range read fails this test with "the landing read share payloads under the settlement lock". * 3.x.x: serialise the coordinator test modules that share the ledger's locks The ledger's advisory locks are cluster-wide constants, not schema-scoped, so two coordinator test modules running in parallel contend for ORDER_LOCK even though each works in its own throwaway schema. Every module held a lock of its own, which serialised it against itself and left cross-module waits to `lock_timeout`, 5 s by default. #324's reconciliation tests hold ORDER_LOCK for up to about 1.5 s, and this slice adds three more modules that open a ledger. Once enough of them ran at once those waits stacked past the timeout: a full `--lib` run failed with "canceling statement due to lock timeout" in `candidate_lease_tests` and `window_switch_tests`, and passed on the next run. A suite that fails for a reason unrelated to what it tests is worse than a slow one. All seven modules now take one shared lock. The run goes from about 35 s to about 62 s, and three consecutive runs pass where the flake had reproduced. * 3.x.x: pass the signer keys #334's wait-metrics tests now need `Ledger::configure` takes the frontend's signing keys since this slice, so the fingerprint contention tests #334 added call it with a fixed pair. That suite measures advisory-lock and pool-acquire waits, not signing, so the only thing the keys have to be is the same on every call. * 3.x.x: resume a job's bundle only while the current inputs still describe it A resumed job reuses the bundle it was issued with, but captures its inputs from this frontend's configuration now. Before this slice that was harmless: the candidate carried the assembled bundle, and landing used it directly. Now the candidate stores the inputs and the claim rebuilds the audit from them, so an old bundle labelled with today's configuration rebuilds to a coinbase the block does not commit to. The claim fails its comparison before `submitblock` and retries until the job expires, which can lose a found block. The stored bundle is now reused only when the captured inputs still describe it, comparing what the bundle itself records about how it was built: the payout policy, and the public keys that actually signed its coinbase manifest and its ledger attestation. A difference is a cache miss, so the bundle is rebuilt rather than mislabelled. Both directions are covered, since over-tightening would silently defeat the job cache and rebuild on every resume: unchanged inputs must still describe the bundle, and a payout-policy change, a full signer rotation and a rotation of either key alone must each refuse it. Known residue, recorded in the doc comment: a bundle records neither the CTV settlement inputs nor `audit_builder_version`, so a change to either between issue and resume is still undetectable here. Closing that needs the issued job to store its inputs, which is #273's format. * 3.x.x: migrate #355's ledger tests to the slim candidate #355 landed deadline and single-execution coverage against the candidate that still carried an assembled bundle, and against `configure` before it took the frontend's signing keys. Adapted, the same way #325's and #267's suites were: a `TestCandidate` pairs the stored candidate with the bundle a landing still needs, claims attach their parts through `with_bundle`, and the conflicting claim that is never landed carries none. `ledger_deadline_atomicity` builds its candidate from a bundle rather than a snapshot, so its window reference is derived from that bundle: the anchor and prior-balances digest it already records, and the range and digest of the shares it carries. Its signer keys come from the public keys that actually signed it, rather than from a local pair, so the stored inputs describe the bundle. * 3.x.x: make the landed-audit forgery always alter the row, and migrate #360's fixture The forged-coinbase case placed a literal '0' at a fixed offset. Whenever the digit already held that value the forgery changed nothing, so the claim was right to accept it and the case failed only by luck. The coinbase varies per run, because the bundle's anchor comes from the ledger clock, so this passed repeatedly and then failed once as "the forgery was accepted" — an alarming message for a case that was in fact a no-op. A security check that can quietly become vacuous is worse than one that is absent. The digit is now flipped to a value it does not currently hold, and the row is read back either side of the statement so a forgery that altered nothing fails the case for that reason instead. Also passes the signer keys #360's `tests/support/fatal_state.rs` now needs, since `configure` takes them in this slice. * 3.x.x: drop the pre-#362 path for the heartbeat SQL gated test #362 moved `live_instance_tests` from `tools` to `ledger::instances`. Merging the gated-test manifest during the rebase kept both paths, because a rename upstream looks like one id removed and another added, and a union keeps the removed one. The old `tools::` path then never executed and the gate refused the run: "194 distinct gated tests executed, below the minimum of 195". The manifest is a superset of the base's ids, and every id this branch adds over the base resolves to a test function that exists in the tree. * v3.0.0 feat: add compact prepared storage and immutable template blobs (#359) * 3.x.x: add migration 007 and refuse pre-007 candidate outbox rows Migration 007 mirrors 008 onto qbit_block_candidate_outbox: the same six window-reference columns, and a three-state CHECK whose body is identical to 008's apart from the table and constraint names. It also adds block_bytes, the nullable bytea the block moves into so the candidate document stays small, and a partial index on window_prior_balances_sha256 for the balance-snapshot GC. Nothing writes any of them yet; this is additive schema only. The runner applies 007 by membership, in its own block between 5 and 8, so it assumes neither 006 nor 008 has run. Before any DDL it refuses while the outbox still holds a pending row in a pre-007 shape: a native inline candidate, a NULL candidate, or storage_version other than 1 on the 2.x.x schemas that have that column, which is checked for first so the predicate does not error on a native schema. The refusal names every offending block_hash and the drain procedure, and the whole migration transaction rolls back, so a refused start leaves the schema untouched. The applied set is now [2, 3, 4, 5, 7, 8, 9], and the four exact migration assertions move with it rather than being weakened to a superset. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: retain the cluster fingerprint configure pinned or verified The candidate enqueue and save_job must fence against a fingerprint reset by re-reading qbit_prism_cluster.config_fingerprint FOR SHARE in their own transaction and refusing a write that is not this frontend's own. That needs the value configure settled at startup, so Ledger keeps it in a shared OnceLock, set only once the pin or the match has committed, and exposes it read-only through config_fingerprint(). configure keeps its signature and its mismatch refusal, and a refused call retains nothing. The rotation refusal in configure, and the writer fence itself, belong to the enqueue change and are not here. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: share the window reference, balance writer and page primitives WindowRef::from_snapshot is the synchronous reference builder both writers need: anchor_ms copied, the semantic balances digest, and for a non-empty snapshot the first and last share_seq, the length, and the share array's SHA-256 streamed through the existing DigestWriter, so the 233 to 260 MB serialized window at 400,000 shares is never built and the digest equals the one qbit_prism_audit_snapshots already stores. An empty snapshot gives the empty-window reference. Callers run it inside their own spawn_blocking. put_balance_snapshot is the one canonical writer of qbit_prism_balance_snapshots, on the caller's transaction: the sort by (order_key, recipient_id, p2mr_program_hex), the semantic digest that keys the row, and compact JSON of the sorted set, all off the runtime, then INSERT ... ON CONFLICT DO NOTHING. On a conflict it reads the stored bytes back and compares them with its own, because these rows are immutable and can only disagree through corruption. The enqueue and save_job and its repair all write through it. read_prior_balances and the current-balance read still keep their SQL order; the writer's sort defines the stored encoding, which is the order read_window(..., AsIssued) returns. probe_share_rows and read_range_paged are read_window's endpoint probe and page loop, lifted onto a caller's connection so the enqueue probe and the landing re-read share one implementation. The predicate, the ascending keyset order, the 4096-row page bound and the per-page count bound are unchanged, and read_window now calls them, with its signature and behaviour unchanged. The paged reader takes the caller's state and a per-page consumer, both of which travel to the blocking thread with the rows, so the landing re-read can compare each page with its slice of a vector it already holds without any whole-window work on the runtime; a dropped read still releases the accumulated state on a blocking thread. read_window_with_permit holds the caller's window_reads permit across the whole read. The permit is moved into a BlockingDrop declared before the read starts, so a cancellation releases it on a blocking thread after the page state queued its own release there, and never with the future; a return releases it inline, before the caller's rebuild. WindowError::TaskFailed separates a cancelled or panicking blocking hand-off from corruption. Every hand-off maps a JoinError to it instead of to Decode, so a cancellation is a retryable failure with its own alert and never takes the abandon path. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: derive the witness merkle leaves from an assembled block A claim rebuilds from stored inputs, and the witness leaves are the one builder input that scales with the block, so they are re-derived rather than stored: one 64-hex string per transaction beside the candidate would grow the document with the block. witness_merkle_leaves_from_block skips the 80-byte header, reads the compact-size transaction count, walks past the coinbase and returns double_sha256 of every remaining transaction's full serialized bytes. That is sound because assemble_submission appends the template's transactions verbatim after the coinbase, so the result equals witness_merkle_leaves_hex(&transactions_from_template(template)) for the block built from that template, with or without segwit transactions. The segwit-aware walk is strip_witness_transaction's own, factored into a helper that also reports where the transaction ends, which is what a block walker needs; strip_witness_transaction keeps its trailing-byte check and its output. A truncated block, trailing bytes, a zero count and a count that disagrees with the transactions present are all errors, never a partial list of leaves. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: version the audit builders and key the CC5 goldens by it A stored window reference reproduces its bundle only under the builder that first built it. The schema strings do not capture that, because the share shape chooses them rather than the builder logic, so qbit-prism gains AUDIT_BUILDER_VERSION, starting at 1. A candidate and a prepared job store it, and a rebuild refuses a reference at another version instead of rebuilding it with the current builder. The bump rule is on the constant: any change that alters canonical_audit_bundle_bytes for the same inputs bumps it in the same commit. The CC5 golden test now selects its expected digests from a table keyed by the constant, and fails when no entry exists, so a new output is recorded as a new entry beside the old one and review sees both. Version 1 holds the existing literals, unchanged. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: cover 007, the fingerprint and the window primitives on PostgreSQL Ten gated database cases, all listed in test/prism-gated-tests.txt. They go in a new file rather than the shared 2.x.x support module, which another open change appends to. Migration 007: a frozen 2.x.x schema carrying only terminal outbox rows upgrades with every row and field intact and the seven new columns NULL; each of the three pre-007 pending shapes is refused by name, with nothing from 007 applied and no version 7 row, and the same binary starts once the row is drained; a database at [2, 3, 4, 5, 8, 9] applies 007 and only 007, leaving every other version's applied_at untouched; the CHECK accepts exactly the three states across all 64 null combinations and rejects a short or uppercase digest, a zero or out-of-range count and a zero sequence; and the retention index is the partial one on window_prior_balances_sha256. config_fingerprint() returns what configure pinned or verified, is shared by clones, and stays empty after a refused configure. from_snapshot's streamed digest equals sha256(serde_json::to_vec) and the snapshot_sha256 landing writes for the same window. The balance writer stores the canonical sort, is idempotent under any permutation, errors rather than accepting a different encoding of the same digest, and read_window(..., AsIssued) hands back the stored order. The probe misses a missing endpoint, the paged reader compares 4,999 rows page by page with a vector held inside the caller's transaction, and a row the predicate skips inside a range is Incomplete with no partial window. The permit case builds a runtime with one blocking thread, occupies it, and cancels a reader parked mid-page on a database gate: no permit is available while the cleanup is queued, and one is once it has run. A failed blocking hand-off surfaces as TaskFailed, never as Decode. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: carry the window reference on prepared work, behind a read permit `Prepared` gains `window: WindowRef`, computed once per non-cached refresh beside `build_bundle` under `tokio::join!`, so submit can clone it instead of re-digesting the window on the share path when a block is found. An empty snapshot gets the empty-window reference on the runtime thread; a resume computes it inside the blocking decode it already runs. `Coordinator` gains the `window_reads` semaphore, sized `clamp(database_max_connections - 2, 1, build_workers)`, and the one entry point callers use: it takes an owned permit after the caller's `build_slots` permit and hands it to `Ledger::read_window_with_permit`, which holds it across the whole read, including the off-runtime cleanup a cancellation leaves behind, and releases it before the rebuild. `Ledger::read_window` is awaited on the runtime, never wrapped in `spawn_blocking`; the test with a single blocking thread pins that. The four gated `window_ref_tests` are listed in the manifest. Part of #265 Co-Authored-By: Claude Fable 5.1 <[email protected]> * 3.x.x: switch the candidate outbox to the window reference `Candidate` drops the embedded `AuditBundle` for `window: WindowRef` and every builder input except the window: `found_block`, `payout_policy`, the nested `ctv` triple (whose presence selects the CTV builder), the stored `bootstrap_share` of an empty window, `audit_builder_version`, `signer_keys`, a `leased` flag and the now-required `coinbase_suffix_hex`. The block leaves the document for the `block_bytes` column, authenticated by `block_sha256`, which `candidate_sha256` covers. The write serializes, digests and checks the candidate before the append or enqueue transaction opens; under `ORDER_LOCK` the transaction re-reads `config_fingerprint FOR SHARE` and refuses a value the writer did not pin, re-inserts a `leased` candidate's as-issued balance snapshot through the shared writer, probes the window's first row (an absent row alerts and still publishes), and inserts only the prepared bytes with the six typed columns. Submit builds the slim candidate from `Prepared.window`, the `BundleInputs` captured where `build_bundle` read configuration, and the job's own bootstrap share; it clones no bundle and reads no config. The claim's `UPDATE … RETURNING` returns the columns and the block, and the decode, off the runtime, checks the document against them, the digest, `sha256(block_bytes)`, the header hash, the required fields and the two reference invariants. A pending row with a NULL anchor is a hard error naming the pre-007 frontend; an inline document is never decoded. Before any read the claim retries, with an alert naming both values, a stored builder version or signer pair that is not this binary's; a landed audit is authenticated against the block (coinbase, audit root as the witness reserved value, share snapshot, bits) and the claim then skips the rebuild and landing and continues to observe, renew and submit. Otherwise it takes `build_slots`, then `window_reads` inside one 60 s deadline around the awaited `read_window(Current)` and the borrowing builder run directly in `spawn_blocking`, and keeps `Arc<AuditBundleBody>` and the shares as `ClaimParts`. `Incomplete`, `SnapshotDigestMismatch`, `Decode`, `BalanceSnapshotMissing`, `TaskFailed` and the deadline retry with their own alerts; `PriorBalancesChanged` finishes only a block `observe_candidate` proves inactive and superseded; `Database` propagates. A `leased` candidate submits from `block_bytes` first, then rebuilds `AsIssued` and lands before any terminal outcome. Rebuilt parts are released off the runtime on every path. Landing takes the parts and does all whole-window work in one blocking closure: `verify_audit_parts`, the raw body, the counted canonical bytes, the leaves and accounts, and the share snapshot digest, which must equal the reference's. The balance fence compares the current set and the parts' through the semantic digest, so an as-issued set compares equal in any order. `persist_audit_snapshot` re-reads the range with the paged reader inside the landing transaction, page against slice on the blocking thread; `read_range` stays for the API. The terminal UPDATE NULLs the six window columns and `block_bytes` with `candidate`. `configure` refuses to pin a fingerprint onto a reset one while a pending row stores other signer keys, and the startup gate requires 007 with 009. The JSONB gate drops its enqueue entry, and every helper that built a candidate builds the slim one, handing the ledger-level landings the bundle's parts through `CandidateClaim::with_bundle`. Part of #265 Co-Authored-By: Claude Fable 5.1 <[email protected]> * 3.x.x: cover the candidate switch on PostgreSQL Ledger-level, in `candidate_window_switch`: a two-page window enqueues a document with no array and no share row, under 1 MB, whose six typed columns equal its reference and whose block is stored as bytes; the writer fence refuses a reset or different fingerprint in the same transaction, share included; a missing window prefix row alerts and still publishes, and its read then meets `Incomplete`; a `leased` enqueue re-inserts the as-issued balance snapshot in the writer's canonical order, writes none when not leased, and refuses balances that do not hash to the reference; every preparation failure is refused without waiting for `ORDER_LOCK`; every column, digest, block, header, NULL-anchor, missing-field, invariant and inline-document disagreement is refused at claim; landing refuses parts that are not the referenced window and a claim without parts; the terminal UPDATE NULLs the six columns and the block for submitted and abandoned rows; the landed-audit authentication rejects a forged coinbase, root, snapshot or bits; and `configure` refuses a rotation over a foreign-signed pending candidate. Coordinator-level, in `window_switch_tests` behind a fake node: a stored builder version or signer pair that is not this binary's retries, naming both values, while the build slot is held; a landed audit is authenticated and the claim continues to `submitblock` without a build slot, and a forged landed coinbase or root is refused with the row left pending; `Incomplete`, a digest mismatch, changed balances on a current block and the rebuild deadline all retry with an alert and release their permits; `classify_window_error` keeps `TaskFailed` apart from corruption and propagates `Database`; the read, rebuild and landing complete while `ORDER_LOCK` is held, with one build worker; a `leased` candidate submits first, then lands from `AsIssued`, and finishes submitted, abandoned with the node's reason, or pending when its balance snapshot is missing; and `OffRuntime` releases on a blocking thread, on cancellation too. The fifteen gated tests are listed in the manifest. Part of #265 Co-Authored-By: Claude Fable 5.1 <[email protected]> * 3.x.x: migrate the imported-audit tests to the slim candidate Slice 1 (#325) merged after this stack branched, and its tests in tests/support/ledger_2x.rs still built the pre-007 candidate: they read block.bundle from a Candidate and called candidate_with_bundle without a window reference or settlement inputs. The rebase merged them cleanly and the tree then failed to compile. The three helpers now take the TestCandidate the constructors return, so they reach the bundle beside the slim candidate, and land_confirmed attaches the claim's parts the way the other ledger tests do. The three constructor calls pass the window reference the bundle was built on, and the settlement inputs for the CTV case. No assertion changes. Part of #265. * 3.x.x: qualify lease renewal and the claim's canonical bytes at scale Incident 1: a candidate whose window holds N shares is claimed and processed under the short lease, and every renewal is read back from claim_expires_at. The largest gap stays below interval + 2 x timeout, the lease never lapses, and a successor ledger cannot take the claim. The bundle a claim rebuilds through the window-read entry point and the borrowing builder has the canonical bytes refresh built for the same job, and the landed audit carries that bundle's digest. Both run at PRISM_WINDOW_QUALIFY_SHARES (20,000 by default); the 400,000-share variants are ignored and run on a larger host. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: measure ACK latency and ORDER_LOCK hold across window sizes Incident 2: two frontends on one database submit ordinary shares at a fixed rate while one of them solves a block on an N-share window and its own submit loop claims, rebuilds, lands and submits it. The solving share's ACK and the bystander's p99 stay within max(2 x baseline p99 + 50 ms, 250 ms), every ACK is well under the share-commit timeout, and the block is enqueued exactly once. Latency is the in-process MiningBackend::submit wall clock; the socket-level harness (#271) does not exist yet. A pg_locks sampler on its own connection measures how long a solving append holds ORDER_LOCK at two window sizes with no other traffic: the larger size stays within a fixed slack of the smaller, and the candidate document is the same size at both and under 1 MiB. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: hold the JSONB gate's enqueue to a window-free row under 1 MiB At every measured size the enqueue must be accepted and every JSONB value it writes, the outbox candidate document included, must stay under 1,048,576 bytes. At the reduced sizes the enqueue, claim and landing phases must all run. The ratchet and its expected values are unchanged. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: make the window-read permit test actually wait before it looks The delay that gives an unpermitted read time to finish was an empty async block, so the check that the read had not finished ran at once and passed whether or not the entry point took a permit. It now sleeps 500 ms inside a 5 s bound, and fails when the permit acquisition is removed from the entry point. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: rebuild a CTV candidate from its stored settlement inputs No host-runnable test reached the CTV branch of the claim rebuild. A CTV-enabled frontend now claims a candidate whose stored direct floor differs from its configuration, and builds a different coinbase than the configured floor would, and the claim must land that candidate's own audit and submit it. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: pin the SQL order of the current-balance reads Nothing defended the ruling that the current-balance path keeps its SQL order: every fixture's balances already arrived in byte-wise canonical order. The carry table's text columns now take an ICU collation, under which the SQL order and the canonical sort disagree, and the snapshot and the current-balance window read must both return the SQL order. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: record what incident 2 must also assert once #324 is in the base After #324 a slow solve is acknowledged late rather than refused, so acceptance proves nothing and the latency percentiles stay the assertion. The doc comment and a TODO at the outcome checks name the counter and outcome to assert at rebase. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: assert incident 2's late-confirm counter now that #324 is in the base W3c wrote the qualification tests against a base that predated #324 and left a marked place for the assertions that only make sense once the commit gate is there. The base now carries it, so apply them: incident 2 asserts `qbit_prism_late_confirmed_shares_total` is zero on both frontends and that no acknowledgement, the block-solving share included, is `ledger-outcome-unknown`. Acceptance alone is no longer proof. #324 gives a share-pass append carrying a candidate its own `block_only_ack_timeout`, so a slow solve is never refused at the share deadline; it is answered late, or answered unknown. Either would have satisfied the acceptance checks with the serialization stall still present. Also set #324's two new `Config` fields in the qualification fixture. * 3.x.x: pin a refused candidate as a definite rejection, not an unknown outcome #324 decides what a miner is told when a block-only enqueue fails: `enqueue_failed_before_commit` answers a provably uncommitted failure with `ledger-confirmation-failed`, and anything else with `ledger-outcome-unknown`, which asks an operator to go and follow the outbox row. Slice 3 added the checks that guard the reference: the block's length, its header hash, its digest against `block_sha256`, the coinbase suffix, the reference invariants, and a leased candidate's balances. All of them are raised by `prepare_candidate` before the enqueue takes a connection, so none carries an `sqlx::Error` and all classify as definite today. That is a property of where the checks sit, not something the classifier knows about them, so it is pinned here rather than left to hold by accident: a corrupt candidate must never send a miner chasing a row that was never written. Verified by mutation: classifying a non-sqlx failure as unknown fails this test. * 3.x.x: say why the full-size qualification variants cannot reach 400k yet Their ignore reasons blamed RAM and the host. The real limit is #273: the job payload still holds three copies of the window (2 x AcceptedShare + 1 x CountedShare), so publishing a job for a 400,000-share window needs about 670 MiB and PostgreSQL refuses the write above its 256 MiB jsonb object limit. Every full-size variant fails at fixture set-up, before it measures anything. The count must also divide the window weight exactly, so the largest usable size today is 125,000, where all four variants pass in release: incident 1 50 renewals, max gap 118.25 ms against a 700 ms bound incident 2 phase-A p99 2.60 ms, phase-B p99 95.79 ms, bound 250 ms lock hold median 0.75 ms at 5,000 against 1.32 ms at 125,000 canonical refresh and claim rebuild both 139,040,610 B, same sha256 The candidate document stays flat at 1103 B and 1107 B, which is the property this slice exists to establish. * 3.x.x: migrate the audit-body normalization tests to the slim candidate #267 landed its own test file against the candidate that still carried an assembled bundle. This slice replaced that with a window reference, so the file keeps a `TestCandidate` pairing the stored candidate with the bundle a test still needs, as `tests/ledger_postgres.rs` does, and attaches the claim's parts through `with_bundle`. One case needed more than a shape change. The four negative cases hand the claim a window the ledger does not hold and require the durable-range proof to be what refuses it. A candidate now commits to a snapshot digest, so a reference taken from the unaltered snapshot would be refused earlier, at the reference check, and the proof under test would never run. `window_ref_for` therefore derives each altered window's reference from that window, leaving the proof as the only thing that can notice, which is what #267 wrote them to prove. * 3.x.x: pin the durable-range proof outside the settlement lock #267 moved the full-equality proof of a candidate's window out of the settlement transaction so the lock is not held for a window-sized read. This slice made that read paged, so it does not occupy a runtime thread either. Reconciling the two is the step that can quietly undo the first: keep this slice's `persist_audit_snapshot` through the rebase and the full read goes back under the lock. The landing stays correct, every other test still passes, and only the lock hold grows, so nothing in the suite can tell. Measured at 100,000 shares on #267's branch that was a 34% longer hold. The guard is deterministic and needs no large window. A second connection holds `SETTLEMENT_LOCK`, so the landing blocks on it once its proof has run. While it waits, one share's `ntime` is altered: full equality sees that, a count over the same anchored predicate cannot. The landing must then succeed, which it can only do if it had already read and compared the shares before taking the lock. Accepted history is immutable and a trigger enforces it, so the test lifts that trigger for the single statement, inside its own disposable schema, and puts it straight back. Verified by mutation: restoring the in-transaction range read fails this test with "the landing read share payloads under the settlement lock". * 3.x.x: serialise the coordinator test modules that share the ledger's locks The ledger's advisory locks are cluster-wide constants, not schema-scoped, so two coordinator test modules running in parallel contend for ORDER_LOCK even though each works in its own throwaway schema. Every module held a lock of its own, which serialised it against itself and left cross-module waits to `lock_timeout`, 5 s by default. #324's reconciliation tests hold ORDER_LOCK for up to about 1.5 s, and this slice adds three more modules that open a ledger. Once enough of them ran at once those waits stacked past the timeout: a full `--lib` run failed with "canceling statement due to lock timeout" in `candidate_lease_tests` and `window_switch_tests`, and passed on the next run. A suite that fails for a reason unrelated to what it tests is worse than a slow one. All seven modules now take one shared lock. The run goes from about 35 s to about 62 s, and three consecutive runs pass where the flake had reproduced. * 3.x.x: add migration 007 and refuse pre-007 candidate outbox rows Migration 007 mirrors 008 onto qbit_block_candidate_outbox: the same six window-reference columns, and a three-state CHECK whose body is identical to 008's apart from the table and constraint names. It also adds block_bytes, the nullable bytea the block moves into so the candidate document stays small, and a partial index on window_prior_balances_sha256 for the balance-snapshot GC. Nothing writes any of them yet; this is additive schema only. The runner applies 007 by membership, in its own block between 5 and 8, so it assumes neither 006 nor 008 has run. Before any DDL it refuses while the outbox still holds a pending row in a pre-007 shape: a native inline candidate, a NULL candidate, or storage_version other than 1 on the 2.x.x schemas that have that column, which is checked for first so the predicate does not error on a native schema. The refusal names every offending block_hash and the drain procedure, and the whole migration transaction rolls back, so a refused start leaves the schema untouched. The applied set is now [2, 3, 4, 5, 7, 8, 9], and the four exact migration assertions move with it rather than being weakened to a superset. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: retain the cluster fingerprint configure pinned or verified The candidate enqueue and save_job must fence against a fingerprint reset by re-reading qbit_prism_cluster.config_fingerprint FOR SHARE in their own transaction and refusing a write that is not this frontend's own. That needs the value configure settled at startup, so Ledger keeps it in a shared OnceLock, set only once the pin or the match has committed, and exposes it read-only through config_fingerprint(). configure keeps its signature and its mismatch refusal, and a refused call retains nothing. The rotation refusal in configure, and the writer fence itself, belong to the enqueue change and are not here. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: share the window reference, balance writer and page primitives WindowRef::from_snapshot is the synchronous reference builder both writers need: anchor_ms copied, the semantic balances digest, and for a non-empty snapshot the first and last share_seq, the length, and the share array's SHA-256 streamed through the existing DigestWriter, so the 233 to 260 MB serialized window at 400,000 shares is never built and the digest equals the one qbit_prism_audit_snapshots already stores. An empty snapshot gives the empty-window reference. Callers run it inside their own spawn_blocking. put_balance_snapshot is the one canonical writer of qbit_prism_balance_snapshots, on the caller's transaction: the sort by (order_key, recipient_id, p2mr_program_hex), the semantic digest that keys the row, and compact JSON of the sorted set, all off the runtime, then INSERT ... ON CONFLICT DO NOTHING. On a conflict it reads the stored bytes back and compares them with its own, because these rows are immutable and can only disagree through corruption. The enqueue and save_job and its repair all write through it. read_prior_balances and the current-balance read still keep their SQL order; the writer's sort defines the stored encoding, which is the order read_window(..., AsIssued) returns. probe_share_rows and read_range_paged are read_window's endpoint probe and page loop, lifted onto a caller's connection so the enqueue probe and the landing re-read share one implementation. The predicate, the ascending keyset order, the 4096-row page bound and the per-page count bound are unchanged, and read_window now calls them, with its signature and behaviour unchanged. The paged reader takes the caller's state and a per-page consumer, both of which travel to the blocking thread with the rows, so the landing re-read can compare each page with its slice of a vector it already holds without any whole-window work on the runtime; a dropped read still releases the accumulated state on a blocking thread. read_window_with_permit holds the caller's window_reads permit across the whole read. The permit is moved into a BlockingDrop declared before the read starts, so a cancellation releases it on a blocking thread after the page state queued its own release there, and never with the future; a return releases it inline, before the caller's rebuild. WindowError::TaskFailed separates a cancelled or panicking blocking hand-off from corruption. Every hand-off maps a JoinError to it instead of to Decode, so a cancellation is a retryable failure with its own alert and never takes the abandon path. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: derive the witness merkle leaves from an assembled block A claim rebuilds from stored inputs, and the witness leaves are the one builder input that scales with the block, so they are re-derived rather than stored: one 64-hex string per transaction beside the candidate would grow the document with the block. witness_merkle_leaves_from_block skips the 80-byte header, reads the compact-size transaction count, walks past the coinbase and returns double_sha256 of every remaining transaction's full serialized bytes. That is sound because assemble_submission appends the template's transactions verbatim after the coinbase, so the result equals witness_merkle_leaves_hex(&transactions_from_template(template)) for the block built from that template, with or without segwit transactions. The segwit-aware walk is strip_witness_transaction's own, factored into a helper that also reports where the transaction ends, which is what a block walker needs; strip_witness_transaction keeps its trailing-byte check and its output. A truncated block, trailing bytes, a zero count and a count that disagrees with the transactions present are all errors, never a partial list of leaves. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: version the audit builders and key the CC5 goldens by it A stored window reference reproduces its bundle only under the builder that first built it. The schema strings do not capture that, because the share shape chooses them rather than the builder logic, so qbit-prism gains AUDIT_BUILDER_VERSION, starting at 1. A candidate and a prepared job store it, and a rebuild refuses a reference at another version instead of rebuilding it with the current builder. The bump rule is on the constant: any change that alters canonical_audit_bundle_bytes for the same inputs bumps it in the same commit. The CC5 golden test now selects its expected digests from a table keyed by the constant, and fails when no entry exists, so a new output is recorded as a new entry beside the old one and review sees both. Version 1 holds the existing literals, unchanged. Part of #265 Co-Authored-By: Claude Opus 5 <[email protected]> * 3.x.x: cover 007, the fingerprint and the window primitives on PostgreSQL Ten gated database cases, all listed in test/prism-gated-tests.txt. They go in a new file rather than the shared 2.x.x support module, which another open change appends to. Migration 007: a frozen 2.x.x schema carrying only terminal outbox rows upgrades with every row and field intact and the seven new columns NULL; each of the three pre-007 pending shapes is refused by name, with nothing from 007 applied and no version 7 row, and the same binary starts once the row is drained; a database at [2, 3, 4, 5, 8, 9] applies 007 and only 007, leaving every other version's applied_at untouched; the CHECK accepts exactly the three states across all 64 null combinations and rejects a short or uppercase digest, a zero or out-of-range count and a zero sequence; and the retention index is the partial one on window_prior_balances_sha256. config_fingerprint() returns wh…
Part of #265 (A1), workstream #261, under #260.
Problem
import-auditswrote the parsed legacy bundle back intoqbit_pool_audit_bundles.audit_bundle. That JSONB value holds the payout window twice, insharesandreward_manifest.shares, so at production window sizes it crosses PostgreSQL's 268,435,455-byte JSONB container limit. The import then stops at the first production-sized block. The #264 JSONB gate listed this write as a known violation:qbit_pool_audit_bundles.audit_bundleat the import phase.The two readers had the opposite problem:
Ledger::audit_bundlereturned only the JSON column, sobackfill-ctvstopped on imported rows with "import legacy audits first".body_uri, so every frontend still needed the legacy audit filesystem.Change
This implements the "import" row of the #265 column in the window-reference design record (#297).
import_legacy_auditsstorescanonical_audit_bytesand the non-share metadata: schema version, network difficulty, coinbase value, and the commitment and witness leaves. It no longer writesaudit_bundleand no longer builds the two-copy JSON value.canonical_audit_bytes IS NULL,body_uri IS NOT DISTINCT FROM, andaudit_bundle_sha256in the WHERE.body_uriNULL. The CHECKaudit_bundle IS NOT NULL OR body_uri IS NOT NULLneeds one of the two, so no schema change is made. The import writes nothing new to these rows' JSONB.found_block_bitsstays as stored. No audit body carries the compact bits:FoundBlockhas none, and landing reads them from the block header.decode_canonical_audit_bodychecks the stored bytes againstaudit_bundle_sha256, parses them withparse_audit_bundle_value, and returns the logical body the import used to store inline. It runs underspawn_blocking.Ledger::audit_bundleserves native snapshot rows first, then imported canonical bytes, then inline bodies.backfill-ctvtherefore works on imported rows, with no change totools.rs./audit/blocks/{hash}/bundleand/audit/commitments/{leaf}/bundle) serve imported canonical bytes before anybody_urifallback, on the same public pool. The response shape is unchanged.Verification
All of these ran against a disposable PostgreSQL 16 through
test/prism-native-tests.sh.cargo fmt --all -- --checkis clean. Clippy onqbit-prism-servershows the same warnings as the base, and none in the changed files.ledger_postgres: 33 passed. The four new tests are:imported_external_audit_is_served_from_canonical_bytes_without_the_legacy_file: the import writes no inline body, both readers and both bundle routes serve the row with itsbody_urifile deleted, the output is identical to before, and the dashboard row is unchanged;corrupt_imported_canonical_bytes_are_refused_not_served_from_the_legacy_file: a flipped byte, a declared-digest mismatch on valid bytes, and digest-valid{},[]and non-JSON bytes are all refused while the file still exists;imported_ctv_audit_backfills_and_links_without_the_legacy_file;inline_only_legacy_audit_import_keeps_its_body_and_serves_canonical_bytes.api_databaseandapi_2xpass.The full native suite: 229 passed, 0 failed.
audit_cli: 18 passed, with the golden bytes unchanged.The JSONB ceiling gate:
canonical_audit_bytesis 445,390,610 B (bytea, report-only; the varlena limit is 1 GiB). The ratchet holds with three known violations.Mutations, each applied alone:
NEW VIOLATION: qbit_pool_audit_bundles.audit_bundle written at phase importbody_urion a decode errorLedger::audit_bundlereturnsNoneon a decode errorLedger::audit_bundleThe existing
legacy_audit_import_validates_envelope_hash_and_pinned_keyandcanonical_2x_sidecar_import_preserves_exact_bytes_and_fails_closedpass unchanged. No canonical hash, payout or credit changes.Notes
Coordination with 3.x.x: Settle migration reversibility and make the audit-body import an enforced step #287: its "rows lacking stored bodies" count should treat
canonical_audit_bytesas a stored body. After this change, an imported externalized row hasaudit_bundleNULL.Out of scope, unchanged from the base:
audit_canonical_bytesstill hashes and parses imported bytes on a runtime thread;Both belong to the artifact-route and audit-body work listed under 3.x.x: Normalize stored audit bodies so they stop growing with the window #267.
🤖 Generated with Claude Code
Need help on this PR? Tag
@codesmith-botwith what you need. Autofix is disabled.