Skip to content

3.x.x: unify heartbeat status writers and self-check reader - #362

Merged
Anatolie merged 2 commits into
3.x.xfrom
unify-heartbeat-status
Sep 14, 2026
Merged

Anatolie merged 2 commits into
3.x.xfrom
unify-heartbeat-status

Conversation

@Anatolie

@Anatolie Anatolie commented Sep 14, 2026 •

Copy link
Copy Markdown
Member

Closes #307.

Heartbeat writers and self-check previously maintained separate definitions of live, starting, and stopped status. This adds shared typed statuses, moves heartbeat persistence and sampling/classification into ledger/instances.rs, and updates startup, coordinator health publication, and shutdown together.

Existing stored JSON remains compatible, including opaque fields and large numbers. Self-check still samples before initialization, uses one PostgreSQL clock sample with an inclusive 15-second window, counts unready-but-live frontends, and emits complete JSON with null unknown/failed counts and a nonzero exit on failure. Stopped markers retain the session admission guard and authoritative process owner token, including mixed legacy health/stopped payloads.

Regression coverage includes legacy and malformed status payloads, writer round-trips, empty/stale/missing-table probes, stopped-session safety, and full-command self-check failure and startup-ordering checks. No database migrations, dependencies, deployment settings, or production infrastructure are changed.

Validation on 7c68a98 plus this change (including integration with the newly landed recovery and metrics work):

  • cargo fmt --all --check and cargo clippy --locked --offline --workspace --all-targets -- -D warnings passed.
  • PostgreSQL 16 with integration required: cargo test --locked --offline -p qbit-prism-server --lib --test ledger_postgres --test self_check_cli --test readiness_rpc --test window_read_oracle --test window_reference passed (273 tests; 2 explicitly ignored measurements). The execution manifest records 110 distinct gated probes, with no skips.
  • Both PostgreSQL observability tests passed when explicitly selected with --test observability_database -- --ignored, including blocked health publication.
  • On feature commit a4b4c07, the unchanged share-append throughput gate passed in isolation at 430/566/600 shares/sec for 1/2/4 appenders against the 250 shares/sec floor. An earlier full server sweep failed its 1-appender level at 201 shares/sec; the isolated rerun passed without changing code or thresholds.
  • Gate environment-read and sorted inventory checks passed; the moved SQL probe and new CLI probe are registered.

Local validation did not exercise the real-qbitd or physical-replica/failover gates, because QBITD_BIN and PRISM_TEST_PG_BIN_DIR are unavailable. CI must cover those paths.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 14, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-14T19:13:10.238546Z f7350a2 New commits
ℹ️ About Codex in GitHub

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

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

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

@Anatolie
Anatolie merged commit 3c0c820 into 3.x.x Sep 14, 2026
16 checks passed
kiwidream added a commit that referenced this pull request Sep 14, 2026
#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.
kiwidream added a commit that referenced this pull request Sep 14, 2026
#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.
kiwidream added a commit that referenced this pull request Sep 14, 2026
…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,…
djh58 added a commit that referenced this pull request Sep 14, 2026
* 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…
Anatolie added a commit that referenced this pull request Sep 16, 2026
…stration (#412)

* Keep one-shot operator commands out of frontend heartbeat registration (3.x.x)

self-check, import-audits, backfill-ctv and broadcast-ctv connected through
the frontend constructors, so every invocation registered a starting
heartbeat that nothing ever attested stopped: a generated instance ID left
a row fatal-state clear refuses, and a configured one overwrote the live
frontend's status and session-owner token.

Add Ledger::connect_tool and Coordinator::new_tool, a third registration
mode beside the frontend and the recovery operator: the same startup gates
(schema version, declared capabilities, migration source, halt guard and
cluster fingerprint) with no heartbeat write. Claims a tool takes remain
fenced by their own tokens.

Part of #260, follows #360 (fatal-state recovery) and #362 (heartbeat
writers). Refs #381.

* Assert self-check preserves the live frontend row and document the non-registering tools

The self-check CLI test asserted the leftover starting heartbeat the old
constructor wrote over the seeded legacy health payload. It now proves the
opposite: the frontend's row, session-owner token included, is byte-identical
after the diagnostic ran under its ID, and a generated ID leaves no row at
all. The slow-cadence sample stops the fixture frontend first, since the
diagnostic no longer re-registers over its row.

Runbooks: the fatal-state recovery and CTV sections, the HA reference's
self-check description, the migration guide's import/backfill notes and the
3.0.0 release notes state that the one-shot commands keep every startup gate
but write no heartbeat, and that rows left by earlier builds still need the
documented investigation. Refs #381.

* Add a regression for one-shot tools registering no heartbeat (#381)

Cover the four one-shot commands (self-check, import-audits, backfill-ctv,
broadcast-ctv) against a real PostgreSQL cluster: a generated instance ID
leaves no qbit_prism_instances row on success or on failure, a live
frontend's row (status with its session-owner token, heartbeat_at and
started_at) is byte-identical after each tool runs under its instance ID,
the halt guard still refuses every tool with "cluster halted", and
fatal-state clear succeeds once the real frontend stops because no tool
row is left to refuse.

With the registering constructors restored in tools.rs the test fails at
the first row-count assertion, so it guards the fix rather than the setup.

Refs #381.

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

---------

Co-authored-by: Claude Fable 5.1 <[email protected]>
kiwidream added a commit that referenced this pull request Oct 29, 2026
* 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…
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant