Skip to content

3.x.x: Make gated tests fail loudly, prove CI execution, add Rust hygiene jobs - #322

Merged
Anatolie merged 11 commits into
3.x.xfrom
gated-tests-ci-hygiene
Sep 11, 2026
Merged

Anatolie merged 11 commits into
3.x.xfrom
gated-tests-ci-hygiene

Conversation

@Anatolie

@Anatolie Anatolie commented Sep 11, 2026 •

Copy link
Copy Markdown
Member

Closes #286 (workstream C, #263; part of #260). This PR targets 3.x.x, so GitHub won't close the issue automatically on merge. It will be closed by hand.

Also carries the parts of #284 and #271 that #286's 2026-09-10 scope update moved here: the toolchain pin, rust-version, and the builder-image digest from #284, and the aliased make test targets from #271. The version-skew check itself landed in #315 and is unchanged.

Why

83 native tests depended on PRISM_TEST_DATABASE_URL, PRISM_TEST_PG_BIN_DIR or QBITD_BIN. With the input absent, most of them printed a line to stderr, which cargo test hides, and reported passed. The one exception was the JSONB ceiling gate, which keyed on CI and was skipped by name in rust-tests. prism-native-postgres supplied the inputs, but nothing proved the tests ran. It was also scoped to -p qbit-prism-server. There was no clippy, fmt --check, dependency audit, or Dockerfile lint, and the toolchain floated on @stable and rust:1-bookworm.

What

  • One shared gate: crates/qbit-prism-test-gate. A dev-dependency-only crate with no dependencies of its own, used by the integration tests, by #[cfg(test)] code in src/, and by qbit-prism. Every gated site now goes through it, including Add a native SQL oracle for the payout-window read #306's window_read_oracle.rs and 3.x.x: assert the server-side D2 payout rules #316's D2 coordinator tests. Its rules, per input:

    Input set and non-empty Switch Result
    yes — run
    no PRISM_TEST_REQUIRE_INTEGRATION=1 fail, naming the variable and the test
    no GITHUB_JOB=prism-native-postgres fail, same
    no — one [prism-test-gate] skipped line, then return
    • It never keys on CI, which GitHub also sets in rust-tests, a job with no database.
    • A non-Unicode value is an error, never treated as absent.
    • Explicitly requested #[ignore] runs always require their inputs.
    • scripts/check_gate_env_reads.py fails if any Rust file reads these variables outside the gate, so a new test can't bypass it.
  • Proof of execution. When PRISM_TEST_GATE_MANIFEST is set, the gate appends one line per decision (one O_APPEND write each). scripts/check_gate_manifest.py compares the manifest with the checked-in test/prism-gated-tests.txt (81 tests; its length is the minimum count). It fails on any of:

    • an expected test that didn't execute
    • any skipped or failed line
    • a count below the minimum
    • an executed test missing from the list
    • skip wording in the test log

    It prints the manifest to the log and the step summary, and the job uploads it as the prism-gate-manifest artifact.

  • prism-native-postgres.

    • Sets PRISM_TEST_REQUIRE_INTEGRATION=1.
    • Runs --workspace --all-targets -- --nocapture instead of -p qbit-prism-server, so tests under crates/qbit-prism/tests/ are covered.
    • Tees every run to a log the checker scans.
    • The job id is unchanged, because the gate keys on it. The timeout rises from 20 to 30 minutes for the wider scope.
  • rust-tests no longer needs --skip jsonb_ceiling_ratchet_at_reduced_sizes.

  • New required jobs under Lint, compile, and test (checks.needs):

    • rust-fmt: cargo fmt --all --check
    • rust-clippy: cargo clippy --locked --workspace --all-targets -- -D warnings. The existing warnings are fixed without changing behaviour, in their own commit.
    • cargo-deny: deny.toml checks advisories, licenses, bans and sources, with no advisory ignores.
    • dockerfile-lint: hadolint over every Dockerfile. Any rule an image can't follow is ignored inline, with its reason.

    cargo-deny and hadolint are pinned versions installed from their release assets, with their sha256 checked (.github/scripts/install-pinned-tool.sh).

  • Toolchain pin.

    • rust-toolchain.toml pins 1.98.1 with rustfmt and clippy.
    • [workspace.package] rust-version = "1.98.1", inherited by every crate.
    • The PRISM builder is rust:1.98.1-bookworm@sha256:9a73a508…, the multi-arch index digest.
    • Every Rust job installs the pin through .github/actions/rust-toolchain, which asserts rustc and cargo --version.
    • docker-builds builds the builder stage and asserts its cargo and rustc match the pin.
    • scripts/check_toolchain_pin.py fails when the toolchain file, rust-version, and the Dockerfile tag disagree.
  • make targets. One target per native suite:

    • test-prism-postgres replaces -ledger, -scale, -native-ledger and -seed-guard.
    • test-prism-regtest replaces test-prism-stratum-regtest-live, -stratum-postgres-regtest-live and test-prism-combined-regtest.
    • test-prism-public-read-replica calls the replica mode directly.

    Eight thin wrapper scripts were deleted, and the docs updated. test-prism-postgres-throughput is untouched (3.x.x: End-to-end throughput floor and load harness #271).

  • test/prism-native-tests.sh switches to required mode once the inputs its mode needs are present, and checks the manifest in its default mode, so a local run matches CI.

  • Docs.

Acceptance criteria

  • With the switch set and PRISM_TEST_DATABASE_URL unset, cargo test -p qbit-prism-server fails: exit 101, and each gated test names the missing variable, e.g. …candidate_lease_tests::landing_transaction_renews_across_expiries_and_terminal_contention_finishes_once requires PRISM_TEST_DATABASE_URL: … PRISM_TEST_REQUIRE_INTEGRATION=1 demands the integration suite. Removing the URL from the native job fails the job, because the switch is set there and the job id fallback also applies.

  • The job publishes a manifest naming every executed gated test, and fails below the expected count of 81.

  • A gated test under crates/qbit-prism/tests/ is covered: the required native job runs the whole workspace, and the env-read lint forces such a test through the gate.

  • clippy, fmt, cargo-deny and hadolint run as required checks.

  • The deleted-test map lives in docs/, with each open gap row linked to the issue that closes it. Partly met. The map is checked in and every open gap row links its issue. But 7 rows are marked needs triage because no open issue closes them:

    • tests/test_prism_reward_window_invariant.py
    • tests/test_prism_settlement_balance_comparison.py
    • tests/test_prism_issue_224_landing.py
    • tests/test_prism_accepted_preview_publication_latency.py
    • tests/test_prism_audit_bundle_view.py
    • tests/test_prism_stratum_restart_bind.py
    • tests/test_prism_ctv_refresh_priority.py

    Each needs an issue, or a decision to retire it, before this criterion is fully met.

Out of scope

Verification

On the implementation host (Linux x86_64, Rust 1.98.1):

  • cargo fmt --all --check, cargo clippy --locked --workspace --all-targets -- -D warnings, cargo deny check, hadolint over all 7 Dockerfiles, shellcheck -x, and actionlint 1.7.12 on ci.yml all exit 0.
  • No inputs: cargo test --locked --workspace --all-targets passes, with one [prism-test-gate] skipped line per gated test.
  • Switch set, no URL: qbit-prism-server fails, naming the variable. So do the 9 D2 tests, and an explicit --ignored JSONB run.
  • Full native run: test/prism-native-tests.sh against a disposable PostgreSQL 16, with QBITD_BIN from the pinned qbit 1.0.0 tarball (sha256 checked), in required mode. Result: 503 passed, 0 failed, 0 skip lines. check_gate_manifest.py confirms all 81 expected gated tests executed.
  • Python: the new tests pass (37, counting the version-skew suite), and all four run_python_test_shard.py shards pass.
  • Drift checks: check_version_skew.py and check_toolchain_pin.py pass. Each was shown to fail on a deliberate drift, which was then reverted.

A second pass on macOS (Rust 1.98.1) re-ran fmt, clippy with -D warnings, check_gate_env_reads.py (106 Rust files), the pin and skew checks, the 37 Python tests, and the qbit-prism-server lib tests. All pass.

An independent review of the gate crate and every converted site found no missed or bypassing site. It also confirmed the clippy commit doesn't change behaviour.

Not run: any Docker build, because the implementation host has no Docker daemon. This PR's docker-builds job is the first to exercise the digest-pinned builder and the new builder-stage toolchain assertion. The digest was resolved from Docker Hub's registry manifests endpoint for rust:1.98.1-bookworm.

🤖 Generated with Claude Code


View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need. Autofix is disabled.

Anatolie and others added 11 commits September 11, 2026 14:02
`cargo clippy --locked --workspace --all-targets -- -D warnings` now
passes on the 1.98.1 toolchain. Each change keeps the code's behaviour:

- `(n + 1) / 2` becomes `n.div_ceil(2)` in both Merkle root loops.
- The two `Default` impls that picked one variant become `#[derive(Default)]`
  with `#[default]` on that variant.
- The eligible-share sort keys on `Reverse(share_seq)` instead of a
  comparator that spelled the same order.
- `&[x.clone()]` becomes `slice::from_ref(&x)` in the CTV manifest test.
- `seq % 4 == 0` becomes `seq.is_multiple_of(4)` in the window fixture.
- `chunks_exact(_mut)` with a constant size becomes `as_chunks(_mut)`, which
  ignores the same remainder.
- The adversarial settlement case that looped over four blocks and broke
  after the first now states that it checks block 0 only, which is what
  it always did.
- `tools.rs` keeps its `live_instance_tests` module after the last item.
- The two owning audit-bundle entry points allow `too_many_arguments`
  with the reason that they mirror the borrowed forms they forward to.

`cargo fmt --all --check` already passed on the base commit, so there is
no formatting-only change to land.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01DzhiDBXX9hveszStKkyFt1
Every test whose execution depends on PRISM_TEST_DATABASE_URL,
PRISM_TEST_PG_BIN_DIR or QBITD_BIN used to open with its own copy of a
skip: read the variable, print a line libtest hides, return Ok. The new
qbit-prism-test-gate crate holds the one decision table that
window_read_oracle.rs already followed, generalised per input: present,
run; missing while PRISM_TEST_REQUIRE_INTEGRATION=1 or
GITHUB_JOB=prism-native-postgres, fail naming the variable and the test;
missing otherwise, print one line with a fixed prefix past libtest's
capture and return. A variable that is not valid Unicode is an error,
never absent, and a switch value other than 1 or 0 is an error too. The
table is a pure function over injected values with a unit test per row,
and a child-process test drives the runtime path.

Every site is converted: the ledger, 2.x upgrade, rollups, API, readiness,
authorization, migration-rollback, failover, replica, live regtest,
candidate-lease, public-service and live-instance tests, and the window
oracle, which drops its private guard. The two explicitly selected
#[ignore] tests use the gate's required entry point, which never skips.
The JSONB ceiling gate moves off its CI keying (GitHub sets CI=true in
rust-tests, which has no database), so rust-tests no longer skips it by
name; its unreadable-variable test now exercises the shared table. The
live fixture keeps the qbitd path it was opened with for node restarts.

The crate is a dev-dependency of qbit-prism-server and qbit-prism, so a
gated test under either crate's tests, or in a #[cfg(test)] module, uses
the same gate. scripts/check_gate_env_reads.py, run in the lint job,
fails when any Rust file outside the gate crate names one of the gate
variables in a string literal, so no new test can read them directly.

Measured gated tests: 74 in the tree, 72 of which the native job runs
(the two JSONB #[ignore] measurement runs are gated but never selected
in CI).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01DzhiDBXX9hveszStKkyFt1
With PRISM_TEST_GATE_MANIFEST set, the gate appends one line per decision,
executed, skipped or failed, followed by <package>::<binary>::<test path>,
in a single O_APPEND write so parallel test threads and separate test
binaries share the file. test/prism-gated-tests.txt is the checked-in
list of the 72 gated tests the native job must execute, including the
two #[ignore] runs it selects explicitly; its length is the minimum.

scripts/check_gate_manifest.py fails when any expected test did not
execute, any skipped or failed line appears, fewer distinct tests
executed than the list holds, a test executed that the list does not
name, or the log shows the gate's skip prefix or the wording of the skip
messages the gate replaced. It prints the manifest to the log and to the
step summary.

The prism-native-postgres job keeps its id (the gate keys on it), sets
PRISM_TEST_REQUIRE_INTEGRATION=1 and the manifest path, runs the whole
workspace with --all-targets and --nocapture through tee, then the two
explicit --ignored runs, then the proof, and uploads the manifest as an
artifact. A gated test added under crates/qbit-prism is therefore covered
by a required job.

test/prism-native-tests.sh mirrors the job: its default mode runs the
workspace, both explicit runs and the proof, and exports the switch once
the PostgreSQL server tools and qbitd are present; the live, replica and
cargo-args modes always export it, since they refuse to start without
their inputs or name their own tests.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01DzhiDBXX9hveszStKkyFt1
Four new jobs join the checks aggregator: cargo fmt --all --check,
cargo clippy --locked --workspace --all-targets -- -D warnings,
cargo deny --locked check, and hadolint over every Dockerfile.

deny.toml checks advisories (nothing ignored), licenses (an allow-list of
what the tree uses, plus CDLA-Permissive-2.0 for the CA bundle that
webpki-roots ships), bans (duplicate versions warn; wildcard requirements
are refused except the workspace's own path dependencies, which needs
qbit-prism and qbit-prism-server to be publish = false, as they are in
practice) and sources (crates.io only).

cargo-deny 0.20.2 and hadolint 2.15.1 are installed by
.github/scripts/install-pinned-tool.sh from their GitHub releases after a
sha256 check. hadolint reads .hadolint.yaml, which ignores nothing
globally: lab/prism/Dockerfile pins its two apt packages, and the other
images, whose behaviour is not this workstream's to change, carry inline
ignores with reasons (unpinned apt versions, the named qbit-src build
context that DL3022 mistakes for a stage, the deliberate separate cmake
layers, and the checked pipes in the Bitcoin Core download).
.github/actionlint.yaml names the Blacksmith runner label so actionlint
runs clean locally.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01DzhiDBXX9hveszStKkyFt1
rust-toolchain.toml pins the exact stable version with rustfmt and clippy
under the minimal profile. [workspace.package].rust-version carries the
same version and every crate inherits it. The lab/prism/Dockerfile
builder is rust:1.98.1-bookworm at the multi-arch index digest Docker
Hub serves for that tag (resolved through the registry API; both the
1.98.1-bookworm and 1.98-bookworm tags point at it today).

scripts/check_toolchain_pin.py fails when the three disagree, when a
crate stops inheriting rust-version, when the builder line lacks a
digest, or, with --installed, when the active rustc or cargo is not the
pin. The lint job runs the static check; the new
.github/actions/rust-toolchain composite action replaces the floating
dtolnay/rust-toolchain@stable in every Rust-using job, installing the
toolchain rustup reads from the file and asserting the installed
version. docker-builds builds the builder stage on its own first and
asserts that its cargo and rustc report the pin.

VERSION and scripts/check_version_skew.py from #315 are unchanged.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01DzhiDBXX9hveszStKkyFt1
test-prism-postgres-ledger, test-prism-postgres-scale,
test-prism-postgres-native-ledger and test-prism-postgres-seed-guard all
ran test/prism-native-tests.sh; they become test-prism-postgres.
test-prism-stratum-regtest-live, test-prism-stratum-postgres-regtest-live
and test-prism-combined-regtest all ran the live mode that
test-prism-regtest already names; they are removed.
test-prism-public-read-replica keeps its name and calls the script's
replica mode directly. The eight wrapper scripts under test/ that only
exec'd prism-native-tests.sh are deleted; test-prism-postgres-throughput
and its script are untouched (#271 owns the throughput floor).

README, the coordinator-refactor validation notes and the overload alert
spec now name the surviving targets; the historical release notes under
doc/ keep the names they shipped with.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01DzhiDBXX9hveszStKkyFt1
docs/prism-integration-test-gate.md is the gate contract: the inputs, the
decision table, the switch, the skip prefix, test identity, the manifest,
the expected list and the proof, local runs, and how to add a gated test.

docs/prism-deleted-test-map.md rebuilds the readiness review's map from
git: every test file under tests/ and test/ on origin/2.x.x (504846c)
absent on 3.x.x, 142 files grouped by area, each with its native
replacement, or the open issue that closes the gap, or a needs-triage
note where neither exists. Both are linked from docs/README.md, and the
wrapper descriptions in PRISM.md, the server README and the ledger
operations guide now describe required mode and the manifest.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01DzhiDBXX9hveszStKkyFt1
#316 landed nine PostgreSQL-gated coordinator tests with a hand-written
copy of the old guard in d2_test_support.rs, which read
PRISM_TEST_DATABASE_URL, PRISM_TEST_REQUIRE_INTEGRATION and GITHUB_JOB
directly and so failed scripts/check_gate_env_reads.py. The guard now
takes the URL through qbit_prism_test_gate like every other #[cfg(test)]
site, the nine callers drop the test name the gate derives itself, and
the tests join test/prism-gated-tests.txt, which the native job's
manifest is checked against: 81 expected gated tests, 83 in the tree.

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

The two JSONB measurement runs, jsonb_ceiling_ratchet_at_full_size and
jsonb_ceiling_baseline_sweep, are #[ignore] tests someone asks for by
name, yet they reached the gate through the non-required entry point, so
a manual --ignored run with no database printed a skip line and reported
ok. They now use the gate's required entry point, as the
observability_database and stratum_admission_postgres runs already did,
and the contract says that every explicit #[ignore] run is required.
They stay out of test/prism-gated-tests.txt because CI never selects
them.

The gate's record_to used write_all, which can split a line across two
writes after a short write and let another thread's line land between
them. It now hands the whole line to one write and treats a short write
as an error, so each manifest line stays a single O_APPEND write; the
skip line on stderr goes out the same way.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01DzhiDBXX9hveszStKkyFt1
The PRISM runtime stage floats on debian:bookworm-slim, and Debian drops
superseded package versions from its archive, so the exact ca-certificates
and curl pins would have broken the build at the next point or security
release, with no Docker here to build-test a bump. The stage carries the
same inline DL3008 ignore and reason as the other images; pinning its base
and packages belongs to #288. The builder stage keeps its digest pin.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01DzhiDBXX9hveszStKkyFt1
The map is now built against 8dccc74, the merge of #316, and pins both
ends of its file list (504846c and 8dccc74), since origin/2.x.x has moved
on and this branch removes wrapper scripts of its own. The nine D2 tests
were read against every row they could touch: ten partial rows now cite
them (below-target credit, lost-reply reconciliation, reorg survival,
bootstrap selection, the retired readiness gate), and the settlement
balance comparison row states why D2c does not cover it. No status
changes; the counts stay 5 full, 67 partial, 8 open gaps, 7 needs
triage, 55 retired.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01DzhiDBXX9hveszStKkyFt1
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 11, 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-11T18:19:24.868655Z 1946cd7 PR opened
ℹ️ About Codex in GitHub

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

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

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

@Anatolie
Anatolie merged commit c9d41e9 into 3.x.x Sep 11, 2026
16 checks passed
kiwidream added a commit that referenced this pull request Sep 11, 2026
Brings in #322 (the shared integration gate, the gated-test manifest and the required fmt, clippy, cargo-deny and hadolint jobs) so the floor test can move onto the gate before this PR leaves draft.

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

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

Part of #271

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Anatolie added a commit that referenced this pull request Sep 11, 2026
…commit (#318 CI)

`docs/prism-deleted-test-map.md` landed on 3.x.x with #322 after this
branch's merge-base, and it names three `lab/prism/*.py` modules that #244
removed: `candidate_window.py`, `bundle_compiler.py` and
`endpoint_registry.py`. The reference guard this branch adds scans every
tracked doc on the merge ref, so CI's "Python unit tests (shard 1)" failed
on those three lines while the same test passed on the branch alone.

The guard's contract offers two ways to name retired code: describe it in
words or link a commit-pinned GitHub URL, which is stable history and
exempt. The three mentions are now links to the files at `700fae0`, the
last commit before #244 deleted them, with the module basename as the link
text so the visible path no longer claims to exist on the branch. The
table's wording is otherwise unchanged.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Anatolie added a commit that referenced this pull request Sep 11, 2026
The branch was rebased onto #322, which fails the prism-native-postgres
job for any gated test that executes without being listed in
test/prism-gated-tests.txt. None of the ten Postgres tests this PR adds
in tests/support/ledger_2x.rs were listed, so the job would have failed
on its manifest check. List them, sorted, and update the count the gate
guide quotes. The other #322 checks (formatting, clippy with -D warnings,
the gate env-read lint, the toolchain pin, version skew) already pass on
this branch and need no change.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_019mWgeEnsyHLZSiGaAj8bZi
Anatolie added a commit that referenced this pull request Sep 11, 2026
The branch was rebased onto #322, which fails the prism-native-postgres
job for any gated test that executes without being listed in
test/prism-gated-tests.txt. None of the ten Postgres tests this PR adds
in tests/support/ledger_2x.rs were listed, so the job would have failed
on its manifest check. List them, sorted, and update the count the gate
guide quotes. The other #322 checks (formatting, clippy with -D warnings,
the gate env-read lint, the toolchain pin, version skew) already pass on
this branch and need no change.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_019mWgeEnsyHLZSiGaAj8bZi
Anatolie added a commit that referenced this pull request Sep 14, 2026
The branch was rebased onto #322, which fails the prism-native-postgres
job for any gated test that executes without being listed in
test/prism-gated-tests.txt. None of the ten Postgres tests this PR adds
in tests/support/ledger_2x.rs were listed, so the job would have failed
on its manifest check. List them, sorted, and update the count the gate
guide quotes. The other #322 checks (formatting, clippy with -D warnings,
the gate env-read lint, the toolchain pin, version skew) already pass on
this branch and need no change.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_019mWgeEnsyHLZSiGaAj8bZi
kiwidream added a commit that referenced this pull request Sep 14, 2026
…323)

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

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

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

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

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

Part of #271

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

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

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

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

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

Part of #271

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

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

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

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

Part of #271

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

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

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

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

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

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

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

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

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

Part of #271

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

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

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

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

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

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

Part of #271

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

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

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

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

Part of #271

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

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

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

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

Part of #271

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

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

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

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

Part of #271

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

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

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

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

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

Part of #271

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

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

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

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

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

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

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

Part of #271

---------

Co-authored-by: Claude Opus 5 <[email protected]>
kiwidream added a commit that referenced this pull request Sep 14, 2026
Brings the load harness onto the current 3.x.x, which carries #322 (the
shared integration gate and the required fmt, clippy and cargo-deny jobs) and
#316. The only conflict was the root Cargo.toml: 3.x.x's file is kept,
including its commented rust-version pin, and the qbit-prism-load member is
added beside qbit-prism-test-gate.

Part of #271
kiwidream added a commit that referenced this pull request Sep 14, 2026
Brings the load harness onto the current 3.x.x, which carries #322 (the
shared integration gate and the required fmt, clippy and cargo-deny jobs) and
#316. The only conflict was the root Cargo.toml: 3.x.x's file is kept,
including its commented rust-version pin, and the qbit-prism-load member is
added beside qbit-prism-test-gate.

Part of #271
kiwidream added a commit that referenced this pull request Sep 14, 2026
Brings the load harness onto the current 3.x.x, which carries #322 (the
shared integration gate and the required fmt, clippy and cargo-deny jobs) and
#316. The only conflict was the root Cargo.toml: 3.x.x's file is kept,
including its commented rust-version pin, and the qbit-prism-load member is
added beside qbit-prism-test-gate.

Part of #271
Anatolie added a commit that referenced this pull request Sep 14, 2026
…commit (#318 CI)

`docs/prism-deleted-test-map.md` landed on 3.x.x with #322 after this
branch's merge-base, and it names three `lab/prism/*.py` modules that #244
removed: `candidate_window.py`, `bundle_compiler.py` and
`endpoint_registry.py`. The reference guard this branch adds scans every
tracked doc on the merge ref, so CI's "Python unit tests (shard 1)" failed
on those three lines while the same test passed on the branch alone.

The guard's contract offers two ways to name retired code: describe it in
words or link a commit-pinned GitHub URL, which is stable history and
exempt. The three mentions are now links to the files at `700fae0`, the
last commit before #244 deleted them, with the module basename as the link
text so the visible path no longer claims to exist on the branch. The
table's wording is otherwise unchanged.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Anatolie added a commit that referenced this pull request Sep 14, 2026
…ns, gate startup (#321)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  sequence qbit_share_ledger_share_seq_seq differs: maximum expected
  9223372036854775807, found 1000000

and an extra sequence is logged with the other extras.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* fix: reject extra constraints on migration source tables

* fix: reject unsatisfied extra migration source columns

* fix: reject extra indexes that affect native writes

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

* fix: reject executable expressions on extra source columns

* fix: fingerprint table rewrite rules before migration

* fix: reject incoming foreign keys from extra source tables

* fix: validate storage version before native migration 006

* fix: reject domain-typed extra migration columns

* fix: reject migration sources resolved outside the current schema

* fix: reject all extra indexes on release tables

* fix: validate source metadata before later native migrations

* fix: reject preexisting source metadata before migration 006

* fix: reject row security on capability metadata

* fix: separate legacy source versions from native capabilities

* fix: reject outbox row security before native migration drain

* fix: validate migration history before trusting version records

* fix: require an ordinary table for capability declarations

* fix: bind the capability declaration to the current schema

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

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

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

* fix: bind migration provenance to the verified schema

* fix: reject object collisions in native migration gaps

---------

Co-authored-by: Claude Fable 5.1 <[email protected]>
kiwidream added a commit that referenced this pull request Sep 14, 2026
Brings the load harness onto the current 3.x.x, which carries #322 (the
shared integration gate and the required fmt, clippy and cargo-deny jobs) and
#316. The only conflict was the root Cargo.toml: 3.x.x's file is kept,
including its commented rust-version pin, and the qbit-prism-load member is
added beside qbit-prism-test-gate.

Part of #271
kiwidream added a commit that referenced this pull request Sep 14, 2026
Brings the load harness onto the current 3.x.x, which carries #322 (the
shared integration gate and the required fmt, clippy and cargo-deny jobs) and
#316. The only conflict was the root Cargo.toml: 3.x.x's file is kept,
including its commented rust-version pin, and the qbit-prism-load member is
added beside qbit-prism-test-gate.

Part of #271
Anatolie added a commit that referenced this pull request Sep 14, 2026
…commit (#318 CI)

`docs/prism-deleted-test-map.md` landed on 3.x.x with #322 after this
branch's merge-base, and it names three `lab/prism/*.py` modules that #244
removed: `candidate_window.py`, `bundle_compiler.py` and
`endpoint_registry.py`. The reference guard this branch adds scans every
tracked doc on the merge ref, so CI's "Python unit tests (shard 1)" failed
on those three lines while the same test passed on the branch alone.

The guard's contract offers two ways to name retired code: describe it in
words or link a commit-pinned GitHub URL, which is stable history and
exempt. The three mentions are now links to the files at `700fae0`, the
last commit before #244 deleted them, with the module basename as the link
text so the visible path no longer claims to exist on the branch. The
table's wording is otherwise unchanged.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
kiwidream added a commit that referenced this pull request Sep 14, 2026
Brings the load harness onto the current 3.x.x, which carries #322 (the
shared integration gate and the required fmt, clippy and cargo-deny jobs) and
#316. The only conflict was the root Cargo.toml: 3.x.x's file is kept,
including its commented rust-version pin, and the qbit-prism-load member is
added beside qbit-prism-test-gate.

Part of #271
Anatolie added a commit that referenced this pull request Sep 15, 2026
…nd guard lab/prism doc references (#318)

* 3.x.x: re-anchor the capacity-readiness runbook to native telemetry (#303)

docs/prism-capacity-readiness.md documented and told the operator to run
lab/prism/metrics.py and lab/prism/process_telemetry.py, which #244 deleted;
lab/prism/ holds only Dockerfile on this line. Decide per section instead of
deleting wholesale:

- Retire the Python-specific material: the interpreter/allocator and
  component-cardinality families, the heap census, malloc_trim, and the
  MALLOC_ARENA_MAX storm instrument. Each keeps a short past-tense note that
  it applied to the retired Python coordinator and names what replaces it or
  who owns the gap (#278 registry, #279 inventory).
- Re-anchor what is runtime-independent on the #308 registry: the process
  block (process_resident_memory_bytes, the collector_* state, runtime_*
  gauges, the #277 snapshot block), the RSS reading order, the 2.0x
  resident-set bound as one awk pass over the sample CSV, and the 24 h soak
  runbook using docker exec, /proc/1/status, and curl against the audit
  listener on 3341. Every command parses and resolves on this branch.
- Mark the Validate Qualification Evidence gate deferred: the native
  validator exists, but no producer on this branch emits the v2 file and the
  strict key set still requires three retired settings. #288 re-keys the
  validator; #291 produces the first native artifact.

tests/test_docs_lab_prism_references.py guards the recurrence: no runnable
python -m lab.* / python lab/*.py command in docs/ may target a module absent
from the branch, and every lab/prism path or lab.prism module reference must
resolve against git ls-files, except GitHub URLs pinned to a commit SHA. The
pre-existing residue in prism-overload-alerts.md, prism-coordinator-refactor/
and prism-rust-migration.md is ratcheted at today's counts; the test fails
when a file grows or when it improves without lowering its ceiling.
Discovery picks the module up in the existing CI shards.

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

* 3.x.x: correct the signal and #278 scope claims in the capacity runbook (#303)

The native server is PID 1 in the shipped container with no init and
installs handlers for SIGTERM and SIGINT only, so the kernel drops SIGUSR1
rather than terminating the process. Thread and open-file-descriptor gauges
fell outside #278's cutover-minimum scope, and #288's docs CI check is still
to land.

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

* 3.x.x: join shell continuations before scanning doc commands (#318 review)

`dead_commands` matched each physical line on its own, so a documented
`python3 -m \` + `lab.prism.deleted` (or `python3 \` + `-m lab.x`,
`python3 -u \` + `-m lab.x`, `python3 \` + `lab/x.py`) slipped past the
guard even though the fence runs the deleted module. Join backslash
continuations into logical shell lines first and report the command at
its first physical line. `dangling_references` and the RATCHET ceilings
are untouched; no wrapped `python ... lab` command exists in docs/ today.

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

* 3.x.x: keep the warm-up boundary sample in the RSS-bound baseline (#318 review)

The Python evaluator this awk pass replaced put a sample taken exactly
warmup seconds after the first one into the warm-up (`t <= warmup_seconds`)
and judged only later samples against the bound (`t > warmup_seconds`).
The awk used a strict `<`, so with the runbook's regular 300 s cadence a
transient peak landing exactly at hour one fell out of the baseline and
could turn a pass into a fail. Use `<=` so the verdict is the Python
tool's, and say so in the prose.

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

* 3.x.x: state the RSS-bound span floor the check actually enforces (#318 review)

The resident-set bound prose said the awk command "refuses a series
shorter than the soak". It does not: `last - t0 < 82800` refuses a series
spanning less than 23 hours from its first sample to its last, exactly as
the retired Python evaluator's RSS_BOUND_DEFAULT_MIN_SPAN_SECONDS did
(23 * 3600, measured from the first sample after re-basing). The
threshold and the expression are unchanged; a 23 h floor is parity with
the tool this runbook qualified under, and 86,400 s from t0 would reject
an honest 24 h soak whose last 5-minute sample lands just short.

The one-hour slack is the reason the Python source recorded on the
constant ("a 24 h soak with an hour of tolerance for a late first
sample", #234); the prose now says so and keeps step 2's 24 h run.

Verified with the unchanged awk program on synthetic 300 s-cadence
series: 82,800 s exits 0, 82,500 s exits 2.

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

* 3.x.x: parse real CPython option forms in the doc-command guard (#318 review)

The command regexes accepted only single-letter switches between the
interpreter and `-m` or a script path, so `python3 -OO -m lab.prism.deleted`
or `python3 -X dev -m lab.prism.deleted` ran deleted code while passing
contract (a). Share one interpreter-plus-options sub-pattern that follows
`python3 --help`: clustered flag letters, `-W`/`-X` with an attached or
following argument, and `--check-hash-based-pycs <mode>`. `-c cmd` stays
excluded because it runs its argument and ends the option list; CPython
rejects the `=` spelling of the long option, so none is accepted. Also scan
version-suffixed interpreters (`python3.12`), as the CI images name them.

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

* 3.x.x: record the image Compose resolved from the soak env files (#318 review)

Step 1 of the testnet soak runbook built the coordinator image through
Compose with the deployment's env files, then inspected
`${PRISM_COORDINATOR_IMAGE:-qbit-lab-prism-coordinator:local}` as a
standalone shell expansion. An operator who sets
`PRISM_COORDINATOR_IMAGE` only in an env file, without exporting it,
would build the configured image and inspect the default one instead.

Substitute the env files once, in a `compose` function, and let the same
invocation build the image and resolve its name through
`config --format json`, reading the `prism-coordinator` service record
with `python3`. `config --images prism-coordinator` is not used because
it prints the images of the services the coordinator depends on as well
(`postgres:16-alpine` and the qbitd image), one per line and in varying
order, so `docker image inspect` would receive one multi-line argument
and fail; `docker compose config` has no `--no-deps`.

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

* 3.x.x: match quoted and ./-relative targets in the doc-command guard (#318 review)

A ratcheted doc could swap one dangling `lab/prism/...` mention for a
runnable `python3 -m 'lab.prism.deleted'` or `python3 ./lab/prism/deleted.py`
command: rule (b) still counted the path, so the ceiling held, and rule (a)
required an unquoted module or `lab/` straight after whitespace, so it saw no
command. Both command rules now share one `quoted` sub-pattern that accepts a
target in matching single or double quotes, the script rule accepts `./`
prefixes, and the reported missing path is the normalised one.

`-m` may also close a flag cluster and take its module attached. On CPython
3.12 `-mjson.tool`, `-Im json.tool`, `-OOm json.tool`, `-Imjson.tool` and
`-m'json.tool'` all run the module, so those spellings are matched; `-Wm`
and `-Xm` hand `m` to `-W`/`-X` and stay unmatched, as does `-c`. A
mismatched quote is a shell syntax error, runs nothing and matches nothing;
the prose rule still sees the reference.

The module docstring now states the contract's limit: rule (a) is a lexical
check of direct python invocations and does not follow `cd`, `PYTHONPATH`,
aliases or shell variables.

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

* 3.x.x: reject malformed RSS rows in the bound check (#318 review)

The `awk` port of the resident-set bound skipped every row with fewer
than two fields under the same rule that skipped `#` comments, so a
sample lost during an RSS excursion (a truncated line in the CSV)
disappeared silently and a valid late sample could still pass the soak.
The deleted `read_rss_samples` raised on any non-blank, non-comment line
that was not `seconds,rss_bytes`, and the `rss-bound` CLI turned that
into exit 2. A non-numeric RSS field was worse than skipped: `abc > n`
compared as strings and reported a breach.

Skip only comment and blank lines, require a numeric first and second
field on every other row (extra trailing fields stay tolerated, as they
were in the Python tool) and report the offending row as unusable input
with exit 2. `exit` inside a main rule still runs `END` in every awk,
so the failure is recorded in a variable that `END` checks before any
verdict logic; verified on the macOS awk (20200816). `-1` samples are
still ignored, after validation.

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

* 3.x.x: sort RSS samples by time before the bound check (#318 review)

The deleted `evaluate_rss_bound` sorted the series by time before it
re-based on the first sample; the `awk` port took the origin from the
first physical row. A nonmonotonic file, such as two partial soak logs
concatenated with the later one first, put a late sample at the origin,
so the warm-up window swallowed every earlier sample (including a
post-warm-up excursion), the baseline rose to the excursion and the
verdict flipped or the span check refused the file.

Sort the file numerically on the first field with `sort -t, -k1,1n`
before the `awk` pass, so the origin is the earliest sample as it was in
the Python tool. Comment and blank lines sort as zero and are skipped
wherever they land, a malformed row is still caught after sorting, and
the pipeline exits with awk's status. Verified with the macOS sort
(2.3-Apple) and awk (20200816) against the deleted evaluator: a
breaching series with its hour-5 sample moved before the hour-0 rows now
fails as the Python tool failed it, where the previous command refused a
24 h file for its span and passed a 28 h one.

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

* 3.x.x: capture the runtime and pool series the RSS reading order cites (#318 review)

Item 3 of "What to look at first when RSS climbs" names
`qbit_prism_runtime_task_stalled{task}`,
`qbit_prism_runtime_poll_lag_seconds{task}` and
`qbit_prism_database_pool_acquire_seconds` as the evidence that a climb is a
blocked worker holding buffers rather than a leak. The five-minute capture
loop kept only the stall gauge, so the poll lag and pool wait at a breach
could not be read back: the full snapshots are taken at hour 1, hour 24 and
the breach itself, and cannot recover what those series showed at an earlier
sample.

Add both families to the `grep -E` filter. The poll-lag gauge renders with
its `task` label and matches the existing `[ {]` anchor as it is. The pool
histogram never renders under its bare family name: the registry emits
`..._bucket{result=...,le=...}`, `..._sum{result=...}` and
`..._count{result=...}`, as the observability tests assert, so the pattern
names those three suffixes explicitly and keeps the anchor after them. The
sentence after the loop now says the log carries the reading order's
runtime and pool series, so a breach is read at its own sample rather than
the nearest hourly snapshot.

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

* 3.x.x: match quoted interpreter names in the doc-command guard (#318 review)

A ratcheted doc could swap one dangling `lab/prism/...` mention for a
runnable `"python3" -m lab.prism.deleted` command: the shell strips the
matching quotes and runs Python, rule (b) still counted the module so the
ceiling held, and rule (a) required whitespace straight after a bare
interpreter name, so it saw no command. The interpreter now goes through
the same `quoted` sub-pattern as the target, bare or in matching single or
double quotes, with the quote in its own named group because `re` rejects
one group name used twice in a pattern.

The word boundary before `python` is kept, so `/usr/bin/python3` and
`env python3` still match. Inside `sh -c "python3 -m lab.x"` no quote
closes right after the name, so the interpreter quote backtracks to empty
and the inner command is read as before; a mismatched quote around the
name is a shell syntax error, runs nothing and matches nothing, and the
prose rule still sees the reference. No ratchet ceiling changed: the
tracked docs contain no such command today.

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

* 3.x.x: pin the deleted-test map's retired module paths to their last commit (#318 CI)

`docs/prism-deleted-test-map.md` landed on 3.x.x with #322 after this
branch's merge-base, and it names three `lab/prism/*.py` modules that #244
removed: `candidate_window.py`, `bundle_compiler.py` and
`endpoint_registry.py`. The reference guard this branch adds scans every
tracked doc on the merge ref, so CI's "Python unit tests (shard 1)" failed
on those three lines while the same test passed on the branch alone.

The guard's contract offers two ways to name retired code: describe it in
words or link a commit-pinned GitHub URL, which is stable history and
exempt. The three mentions are now links to the files at `700fae0`, the
last commit before #244 deleted them, with the module basename as the link
text so the visible path no longer claims to exist on the branch. The
table's wording is otherwise unchanged.

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

* 3.x.x: pin candidate_window.py to the commit that last carried it (#318 CI)

`lab/prism/candidate_window.py` was removed before #244, so the link 4d6d0c8
added at `700fae0` pointed at a commit without the file. The other two
modules did exist there; this one now links to `^`, the last
commit before its own deletion. Verified with `git cat-file -e` on the
pinned tree.

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

* 3.x.x: pin candidate_window.py to v2.0.2, where the module lives (#318 CI)

bd35536 rewrote the `candidate_window.py` link with a malformed revision
(`blob/^/`), which the reference guard no longer recognised as a
commit-pinned URL. The module never existed on the 3.x.x line; it was
added on the 2.x line by the v2.0.0 consolidation (#246) and is present at
v2.0.2, `504846c`, the same pinned commit the guard's own tests use as
their example. The link now points there, checked with `git cat-file -e`
against that tree before committing. The guard passes on the merged tree.

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

* 3.x.x: gate the soak pre-check on a fresh metrics body (#318 review)

The soak pre-check matched any x-prism-metrics-state value, so a stale or
unavailable body whose cached process gauge still read 1 printed two lines,
grep exited 0, and the prose told the operator the RSS series was
trustworthy. Every gauge in the body is a scrape-time render of cached
observations, and the header is what says whether that render is current.

Replace the grep with an awk verdict in the style of the RSS bound check:
it sets a flag on the exact `x-prism-metrics-state: fresh` line and on the
process collector gauge at 1, prints `ready` and exits 0 only when both are
present, and otherwise names the failed condition and exits 1. The sentence
after it now says both lines are required, that a stale or unavailable body
can still carry a cached gauge at 1, and that the run must not start until
the check passes. The step-3 capture loop is unchanged; it records the state
header whatever its value on purpose.

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

* 3.x.x: require a runnable entry point for -m targets in the doc-command guard (#318 review)

The doc-command guard accepted a `python -m lab.pkg` command when only
`lab/pkg/__init__.py` was tracked, because it reused the prose contract's
candidate list and took its first two entries. CPython does not run such a
package: on 3.14, `python3 -m lab.pkg` against an `__init__.py`-only package,
or against a bare directory, prints "No module named lab.pkg.__main__;
'lab.pkg' is a package and cannot be directly executed" and exits 1. It runs
the package only when `lab/pkg/__main__.py` exists, and it runs
`lab/auxpow/vardiff.py` even though `lab/auxpow` has no `__init__.py`.

Commands now resolve through a separate `runnable_candidates` helper that
admits only `<relative>.py` or `<relative>/__main__.py`; the prose contract
keeps `module_candidates`, so a `lab.prism.pkg` mention of an
`__init__.py`-only package is still not dangling. A dead `-m` command reports
both paths joined by `or`, so a reader is not told to create `lab/pkg.py`
beside a tracked package that merely lacks `__main__.py`. The docstring
states the new rule, the passing fixtures gain `lab/pkg/__main__.py`, and
tests cover the four package shapes and the prose exemption.

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

* 3.x.x: pin the B8 parity record's retired module paths to the commit it cites (#318 CI)

`docs/prism-b8-miner-parity.md` landed on 3.x.x with #313 after this
branch's last merge of the base, and its reference line names
`lab/prism/tip_refresh.py` and `lab/prism/job_delivery.py`, which #244
removed. The reference guard this branch adds scans every tracked doc on
the merge ref, so CI's "Python unit tests (shard 1)" failed on that line
while the test passed on the branch alone.

The line already anchors itself to a 2.x.x commit; the two module mentions
are now links to those files at `95ffe06`, checked with `git cat-file -e`
against that tree, with the basenames as link text so the visible path no
longer claims to exist on the branch. The guard treats a commit-pinned
GitHub URL as stable history. The sentence is otherwise unchanged.

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

* 3.x.x: parse quoted option arguments in the doc-command guard (#318 review)

The doc-command guard read a `-W`, `-X` or `--check-hash-based-pycs`
argument only as a bare non-whitespace word, so `python3
--check-hash-based-pycs 'always' -m lab.prism.deleted` and `python3 -X 'dev
mode' -m lab.prism.deleted` ran and yet were not reported: the quoted mode
broke the `always|default|never` match, and the space inside the quotes
ended the `-X` argument early. The bare word also swallowed an unterminated
quote, so `python3 -X 'dev" -m lab.prism.x`, which bash rejects before
Python starts, was reported as a dead command. On CPython 3.14, `-X 'dev'`,
`-X "dev mode"`, `-X'dev'`, `-X"dev mode"`, `-W 'error'`, `-W"error"`,
`-W 'error'::DeprecationWarning` and `--check-hash-based-pycs "always"` all
run `json.tool` exactly as their bare spellings, because the shell strips
matching quotes, attached or not, before CPython sees them.

An option argument is now a shell word: runs of unquoted characters
alternating with matching-quoted strings, non-empty, ending at whitespace.
The runs and strings alternate rather than nest, so one word has a single
parse and a long argument cannot backtrack exponentially. `-W` and `-X`
take that word attached or after whitespace; `--check-hash-based-pycs`
reuses `quoted()` around its three modes with its own group name, since the
command patterns already use that group for the interpreter and the target.
An unquoted run holds no quote character, so a mismatched quote matches no
option and the line is left to the prose contract. Tests cover each quoted
form against missing and existing targets, a wrapped form, and the
mismatched forms.

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

* 3.x.x: accept -R and the -- terminator in the doc-command guard (#318 review)

`PYTHON_FLAG` listed every single-letter option but `-R`, so `python3 -R -m
lab.prism.deleted` ran and was not reported. On CPython 3.14 the option
lines of `python3 --help` are `-b -B -c -d -E -h -i -I -m -O -OO -P -q -R
-s -S -u -v -V -W -x -X`, with `-h : print this help message and exit (also
-? or --help)`; `-R` was the only letter missing, and `python3 -R -m
json.tool --help` and `python3 -Rm json.tool --help` both run the module,
so `-Rm` joins the adjacent `-m` spellings. Separately, the standard `--`
terminator before a script path evaded `SCRIPT_COMMAND`: `python3 --
s.py`, `python3 -O -- s.py` and `python3 -OO -- ./s.py` run the script.

`R` is in the flag class and `SCRIPT_COMMAND` accepts an optional `--`
followed by whitespace before the script target. `MODULE_COMMAND` does not:
after `--` CPython takes `-m` as a script name, and `python3 -- -m
json.tool` fails with "can't open file '.../-m'", so that line runs nothing
and stays with the prose contract, which a test asserts. Tests cover `-R`
and `-ER -X dev` in the option table, `-Rm`, and `--` before a script with
missing and existing targets, in a wrapped form, and with `./`.

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

* 3.x.x: invalidate the soak when the coordinator restarts (#318 review)

`compose.yaml` gives `prism-coordinator` `restart: on-failure`, so a
coordinator that exits mid-soak is started again by Compose inside the same
container, and the step-3 capture loop, which only read `/proc/1/status`,
would go on sampling the new PID 1 without a word. The CSV would then splice
several short lifetimes into one 23 h span, each restart's low RSS and reset
share counters would hide the growth, and the bound, which assumes one
process, could pass.

The loop now reads `docker inspect` for the container's status, `StartedAt`
and `RestartCount` once before it starts and again before every sample,
appends each reading to `soak-process.log`, and on any change prints both
readings with the time to stderr and stops. The container is the same across
a Compose restart, so `$c` stays the handle and `docker inspect` on it is the
right probe. The prose says the bound is evidence about one process, why the
restart policy would otherwise hide a restart, that the log lets a later
reader show the run was one process, and that a change invalidates the run:
keep the message and the log, attach `docker logs "$c"`, and start over from
step 2. Step 6 gets one sentence saying such a run is not judged. Verified
against a throwaway container with the same restart policy, where two policy
restarts moved `StartedAt` and took `RestartCount` from 0 to 2, and with a
stub `docker` that changes `StartedAt` on the second iteration.

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

* 3.x.x: invalidate the soak when an RSS sample is missing (#318 review)

The step-3 capture loop piped `/proc/1/status` straight into `awk`, so when
`docker exec` failed transiently, or the body had no `VmRSS:` line, the awk
printed nothing and exited 0 and the loop went on without a word. The bound
check only enforces the overall 23 h span from the first sample to the last,
so two successful samples 82,800 s apart pass it while the missing
five-minute samples between them can hide an excursion, and the judge's
malformed-row rule cannot catch this because no row is written at all.

Each iteration now writes exactly one `seconds,bytes` row or stops the run.
The body is read into a variable first and its exit status kept, because the
block is pasted into an operator's bash or zsh and a pipeline's status is its
last command's without `pipefail`; the awk prints a row only when the body
carries exactly one `VmRSS:` line in kB; and an empty or malformed result
prints the time, the exec's exit status when it was non-zero, and the body
that was read to stderr, then breaks, in the restart guard's style. The
variable is `body`, not `status`, because `status` is read-only in zsh. The
prose says a missing sample invalidates the run for the same reason a
restart does, that a transient `docker exec` failure is therefore not
skipped, and that the operator starts over from step 2; step 6 now says a
run stopped on a missing sample is not judged. Verified with `sh -n`,
`bash -n` and `zsh -n` on the extracted loop, with a stub `docker` in sh,
bash and zsh that returns a normal body, then a body without `VmRSS:` or a
non-zero exit, where each run wrote one row and stopped with the message, and
with a live throwaway container, where the exec line produced one row and,
after the container was removed, an empty body with exit status 1.

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

* 3.x.x: tokenize shell-quoted targets in the doc-command guard (#318 review)

The command contract accepted a `-m` target or script path that was entirely
bare or entirely inside one pair of quotes, so a target the shell assembles
from several pieces slipped through: `python3 -m "lab.prism."deleted`,
`python3 -m lab."prism".deleted` and `python3 "lab/prism/"deleted.py` all run
the missing target (bash 3.2 and CPython 3.14 run `python3 -m "json."tool`
exactly as the bare spelling), yet the scanner reported nothing, and the
prose rule saw only `lab.prism`, which resolves to the tracked directory.

The target is now read as a whole shell word: the tokenizer that already
parsed quoted option arguments is generalised to `SHELL_WORD` and used for
the `-m` target and the script path as well. `dead_commands` removes the
matching quotes, strips any `./` prefixes from a script path, and only then
reads the word against the target grammar and resolves it, reporting the
normalised target. A word that then names no `lab` module or script, such as
`$VAR`, another package, or `"lab.prism."` with nothing after the dot (which
CPython answers with "No module named lab.prism."), is not a `lab` command.
An unterminated opening quote still matches nothing. `quoted()` stays for
the interpreter name and the `--check-hash-based-pycs` mode, whose values
are fixed words with nothing to concatenate.

A word ends at whitespace, at a bash metacharacter (`;`, `|`, `&`, `(`, `)`,
`<`, `>`), at a backtick, or at a quote that opens no string, so the forms
the previous `\b` boundary caught keep being caught: `` `python3 -m lab.x` ``
in inline code, `python3 -m lab.x; ...`, `$(python3 lab/x.py)` and the inner
command of `sh -c "python3 -m lab.x"`. Backslash escapes are out of scope and
the docstring now lists them with the other things the lexical check does not
follow.

`dangling_references` is unchanged: the prose rule is about mentions, and
`"lab.prism."deleted` in prose is not a mention of a module, while the
runnable form is now caught by the command rule.

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

* 3.x.x: skip patch and diff files under docs/ in the reference guard (#318 CI)

The guard read every tracked file under `docs/`, and #320 (22bd1a2) added
`docs/prism-alert-rules-qbit-tools.patch`, a unified diff of qbit-tools'
Ansible monitoring role. Its line 991 is a `-` line quoting a comment that
used to name `lab/prism/block_candidates.py` in that other tree, so the
prose contract reported it as a dangling reference on this branch. The
mention is quoted history, not this repository's prose: the patch records
another tree's text before and after a change, editing a line of it would
break the patch, and neither contract has anything to say about it.

Both contracts now skip tracked files under `docs/` whose suffix is in
`QUOTED_HISTORY_SUFFIXES` (`.patch` and `.diff`). The selection is factored
into `documented(paths)`, which `setUpClass` filters to files, so the rule
is testable without git: a new test checks that a patch and a diff are left
out while `.md`, `.json` and `.yaml` paths stay in, and that no selected
doc carries a skipped suffix. The scope is not narrowed to Markdown: every
other suffix is still read. The module docstring states the exemption. With
the skip in place the real-docs tests pass again, `dead_commands` over the
59 documents in scope is empty, and every RATCHET count equals its ceiling.

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

* 3.x.x: tokenize the interpreter word in the doc-command guard (#318 review)

The command contract accepted an interpreter name that was wholly bare or
wholly inside one pair of quotes, so a name the shell assembles from pieces
slipped through: bash 3.2 runs `"python"3 -m json.tool`, `'pyth'on3 -m
json.tool`, `python"3" -m json.tool` and `"/usr/bin/pyth"on3 -m json.tool`
exactly as `python3`, yet the scanner reported nothing for `"python"3 -m
lab.prism.deleted`, `'pyth'on3 -m lab.prism.deleted` and `python"3"
lab/prism/deleted.py`, while `/usr/bin/python3 …` and `env python3 …` were
caught and `mypython3 …` was correctly not.

The interpreter is now read as a whole shell word, the way 43609d1 reads
the target. `dead_commands` strips the matching quotes, takes the basename
after the last `/`, so `/usr/bin/python3` keeps matching, and accepts the
word only if it is wholly `python`, `python3` or `python3.N`; `mypython3`,
`cpython3`, `python2` and `python3x` are other programs and are not
commands, while the prose contract still sees their reference. Option
parsing, the `-m` and script handling and the target tokenizer are
untouched: `SHELL_WORD`, `PYTHON_OPTION` and `MODULE_OPTION` are the same
strings as before, and the same 21 commands are found across the tracked
documents by the old and the new grammar.

Two details make reading a word from every position of a line sound.
First, a word may start right after a closing quote, so `"/usr/bin/"python3`
is one candidate and its tail `python3` another: the command patterns are
lookaheads that consume nothing, and `python_commands` drops a candidate
that starts inside the interpreter word of the one before it, whether or
not that word named Python, so `"/usr/bin/"python3 lab/prism/x.py` is
reported once and `"my"python3 -m lab.prism.x` (`mypython3` to bash) not at
all. Second, the interpreter word's quoted pieces hold no whitespace: a
program name is one word, and with arbitrary quoted pieces `"$c" sh -c
"python3 …` read from `$c` would pair the closing quote of `"$c"` with the
opening quote of the `sh -c` string and hide the `python3` inside it. A
word starts where no unquoted word character precedes it, so `env python3
…`, `docker exec "$c" python3 …`, `sh -c "python3 …"`, inline-code
`python3 …` and `$(python3 …)` are caught as before, and a mismatched
interpreter quote still matches nothing. The docstring and the grammar
comments now cover the interpreter alongside the target.

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

* 3.x.x: invalidate the soak when a metrics sample fails or is stale (#318 review)

The step-3 capture loop piped the `/metrics` scrape through `tr`, `grep`
and `sed` straight into `soak-metrics.log`, so when the `curl` failed, the
body carried none of the expected families, or its header said `stale` or
`unavailable`, the trailing `sed` still exited 0 and the loop went on
without a word. The correlated series is what reads an RSS excursion back
at its own five-minute sample, so the log could omit exactly the interval
where RSS breached while the run stayed eligible for judgment, and the
step-2 gate could not catch it because it proves the body fresh once, at
the start.

Each iteration now appends the filtered lines or stops the run, in the RSS
guard's style. The response is read into a variable first and the exec's
exit status kept; the `\r` strip runs as a second step on the variable
rather than in the same pipeline, because the status of a command
substitution is its last command's without `pipefail`, which not every
operator shell sets. An awk then requires, in order, that the exec
succeeded, that the body carries exactly the line
`x-prism-metrics-state: fresh`, and that the RSS gauge family
`qbit_prism_process_resident_memory_bytes`, the series the reading order
starts from, is present; the other families in the filter are not
required, since a histogram bucket or a `runtime_task_stalled{task}`
series can legitimately be absent from a scrape. On any failure the loop
prints the time, the condition that failed (the exit status, the state
header actually seen, or the missing family) and the header lines to
stderr, then breaks. The `grep -E` filter and the `sed` timestamp prefix
are unchanged; the restart guard and the RSS-sample guard are untouched.
The prose holds the metrics sample to the missing-sample rule and says the
step-2 gate proves freshness only once, and step 6 now lists a failed or
non-fresh scrape among the reasons a run is not judged.

Verified with `sh -n`, `bash -n` and `zsh -n` on the extracted loop, and
with a stub `docker` and a stub `sleep` in sh, bash and zsh that serve a
normal `/proc/1/status` body to the `cat` call and, for the `curl` call, a
fresh body (two samples, eight rows, no message), then from the second
sample a `curl` exit 7, a `stale` header, or a fresh header without the
RSS gauge: each of the nine failure runs wrote the first sample's four
rows and stopped with its message. `python3 -m unittest
tests.test_docs_lab_prism_references -v` passes (56 tests).

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

* 3.x.x: normalise ANSI-C quoted words in the doc-command guard (#318 review)

bash treats $'…' (ANSI-C quoting) and $"…" (locale quoting) as quoted
strings and strips them like plain quotes: on bash 3.2, `python3 -m
$'json.tool'`, `python3 -m $'json.'tool`, `python3 -m $"json.tool"` and
`$'python3' -m json.tool` all run json.tool. The word grammar read the `$`
as an unquoted character, so `unquote` produced `$lab.prism.deleted`, which
matched no target, and the guard reported nothing for a command that runs a
deleted module.

A quoted piece may now carry the `$` prefix, in both the target word and the
interpreter word, and `unquote` strips it with the quotes, so
`$'lab.prism.'deleted` reads as `lab.prism.deleted` and `$'python3'` as
`python3`. A `$` directly before a quote belongs to the quoted piece and is
never an unquoted character, which keeps the split of a word unique and the
alternation free of ambiguous nesting; a `$` before anything else is an
ordinary character, so `$VAR` words behave as before. Backslash escapes stay
out of scope as the docstring says: `$'lab\x2eprism.deleted'` keeps its
backslash, names no target and is not reported. Tests cover the evading
module, script and interpreter forms, the same forms with existing targets,
the escape and unterminated-quote cases, and a wrapped form at its line.

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

* 3.x.x: invalidate the soak on a failed process collection (#318 review)

The step-3 capture loop accepted a `/metrics` scrape when the exec exited
0, the body carried exactly `x-prism-metrics-state: fresh` and the family
`qbit_prism_process_resident_memory_bytes` was merely present. The header
proves less than that check assumed. `metrics_snapshot.rs` describes only
the age of the last snapshot publication and says a fresh failed probe is
still fresh, and the collector families are overlaid at scrape time by
`Metrics::overlay_collections`: when the process collector's last success
is absent or older than `COLLECTOR_STALE_AFTER` (30 s),
`snapshots::invalidate` renders
`qbit_prism_collector_available{collector="process"} 0` and
`qbit_prism_process_resident_memory_bytes -1`, the rendering the registry
test `process_collector_reads_real_input_and_distinguishes_failure_from_zero`
asserts for a failed read. Such a body passed the loop, so it recorded a
correlated sample with no RSS value, the series the reading order starts
from, instead of invalidating the soak. The step-2 gate already requires
the gauge at exactly 1, but proves it once, at the start.

The awk now requires, in order, that the exec exited 0, the exact line
`x-prism-metrics-state: fresh`, the exact line
`qbit_prism_collector_available{collector="process"} 1`, and an RSS sample
whose value is a nonnegative integer, so `-1` is rejected. On failure it
prints the first condition that failed in the existing style: the exit
status, the state header seen or its absence, the collector gauge line
seen or its absence, or the RSS line seen or its absence. The surrounding
shell is unchanged. The prose states the new conditions and why the header
alone is not enough, and step 6 lists an unavailable process collector and
an unusable RSS value among the reasons a run is not judged. Step 2, the
RSS `/proc/1/status` guard and the restart guard are untouched.

Verified with `sh -n`, `bash -n` and `zsh -n` on the extracted loop, and
with a stub `docker` and a stub `sleep` in sh (bash 3.2), bash 3.2 and zsh
5.9. The stub serves a normal `/proc/1/status` body to the `cat` call and,
for the `curl` call, a fresh body with the gauge at 1 and RSS at 4194304
first, then the case under test: the gauge at 0 with RSS `-1`, the gauge
at 1 with RSS `-1`, no gauge line, and a `stale` header. Each of the
twelve failure runs wrote the first sample's five rows to
`soak-metrics.log` and stopped with its own message; the second sample's
RSS row still lands in `soak-rss.csv`, since that read precedes the
scrape. The three control runs, with the second body also good and the
stub `sleep` ending the loop, wrote ten rows and no message. The awk
program gives the same answer for every case under macOS awk 20200816,
busybox 1.37.0, gawk 5.3.2 and mawk 1.3.4. `python3 -m unittest
tests.test_docs_lab_prism_references` passes (60 tests).

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

* 3.x.x: require exactly two fields in the soak judge (#318 review)

The `awk` bound check refused a row with fewer than two fields but read
any row with more, so `82800,300,000` judged as 300 bytes and
`0,100,garbage` set the baseline, and corrupted input could suppress a
breach while the prose promised an exact `seconds,rss_bytes` format. The
deleted Python evaluator had the same looseness (`read_rss_samples` at
`1398bbc^` took the first two comma-separated fields and ignored the
rest), so the port was faithful to it and wrong with it.

The predicate is now `NF != 2`: a row with a third field, including a
trailing comma, is unusable input (exit `2`) like a truncated one. The
capture loop writes exactly two fields, so a row with more was corrupted
somewhere between the loop and the judge and is refused rather than read.
The prose says the field count is exact and names the tightening over the
Python tool.

Verified with the judge fence extracted from the doc and run under `sh`
with BSD awk: a flat 24 h series passes (exit 0), `0,100,garbage`,
`82800,300,000`, `100,200,` and a one-field row each exit 2 with the row
named, `-1` samples, comments and blank lines are still skipped, a
post-warm-up breach still exits 1, and whitespace around a field still
counts as two fields; the `NF < 2` form exited 0 on both three-field
rows. `python3 -m unittest tests.test_docs_lab_prism_references` passes
(60 tests).

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

* 3.x.x: write each soak run into its own directory (#318 review)

The step-3 capture loop appended every sample to `soak-process.log`,
`soak-rss.csv` and `soak-metrics.log` in the working directory with `>>`,
and nothing truncated them or moved them aside. The restart rule says an
invalid run is started over from step 2, so a second run appended to the
first run's files, and the judge, which sorts by timestamp before it
reads, then took its first hour, and so its baseline, from the earlier
run, judged the later run against that baseline, and satisfied the span
floor with the earlier run's first sample and the later run's last.
Truncating instead would have destroyed the evidence the restart rule
says to keep.

Every run now writes into its own directory, `soak-<UTC start time>`,
and the loop is chained to the `mkdir` that creates it with `&&`: `mkdir`
without `-p` refuses a name that already exists, and on that refusal the
loop does not run at all, so a run can never append to another run's
files and never writes anything the operator did not name. The share-ack
histogram and the `/metrics` snapshots in steps 3 and 4 go into the same
directory, step 6 judges the run's own `soak-rss.csv`, step 7 records the
run directory, and the restart rule keeps the directory rather than "the
log". The bound section says the sort applies to partial logs of one run
and points at the per-run directory as the reason two runs never share a
file.

Verified with `sh -n`, `bash -n` and `zsh -n` on the loop extracted from
the doc, and with a stub `docker`, `sleep` and `date` in sh, bash and zsh:
a fresh run created its directory and wrote two RSS rows, three process
readings and eight metrics lines before the stub flipped the process
state and the restart guard stopped it; a second run under the same
start time was refused by `mkdir`, the loop did not run, the first run's
files were byte-identical afterwards and nothing was written at top
level; a third run under a later start time created a second directory
and left the first untouched. `python3 -m unittest
tests.test_docs_lab_prism_references` passes (60 tests).

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

* 3.x.x: leave -h and -V out of the doc-command guard's prefix options (#318 review)

`PYTHON_FLAG` listed `h` and `V` among the option letters that may sit
between the interpreter and its target, so the guard read `python3 -V
lab/removed.py` and `python3 -h -m lab.removed` as commands that run the
missing target and would have failed CI on a diagnostic that never
reaches it. CPython prints the help text for `-h` and its alias `-?`, and
the version for `-V`, and exits before it reads the target, so such a
command runs nothing; the comment above the class already excluded `-c`
for the same reason.

The class is now every single-letter option other than `-c`, `-m`, `-h`
(with `-?`) and `-V`. Because `PYTHON_FLAG` also builds the `-W`/`-X`
cluster form and the `-m` cluster (`MODULE_OPTION`), `-hW error`, `-VX
dev`, `-hm lab.x` and `-Vm lab.x` are no longer read as options either,
which is what CPython does with them. The comment names the letters, the
behaviour and the spellings checked, and a new `ScannerTests` case covers
`-h`, `-?`, `-V`, `-VV`, `-OO -h`, `-Oh`, `-hOO`, `-V -X dev`, `-VX dev`
and `-hW error` before a missing module (bare and quoted) and a missing
script, `-V --` before a script, and the clusters `-hm`, `-Vm`, `-Ohm`,
`-hIm` and `-VVm` with the module attached or following; each is not a
command, and the prose contract still sees the reference.

Verified on CPython 3.14.6 with `lab/gone.py` and `gone.py` that raise
`SystemExit("RAN")`: every spelling above printed the help text or the
version and exited 0 with neither file run, while `python3 -m lab.gone`
and `python3 gone.py` printed `RAN`. Mutation check: with the old class
restored in a copy of the module, the new test fails in ten of its
subtests (every one but `-?`, which was never in the class). `python3 -m
unittest tests.test_docs_lab_prism_references` passes (61 tests).

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

* 3.x.x: invalidate the soak on a gap between samples (#318 review)

The step-3 capture loop never compared one sample's time with the
previous one's, and the `awk` judge's span floor reads only the first
and last timestamps. A host suspended for an hour, or a `docker inspect`
or `docker exec ... cat` that stalled for one (neither call is bounded;
only the `curl` carries `--max-time`), therefore left a hole in the
series that nothing reported: the iteration after the stall wrote a
valid row, the loop went on, and the judge passed a file in which an
excursion could have risen and drained unseen. The deleted Python
evaluator (`evaluate_rss_bound` in `lab/prism/process_telemetry.py` at
`1398bbc^`) had no gap rule either, so the port was faithful to it and
wrong with it.

The judge now takes `max_gap=360` and refuses a series in which two
consecutive usable samples are more than 360 s apart as unusable input
(exit 2), naming the interval and both timestamps. The rule sits after
the `-1` skip, so a hole bridged by `-1` rows is still a hole, and a
single `-1` row between two cadenced samples opens a 600 s gap; the loop
never writes one, and the prose says so. The loop keeps the previous
iteration's `now` and, before anything is written, stops the run as
invalid when more than 360 s have passed since it, printing the interval,
its own timestamp and the last sample's. The tolerance is the 300 s of
sleep plus a minute for the three reads. The prose explains the rule in
the bound section as a tightening over the Python tool of the same kind
as the exact field count, adds a step-3 paragraph on the interval check
beside the missing-sample one, and lists a gap among the reasons step 6
does not judge a run.

Verified with the judge fence extracted from the doc under macOS awk
20200816, and under busybox 1.37.0, gawk 5.3.2 and mawk 1.3.4 in an
alpine container, all agreeing: a flat 300 s series passes (exit 0); a
3900 s hole after hour 2, the same hole bridged by `-1` rows, a 2.5x
excursion that drained inside the hole, the hole in shuffled input and a
hole inside the warm-up each exit 2 with the gap named; a 360 s interval
passes and a 361 s one exits 2; a breach still exits 1, and a malformed
row, a short span, comments and blank lines behave as before. The
unchanged judge at the previous HEAD passed every hole case. The loop,
extracted from the doc, passes `sh -n`, `bash -n` and `zsh -n`, and with
a stub `docker`, `sleep` and `date` under sh (bash 3.2 in POSIX mode),
bash 3.2 and zsh 5.9: a control run in cadence wrote three RSS rows
before the stub's process flip ended it; a run whose second `date +%s`
is 3900 s after the first stopped with the gap message after exactly one
row, one process line and one metrics sample; a 360 s interval continued
and a 361 s one stopped. `python3 -m unittest
tests.test_docs_lab_prism_references` passes (61 tests).

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

* 3.x.x: stop the soak when an append to the run's files fails (#318 review)

The step-3 capture loop appended its process reading, RSS row and
metrics lines with `>>` and never looked at the status. The operator's
shell is not under `set -e`, so when the run directory filled or its
filesystem returned an I/O error the loop went on reading and failing to
write, and once the rows already on disk spanned the 82,800 s the judge's
floor asks for they would have passed it, with the hours after the disk
filled, and the process readings and metrics lines that should explain
them, missing from the record. The gap rule cannot see this: the series
simply ends.

Each of the three appends is now checked and the first that fails stops
the run as invalid, naming the file and the sample time, in the style of
the other stop paths. The metrics lines are read into a variable before
they are appended, as the body and the response already are: the status
of the pipeline would be `sed`'s, and what a failed write does to that is
each implementation's own affair, whereas the builtin `printf` reports one
as `1` in `sh`, `bash` and `zsh` alike. The grep pattern is unchanged. The
prose adds the rule beside the missing-sample and gap paragraphs, and
step 6 lists a failed append among the reasons a run is not judged.

Verified with the loop extracted from the doc: `sh -n`, `bash -n` and
`zsh -n` pass, and with the stub `docker`, `sleep` and `date` under sh
(bash 3.2 in POSIX mode), bash 3.2, zsh 5.9, busybox 1.37.0 sh and dash
0.5.13, the control and gap runs behave as before; with the stub `sleep`
replacing `soak-rss.csv`, `soak-process.log` or `soak-metrics.log` by a
directory after the first iteration, the second iteration stops with the
append message naming that file and nothing further is written. In an
alpine container, `echo x >> /dev/full` and `printf '%s\n' x >> /dev/full`
return 1 in busybox sh, dash, bash 5.3.9 and zsh 5.9, and `if !` and `||`
take the failure branch while the shell keeps running. `python3 -m
unittest tests.test_docs_lab_prism_references` passes (61 tests).

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

* 3.x.x: record why a soak is invalid and return nonzero (#318 review)

Every stop path of the step-3 capture loop printed its message to stderr
and left the loop with `break`, whose status is 0, and wrote nothing to
the run directory to say the run was cut short. The iteration that finds
a bad metrics sample has already written its RSS row, so a stop after 23
hours left a directory whose CSV satisfies the span floor and nothing, in
the directory or in the status, to say it was invalid: a wrapper that ran
the fence as a script, or an operator who kept the directory and lost the
shell's scrollback, would have judged and passed it.

The fence now defines `invalid`, which copies what it is piped to
`$run/soak-invalid` and to stderr, and `capture`, a function that holds
the loop and is called at the end of the fence. Every stop path writes
its message through `invalid` and returns 1 from `capture`; `mkdir
"$run" || return` keeps the per-run-directory guard and returns `mkdir`'s
status before the loop runs. The loop body is otherwise unchanged. The
fence is pasted into the operator's interactive shell, which steps 4 to 7
read `$run` from, so the stop paths `return` rather than `exit`, and
`run=` and `c=` stay outside the function. The prose describes `capture`,
says the directory now records why it is invalid and that the only way
`capture` returns by itself is an invalidation, notes that `tee` still
delivers the message to stderr when the disk itself is the fault, and
step 6 refuses to judge a directory that holds `soak-invalid` whatever
its CSV would say; the restart rule points at the marker for the message.

Verified with the fence extracted from the doc: `sh -n`, `bash -n` and
`zsh -n` pass, and with the stub `docker`, `sleep` and `date` under sh
(bash 3.2 in POSIX mode), bash 3.2, zsh 5.9, busybox 1.37.0 sh and dash
0.5.13: the control, gap and three append-failure runs write the same
rows as before, `capture` returns 1 on each, `soak-invalid` holds exactly
the stop message (`cmp`-identical to the stderr text for the control and
gap runs), and `$run` is still set afterwards; a refused `mkdir` returns
its status, runs nothing and writes no marker. In an alpine container,
`tee -a /dev/full >&2` still delivers its input to stderr and exits 1
with busybox and coreutils tee, through `invalid` in busybox sh, dash,
bash 5.3.9 and zsh 5.9. `python3 -m unittest
tests.test_docs_lab_prism_references` passes (61 tests).

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

* 3.x.x: read quoted option words in the doc-command guard (#318 review)

The guard read the interpreter and the target as whole shell words and
unquoted them, but matched the option words between them with a regex
on the raw line, so the hyphen and the letters had to be bare. bash
strips the quotes of an option word before CPython sees it, so `python3
"-O" -m lab.prism.deleted`, `python3 '-m' lab.prism.deleted`, `python3
"-m"lab.prism.deleted`, `python3 $'-OO' -m …`, `python3 "-"O -m …`,
`python3 "-X" dev -m …` and `python3 "--" lab/prism/deleted.py` all run
the deleted target and were reported as nothing, and in a ratcheted
document such a spelling could replace a dangling mention without moving
the count.

The option regexes and the `quoted` helper are replaced by a tokenizer.
`INTERPRETER_CANDIDATE` finds each candidate interpreter word as before;
`command_target` then reads the words after it one shell word at a time
with `NEXT_WORD`, unquotes each, and applies the option grammar to the
unquoted word in order: a flag cluster is skipped; a `-W`/`-X` cluster
takes its argument attached or as the next word; `--check-hash-based-pycs`
takes the next word, which must be one of its three modes; a `-m` cluster
names the module attached or as the next word; `--` makes the next word
the script; any other word is the script, so `-c…`, `-h…`, `-?`, `-V…`
and long options still end the command at a word that names no lab
target. A word with a mismatched quote is no shell word, so the command
ends there, as bash rejects the line. `dead_commands` reports the same
`(first line, command, missing path)` rows, with the command sliced from
the interpreter word to the target word; the only observable change is
that a module and a script command on one line now report in source
order. `PYTHON_FLAG` and the target grammar are unchanged; the comments
describe the tokenizer and the spellings checked.

Verified on bash 3.2 and CPython 3.14.6 that every spelling above runs
`json.tool` or a `lab/gone.py` that raises exactly as its bare form,
that `'-h'`, `"-hm"`, `"-V"`, `"-Wm"`, `"-Xm"`, `"--check-hash-based-pycs"
sometimes` and `'--' -m` still run nothing, and that `"-O'` and `-X "dev'`
are rejected by bash before Python starts. Five new `ScannerTests` cover
the quoted, concatenated and ANSI-C option words before missing and
existing module and script targets, the wrapped form at the right line,
the quoted non-command options, and mismatched option-word quotes.
Mutation check: with the scanner at the previous HEAD, the new tests fail
in 16 places. Over the 59 docs in scope the old and new scanners read the
same 17 Python commands with identical kind and target. `python3 -m
unittest tests.test_docs_lab_prism_references` passes (66 tests).

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

* 3.x.x: cover quoted --check-hash-based-pycs modes in the doc-command guard (#318 review)

A review of the regex scanner noted that `python3 --check-hash-based-pycs
$'always' -m lab.prism.deleted` and `python3 --check-hash-based-pycs
alwa"ys" -m lab.prism.deleted` were read as no command, while bash hands
CPython the bare mode and the missing target runs. The tokenizer that
replaced the regexes in a1c542a unquotes every word after the interpreter
before the grammar sees it, the mode included, so both spellings are
reported there; this adds the test that says so.

`test_quoted_hash_mode_arguments_are_read_as_shell_words` covers
`$'always'`, `alwa"ys"`, `'never'`, `$"default"`, `de'fault'` and
`"al"ways` before a missing module and a missing script, and the same
before an existing module, and checks that `"sometimes"`, `$'some'times`
and two mismatched-quote spellings are no command while the prose
contract still sees the reference.

Verified on bash 3.2 and CPython 3.14.6 that each of the six spellings
runs `json.tool`, and that `$'some'times` is rejected with
"--check-hash-based-pycs must be one of 'default', 'always', or 'never'"
before anything runs. `python3 -m unittest
tests.test_docs_lab_prism_references` passes (67 tests).

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

* 3.x.x: re-read the coordinator identity after each soak sample (#318 review)

The step-3 `capture` function checked the coordinator's identity before
each sample's reads and nowhere else. A restart between that check and
the `/proc/1/status` and `/metrics` reads recorded the replacement's RSS
and metrics under the original identity in `soak-process.log`; every
later iteration's check would catch it, but the last iteration of a
valid run has no later iteration, since the operator ends the run after
24 h, so a restart in that window on the last sample left a directory
with no `soak-invalid` that read as a single-process run.

The identity is now read again after the two reads, after the metrics
append and before the sleep, and a change ends the run as invalid
through `invalid` and `return 1` like every other stop path, printing the
sample time and both readings. The pre-sample check and the one
`soak-process.log` line per sample are unchanged. That sample's rows are
already in the files, which is fine because the marker keeps the
directory from being judged, as step 6 says. The step-3 intro names the
second check and the restart paragraph explains the window.

Verified with the fence extracted from the doc, `sh -n`, `bash -n` and
`zsh -n` passing, and with the stub `docker`, `sleep` and `date` under sh
(bash 3.2 in POSIX mode), bash 3.2 and zsh 5.9, where the stub's inspect
answer flips `RestartCount` at a chosen call: flipping at the post-read
check of the second sample stops the run with the new message after two
RSS rows, two process lines at the original identity and eight metrics
lines; flipping at the first sample's post-read check stops it after one
row; flipping at the second sample's pre-check still stops with the
existing message; with no flip, five samples run with no identity or gap
message and the run ends on a gap sentinel. In every case `capture`
returns 1 and `soak-invalid` is byte-identical to stderr. `python3 -m
unittest tests.test_docs_lab_prism_references` passes (67 tests).

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

* 3.x.x: fetch the pinned qbit through a cached, two-route, digest-checked installer (#318 CI)

Run 34857720110 lost the native PRISM job before any Rust test started:
the release download route on github.com answered 504 for the whole of
curl's seven-second --retry 3 window (an eleven-second first attempt, then
three instant 504s carrying github.com's own error page), so the install
step exited 22 and the gate-manifest proof failed for want of a manifest.
The run four minutes earlier fetched the same asset in seven seconds.

Replace the inline curl with .github/scripts/install-prism-qbit.sh, which
keeps the version, asset id and digest pinned in one place and takes the
tarball from the first source that verifies:

- a cached copy (actions/cache keyed on the script's hash, so a pin bump
  rotates the key); a cached file with the wrong digest is deleted, and a
  cache-service error is only a warning;
- the release download route, with five retries under a bounded
  ninety-second retry timer plus connect and stall timeouts;
- the release-asset API route on api.github.com, which fronts the same
  storage through a different tier and needs no token for a public repo.

Nothing is extracted before its sha256 matches the pin, whichever source
delivered it, and QBITD_BIN is still written to the job environment.

tests/test_install_prism_qbit.py drives the real script against a loopback
server scripted per route: fallback after a gateway error, rejection of
wrong-digest bytes from a route or the cache, failure when every source is
unusable, a verified cache hit making no request, and the workflow calling
the script with only the cache directory configured.

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

* 3.x.x: end the soak from the capture loop and gate the judge on its marker (#318 review)

The step-3 `capture` loop returned only through its `invalid` paths; a
valid run was "ended by the operator after 24 h". So a SIGHUP from a
closed terminal, a SIGTERM from a host going down or an interrupt after
the CSV spanned the judge's 82,800 s floor but before 24 h ran no stop
path, wrote no `soak-invalid`, and left a directory that step 6 judged
and the floor passed, indistinguishable from a valid run.

The loop now keeps the time of its first sample and ends the run itself:
after the first sample taken 86,400 s or more after it, once that
sample's reads, appends and both identity checks have passed, it writes
one line to `$run/soak-complete.tmp`, renames it to `$run/soak-complete`
and returns 0. The rename publishes the marker whole or not at all: a
redirect straight to the marker's name would create the file before the
write, and a write that then failed on a full disk could keep `invalid`
from writing `soak-invalid` on the same disk, leaving an empty marker
and no invalid marker. A failed write or rename ends the run as invalid
through `invalid` like a failed append; an interruption between the two
leaves only the temporary file, which nothing reads. The `mkdir` rule
already keeps `capture` out of an existing directory, so a marker is
only ever written by the loop that took every sample in it.

Step 6 gains an executable gate, `completed`, that refuses a directory
holding `soak-invalid` or lacking a regular-file `soak-complete`, and
prints the completion line otherwise; the bound check runs only after
it. The awk judge is unchanged. The prose that said the operator ends a
valid run is reworded, the judge's hour of slack is tied to the marker,
and the marker joins step 7's record.

`tests/test_prism_soak_capture.py` extracts the capture, gate and judge
fences from the doc and runs them under sh (dash) and bash with shell
functions for `date`, `sleep` and `docker`, where `sleep` advances a
file-backed clock: a full run completes with 289 samples, the marker,
no stderr and a passing gate and judge; a SIGTERM at 23 h leaves a CSV
the judge alone accepts and a directory the gate refuses; an identity
change on the final sample's post-read check writes `soak-invalid` and
no marker; a marker write onto /dev/full with an unwritable
`soak-invalid` publishes nothing and the gate still refuses; a SIGTERM
between the write and the rename leaves only the temporary file; an
existing directory is not written into; and the gate refuses a directory
with both markers, a directory as the marker, or only the temporary
file. Mutating the gate to ignore the marker, or the fence back to a
direct redirect, fails the corresponding tests. `python3 -m unittest
tests.test_prism_soak_capture tests.test_docs_lab_prism_references`
passes (75 tests).

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

* 3.x.x: hold each soak sample's end to the previous one's before completing the run (#318 review)

`capture` stamped every row with the `now` it read before the sample's
reads, and its completion check used that same `now`. A `docker inspect`
or `docker exec ... cat` that stalled inside the final sample's reads was
therefore invisible: on any other sample the next iteration's start-time
gap check would have seen it, but the sample that completes the 24 h has
no next iteration, so a stall of an hour passed both identity checks,
published `soak-complete` claiming the samples span 0..86400 s for a
process observed at 90000, and returned 0.

Read the clock again after the post-read identity check and hold each
sample's end to the previous sample's end with the same 360 s tolerance
the start-time check and the judge's `max_gap` use, before the completion
block can run. The 300 s sleep lies inside that interval, so the reads
get the same minute on the final sample that the start-time check leaves
them on every other one; a read that overruns it ends the run through
`invalid` with the sample's time, when its reads ended and how far behind
the previous sample's that was, publishes no marker and returns 1. The
start-time check stays for a hole in the sleep, and the marker is still
written to `soak-complete.tmp` and renamed.

Cover it on the fake clock: the final pre-read inspect advancing the
clock from 86400 to 90000 with the identity and both bodies healthy now
returns 1, records that message, leaves no marker, and is refused by the
gate although the bound check alone would pass the CSV; a 60 s overrun on
the final sample still completes, and a 61 s one is rejected on the final
sample as it already was on an ordinary one.

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

* fix: reject failed soak process identity probes (#318)

* fix: recognize non-identifier Python module targets

* fix: preserve quoted literal module targets (#318)

* fix: require fresh share-ack soak snapshots (#318)

* fix: preserve literal script targets in documentation guard (#318)

* fix: validate and atomically publish full soak snapshots (#318)

* fix: invalidate soak captures on backward clock readings (#318)

* fix: skip shell comments in documentation command guard (#318)

* fix: schedule soak snapshots during capture (#318)

* fix: resolve complete prose references in documentation guard (#318)

* fix: normalize lab script paths in documentation guard (#318)

* fix: reject failed RSS reads during soak capture (#318)

* docs: mark retired soak settings for the native guidance guard (#318)

* test: avoid redundant full-soak identity fault simulations (#318)

* fix: distinguish shell data from executable documentation commands (#318)

* test: publish supervisor fixture readiness atomically (#318)

* fix: require accepted-share progress throughout the soak (#318)

* fix: recognize compound-shell documentation commands (#318)

* fix: consume shell option arguments before command strings (#318)

* fix: consume sudo chdir arguments in doc commands (#318)

* fix: exclude sudo edit mode f…
kiwidream added a commit that referenced this pull request Sep 15, 2026
Brings the load harness onto the current 3.x.x, which carries #322 (the
shared integration gate and the required fmt, clippy and cargo-deny jobs) and
#316. The only conflict was the root Cargo.toml: 3.x.x's file is kept,
including its commented rust-version pin, and the qbit-prism-load member is
added beside qbit-prism-test-gate.

Part of #271
kiwidream added a commit that referenced this pull request Sep 16, 2026
… dense-cadence scenario (#342)

* 3.x.x: add the qbit-prism-load Stratum-to-PostgreSQL load harness

Adds a new workspace crate that drives real Stratum sockets against real
`qbit-prism-server run` child processes and produces the
`qbit-prism-capacity-evidence/v2` artifact nothing produced before (#303),
plus a side report carrying everything the artifact's schema cannot say.

The crate owns:

- a fake qbit node with a real height-to-hash map, a hash-to-parent map,
  strictly increasing chainwork, `submitblock` and `waitfornewblock`, and
  an in-process way to mint an external tip. It serves `1e7fffff` template
  bits: the stock `207fffff` makes every valid share a block, because the
  codec caps the share target at the network target;
- window arithmetic that solves for the diff-1 share difficulty whose
  scaled weight makes the payout window exactly the requested length, and
  asserts the result rather than assuming it;
- a production-shaped window seed adapted from the #264 gate fixture,
  parameterised by the network difficulty and the live share difficulty;
- managed PostgreSQL: a primary plus one streaming standby, with the
  physical slot, an explicit `application_name`, the D3 synchronous flip
  and a teardown that runs on every exit path;
- an in-harness TCP delay proxy between the frontends and PostgreSQL;
- Stratum client sessions whose header recipe reproduces the server's
  `codec::Job::assemble_submission` byte for byte, so a share identifier
  computed before the submit is the identifier the ledger stores;
- measurement: client ACK percentiles, server histogram bucket deltas,
  ORDER_LOCK wait sampling from `pg_locks.waitstart`, per-frontend CPU and
  RSS, reconnect statistics, time to usable work and a rejection census;
- exact reconciliation with a documented canonical share-identifier digest.

Unknown, stale and failed measurements stay distinct from zero, and the
three configuration keys the native runtime does not read (#288) are
recorded as unread rather than presented as tuning controls.

Part of #271

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

* 3.x.x: document the load harness and quiesce it before the sockets close

Adds the crate README: prerequisites, every flag, the D1 plan, the outputs
and their schemas, how to validate the artifact, the honest-value notes,
measurement hygiene, and the sizes that are blocked until #273 and #265.

Two fixes a first end-to-end run found:

- the run now quiesces every session and waits for outstanding submits to
  settle before it closes the sockets. Stopping with submits in flight
  manufactured indeterminate shares, two of which had already committed,
  and the run then reported a durability finding it had created itself.
  Offers a paused session will never send release their outstanding slot,
  so the drain cannot wait for work that is not coming;
- the side report now carries the ACK p99 the artifact phases actually
  reached and the limit that would admit it, beside the forecast that
  would admit the slowest phase's rate.

The ORDER_LOCK sampling predicate is derived from the hex key rather than
typed in decimal, and the report prints the derivation: the high half of
0x505249534d000002 is 0x50524953, which is 1347570003.

Part of #271

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

* 3.x.x: count backend refusals as offered shares the artifact cannot hide

The first two-frontend run at a 20,000-share window showed what a 10 ms
one-way database delay does: the refresh loop blocks, each frontend's
readiness poll goes stale behind it, and 1,873 submits come back with
`current chain state is unavailable`, with another 167 hitting the
share-commit timeout.

Those refusals were being excluded from `offered_valid_shares` alongside
the races the server is entitled to lose, which let the slow_database
phase report offered == acknowledged == 399 and look clean while 2,040
submits had failed. Only the transient classes are excluded now — a stale
job after a tip change or a payout-revision bump, an unknown or retired
job, a closed pool — and each of those is a share PostgreSQL never saw, so
reconciliation is untouched.

A backend refusal is a capacity result, not a harness defect, so it still
does not make the run exit non-zero; it simply makes the artifact honestly
invalid for that phase. The side report now carries the rejected-valid and
harness-bug counts per phase, and the README says which gates bind under
delay and what each would need.

Part of #271

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

* 3.x.x: account for offers a paused session never sent

A drained frontend restart pauses that frontend's sessions, and any offer
the scheduler had already placed on a paused session is discarded rather
than sent. The two-frontend run showed the gap as one dispatched share
that appears in no phase's offered set. The sessions now report each
discarded offer, and the side report carries the count, so `dispatched`
reconciles against `offered` without a reader having to guess.

Part of #271

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

* 3.x.x: separate an ACK/commit divergence from a durability loss

Two back-to-back two-frontend runs at a 20,000-share window found the same
thing under a 10 ms one-way database delay: two shares per run that
PostgreSQL holds and that the server had already refused with
`ledger-confirmation-failed`. Nothing acknowledged was ever lost -
`missing_acknowledged_share_ids` was 0 in every phase of both runs - so the
gap runs the other way.

The mechanism is in the coordinator: the append is wrapped in
`tokio::time::timeout(share_commit_timeout, save)`, and when that deadline
fires the sqlx future is dropped mid-COMMIT, which PostgreSQL may still
complete. The share is then credited in the payout window while its miner
is told it was not confirmed.

That is not the same failure as credited work disappearing, so the harness
no longer reports them as one thing:

- an acknowledged share PostgreSQL does not hold, or a committed share
  nothing explains, stays a durability loss and exits 4;
- a share PostgreSQL holds that the server refused with
  `ledger-confirmation-failed` is an ACK/commit divergence and exits 5,
  listed under `ack_commit_divergence` with its phase, frontend, session,
  send-to-response time and the commit deadline it crossed;
- harness-bug rejections move to exit 7.

Divergent shares stay counted in `unexpected_committed_share_ids` and in
`rejected_valid_shares`, so the artifact is honestly invalid for the phase
and cannot hide them.

Also from the coordinator's review of the ORDER_LOCK sampler: the lock is
database-wide, so each frontend now connects with
`application_name=load-fe-<i>` and the sampler attributes waiters by it,
verifying against `pg_stat_activity` that the driver really carried the
name rather than assuming it. Waiters that are not this run's frontends
are reported separately as foreign, and the sampling intervals are bounded
above as well as below.

Part of #271

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

* 3.x.x: make the printed capacity-evidence command shell-safe

`SHOW server_version` returns `16.15 (Ubuntu 16.15-0ubuntu0.24.04.1)` on
Ubuntu, and the harness printed it unquoted, so pasting the command it told
the reader to run produced a bash syntax error rather than a verdict. Every
value in the printed command is now quoted when it needs to be, and a test
parses the rendered command with `bash -n` to prove a shell accepts it.

Part of #271

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

* 3.x.x: keep the outstanding-submit counter exact for every submit kind

A scheduled block and a re-offer both insert a pending submit, and both
responses go through the path that releases an outstanding slot, but
neither took a slot first. The counter is unsigned, so the first such
response would have wrapped it and left that session looking permanently
full to the scheduler. Both now take a slot and give it back on a write
failure, and a re-offer whose write fails no longer leaves a pending entry
behind that a later response id could match.

Found by review, before either code path had run under load.

Part of #271

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

* 3.x.x: say what a zero warm-up does to the tip measurements

`--external-tips` mints during warm-up, so `--warmup-seconds 0` leaves the
time-to-usable-work section empty rather than zero, and a scheduled block
is followed by a burst of payout-revision rejections on every frontend.
Both are now in the flag table.

Part of #271

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

* 3.x.x: unit-test the two reconciliation classifications directly

The decision that separates an ACK/commit divergence from a durability
loss, and the decision about what belongs in a phase's offered set, were
only exercised end to end by a live run. Both are now pure functions with
their own tests: only `ledger-confirmation-failed` makes a committed share
a divergence, a committed row the harness never offered is a loss, and the
offered set keeps every backend refusal, harness bug and lost response
while excluding only the races the server was entitled to lose.

Part of #271

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

* 3.x.x: adopt the #322 gate rules and cite #324 for the divergence

The shared test-gate variables belong to the gate crate, and
`scripts/check_gate_env_reads.py` fails on a second reader of one, so the
harness takes its own `QBIT_PRISM_LOAD_PG_BIN_DIR` before falling back to
`pg_config --bindir`. A test pins the name and asserts it is none of the
shared ones.

The crate manifest now matches the others: `rust-version.workspace = true`
alongside `version.workspace = true`, with edition 2021, MIT and
`publish = false` unchanged. The base predates #322, which is what adds
`rust-version` to `[workspace.package]`, so this branch adds it there too
at the pinned 1.98.1; #322 already carries that line on 3.x.x and the
integration should keep its own.

Toolchain 1.98.1 found one new lint in this crate, `chunks_exact_to_as_chunks`
on the word swap, now written as `as_chunks_mut::<4>().0`.

The operator's decision is recorded where a reader will meet it: the
README's ACK/commit divergence section, its exit-code table and the side
report's own section all cite #324, and so does the evidence note.

Part of #271

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

* 3.x.x: make the mid-flight kill land while submits are outstanding

The first mid-flight-kill run reported zero indeterminate shares, because
with no database delay an acknowledgement takes about four milliseconds:
at twenty shares a second across fifty sessions, almost nothing is in
flight at any instant and the SIGKILL tore down an idle socket.

The phase now runs under the same one-way proxy delay as `slow_database`,
which holds submits open long enough for the kill to mean something, and
the kill waits for the target frontend to actually be holding work before
it fires. The report carries `submits_outstanding_at_kill` so a reader can
see whether the scenario exercised at all rather than reading an empty
list as a clean result.

Part of #271

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

* 3.x.x: measure the dense-cadence scenario against the payout revision

#271's sixth acceptance criterion asks what a payout-revision bump costs
every frontend when own blocks land on #224's shape: about 9 s apart, and
in 18-20 s pairs. `--cadence dense` adds a side phase that lands them on
that pattern and measures the cost three ways, per landing and per
frontend.

The authoritative list of bumps comes from the database, not from a
rejection: the harness samples `payout_revision` and `clock_timestamp()`
out of the singleton `qbit_prism_cluster` row every 25 ms on its side
pool, outside the frontends' path and outside the delay proxy, and records
every change on both clocks. One landing can cause more than one bump --
the chainwork increase at the new tip in `ledger/window.rs`, then
candidate confirmation in `ledger/blocks.rs` -- so the report counts them
rather than assuming.

`coordinator.rs` checks the observed tip before the payout revision, which
is why W2's one scheduled block produced `new tip work is pending` and not
`new payout work is pending`. The two windows are therefore reported
apart, with a combined window beside them, and it is the combined one that
#291 should budget against.

Time to new-tip work is the run's existing definition restricted to one
frontend's sessions. Time to new-revision work cannot be exact: the wire
carries no payout revision, so the first `clean_jobs=true` notify at or
after the bump stands in for the first job built at the new revision, and
every field that uses it says so.

Attribution is total. A landing's span runs from its own pool tip change
to the next landing's, so every rebuild-pending rejection and every bump
belongs to exactly one landing or to `unattributed`, and both counts are
reconciled in the report. A landing the session could not produce, one the
frontend rejected and one the node rejected each get their own entry. A
run with no landing reports `landings: 0` and `bumps: 0` with the reason
and no windows, and the budget proposal is null rather than zero.

The blocks are matched to the node by hash, not by time: the part of a
share identifier after the colon is the header's display hash, which is
exactly what the fake node records for `submitblock`.

The gap pattern and the phase length are checked against each other at the
entry boundary, because a pattern that cannot hold ten landings measures
nothing. With `--cadence dense`, `--scheduled-blocks` becomes the dense
phase's landing budget and `steady_state` schedules none, so the budget is
not spent before the phase that measures it; without it, nothing about a
run changes, and the capacity-evidence artifact is untouched either way.

Part of #271

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

* 3.x.x: unit-test the cadence schedule and its attribution

The report builder is a pure function over already-collected records, so
the parts that decide what a number means are testable without a database.

Three tests cover them: the gap generator repeats cyclically, starts at the
lead-in and reserves the measurement tail, and its entry validation refuses
a gap below the floor, a non-finite one, an empty field and a phase too
short for ten landings; synthetic rejections and bumps land on the right
landing, with the ones before the first landing counted as unattributed
rather than dropped, and a landing the session never produced keeping its
error text; and a run with no landing reports zeros, a reason and no
percentile.

A fourth asserts the wiring: the dense phase is a side phase with no proxy
delay after `slow_database`, a run without `--cadence dense` does not grow
one, and the artifact's phases are the same either way.

Part of #271

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

* 3.x.x: document the dense-cadence scenario

The flag table, the phase list and the outputs section gain the new phase
and its four flags, and a section of its own says where the bumps come
from, why the tip and payout windows are reported apart, which of the two
times is an approximation and why, what "lost valid work" counts, and what
the report says when nothing landed.

Part of #271

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

* 3.x.x: ship the profile bytes the artifact's digest names (F1)

`subject.database_profile_sha256` was taken over the canonical JSON string
while the file was written with a trailing newline appended, so the two
never agreed and `sha256sum database-profile.json` disagreed with the
artifact in every bundle the harness has produced. A mismatched digest in
an evidence bundle honestly reads as corruption or tampering, and nothing
inside the harness could catch it: the self-check and
`--expect-database-profile-sha256` both compare the in-memory digest with
itself.

The document is now written through `profile::write_document`, which writes
exactly the bytes that were digested and says why nothing may be appended.
Digesting the file's bytes instead would have made the digest a function of
the serializer, which that module exists to avoid.

The regression test writes the profile, reads the file back and asserts
that the SHA-256 of its bytes is the digest the artifact names, that the
last byte is not a newline, and that the file still parses. The README's
claim now says the digest is over the file's exact bytes and that
`sha256sum` is the value the artifact names.

Found by the adversarial review of W2 (F1).

Part of #271

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

* 3.x.x: say 7, not 5, for a harness-bug rejection (F4)

The honest-values section still said the harness-bug classes exit 5, which
was true before the ACK/commit divergence was split into its own class and
took that code. The exit-code table and `run.rs` both say 7.

Found by the adversarial review of W2 (F4).

Part of #271

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

* 3.x.x: check the PostgreSQL bin directory at the entry boundary (F5)

Every other input was range-checked in `Args::validate`; `--pg-bin-dir` was
not, so a typo surfaced as `running initdb: No such file or directory` long
after the output directory and the temporary cluster root had been created,
and named neither the flag that was wrong nor what was missing.

`cluster::verify_bin_dir` checks that the resolved directory exists and
holds `initdb`, `pg_ctl` and `pg_basebackup`, and `run::execute` resolves
and checks it immediately after `Args::validate`, before it creates
anything. A `--database-url` run needs none of those binaries and is not
asked for them, which is also why the check is not in `Args::validate`
itself: it would make the crate's own unit tests depend on a PostgreSQL
installation, and they stay database-free.

The test covers the four answers: a directory that does not exist, one with
no binaries, one with all three, and one missing a single binary.

Found by the adversarial review of W2 (F5).

Part of #271

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

* 3.x.x: let the temporary cluster root own its own cleanup (F3)

`create_dir_all` ran before the `ManagedPostgres` whose `Drop` removes the
root existed, so every `?` in between -- reading the current user,
`initdb`, allocating a port, starting the primary -- returned with
`/tmp/prism-load-<uuid>` still on disk. An operator iterating on flags
accumulated empty directories, and a failure after `initdb` succeeded left
a whole data directory behind.

`TempRoot` is created the instant the directory is, honours
`--keep-artifacts` and is moved into `ManagedPostgres`, which no longer
removes the root itself: the guard drops after `stop` returns, so the data
directory is never removed under a live server. The whole window is closed
without a second copy of the cleanup.

The test writes a file into the root and asserts nothing survives the
guard, and that `--keep-artifacts` keeps it.

Found by the adversarial review of W2 (F3).

Part of #271

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

* 3.x.x: see the foreign ORDER_LOCK holder, not just the waiter (F2)

The sampler selected only ungranted rows, so a process that *held*
ORDER_LOCK was invisible to every number in the section. That is exactly
what a foreign stall looks like: the holder blocks every frontend, the
frontends queue up as waiters and are correctly recognised as this run's
own, and the report then billed the whole stall to them while asserting
`foreign_waiter_samples: 0`. The adversarial review held the lock for 3.02 s
from a separate `psql` and watched `waiter_seconds_estimate` inflate 19x
with nothing foreign reported anywhere.

The query now selects `l.granted` and keeps granted rows, and
`split_lock_rows` splits one sample four ways: this run's waiters, this
run's holders, foreign waiters and foreign holders. Every existing waiter
number -- `max_waiters`, `mean_waiters`, `waiter_seconds_estimate`, the
episode count and the longest observed wait -- still comes from this run's
ungranted rows alone, so nothing changes meaning; the granted rows are new
information beside them. A frontend holding the lock is the normal case and
is in no foreign counter.

Beside the waiter fields there are now `foreign_holder_samples`,
`foreign_holder_application_names` and `foreign_holder_seconds_estimate`,
and one `foreign_contention_observed` so a reader does not have to notice a
zero in the right field. It is `null`, not `false`, when the sampler could
not attribute rows at all: unknown is not the absence of a problem.

The split is a pure function and has its own test, including the
no-attribution case where nothing can be called foreign. The README now
describes holders and waiters as the different events they are.

Found by the adversarial review of W2 (F2).

Part of #271

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

* 3.x.x: give the README the length the validator actually asks for

The default gap pattern needs a 150 s phase to place ten landings, not the
170 s the README said. The number the code computes is the one in the
refusal message, which a reader is more likely to meet than this sentence,
so the sentence now points at it.

Part of #271

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

* 3.x.x: left-join the activity row and stamp every lock poll (F2 addendum)

Two ways the ORDER_LOCK sampler could still be wrong about what it saw.

The inner join to `pg_stat_activity` dropped any lock row whose backend the
sampler's role cannot read, so such a row was invisible rather than
foreign. It is now a left join, and a row with no readable activity counts
as foreign: nothing about it can be shown to belong to this run, and
counting it as one of this run's frontends is the direction that hides a
stall. That holds even with no attribution at all, where every other row
counts as ours. In the foreign name lists it appears as
`(activity row not visible to the sampler's role)` rather than as an empty
`application_name`.

The server timestamp was read out of the first returned row, so a poll that
found no lock had no server clock and fell back to the harness's own
`Utc::now()` -- one sample, two clocks. `clock_timestamp()` now comes from a
one-row outer source left-joined to the locks, so every poll carries it,
including a poll that finds nothing. If it is ever missing the sampler
records a failure instead of substituting its own clock.

Rows that are this run's own and ungranted are unchanged, so every waiter
figure keeps its meaning. The split's test covers the unreadable row in
both the attributed and the unattributed case.

Part of #271

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

* 3.x.x: sample the lock the rebuild queues on, not just the one the append takes (F1)

The dense-cadence phase exists to measure the rebuild after a landing, and the
rebuild path takes SETTLEMENT_LOCK (0x505249534d000003) first and ORDER_LOCK
second -- observe_chain_view, the job build and candidate confirmation or
abandonment all do. The sampler watched ORDER_LOCK alone, so in an adversarial
run 37.3% of this run's ungranted PRISM advisory-lock samples in the dense
phase were invisible to every reported number, and a reader sizing #291's soak
budget off waiter_seconds_estimate was reading part of the queueing with no way
to tell which part.

The sampler now selects both locks in one poll, tags each row with its objid,
and summarizes them apart: each phase carries a settlement_lock block beside
order_lock with the same shape and the same own/foreign split. Because one poll
carries both, the two blocks cover exactly the same instants and share a
samples count and a sampler cost, which the definitions say. Every existing
order_lock key keeps its name and its meaning; the blocks gain taken_by, which
names the server path that takes the lock, so a block says what it measures
rather than leaving it to be inferred from the name.

The dense section's definitions gain advisory_locks_sampled: which locks are
sampled, which path takes each, which are not sampled and why, and where the
blocks live. MIGRATION_LOCK and CPFP_FUNDING_LOCK stay unsampled -- neither is
on the append or rebuild path this phase measures.

Part of #271

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

* 3.x.x: count and verify every lost share, not only the attributed ones (F2)

lost_total and lost_in_postgres were accumulated inside the per-landing,
per-frontend loop, so they covered exactly the rejections a landing's span
owns. A rebuild-pending rejection that fell inside no span was reported in
rejection_attribution.unattributed and then silently left the lost-work census
-- and was never looked up in this run's committed share identifiers.

That is the one case the cross-check exists for. A landing whose pool tip
change is missing -- accepted_without_node_submission, a tip record lost to a
frontend restart, a block the node recorded late -- leaves its rejections
unattributed, so a lost share that really is in qbit_share_ledger would have
been reported as shares_found_in_postgres: 0. The check read as a clean pass in
exactly the situation that would make it fail.

lost_valid_work now counts every rebuild-pending rejection in the phase and
publishes the split -- shares, shares_attributed, shares_unattributed -- with
shares_found_in_postgres checked over all of them. The per-landing,
per-frontend lost_valid_shares tables are untouched and still sum to
shares_attributed.

The attribution test is extended to arm the case: its unattributed rejection,
and only it, is placed in the committed set, so the test asserts shares == 5,
shares_unattributed == 1 and shares_found_in_postgres == 1 naming the share.
Before this change that last number was 0.

Part of #271

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

* 3.x.x: let the revision sampler report partial blindness (F3)

blind() was `baseline.is_none()`, so it could only fire for a sampler that
never read anything. A sampler whose first read succeeded and whose next
thousand failed -- the side pool loses its connection, the primary restarts,
the pool is exhausted -- reported blind: false, blind_reason: null and
changes_observed: 0 beside an error count in the thousands. The one boolean a
reader is invited to trust to tell "observed zero" from "observed nothing" said
"observed zero", which is the misreading the flag exists to prevent.

blind() is now also true when no change was observed and errors occurred, and
blind_reason names which of the two cases it is rather than repeating one
sentence for both. Errors beside observed changes stay non-blind: the sampler
did see the revision move.

Beside samples and errors the section now reports coverage -- samples over
samples plus errors, null rather than 0 when the sampler never ticked -- so a
sampler that watched 3% of the phase is visible as such whatever blind says
(EP-OBSERVABILITY).

Part of #271

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

* 3.x.x: keep the approximation label on the summaries (F4)

Time to new-revision work is an approximation -- mining.notify carries no
payout revision, so the first clean_jobs notify at or after the bump stands in
for it -- and it was labelled in two of the three places it appears. The
per-landing, per-frontend tables carry new_revision_work_approximation beside
the number, and definitions carries it under time_to_new_revision_work. The
four summaries.overall and summaries.per_frontend[] fields carried nothing.

Those are the numbers people quote: the headline tables in the run reports
carry a "time to new-revision work ms" column and it comes from the summaries.
Quoted from there, an approximation built on a clean_jobs proxy reads as a
measured time to the first job at the new payout revision, which is the one
thing the Stratum wire cannot tell you.

The label is carried into the summarised objects rather than adding definitions
entries keyed on the summary names. Both fixes were acceptable; this one puts
the label beside the number, so it survives a reader copying the object out,
while a definitions entry only helps a reader who goes looking -- and the
finding was that readers quote the summary and do not go looking.

Part of #271

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

* 3.x.x: give summarize a unit, because counts are not milliseconds (F5)

measure::summarize hard-coded unit: "milliseconds", and five of the dense
section's distributions are counts of shares. They shipped as

  "combined_rebuild_pending_rejections_per_landing": {
    "clock": "counts, not milliseconds; one sample per landing",
    "unit": "milliseconds", "p50": 61.0, "p99": 85.0, "max": 85.0 }

with the clock string apologising for the unit rather than the unit being
right. A consumer generic over the summary shape -- a dashboard, a diff of two
runs -- reads `unit` and renders 85 discarded shares as "85 ms"; it does not
look at a clock field. EP-OBSERVABILITY asks that every number carry its unit,
and here one was carried and was wrong, which is worse than absent.

summarize now takes the unit. measure::MILLISECONDS and measure::COUNT name the
two in use; the five count call sites pass COUNT through a count_summary helper
and everything else passes MILLISECONDS. COUNT_CLOCK drops the apology and
names the clock again: one sample per landing and frontend, counting rejections
stamped on the harness monotonic clock.

Part of #271

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

* 3.x.x: make bumps mean what definitions.bump says (F6)

definitions.bump is "an observed change of qbit_prism_cluster.payout_revision",
and the top-level bumps key published attributed_bumps -- the subset a landing's
span owns. The crate's own test made the divergence concrete: bumps 3 while
bump_records held 4 and bump_attribution.unattributed was 1.

The failure is a no-landing run in which the revision moves anyway -- an
operator touching the cluster, a migration, a second harness. It reported
landings: 0 and bumps: 0, which the README presents as the honest no-landing
output, while changes_observed and bump_attribution.unattributed both said
otherwise two keys away. Nothing was hidden, but the headline number meant
something other than the word next to it.

bumps is now revisions.changes.len(), equal to revision_sampler.changes_observed,
and bump_attribution carries the split -- it gains observed so the three
reconcile in one place. definitions.bump says which key is which, and
unknown_is_not_zero no longer claims a no-landing run reports bumps 0.

The test that pinned the old meaning now asserts bumps == 4 ==
changes_observed with attributed 3 / unattributed 1, and the no-landing test
gains the case the finding named: nothing landed, the revision moved twice,
bumps 2, both unattributed.

Part of #271

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

* 3.x.x: count the landings that have a window, not the ones that landed (F7)

landings and windows_available were derived from the `landed` tally, while
resolve grants a landing its attribution span whenever its own pool tip change
is present -- regardless of outcome. A landing whose tip moved but whose
submitblock record is missing falls to AcceptedWithoutNodeSubmission and still
receives a span, and therefore a full per-frontend window table and a
contribution to summaries. If that were the only such landing the section would
have reported landings: 0, windows_available: false and a reason saying every
attempt failed, while landing_records[].frontends and summaries.overall carried
real windows and proposed_budget_for_issue_291 carried a real p99.

Both now count the spans that were actually created, and the no-landing reason
keys on the same number, so "a window exists" and "a window is reported as
existing" cannot disagree. landing_outcomes.landed is unchanged and still
reported one key away, so the two can be read against each other, and
definitions.landings says which is which.

Part of #271

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

* 3.x.x: name the new crate in the release-identity assertion

`check_version_skew.py` prints every workspace crate it matched, and
`test_checked_in_tree_has_one_release_identity` asserts that line
literally. Adding `qbit-prism-load` to the workspace changes the line, so
the assertion has to name it too. The script itself already passes; only
the expected text was stale.

Part of #271

* 3.x.x: keep an unknown commit outcome apart from a lost share

PR #333 adds a third answer to the share-commit path: when the COMMIT
still has no reply after the deadline and its grace window, the server
answers `ledger-outcome-unknown` instead of claiming the append failed.
The harness did not know the reason, so it fell through to
`RejectionClass::Unknown`, and a share PostgreSQL then held was filed as
"committed share that was never acknowledged" -- a durability loss, exit
4. That is a false data-loss alarm for the one case where the server was
being honest about not knowing.

Give it its own gap kind and its own report block. The three outcomes are
three different claims: the server said no and was wrong
(`ack_commit_divergence`), the server said it did not know
(`unknown_outcome_commits`), and nothing explains the row at all
(`durability_findings`). Only the last means credited work disappeared.
The run still fails, with exit 5, because the miner was refused a share
the database holds either way.

Found by running this harness against PR #333 for #324's confirmation.
That run produced no `ledger-outcome-unknown` at all -- with an
asynchronous standby the COMMIT reply takes milliseconds -- so the gap
was never hit, but the next run on a slower database would hit it.

Part of #271

* 3.x.x: redact the password inside any URL the reports print (F4)

`--database-url` in the usual `postgresql://user:password@host/db` form is
carried to the frontends as `PRISM_DATABASE_URL`, and the predicate that
decided what to redact only looked at the key: the secret list, or a name
containing SEED or PASSWORD. So `database-profile.json` and
`load-harness-report.json`, both meant to be attached to issues and pull
requests, printed the database password in clear.

Redact by value as well as by key: every URL-valued variable loses the
password half of its userinfo and the value of any `password` query
parameter (the form libpq and sqlx also accept), whatever the variable is
called, so a URL added later is covered without special-casing its name.
The user, host, port, database and the non-secret parameters stay legible,
because they are what a reader of the profile needs.

Review feedback on the load-harness pull request.

Part of #271

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

* 3.x.x: start every invocation's frontend logs empty (F9)

Frontend stdout and stderr were opened in append mode on every spawn, so a
reused `--out` directory kept the lines of earlier invocations. The
blocked-run classifier reads and classifies the whole stderr file, so one
JSONB-ceiling refusal from a previous, failed run made a currently healthy
run exit 3 and report itself blocked.

Truncate on the first launch of an invocation and append only for a
restart within it: the previous process's lines in a mid-flight-kill or
drained-restart scenario are this run's evidence and must stay.

The test launches a stand-in shell script as the frontend, seeds a stale
refusal line into its log, and checks that the launch discards it while a
restart keeps this invocation's own lines.

Review feedback on the load-harness pull request.

Part of #271

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

* 3.x.x: make an unknown server build profile need the override too (F3)

The guard was `profile != Debug || --allow-debug-server`, so
`BuildProfile::Unknown` passed with no override. The profile is inferred
from the binary's parent directory, so a copied binary, a symlink or an
installed path is `Unknown`, and a debug build at such a path could
produce a qualification artifact the harness otherwise treats as invalid.

Resolve symlinks before reading the directory, so a link into
`target/release` is shown to be a release build, and require
`--allow-debug-server` for `Unknown` as for `Debug`: a profile that cannot
be determined is not evidence of a release build. The refusal says why and
what to do. The check moves into `frontend::check_server_profile`, where a
test can reach it.

Review feedback on the load-harness pull request, confirmed by the
coordinator.

Part of #271

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

* 3.x.x: let the delay proxy front a database named by hostname (F7)

The proxy's upstream was built with `"host:port".parse::<SocketAddr>()`,
which only accepts a numeric address. `postgresql://[email protected]/db`
is an ordinary PostgreSQL URL, and the SQLx connections before that point
succeed on it, so external-database mode got as far as the proxy and then
failed before a single frontend started.

Resolve the host once, at the entry boundary, through the same system
resolver SQLx used, refuse a host that does not resolve with its name, and
try every address the name resolved to when a frontend connects, as
`TcpStream::connect` does for a name, so a host that resolves to both
address families works whichever one PostgreSQL listens on. The written
upstream and the resolved addresses are recorded in the side report's
`delay_proxy` block.

Review feedback on the load-harness pull request, confirmed by the
coordinator.

Part of #271

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

* 3.x.x: gate startup on sessions holding work, not connection events (F12)

The startup gate compared a cumulative count of `Connected` events with
the session count. Every successful connection increments it, so a
session that dropped and reconnected while another had not finished its
initial handshake satisfied the total on the other's behalf. The phases
then began although the stated precondition -- every session holds work
-- was false, and the churn showed up as phase shortfall.

Fold the events in one place, `Collected::apply`, and keep the set of
sessions that are connected right now: added on `Connected`, removed on
`Disconnected`. The gate reads that set's size. The event count stays in
the report as what it is, a count of events.

Review feedback on the load-harness pull request.

Part of #271

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

* 3.x.x: record a submit under the phase that offered it (F8)

A session stamped each submit with `SessionShared::phase` at the moment
it sent it. An offer the scheduler placed while the session could not
send -- mid-reconnect, or still in its handshake -- sat in the work
channel across the phase boundary and was then stamped with the next
phase. It had been counted as `dispatched` in the old phase, but landed
in the new phase's reconciliation and latency, possibly during its
boundary scrapes, before its measured duration even started, so a phase's
rate and its artifact described different offers.

Carry the phase in the work item: `Work::Submit { phase }` is stamped by
the scheduler, and the session records the submit under it however late
it sends it. Scheduled blocks and re-offers are sent the instant their
control message arrives and keep reading the live phase.

The test drives a real session against a minimal in-process Stratum
server that holds the authorize reply, queues two offers in
`steady_state`, moves the run to `reconnect`, releases the handshake and
checks both records say `steady_state`.

Review feedback on the load-harness pull request.

Part of #271

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

* 3.x.x: tie the server binary to the revision the artifact names (F1)

`coordinator_revision` came from `git rev-parse HEAD` in the harness's
checkout, while the server under test was whatever `--server-bin` pointed
at. A `target/release/qbit-prism-server` left over from an earlier
checkout kept the tree clean and the recorded revision current while the
bytes that ran were older, and the artifact then self-validated and
attributed measurements to a commit that did not produce them. The
binary digest identifies the bytes, not the source, so it did not help.

The server embeds no build revision, and this crate cannot add one. What
it can do is apply Cargo's own freshness test: the dep-info file Cargo
writes beside the binary lists every workspace source it was compiled
from. If that file exists, names this checkout's server crate root, and
no listed source -- nor `Cargo.lock` or the workspace `Cargo.toml`,
which the list omits -- is newer than the binary, then the binary is what
this tree builds, and with a clean tree that is HEAD. Otherwise the
revision cannot be established and the run is refused with the reason:
no dep-info (a copied or installed binary), a newer source, or a
different checkout. `--allow-unverified-server-revision` runs anyway and
forces `artifact_kind: example`, as `--allow-dirty-tree` does, and the
side report records the evidence under
`versions.server_revision_evidence`.

Review feedback on the load-harness pull request, confirmed by the
coordinator.

Part of #271

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

* 3.x.x: withhold the artifact when the run aborts (F6)

Crossing the memory floor or losing a frontend only broke out of the
phase loop; execution continued into artifact generation. An abort
before the three required phases made `artifact::build` error out before
the side report was written or `EXIT_ABORTED` returned, so the abort
report never existed. An abort during a long `slow_database` phase
emitted the partial phase as `completed: true`, so an aborted run could
produce a self-validating qualification artifact.

Decide about the artifact before building it. An aborted run withholds
`capacity-evidence.json`, removes one an earlier run left at the same
path so nothing self-validating survives the abort, writes the side
report with `aborted` set, the cut-short phase marked `completed: false`
and `validator.artifact_written: false` with the reason, and exits 6.
A completed run is unchanged.

Review feedback on the load-harness pull request.

Part of #271

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

* 3.x.x: drive the drained restart without stalling the scheduler (F2, F5)

The reconnect phase's restart awaited `drained_restart` from inside the
1 ms scheduling loop, so the drain, kill, relaunch and readiness wait
stopped every other frontend's scheduled traffic for the whole outage,
and afterwards the elapsed-time token calculation turned the missed
interval into one burst plus shortfall. The phase exists to measure the
offered rate *while one frontend is unavailable*, which is exactly what
that stalled scheduler could not measure (F2).

The same function waited a fixed 10 s for the frontend's submits to
settle and then restarted it anyway. That is reachable with the default
15 s share-commit timeout and likely with a longer one or a contended
database, and killing the process then converts the harness's own
in-flight requests into `NoResponse` records inside the artifact's
reconnect phase, misclassifying the experiment (F5).

Replace the awaited function with `restart::RestartDriver`, a state
machine the loop polls: every poll returns after bounded synchronous
work (a counter read, a channel `try_recv`, a kill-and-spawn) and the
readiness probe and metrics scrapes run in spawned tasks. The drain
waits the configured share-commit timeout plus a 5 s margin, one
deadline carried through the dependent work, and a frontend whose
sessions still have submits outstanding after that is not restarted:
the driver reports the failure and the run aborts with exit 6 and its
report, rather than proceeding and pretending it drained. A restart
still in flight at the phase boundary is seen through so its sessions
are retargeted before the next phase offers to them. Each side of the
restart is scraped, which the next commit uses.

The tests launch stand-in frontends (a shell script and a one-line HTTP
server for `/healthz` and `/metrics`) and check that no single poll
exceeds 100 ms while the whole restart takes hundreds, that only the
restarted frontend's sessions are paused and retargeted, and that a
frontend whose submits never settle is left running and the failure
named.

Review feedback on the load-harness pull request.

Part of #271

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

* 3.x.x: assemble the server ACK histogram across a restart (F10)

The reconnect phase restarts a frontend between its two boundary
scrapes, so that frontend's in-process Prometheus counters go back to
zero, and subtracting the old process's pre-phase values from the new
process's post-phase values gave negative counts, sums and buckets. The
coordinator confirmed it against real data: in two runs of the #324
reproduction the `reconnect` phase's `server_share_ack_seconds` for
`load-fe-1` reported `accepted` counts of -1273 and -1238 with every
bucket negative. The report had been shipping negative share counts.

Assemble the delta from one segment per process, each bracketed by its
own scrapes: the phase-start scrape to the pre-kill scrape, then the
post-restart scrape to the phase-end scrape, summed. The entry says what
happened -- `counter_resets`, `segments`, and a note -- so a summed
number is never mistaken for a plain difference. A reset no scrape
bracketed (a mid-flight kill) leaves `counts` empty with
`unavailable_reason` set: unknown, which is kept apart from zero
(EP-OBSERVABILITY). A counter that went backwards between two scrapes
with no recorded restart is reported the same way rather than as a
negative number, so the failure mode cannot come back by another route.

The test replays the coordinator's case: 1300 before, 27 after, no
restart recorded gives unknown with the reason, not -1273; a restart
without scrapes gives unknown with the reset count; a restart with both
sides scraped gives (1500 - 1300) + (27 - 0) = 227 over two segments; a
failed scrape on one side fails the whole delta.

Review feedback on the load-harness pull request, confirmed by the
coordinator against measurement data.

Part of #271

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

* 3.x.x: resolve dep-info paths before matching them, and record why try_offer is safe

Two things found reviewing the review fixes locally.

The revision check compared a canonicalised `repo_root` against the paths
Cargo wrote into the dep-info file, which are the paths it was invoked
with and are not canonical. On macOS a checkout under /tmp or /var really
lives at /private/tmp or /private/var, and a symlinked home or work
directory does the same anywhere. The exact `PathBuf` comparison then
refused a binary that had in fact just been built from this checkout, so
the run either stopped or fell back to an `example` artifact -- the
opposite of what the check is for. A plain Linux CI checkout is
unaffected, which is why this passed on the worker's host and failed
here. Resolve each listed source before matching, keeping an unresolvable
path as written so the error still names what the file said.

`try_offer`'s safety was established during review and then lived only in
a report that is not committed. It rests on the function being
synchronous and the counter being read from one task, neither of which is
visible at the call site: the wrapping `fetch_sub` through `usize::MAX`
between the `try_send` and the `fetch_add` is unobservable only under
those conditions. Written down, because the obvious tidy-up -- making it
async, or reading the counter from a spawned task -- reintroduces the bug
that was argued not to exist.

Part of #271

* 3.x.x: make a paused session ineligible for offers, not a queue for them (G1)

The drained restart pauses the affected frontend's sessions and lets the
scheduler keep running, but the scheduler still offered to every session
and `SessionHandle::try_offer` had no notion of paused, so each paused
session kept accepting offers into its bounded queue. That was wrong in
three ways. Every offer a paused session absorbed was a token taken from
the frontends that were up. The queued offers counted as outstanding, so
the drain that waits for outstanding to reach zero could not complete
while the scheduler ran and the restart aborted the run at its deadline
instead of happening. And whatever had queued went out as one burst on
resume, which is the failover behaviour the reconnect phase exists to
measure rather than manufacture.

The paused state was private to the session task, so the scheduler could
not see it. It is now a shared flag on `SessionHandle`, read by both the
decisions it governs (EP-STATE): the session task reads it to decide
whether it may send, and `try_offer` refuses while it is set so the token
goes to the next session. The restart driver sets it before it sends the
pause, so nothing queues between the decision and the task reading its
control channel, and clears it with the retarget that ends the restart;
the teardown pause sets it the same way. A client-initiated reconnect
that lands on a paused session no longer lifts the pause, since the
pause belongs to the frontend being restarted and lifting it would
resume offers to a session whose frontend is down.

Test: a_paused_session_is_not_offered_work_until_it_is_retargeted keeps
offering through a stand-in restart and shows the paused session refuses
every offer, the healthy one takes the token, the drain completes on the
in-flight submits alone, and the retarget makes the session eligible
again. It fails at the previous head on the first refusal.

Part of #271

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

* 3.x.x: count the package manifests among the revision check's inputs (G2)

The check that ties the server binary to the checkout's HEAD compared
the binary's timestamp with Cargo's dep-info sources plus the lock file
and the workspace manifest. It left out the server package's own
Cargo.toml and the manifests of its path dependencies. A package
manifest can change what is built without touching a source or the
lock file -- enabling a feature of a dependency already in the lock is
the plain case -- so a binary built at an older checkout, with only such
a change between it and the current clean HEAD, passed every timestamp
comparison, was reported Established, and the artifact attributed the
run to a HEAD that did not build it. That is the stale-binary case the
check exists to close (EP-OBSERVABILITY).

The server manifest is now always an input, and the manifests of the
path dependencies are derived rather than listed: Cargo's dep-info
covers the server's path dependencies transitively, so each listed
source is walked up to the nearest Cargo.toml inside the checkout, and
that set of manifests is checked with the rest. The list comes from the
same record as the sources, so it cannot drift from the manifests as a
hand-written one could. `sources_checked` counts the distinct inputs,
manifests included; the README and the flag's help say so.

Test: a_package_manifest_newer_than_the_binary_leaves_the_revision_unestablished
builds a fake checkout with three crates, checks the derived manifest
set, and shows that a newer server manifest, a newer path-dependency
manifest, or a missing server manifest each leave the revision
unestablished naming the file. It fails at the previous head, where the
newer manifests go unnoticed. The existing revision test's fixture now
carries the crate manifests it was missing.

Part of #271

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

* 3.x.x: clear an earlier run's outputs when an invocation takes --out (G3)

The abort path withheld the artifact and removed a stale
capacity-evidence.json, but the blocked path did not: it wrote its side
report and left whatever else was in the directory. Reusing a default
--out after a successful run and then blocking during frontend startup
left a fresh blocked report beside the previous run's self-validating
artifact and database profile, which read as evidence for a run that
did not produce them (EP-OBSERVABILITY). The same held for a run that
failed before it measured anything, which writes no report at all.

Rather than teach the blocked path what the abort path knows and leave
the error path still wrong, the obligation is met once, at entry: when
an invocation takes the directory it removes any capacity-evidence.json,
database-profile.json and load-harness-report.json an earlier run left
there, and both the completed and the blocked side report list what was
removed under stale_outputs_removed. Every exit path then has the same
guarantee -- the directory holds only this invocation's outputs --
without each one having to repeat the removal, and a path added later
gets it for free. The abort path keeps its own removal as defence in
depth; the frontend logs are untouched here because Frontend::launch
already starts each one empty.

Test: an_invocation_removes_the_previous_run_s_outputs_when_it_takes_the_directory
seeds an earlier run's three outputs and a frontend log, takes the
directory, and shows the outputs gone and named, the log kept, and a
partial leftover removed by name. The entry point is new, so at the
previous head the test does not build rather than fail.

Part of #271

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

* 3.x.x: read the proxy's upstream with the parser that accepted the URL (G4)

`host_port` decided whether a database URL already carried a port by
looking for a colon in its authority. A bracketed IPv6 literal such as
`postgresql://user@[::1]/db` has colons inside the brackets, so the
authority was returned as `[::1]` with no port, `DelayProxy::open`
handed that to a lookup that needs one, and the run failed after SQLx
had already connected with the same URL.

The URL is now read with SQLx's own connect-options parser, the one
that accepted it, so the host and port the proxy fronts are the ones
SQLx dialled: a hostname, an IPv4 or a bracketed IPv6 literal, with or
without an explicit port, the libpq-style `host` and `port` query
parameters, and the default port when none is given (EP-VALIDATION).
An IPv6 literal is bracketed on the way out, which is what a
`host:port` lookup needs. A URL naming a Unix socket is refused with
the reason, since the proxy cannot front one, and one that does not
parse is refused with the URL redacted.

Test: a_bracketed_ipv6_authority_keeps_or_gains_its_port covers both
bracketed forms, keeps the hostname and IPv4 cases, adds the query
parameter, socket and unparsable cases, and checks the result composes
with the authority rewrite that follows. At the previous head it fails
on the portless bracketed form, which came back as `[::1]`.

Part of #271

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

* 3.x.x: refuse a socket that arrives as a path-shaped host, and stop pinning a platform default

The G4 fix reads the upstream through SQLx's own parser, which is right,
but it inherited a default this code had not had to think about before.
A URL with no host does not fail: SQLx supplies one, and what it supplies
depends on the platform. On macOS it is a Unix socket directory, which
arrives as a *host* that happens to be a path, so `get_socket()` is empty
and the socket guard does not fire. `lookup_host` is then handed
`/private/tmp:5432` and reports a path as a DNS failure, which is the
confusing error G4 set out to remove, one case further along.

Refuse a path-shaped host with the same reason as an explicit socket, and
name the offending host in the message.

The test pinned that default to `localhost:5432`, so it passed on the
Linux host it was written on and failed here. A platform-dependent value
is not something to assert; what must hold everywhere is that a socket is
refused however it arrives and a frontable default is a TCP host. The
case now asserts that instead, and holds either way.

Part of #271

* 3.x.x: keep the endpoint parameters out of the proxied URL, and prove the delay before believing it (H1)

`rewrite_host` replaced the authority and kept the query string. SQLx reads
the libpq-style `host`, `hostaddr` and `port` parameters after the authority
and lets them win, so with `postgresql:///db?host=db.internal&port=5433`
every frontend dialled the database directly, the proxy carried nothing, and
the `slow_database` phase reported a 10 ms delay that was never applied.

The rewrite now drops those three parameters, compared percent-decoded as
SQLx decodes them, and keeps every other option in its order; user info is
looked for inside the authority only, so an `@` in the query is not taken
for it.

The run no longer assumes the proxy is on the frontends' path. Before the
run, with the slow phase's delay set, and again before every phase with its
own delay set, a SELECT 1 round trip is timed through the proxied URL exactly
as the frontends received it. Each direction is held once and the proxy's
sleep never returns early, so a proxied trip costs at least twice the delay;
one that comes back sooner did not go through the proxy. The entry check
refuses to start, and a delayed phase that fails it aborts the run with the
artifact withheld. Every phase's observation and the floor it was checked
against are in the side report.

Tests: endpoint_parameters_never_survive_the_rewrite (fails at the base with
the bypass URL rewritten to itself), a_round_trip_that_did_not_pay_the_delay_is_refused.

Part of #271

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

* 3.x.x: change the proxy delay only once the previous phase has settled (H2)

At a phase boundary the proxy's delay was set the moment the previous phase's
scheduler returned, with that phase's last submits still in flight. The
proxy reads its delay per chunk, so reconnect-phase submits could pay the
slow-database delay and slow-database submits outstanding when it was
cleared could finish without it, each keeping the phase stamp it was offered
with. A phase's rate and p99 then no longer described the delay it reported.
Teardown had the same shape: the delay was cleared before the drain.

The boundary now applies a phase's delay through `apply_phase_delay`, which
leaves a delay that is not changing alone, otherwise waits for every
session's outstanding count to reach zero -- nothing is offered meanwhile,
the scheduler has returned -- and only then sets the new delay. If the
submits have not settled within the share-commit timeout plus its margin,
the delay is left where it was and the run aborts with the count, as the
reconnect phase's restart already does, rather than leak records across the
change. Teardown clears the delay after its drain. The wait is recorded in
the next phase's entry, null when the delay did not change.

Test: a_phase_delay_is_applied_only_once_the_previous_phase_has_settled,
against a real DelayProxy and stand-in sessions: unchanged delays wait for
nothing, a change waits for the last outstanding submit, and a change whose
submits never settle is refused with the delay untouched.

Part of #271

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

* 3.x.x: summarise ACK latency over acknowledgements only (H3)

`phase_latency` filtered on the phase and `!reoffer`, so a refused share's
response time was summarised with the acknowledgements, and the artifact's
overall ACK figures were built the same way. A refusal is answered in
microseconds because the server never reached PostgreSQL for it, so a phase
dominated by refusals reported a p50 of 0.70 ms while its accepted shares
took seconds, and an artifact could pass the ACK p99 limit its accepted
shares were over. Refusals are already kept out of offered_valid_shares;
their timing had no business in the ACK percentiles either.

`ack_latency` now keeps only `Outcome::Accepted` records that are not
re-offers, and is used for every phase's ack_p50/p99 and for the overall
figures. The refusals' timing is not dropped: each phase's side-report entry
carries `client_rejection_latency` beside `client_ack_latency`, with a
definition saying which is which.

Every other summary that walks SubmitRecords was checked: rejection_report
counts refusals by reason, classify_gaps reads a refused share's own
latency to say whether the answer came after the commit deadline, the
mid-flight report reads re-offers, the dense-cadence windows read refusals
by the instant they were read, and time_to_usable_work reads tip sightings.
Each of those means to read what it reads; none feeds the ACK figures.

Test: ack_latency_is_the_latency_of_acknowledgements_only -- two accepted
shares in the seconds and ninety-eight sub-millisecond refusals give a p50
of 2,400 ms, not 0.7; the same holds for the overall aggregation, and the
refusals are summarised apart. At the base the same records gave a
sub-millisecond p50 through the old filter.

Part of #271

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

* 3.x.x: stop the new-revision search at the landing's span (H4)

The search for a frontend's first clean_jobs job after a bump ran to the
end of the phase. When the frontend had not served the new revision before
the next landing, that landing's own clean_jobs notify was selected and
reported as the earlier landing's new-revision work: time_to_new_revision_work
was understated by however long the frontend had really gone without, and
rejected_before_new_revision_work stopped at the wrong event.

The search now ends at the landing's span, which is where the next landing's
tip change begins. A frontend with no such job inside the span is its own
outcome: sessions_with_new_revision_work is 0, the time is unknown rather
than a number, rejected_before_new_revision_work is null, and both carry
new_revision_work_unavailable_reason saying no job at the new revision was
seen inside the span. The approximation label and the definitions say where
the search stops.

Test: new_revision_work_is_never_borrowed_from_the_next_landing. At the base
the first landing's frontend reported one session with new-revision work,
9.3 s of it, and two rejections before it; all three were the next
landing's.

Part of #271

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

* 3.x.x: attribute a reconnect to the phase that asked for it (H5)

A reconnect record was stamped with the run's phase at the moment the new
connection completed. A reconnect started near the end of the `reconnect`
phase that finished its handshake after `slow_database` began was therefore
labelled slow_database: it went missing from phases.reconnect.reconnect_events,
which can fail the reconnect gate although the reconnect the run configured
did complete, and turned up under a phase that configured none.

`Control::Reconnect` now carries the phase that sent it, as `Work::Submit`
has since the same mistake was fixed for submits, and the session keeps the
initiating phase for the reconnect in progress: the sender's phase for a
requested reconnect, and the run's phase at the instant the socket closed
or a retarget asked for a fresh connection. Every attempt's record, failed
or completed, carries that phase however many boundaries pass before the
reconnect completes.

Test: a_reconnect_is_attributed_to_the_phase_that_asked_for_it, against the
fake Stratum server with the new connection held inside its handshake while
the shared phase moves on. At the base the record read "slow_database".

Part of #271

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

* 3.x.x: withhold the artifact when a hard block is logged after startup (I1)

The startup check re-read every frontend's stderr once all of them were
ready and returned blocked on a JSONB-ceiling refusal. The same scan ran
again after the load stopped, but its result only went into the side
report's log_matches under a hard-coded `blocked: false`: a ceiling
refusal logged during the run -- a scheduled-block rebuild persisting a
job over the container ceiling, say -- left the artifact built, written,
self-validated, and the run able to exit 0. A candidate refusal leaves
ordinary shares flowing, so the capacity validator's own gates would not
necessarily catch it (EP-OBSERVABILITY).

The late scan is now checked with `is_hard_block` like the early one. A
hit withholds the artifact with the log line as its reason, removes a
stale artifact at the path as the abort path does, sets `blocked.blocked`
true with the line under `blocked.error`, and exits 3 ahead of every
other outcome; the side report still carries every number the run
produced. `artifact::write_or_withhold` takes a `Withhold` naming which
claim applies -- aborted or blocked -- instead of an abort reason alone,
and the exit code order is one function, `RunOutcome::exit_code`, so a
test can pin it.

Test: a_hard_block_logged_after_startup_withholds_the_artifact_and_exits_blocked.
At the base a ceiling line found by the final scan changed nothing: the
artifact was written and the exit code came from the reconciliation
findings alone.

Part of #271

Co-Authored…
kiwidream added a commit that referenced this pull request Oct 22, 2026
* Freeze money-path vectors from 2.x.x and record the D2 payout differences (#302)

* Freeze money-path vectors from 2.x.x and record D2 payout differences (#269)

Export 48 money-path cases from 2.x.x (504846cc) into
crates/qbit-prism/fixtures/vectors/. Topics 1-7 (window clipping,
fractional oldest share, carry-only recipients, pool fee, dust recompute,
largest-remainder ties, CTV chunks) come from the 2.x.x qbit-prism entry
points. The bootstrap transition and below-target credit come from the
2.x.x Python rule code, with each rule's payout computed by the same
engine. The exporter source and its regeneration command sit under
fixtures/vectors/exporter/, outside any cargo target.

tests/money_path_vectors.rs replays every case through the 3.x.x engine
and reports all mismatches at once. Topics 1-7 match 2.x.x exactly. The
five differing cases carry expected_2xx, expected_3xx and a d2_entry
whose anchor must exist in docs/prism-rust-migration.md. That doc now
records D2a bootstrap pooling, D2b below-target credit, and D2c prior
balances during bootstrap, the last pending the umbrella owner's approval.

checked_in_hand_worked_fixtures_match_engine now also asserts the
power-law-accrual fixture's floor, on-chain count and accrued recipients.

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

* Pin the money-path vectors and freeze the zero-fee boundary (#269)

The vector test now pins the sha256 of every vector file next to
SOURCE_COMMIT, so a vector changes only through a re-export from 2.x.x
in a reviewed commit that updates the pin. It also requires the set of
d2_entry anchors used by the cases to equal the entries documented in
the "Payout differences from 2.x.x (decision D2)" section, which must be
exactly D2a, D2b and D2c. Deleting a D2 case, or rewriting one into a
plain matching case, now fails.

pool_fee.json gains three cases where a 1-bps fee on a 9999-sat coinbase
floors to zero. With a 1000-sat fixed floor, 2.x.x records the pool-fee
account at 0 sats and emits no fee output, under both canonical and
pool-fee-first ordering; with the day-one floor the coinbase is below
14720 and the policy fails. 3.x.x reproduces all three.

The exporter's implemented_at citations now point at the lines that
implement each rule (coordinator.rs:747 and 759,773; job_bundle.py:3400;
accepted_preview_telemetry.py:144). The D2c reason labels
build_collection_bundle as 2.x.x code, and D2b states the confirmation
timing assumption behind its next-block payout. A real 1160-recipient
TRUC chunk is left as a documented gap: it would add about 1.6 MB.

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

* Note the 2.x.x share-weight settings 3.x.x does not carry (#269)

2.x.x read PRISM_STRATUM_SHARE_WEIGHT and PRISM_STRATUM_SHARE_WEIGHTS_JSON.
A per-worker entry in the JSON object credited max(1, override) instead of
the share target's difficulty; the default weight only filled the job's
delivered share_weight field. 3.x.x supports neither. With the 2.x.x
defaults crediting is unchanged, so this is not a D2 payout difference,
but a deployment that set either variable must remove it before cutover.

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

---------

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

* Add a native SQL oracle for the payout-window read (#306)

* Add a native SQL oracle for the payout-window read (#269)

Item 3 of #269 asks for an independent proof that `Ledger::snapshot`
returns exactly the eligible payout window. The 2.x.x oracle was a Python
module written against the old per-row read; 3.x.x pages the window
backwards through a different query, so this is a new oracle written
natively in Rust.

Each test gets a throwaway schema, drives the read through the public
`Ledger` API only, and recomputes the expected window in one unpaged
statement: an eligibility filter, a running-sum window function standing
in for the subtract-until-zero loop, and a single `json_agg`. The oracle
shares no SQL text, constants or private items with `ledger.rs`, so it
survives the pending split of that module. It then compares membership,
order and every field of every share, plus the captured cutoff.

The anchor barrier is expressed with exact integer millisecond
arithmetic rather than the read's `to_timestamp(double precision/1000)`,
so the two sides are genuinely independent. Scenarios cover the 4096-row
page boundary from either side and three pages deep, the row that
straddles the remaining weight, rows sitting exactly on the anchor and
one millisecond past it on each timestamp, rejected rows interleaved
with accepted ones, difficulties at the top of the `u128` range, anchors
ending in 999/000/001 near 2^41 and 2^43 milliseconds, and empty windows.

Each read is given a ceiling so a cursor that stops advancing fails with
a named error instead of hanging the run.

The database URL comes from `PRISM_TEST_DATABASE_URL`. One guard decides
the outcome: run when it is set, fail when it is missing while
`PRISM_TEST_REQUIRE_INTEGRATION=1` or `GITHUB_JOB=prism-native-postgres`
demands the integration suite, and otherwise print a skip line. Keying on
`CI` would break `rust-tests`, which runs the whole workspace with no
database.

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

* Derive oracle anchors from the clock and assert the append path at the anchor (#269)

Two follow-ups to the payout-window oracle.

The suite pinned fixed anchors in 2030 and 2039. Because a pinned anchor
has to sit above the wall clock, those were dated fuses: from January 2030
every test would have failed in CI for no reason in the code. Anchors at an
ordinary magnitude are now derived from the database clock at run time --
a day of margin, rounded up to a round millisecond, plus the scenario's own
`999`, `000` or `001` suffix -- so the millisecond coverage is unchanged and
the date is gone. Fixed anchors are kept only for the far-future magnitude
cases, and the 2^41 anchors move to 2^42.

The second change turns a comment into an assertion. `Ledger::append`
stamps `accepted_at` with `GREATEST(ledger_clock_ms, floor(now))` and
requires `job_issued_at_ms <= accepted_at_ms`, so pinning the ledger clock
lets the public API alone place a real share exactly on an anchor and
another a millisecond past it. Every anchor in the barrier scenarios now
does that, and asserts the first is credited and the second is not.

Doing so surfaced why those two changes belong together. Past roughly 2^43
epoch-milliseconds a `double precision` no longer resolves a microsecond,
so the read's `to_timestamp(double precision/1000)` barrier lands up to a
microsecond either side of the true millisecond. A fixture storing the exact
millisecond and a share written through the writer's own conversion then
fall on opposite sides, and no single barrier makes both agree. The
exact-time oracle therefore runs only where the conversion is exact -- the
derived anchors and 2^42 -- with a runtime guard that refuses an anchor
which is not, so the fixture cannot silently pick one.

Behaviour past 2^43 gets its own test, in the integer milliseconds
`AcceptedShare` carries and with no oracle and no direct inserts: three
shares per anchor, all through `Ledger::append`. Membership follows the
contract at every anchor. The read-back does not: `share_from_row` floors,
so a millisecond whose conversion lands low reads back one millisecond
early -- 480000 of every 2000001 milliseconds measured near 2^43, none near
2^42 or at any realistic date. Rather than skip that check, the test pins it
from both sides: a millisecond converting at or above itself must round-trip
unchanged, one converting below must be early by exactly one millisecond and
no more. Nothing known-wrong is asserted as right, and a regression in
either direction fails.

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

* Bound the far-future read-back drift instead of pinning it (#269)

`writer_rows_follow_integer_milliseconds_past_2_43` required the read-back
drift to be exactly one millisecond wherever the stored timestamp converts
below its own millisecond. That asserted a known defect as expected
behaviour: the day `share_from_row` rounds instead of flooring, the drift
becomes zero and the test would have failed the fix.

The branch now bounds the drift rather than requiring it -- at most one
millisecond early, never late -- and pushes to the printed
`read_back_early` list only when a millisecond actually drifted. The defect
stays visible in the per-scenario output, a silent change of behaviour is
still obvious, and a fix passes instead of failing.

The other side of the classification is unchanged: a millisecond the
conversion represents at or above itself must still round-trip unchanged.
Membership is still asserted exactly at every anchor, and both timestamps
must still drift alike.

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

* Tolerate the read-back convention for off-grid fixture rows and tidy the oracle (#269)

The oracle held the read's millisecond fields to its own `floor(extract(epoch
…)*1000)`. Every timestamp a writer can produce lands on a whole millisecond,
so that was exact for real rows -- but scenarios c and e deliberately insert
rows 400 microseconds either side of the anchor, to prove the barrier compares
instants rather than milliseconds, and `AcceptedShare` cannot say which side of
a millisecond such a row fell on. Flooring one is no more correct than rounding
it, yet the oracle demanded the floor, so the separately-reported
`share_from_row` rounding fix would have failed `c:anchor-barrier` and every
`e:` sub-case on `accepted_at_ms` and `job_issued_at_ms`.

The oracle now reports, per share and per timestamp, whether the stored value
lies on a whole millisecond. On the grid the read-back must still be exact,
which covers every row the writer can write. Off the grid the read may return
the floor or the floor plus one and nothing else, so a read that lost a whole
millisecond or gained two still fails. Each timestamp is judged on its own
flag, so a read that treated the two fields differently is still caught, and
membership, order and every other field stay exact.

Every test now drops its throwaway schema on the failing path too, through a
helper that runs the body and then always closes the ledger and drops the
schema. The body's error is what a failing test reports; a cleanup failure is
attached to it as context rather than replacing it, so a leaked schema can
never hide the assertion that actually failed. That covers the per-sub-case
schemas in `check_anchor_boundary` and in the 2^43 loop, which previously
leaked one schema per sub-case whenever a run went red.

Three comments were also wrong. The module header claimed the oracle shares no
SQL text with `ledger.rs`, but `oracle_cutoff` repeats the read's cutoff query
and `compare_conversion` embeds the read's own `to_timestamp`; both are
deliberate and the header now says which, and why each is acceptable. The
guard said the repository sets both "required" signals, when it sets only
`PRISM_TEST_DATABASE_URL` -- GitHub sets `GITHUB_JOB`, and nothing sets
`PRISM_TEST_REQUIRE_INTEGRATION`, the opt-in switch proposed by #286. And the
2^43 measurement spans 2000001 milliseconds, about 33 minutes, not two seconds.

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

---------

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

* Retry CI apt installs through Ubuntu mirror blips (#311) (#312)

Three CI jobs install Ubuntu packages with a bare `apt-get update` and
`apt-get install`. On 2026-09-11 the Ubuntu archive refused connections
and served hash-sum mismatches to the runners. Each of those jobs failed
with exit 100 before any test ran.

Add `.github/scripts/apt-install.sh` and use it in all three jobs. apt
retries each download (Acquire::Retries=5, with 30 s timeouts). If the
update-and-install still fails, the helper clears the package lists,
waits 30 s, then 60 s, then 90 s, and tries again, for up to four
attempts. Every attempt but the last treats a partially failed
`apt-get update` as a failure, instead of installing from stale indexes.
The last keeps apt's default leniency, so the step is never stricter
than before. Each failed attempt is annotated as a warning.

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

* Record the approved D2 payout decision in the migration guide (#310)

Decision D2 in #260 was approved on 2026-09-11: keep the 3.x.x behaviour
for D2a (bootstrap pooling), D2b (below-target block credit) and D2c
(prior balances during bootstrap). Mark D2c as approved, and point the
configuration note at the operator release notes.

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

* 3.x.x: native metrics registry with the cutover-minimum series (#308)

* feat(metrics): add native cutover registry and producer hooks

* fix(metrics): enforce registry ownership and live observation contracts

* docs(metrics): align operator guidance and collector validation

* test(metrics): pass registry to merged admission fixture

* test(metrics): reset whole socket before failed-write assertions

* fix(metrics): validate listeners before coordinator startup

* fix(metrics): bound progress guard to health publication

* fix(metrics): render registry before first publication

* Survive Ubuntu mirror outages in CI package installs (#311) (#314)

#312 made the three CI apt steps retry, which rides out short blips. An
outage like the one on 2026-09-11, about 35 minutes of refused
connections and hash-sum mismatches from Canonical's archive, still
fails them.

- Pin fallback mirrors in .github/apt/ubuntu-mirrors.txt: Azure's cloud
  mirror, kernel.org and Princeton, with Canonical's archive last. After
  the first failed attempt, apt-install.sh replaces the runner's Ubuntu
  sources with that list. Priority tags make apt try the mirrors in
  order, and retries skip apt's growing delay so a refused mirror doesn't
  hold up every download. Healthy runs keep the runner's own sources.
- Cache the downloaded packages. The new composite action
  .github/actions/apt-install restores and saves them with actions/cache,
  keyed on the package set and the month. The helper downloads into its
  own directory, keeps exactly the packages a successful install used,
  seeds the next install from them, and if every online attempt fails,
  installs them directly with dpkg. It never reinstalls or downgrades
  anything the runner already has.
- Stop retrying after a deadline (480 s by default), so the cache still
  gets its turn well inside the jobs' timeouts.

The three CI apt steps now use the composite action.

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

* 3.x.x: ratchet the payout window against the PostgreSQL JSONB ceiling (#298)

* 3.x.x: ratchet the payout window against the PostgreSQL JSONB ceiling (#264)

At the production window the native server stores the whole share window
inside single JSONB documents. PostgreSQL refuses any container whose
elements exceed 268,435,455 bytes. CI never saw this, because the largest
native fixture had 800 shares.

Add a deterministic production-shaped window fixture, an in-process fake
node, and a gate that drives refresh, enqueue, claim, landing and import
against PostgreSQL 16. After each phase the gate measures every JSONB
column, and it fits bytes per share at two reduced sizes to project to
400,000 shares. Four known violations are checked in as a ratchet. The
gate fails on a new crossing and on a listed write that stops crossing,
and it never skips when CI is set without a database. It runs in the
prism-native-postgres job; the database-free rust-tests job skips it by
name. The full-size run and the baseline sweep are #[ignore]d and
documented. test/prism-native-tests.sh gains a cargo-args mode, and the
measurement and capacity docs record the baselines.

Part of #261.

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

* 3.x.x: attribute refused JSONB writes and check the sweep's fit stability (#264)

Two accepted review findings on the JSONB ceiling gate, both in test code and
the measurement document.

A refused write was attributed to a hard-coded column. PostgreSQL's ceiling
error names neither the table nor the column, and the server adds no context
naming the write, so each of the four `ceiling_rejection` sites was recording an
assumption: a phase that ever wrote a second oversized JSONB value would have
had the refusal blamed on the expected column, and the new offender would never
have been seen. Every refusal now goes through `attribute_refusal`, which takes
the refused phase, the refused share count and what that phase's accepted
measurements project for each of its columns there. Exactly one column must
project past `ATTRIBUTION_FLOOR`, 90% of the hard limit - seven times the 1.4%
the measured fits disagree by - and it must be the write the call site expects;
no candidate, two candidates, or the wrong one fails the gate with both names.
The full-size run and the baseline sweep now run the reduced pair first for
those projections; the reduced run attributes a refusal at `n2` from the `n1`
measurement scaled to it, and a refusal at `n1` fails outright, since nothing
smaller was accepted to attribute it from. The ratchet row says how it was
attributed and still never shows a byte count.

The baseline sweep never checked fit stability. Its comment claimed the CI-pair
projection had to agree with the large-pair one, but it only computed the large
pair, and with the default sizes refresh is refused there and has no projection
at all. The sweep now also runs the reduced pair for the CI projection, skipping
a size its list already has, and compares the two per write: the large pair is
the two largest sweep sizes at which that write was accepted, since the writes
are refused at different sizes and no single pair fits them all. A disagreement
over `FIT_STABILITY_TOLERANCE` fails the sweep, naming the write, both
projections and both pairs; a write accepted at fewer than two sweep sizes fails
rather than going unchecked; a CI projection below 1 MiB is printed as not
compared, because relative noise on a write that small says nothing about the
window's growth. The table has the columns of the document's own.

Unit tests cover attribution (unique, ambiguous, unexplained, another phase's
column, and a candidate that is not the expected key) and fit stability
(agreement, a 10% divergence, pair selection skipping refused sizes, fewer than
two accepted sizes, and the 1 MiB floor), all without a database.

Verified on PostgreSQL 16: the reduced gate ends with the ratchet holding at
exactly the four known violations, and the sweep at 10000,20000,40000 prints the
comparison table with every compared write inside 0.22%.

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

* 3.x.x: keep the n1-scaled projection for a write refused at n2 (#264)

A write PostgreSQL refuses at n2 gets a Rejected verdict in the reduced
fit, so projections_at gave it no projection. With PRISM_JSONB_GATE_N2
equal to the target, the full-size run then met the same refusal with
nothing to attribute it from, and failed as unexplained although the
write is a known violation. The sweep had the same gap at larger sizes.

reduced_projections keeps the projection that attributed the n2 refusal,
the n1 measurement scaled to the size in question, for every write the
reduced pair refused. The full-size run and the sweep now use it. A unit
test covers the refused write, the fitted write it leaves alone, and the
attribution at the target.

Part of #261.

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

* 3.x.x: attribute refusals before any table names their column (#264)

The full-size run, the reduced run's n2 half and the baseline sweep printed
their measurement tables before attribute_refusals ran, and
write_table_lines named each refusal's table and column as the call site
recorded it. A moved or new oversized write would have been shown under
the old column before the attribution check disputed it.

Every path now attributes first and still prints its table whatever the
outcome. write_table_lines shows an unattributed refusal by phase only, as
(refused) (not attributed). attribute_refusals no longer empties the map
before every refusal has attributed, so a failure keeps the refusals in
the report. The sweep attributes through a new attribute_sweep before
printing any size. A unit test covers both rows.

Part of #261.

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

* 3.x.x: fail on an unreadable database URL instead of skipping the gate (#264)

database_url read PRISM_TEST_DATABASE_URL and CI with .ok(), which turns
VarError::NotUnicode into "unset". Outside CI, a deliberately configured
but malformed URL therefore skipped the ratchet silently, and a
non-Unicode CI value counted as unset too.

Both reads now go through database_url_from, where an unreadable variable
is an error, as every other gate setting already is. The existing rule is
unchanged: with CI set and no URL, the gate fails. A unit test covers a
set URL, unset and blank values, CI without a URL, and non-UTF-8 values
of both variables on Unix.

Part of #261.

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

---------

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

* 3.x.x: Set one 3.0.0 release identity across VERSION and every crate (#315)

* 3.x.x: set one 3.0.0 release identity across VERSION and every crate

After #283 the tree carried three version strings on the 2.0.x line:
VERSION and the two library crates read 2.0.2 by inheritance from the
2.x.x merge, and the rewritten server still read 2.0.0 from #244. None
of them named a 3.x.x release.

Declare the version once, as [workspace.package].version = "3.0.0" in
the root Cargo.toml, and have every crate inherit it with
version.workspace = true. VERSION reads 3.0.0 to match. Cargo.lock only
moves the three workspace-member entries; no third-party dependency
changes, and `cargo metadata --locked` and `cargo check --workspace
--locked` pass.

The toolchain pin and builder-image digest stay with #286; the 3.0.0
release notes stay with #291.

Part of #284.

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

* 3.x.x: gate the release identity with a version-skew check

scripts/check_version_skew.py asserts that VERSION equals the version
Cargo resolves for every workspace crate. It reads crate versions from
`cargo metadata --no-deps` rather than the manifests, so a crate that
later drops version.workspace = true for its own literal is still
caught. It names each mismatching crate with both versions and exits
non-zero on any mismatch, on a missing, empty, or malformed VERSION, and
when cargo itself cannot describe the workspace.

CI runs it as the first step of the rust-tests job, which already has a
Rust toolchain and is in the required checks aggregator's needs list, so
skew fails the merge gate without a new job. `make check-version-skew`
runs the same command locally.

tests/test_check_version_skew.py drives the script against temporary
workspaces: matching versions pass; VERSION behind the workspace names
every crate; one crate with a literal version is named alone; empty,
missing, and malformed VERSION files fail; an unusable cargo is reported
rather than passing. It also asserts the checked-in tree passes, that
the CI step lives in a job the gate needs, and that the make target
exists.

The 3.x.x development-line note records the single source and points
the real release notes at #291.

Part of #284.

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

---------

Co-authored-by: Claude Fable 5.1 <[email protected]>

* 3.x.x: assert the server-side D2 payout rules (#316)

* Cover the D2b below-target block credit against PostgreSQL

Decision D2 on #260 keeps 3.x.x's payout behaviour, and entry
d2b-below-target-credit of the migration guide is the one that changes a
miner's money: a proof that meets the network target but misses its
assigned share target is credited at network difficulty, and only once the
block it solved is observed on the active chain. 2.x.x credited the
assigned share difficulty the moment the node accepted the block. Until
now the only in-tree coverage of that shape ran against an in-memory
stratum backend, which can see the frame being forwarded but neither the
credited amount nor when it lands.

Add coordinator::d2_below_target_tests, which drives the real Coordinator
against a throwaway PostgreSQL schema and a scripted qbit JSON-RPC node,
one test per case of the frozen below_target_credit vectors. Each test
seeds the vector's ledger window, builds the found-block work, mines a
proof of the shape the case names, and starts a real submission, then
asserts:

* the credit is published only inside the confirmation transaction. While
  the candidate is pending there is no credit row, exactly one deferred
  share, and no acknowledgement to the miner;
* the credited difficulty is the proven network work and not the 2.x.x
  assigned difficulty, read from both sides of the vector rather than
  written here;
* a lost submitblock reply ends in exactly one credit, published by
  reconciliation, and repeating that observation does not credit twice;
* a reorg after publication leaves the credit intact while the block goes
  inactive;
* a block the node refuses is abandoned, credits nothing, and fails the
  submission with reason ledger-confirmation-failed, with the internal
  reason the miner never sees captured from the log;
* a share-passing proof is still credited its assigned difficulty at once,
  with nothing deferred;
* the block after the solved one pays exactly what the vector projects,
  compared leaf by leaf, which is where a wrong credit would become a
  wrong payout.

The assigned share target is reached through the stratum difficulty floor,
because reassign clamps a target easier than the network target back to
the network target and the floor is the only way to get a share target
harder than the block target. The two difficulty units differ, so the
floor is converted from the vector's scaled unit and stepped up until it
is at least as hard as the vector's target; no f64 divides to that exact
256-bit value.

The tests carry the same integration guard as the window read oracle:
they run when PRISM_TEST_DATABASE_URL is set, fail by name when
PRISM_TEST_REQUIRE_INTEGRATION=1 or GITHUB_JOB=prism-native-postgres
demand the suite, and otherwise print a skip line, so a database outage in
that job cannot pass silently. Each test takes its own schema, serialises
against the cluster-wide advisory locks the other coordinator tests share,
bounds every wait, and drops its schema and aborts its tasks on the error
paths too.

Also point the stratum protocol test at this module, so the boundary
between the two is written down where a reader meets it.

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

* Pin the D2a bootstrap-pooling selection with coordinator tests

Decision D2 on #260 keeps 3.x.x's payout behaviour during pool bootstrap,
and nothing yet fails if that behaviour drifts back towards 2.x.x. This
adds an in-crate test module that drives Coordinator::refresh_once against
a fake qbit JSON-RPC node and asserts on the work it actually publishes.

What is asserted, and why it is asserted this way:

* D2a, bootstrap pooling. With two accepted shares from two miners -- below
  2.x.x's readiness gate of three, above 3.x.x's rule of "any share at all"
  -- refresh_once must select the ledger window, and the payout must be the
  proportional split the bootstrap_transition vectors record for 3.x.x, and
  must not be the 2.x.x whole-coinbase-to-the-finder outcome. Restoring any
  readiness gate of three or more fails this test.

* The one-share boundary the vectors do not cover: a single share from a
  miner who is not the solver takes the whole coinbase. A restored gate of
  two or more fails this test.

* An empty ledger and no balances still pays the solver, through the one
  synthetic bootstrap-share the bootstrap path builds.

Every expectation is read out of the vector file by case name, checked
against the D2 anchor the case carries, so a renamed, re-anchored or
weakened case fails here rather than passing quietly. The assertions read
the Prepared work refresh_once published and the bundle build_job hands a
solver; build_bundle is never called directly, because that would compute
the answer the selection under test was supposed to make.

The harness template's network difficulty is 1_000_000 rather than the
vectors' 100, so payouts that turn on the synthetic share are compared in
units of each side's own network difficulty, with exact divisibility
asserted rather than rounded away. Seeded-share payouts are compared
exactly: the 8x window counts every seeded share at either scale.

The integration guard is the one from the payout-window oracle: it runs
when PRISM_TEST_DATABASE_URL is set, fails and names the variable under
PRISM_TEST_REQUIRE_INTEGRATION=1 or GITHUB_JOB=prism-native-postgres, and
otherwise prints a skip line. Keying on CI would be wrong, because the
no-database job sets it too.

The D2c carry-only case is not covered yet: an empty payout window
alongside a non-zero carry-forward balance is not reachable from 3.x.x's
own write paths, and how to reach it is still being decided.

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

* Pin D2c: a bootstrap block still pays carried-forward balances

Decision D2 on #260 keeps carried-forward balances in the payout of a
bootstrap block, where 2.x.x dropped them from its collection bundle and
left the account unpaid. Nothing failed if that regressed.

This adds the carry-only case from the bootstrap_transition vectors. With
an empty share window and one carry-only account whose balance is above
the day-one floor, refresh_once must publish no window bundle, the bundle
build_job hands the solver must carry the ledger's prior balances, and its
payout policy manifest must match the recorded 3.x.x outcome exactly -- the
solver paid the coinbase less the carried account's settlement, and the
carried account paid out of this block. It must also differ from the 2.x.x
outcome, which pays the solver everything. Passing an empty prior-balance
list on the bootstrap path fails this test and no other.

Reaching that state takes an explanation, because 3.x.x cannot produce it.
An empty window beside a non-zero carry is the migrated, or archived, state
of a pool that inherited balances without the share history behind them,
and every route to it from a running 3.x.x is closed: a block that accrues
must carry real ledger shares, because the landing path re-reads the
bundle's share range out of the ledger and requires a match; a
bootstrap-shaped block cannot accrue at all, because its single entitlement
always takes the whole miner reward and so always clears the floor that was
just checked against it; and shares can never be removed afterwards,
because the share ledger refuses every update, delete and truncate at the
database level, and one accepted row is enough to keep the window non-empty
forever.

So the test records the carrying parent block's rows directly, and does it
without inventing a single figure. The parent's payout is built by the
engine and verified through the public audit verifier, the test asserts the
engine accrued exactly the balance the vector expects before anything is
written, and then only that manifest's own accounts are recorded -- through
the same statements, the same account-type filter and the same order the
landing path uses, the block row prepared first and flipped to confirmed
separately so the summary triggers count its carry once. Nothing writes a
summary table by hand. A schema change that moves the real landing path
leaves this copy failing loudly rather than quietly seeding some other
state. The fake node's tip at that height is that parent block, so
reconciliation sees it on the active chain, and the block under test is its
child.

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

* Share the D2 test harness and apply the review findings

Both decision-D2 coordinator test modules carried their own copy of the
same harness. Move it into coordinator::d2_test_support: the integration
guard, a throwaway schema that is removed on success, on failure and when
a fixture fails to open, the coordinator configuration both run, the
payout projection with its leaf-level diff, and the shared constants.

Also apply what review of the two modules found:

* the bootstrap tests' fake node served a fixed template time, so every
  one of them would have started failing as stale in January 2027; it now
  serves the wall clock, as the below-target node already did;
* each test now reports its own failure ahead of any cleanup failure,
  instead of letting a cleanup error replace it;
* the below-target fixture now drops its schema when setup fails;
* assertions that could no longer fail once the exact 3.x.x match had
  passed now check that the vector itself still records a difference
  from 2.x.x, which is what they were meant to guard;
* the carry-seeding comment now says exactly which landing statements it
  repeats verbatim and which parts of landing it leaves out.

No production code changes.

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

---------

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

* 3.x.x: Make gated tests fail loudly, prove CI execution, add Rust hygiene jobs (#322)

* Fix every clippy warning without changing behaviour

`cargo clippy --locked --workspace --all-targets -- -D warnings` now
passes on the 1.98.1 toolchain. Each change keeps the code's behaviour:

- `(n + 1) / 2` becomes `n.div_ceil(2)` in both Merkle root loops.
- The two `Default` impls that picked one variant become `#[derive(Default)]`
  with `#[default]` on that variant.
- The eligible-share sort keys on `Reverse(share_seq)` instead of a
  comparator that spelled the same order.
- `&[x.clone()]` becomes `slice::from_ref(&x)` in the CTV manifest test.
- `seq % 4 == 0` becomes `seq.is_multiple_of(4)` in the window fixture.
- `chunks_exact(_mut)` with a constant size becomes `as_chunks(_mut)`, which
  ignores the same remainder.
- The adversarial settlement case that looped over four blocks and broke
  after the first now states that it checks block 0 only, which is what
  it always did.
- `tools.rs` keeps its `live_instance_tests` module after the last item.
- The two owning audit-bundle entry points allow `too_many_arguments`
  with the reason that they mirror the borrowed forms they forward to.

`cargo fmt --all --check` already passed on the base commit, so there is
no formatting-only change to land.

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

* Route every environment-gated test through one shared gate

Every test whose execution depends on PRISM_TEST_DATABASE_URL,
PRISM_TEST_PG_BIN_DIR or QBITD_BIN used to open with its own copy of a
skip: read the variable, print a line libtest hides, return Ok. The new
qbit-prism-test-gate crate holds the one decision table that
window_read_oracle.rs already followed, generalised per input: present,
run; missing while PRISM_TEST_REQUIRE_INTEGRATION=1 or
GITHUB_JOB=prism-native-postgres, fail naming the variable and the test;
missing otherwise, print one line with a fixed prefix past libtest's
capture and return. A variable that is not valid Unicode is an error,
never absent, and a switch value other than 1 or 0 is an error too. The
table is a pure function over injected values with a unit test per row,
and a child-process test drives the runtime path.

Every site is converted: the ledger, 2.x upgrade, rollups, API, readiness,
authorization, migration-rollback, failover, replica, live regtest,
candidate-lease, public-service and live-instance tests, and the window
oracle, which drops its private guard. The two explicitly selected
#[ignore] tests use the gate's required entry point, which never skips.
The JSONB ceiling gate moves off its CI keying (GitHub sets CI=true in
rust-tests, which has no database), so rust-tests no longer skips it by
name; its unreadable-variable test now exercises the shared table. The
live fixture keeps the qbitd path it was opened with for node restarts.

The crate is a dev-dependency of qbit-prism-server and qbit-prism, so a
gated test under either crate's tests, or in a #[cfg(test)] module, uses
the same gate. scripts/check_gate_env_reads.py, run in the lint job,
fails when any Rust file outside the gate crate names one of the gate
variables in a string literal, so no new test can read them directly.

Measured gated tests: 74 in the tree, 72 of which the native job runs
(the two JSONB #[ignore] measurement runs are gated but never selected
in CI).

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

* Prove in CI that every gated test executed

With PRISM_TEST_GATE_MANIFEST set, the gate appends one line per decision,
executed, skipped or failed, followed by <package>::<binary>::<test path>,
in a single O_APPEND write so parallel test threads and separate test
binaries share the file. test/prism-gated-tests.txt is the checked-in
list of the 72 gated tests the native job must execute, including the
two #[ignore] runs it selects explicitly; its length is the minimum.

scripts/check_gate_manifest.py fails when any expected test did not
execute, any skipped or failed line appears, fewer distinct tests
executed than the list holds, a test executed that the list does not
name, or the log shows the gate's skip prefix or the wording of the skip
messages the gate replaced. It prints the manifest to the log and to the
step summary.

The prism-native-postgres job keeps its id (the gate keys on it), sets
PRISM_TEST_REQUIRE_INTEGRATION=1 and the manifest path, runs the whole
workspace with --all-targets and --nocapture through tee, then the two
explicit --ignored runs, then the proof, and uploads the manifest as an
artifact. A gated test added under crates/qbit-prism is therefore covered
by a required job.

test/prism-native-tests.sh mirrors the job: its default mode runs the
workspace, both explicit runs and the proof, and exports the switch once
the PostgreSQL server tools and qbitd are present; the live, replica and
cargo-args modes always export it, since they refuse to start without
their inputs or name their own tests.

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

* Add fmt, clippy, cargo-deny and hadolint as required checks

Four new jobs join the checks aggregator: cargo fmt --all --check,
cargo clippy --locked --workspace --all-targets -- -D warnings,
cargo deny --locked check, and hadolint over every Dockerfile.

deny.toml checks advisories (nothing ignored), licenses (an allow-list of
what the tree uses, plus CDLA-Permissive-2.0 for the CA bundle that
webpki-roots ships), bans (duplicate versions warn; wildcard requirements
are refused except the workspace's own path dependencies, which needs
qbit-prism and qbit-prism-server to be publish = false, as they are in
practice) and sources (crates.io only).

cargo-deny 0.20.2 and hadolint 2.15.1 are installed by
.github/scripts/install-pinned-tool.sh from their GitHub releases after a
sha256 check. hadolint reads .hadolint.yaml, which ignores nothing
globally: lab/prism/Dockerfile pins its two apt packages, and the other
images, whose behaviour is not this workstream's to change, carry inline
ignores with reasons (unpinned apt versions, the named qbit-src build
context that DL3022 mistakes for a stage, the deliberate separate cmake
layers, and the checked pipes in the Bitcoin Core download).
.github/actionlint.yaml names the Blacksmith runner label so actionlint
runs clean locally.

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

* Pin the Rust toolchain to 1.98.1 in one place

rust-toolchain.toml pins the exact stable version with rustfmt and clippy
under the minimal profile. [workspace.package].rust-version carries the
same version and every crate inherits it. The lab/prism/Dockerfile
builder is rust:1.98.1-bookworm at the multi-arch index digest Docker
Hub serves for that tag (resolved through the registry API; both the
1.98.1-bookworm and 1.98-bookworm tags point at it today).

scripts/check_toolchain_pin.py fails when the three disagree, when a
crate stops inheriting rust-version, when the builder line lacks a
digest, or, with --installed, when the active rustc or cargo is not the
pin. The lint job runs the static check; the new
.github/actions/rust-toolchain composite action replaces the floating
dtolnay/rust-toolchain@stable in every Rust-using job, installing the
toolchain rustup reads from the file and asserting the installed
version. docker-builds builds the builder stage on its own first and
asserts that its cargo and rustc report the pin.

VERSION and scripts/check_version_skew.py from #315 are unchanged.

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

* Keep one make target per native test suite

test-prism-postgres-ledger, test-prism-postgres-scale,
test-prism-postgres-native-ledger and test-prism-postgres-seed-guard all
ran test/prism-native-tests.sh; they become test-prism-postgres.
test-prism-stratum-regtest-live, test-prism-stratum-postgres-regtest-live
and test-prism-combined-regtest all ran the live mode that
test-prism-regtest already names; they are removed.
test-prism-public-read-replica keeps its name and calls the script's
replica mode directly. The eight wrapper scripts under test/ that only
exec'd prism-native-tests.sh are deleted; test-prism-postgres-throughput
and its script are untouched (#271 owns the throughput floor).

README, the coordinator-refactor validation notes and the overload alert
spec now name the surviving targets; the historical release notes under
doc/ keep the names they shipped with.

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

* Document the integration test gate and the deleted-test map

docs/prism-integration-test-gate.md is the gate contract: the inputs, the
decision table, the switch, the skip prefix, test identity, the manifest,
the expected list and the proof, local runs, and how to add a gated test.

docs/prism-deleted-test-map.md rebuilds the readiness review's map from
git: every test file under tests/ and test/ on origin/2.x.x (504846c)
absent on 3.x.x, 142 files grouped by area, each with its native
replacement, or the open issue that closes the gap, or a needs-triage
note where neither exists. Both are linked from docs/README.md, and the
wrapper descriptions in PRISM.md, the server README and the ledger
operations guide now describe required mode and the manifest.

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

* Route the D2 payout tests through the shared gate

#316 landed nine PostgreSQL-gated coordinator tests with a hand-written
copy of the old guard in d2_test_support.rs, which read
PRISM_TEST_DATABASE_URL, PRISM_TEST_REQUIRE_INTEGRATION and GITHUB_JOB
directly and so failed scripts/check_gate_env_reads.py. The guard now
takes the URL through qbit_prism_test_gate like every other #[cfg(test)]
site, the nine callers drop the test name the gate derives itself, and
the tests join test/prism-gated-tests.txt, which the native job's
manifest is checked against: 81 expected gated tests, 83 in the tree.

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

* Require every explicit #[ignore] run and write manifest lines in one write

The two JSONB measurement runs, jsonb_ceiling_ratchet_at_full_size and
jsonb_ceiling_baseline_sweep, are #[ignore] tests someone asks for by
name, yet they reached the gate through the non-required entry point, so
a manual --ignored run with no database printed a skip line and reported
ok. They now use the gate's required entry point, as the
observability_database and stratum_admission_postgres runs already did,
and the contract says that every explicit #[ignore] run is required.
They stay out of test/prism-gated-tests.txt because CI never selects
them.

The gate's record_to used write_all, which can split a line across two
writes after a short write and let another thread's line land between
them. It now hands the whole line to one write and treats a short write
as an error, so each manifest line stays a single O_APPEND write; the
skip line on stderr goes out the same way.

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

* Leave the runtime image's apt packages unpinned

The PRISM runtime stage floats on debian:bookworm-slim, and Debian drops
superseded package versions from its archive, so the exact ca-certificates
and curl pins would have broken the build at the next point or security
release, with no Docker here to build-test a bump. The stage carries the
same inline DL3008 ignore and reason as the other images; pinning its base
and packages belongs to #288. The builder stage keeps its digest pin.

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

* Re-check the deleted-test map against the D2 payout tests

The map is now built against 8dccc74, the merge of #316, and pins both
ends of its file list (504846c and 8dccc74), since origin/2.x.x has moved
on and this branch removes wrapper scripts of its own. The nine D2 tests
were read against every row they could touch: ten partial rows now cite
them (below-target credit, lost-reply reconciliation, reorg survival,
bootstrap selection, the retired readiness gate), and the settlement
balance comparison row states why D2c does not cover it. No status
changes; the counts stay 5 full, 67 partial, 8 open gaps, 7 needs
triage, 55 retired.

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

---------

Co-authored-by: Claude Fable 5.1 <[email protected]>

* 3.x.x: Assert stale-grace anchoring, retained-job and hot-path submit semantics (#313)

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

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

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

Refs #280

* docs: reference PRISM miner parity settings

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

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

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

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

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

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

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

* test(prism): verify issued job dependency persistence

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

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

* docs: point D2 credit explanation to miner submit module

* test: align candidate lease tip fixture with coordinator state

* fix: integrate miner parity with native metrics registry

* fix: integrate miner parity with metrics registry API

* ci: run issued job dependency acceptance explicitly

* test: keep miner parity fixture publication reachable

* test: complete JSONB gate fixture config

* test: restore D2 coordinator coverage

* fix: bound configurable tip freshness durations

* test: retain tokio time controls under pinned toolchain

* chore: satisfy pinned toolchain checks

* test: route issued job dependency through integration gate

---------

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

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

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

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

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

It went through two adversarial reviews.

Part of #261.

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

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

Two fixes to the WindowRef design record after review:

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

Part of #261.

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

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

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

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

Part of #261.

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

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

Two fixes to the WindowRef design record after review.

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

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

Part of #261.

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

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

Two fixes to the WindowRef design record after review.

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

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

Part of #261.

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

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

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

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

Part of #261.

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

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

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

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

Part of #261.

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

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

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

Part of #261.

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

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

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

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

Part of #261.

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

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

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

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

Part of #261.

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

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

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

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

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

Part of #261.

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

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

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

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

Part of #261.

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

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

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

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

Part of #261.

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

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

Two review fixes.

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

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

Part of #261.

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

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

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

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

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

Part of #261.

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

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

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

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

Part of #261.

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

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

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

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

Part of #261.

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

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

Two review fixes.

A resumed Snapshot now keeps StoredPrepared.payout_revision, the revision
the job was issued with. read_window's current revision is only B's
eligibility input and the claim's probe hint. The job wire and any
candidate take their revision …
kiwidream added a commit that referenced this pull request Oct 27, 2026
* docs: design record for WindowRef and Ledger::read_window (#297)

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

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

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

It went through two adversarial reviews.

Part of #261.

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

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

Two fixes to the WindowRef design record after review:

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

Part of #261.

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

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

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

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

Part of #261.

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

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

Two fixes to the WindowRef design record after review.

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

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

Part of #261.

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

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

Two fixes to the WindowRef design record after review.

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

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

Part of #261.

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

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

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

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

Part of #261.

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

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

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

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

Part of #261.

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

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

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

Part of #261.

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

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

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

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

Part of #261.

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

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

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

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

Part of #261.

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

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

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

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

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

Part of #261.

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

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

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

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

Part of #261.

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

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

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

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

Part of #261.

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

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

Two review fixes.

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

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

Part of #261.

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

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

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

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

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

Part of #261.

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

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

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

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

Part of #261.

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

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

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

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

Part of #261.

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

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

Two review fixes.

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

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

Part of #261.

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

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

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

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

Part of #261.

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

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

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

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

Part of #261.

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

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

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

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

Part of #261.

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

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

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

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

Part of #261.

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

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

Two review fixes.

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

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

Part of #261.

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

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

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

Part of #261.

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

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

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

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

Part of #261.

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

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

Two review fixes.

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

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

Part of #261.

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

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

Two review fixes.

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

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

Part of #261.

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

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

Three review fixes.

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

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

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

Part of #261.

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

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

Two review fixes.

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

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

Part of #261.

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

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

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

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

Part of #261.

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

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

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

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

Part of #261.

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

---------

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

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

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

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

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

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

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

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

* test(prism): register all gated session coverage

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

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

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

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

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

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

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

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

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

* fix(prism): alert when public scrape fails

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

* fix(prism): preserve native alert tuning overrides

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

This reverts commit 31b26812ef133a6cfb7e76deefb11e50a2bf306e.

* fix(prism): preserve configurable alert tuning

* fix(prism): render tuning dwells as JSON

* fix(prism): validate rendered alert dwell overrides

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

* docs(prism): pin intentional legacy health differences

* docs(prism): correct legacy max blocks semantics

* style(prism): format health snapshot assertions

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

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

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

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

Refs #280

* docs: reference PRISM miner parity settings

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

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

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

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

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

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

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

* test(prism): verify issued job dependency persistence

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

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

* docs: point D2 credit explanation to miner submit module

* test: align candidate lease tip fixture with coordinator state

* fix: integrate miner parity with native metrics registry

* fix: integrate miner parity with metrics registry API

* ci: run issued job dependency acceptance explicitly

* test: keep miner parity fixture publication reachable

* test: complete JSONB gate fixture config

* docs: specify prepared window reference integration plan

* test: restore D2 coordinator coverage

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

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

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

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

* Qualify landed 008 and 009 migration orders on current base

* Preserve legacy balance order and reject fatal window reads

* Prove legacy balance order preservation in PostgreSQL

* Run all gated suites before manifest proof

* Revert "Run all gated suites before manifest proof"

This reverts commit b11cbbb183927db9b51daf6bf0176a09c4afc0b8.

---------

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

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

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

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

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

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

Part of #265.

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

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

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

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

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

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

Part of #265.

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

---------

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

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

* test: add deterministic HA readiness probe harness

* test: qualify readiness probe timing

* test: preserve probe state in jsonl harness

* test: harden readiness probe input boundaries

* test: reject overlapping readiness probes

* docs: use generic HA readiness contract wording

* test: classify malformed probe durations as failures

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

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

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

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

* metrics: count late share confirmations and unknown outcomes

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

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

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

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

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

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

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

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

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

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

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

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

Review feedback on PR #333.

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

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

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

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

Review feedback on PR #333.

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

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

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

---------

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

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

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

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

* fix(prism): harden WAL qualification failure semantics

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

* fix(prism): sanitize WAL helper connection inputs

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

* fix(prism): preserve WAL operation outcome uncertainty

* fix(prism): bound WAL measurement subprocesses

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

* test(prism): repair WAL helper test layout

* test(prism): stabilize WAL diagnostic mocks

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

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

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

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

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

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

Part of #271

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

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

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

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

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

Part of #271

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

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

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

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

Part of #271

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

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

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

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

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

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

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

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

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

Part of #271

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

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

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

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

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

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

Part of #271

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

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

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

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

Part of #271

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

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

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

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

Part of #271

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

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

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

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

Part of #271

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

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

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

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

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

Part of #271

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

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

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

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

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

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

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

Part of #271

---------

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

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

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

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

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

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

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

Part of #338

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

* fix: record cancelled collector pool acquisitions

* docs: align collector cancellation timing contract

* docs: qualify cancelled collector waits in alert contracts

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

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

(cherry picked from commit 4e5b4c41e980a3ebd956f39d5ed4d4676083d04e)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

State the measured stored bytes per block at 20,000 and 100,000 shares before
and after `reward_manifest.shares` left the stored body,…
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant