Repository navigation
3.x.x: the /audit integrity routes run one report at a time under their own timeout and serve a dated result; fatal-state clear asks the node once per height (#737, #690) - #833
Conversation
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
| `payout_divergence` line in that transaction first, under the session's | ||
| statement timeout as before, then the report, and closes its connection when | ||
| it ends. A | ||
| request that arrives during a run waits for that run, up to its 300 s, and |
There was a problem hiding this comment.
1. [low · nit] Docs say a waiting request waits up to 300 s, but the run's client-side cutoff is 305 s (CANCEL_GRACE)
docs/prism-ledger-ops.md:1330
A request that arrives during a run waits on the run's outcome. The run's task wraps the run in tokio::time::timeout_at(deadline + CANCEL_GRACE, ...), with CANCEL_GRACE = 5 s (crates/qbit-prism-server/src/api/integrity.rs:48, :295). The run's own unit test expects the timeout answer between 305 s and 306 s. Even a report the server cancels at the deadline answers one or two round trips after 300 s. An operator who sets a monitor's HTTP timeout to 300 s, as this doc line suggests, gives up just before the 503 that carries the reason. The next line of the doc does say a client that gives up sooner leaves the run going, so the harm is small.
| request that arrives during a run waits for that run, up to its 300 s, and | |
| request that arrives during a run waits for that run, up to its 300 s and 5 s of grace after them, and |
…ir own timeout and serve a dated result; fatal-state clear asks the node once per height (#737, #690) ## Problem **The `/audit` integrity routes (#737, remaining part).** `GET /audit/carry-forward-integrity` and `/audit/ledger-integrity`, on a frontend's operator listener, ran `SELECT qbit_carry_forward_integrity_report()` on the writer pool under the pool's statement timeout (`PRISM_DATABASE_STATEMENT_TIMEOUT_MS`, 15 s by default). They had no cache and no limit on concurrent runs. At production size (2.75M active carry-forward rows) the report took about 57 s before migration 026; since 026 it is estimated at about 29 s, never measured there. So every call: - was cancelled at 15 s; - held a writer connection for those 15 s; - answered 503 `read_timeout`. Concurrent calls each did the same. `self-check` and `fatal-state clear` already run the report under a statement timeout of their own (#742). **#690 (#737's F3).** `clear_fatal_state` called `getblockhash` once per pool block and once per deep-confirmed fanout. The calls ran one after another inside the recovery transaction, which holds `SETTLEMENT_LOCK`, `ORDER_LOCK` and more. At mainnet's rate that is 65,000–130,000 calls per year of history; the rc.4 drill spent about 4.5 s idle in that transaction. ## Change ### Part A: the routes run one report at a time and serve a dated result New module `api/integrity.rs`, held in `ApiState`: - **One run at a time per frontend.** A run checks out one connection, marked `close_on_drop` so it is closed rather than returned to the pool when the run ends. On it the run opens one read-only transaction and reads the `payout_divergence` line, under the session's statement timeout as before, and then the report. The report runs under a statement timeout of its own: the time left to the run's 300 s deadline, which is self-check's allowance. Because the report is the run's last statement, the server cancels it by the deadline. There is no explicit ROLLBACK: the transaction ends when the connection closes. A client-side backstop 5 s after the deadline covers the report's last round trip (restoring the session timeout) and a server or network that doesn't answer. - **Concurrent callers share the run.** A request that arrives during a run waits for that run and gets its outcome. - **A report is served for 5 minutes after its run ends.** A failure is served for as long as its run took, at most 5 minutes. Only the first request after that starts another run. No request starts a fresh report per call. - **Dated output, added fields only.** Each report keeps its old fields, including `payout_divergence` and `ledger_backend`, and adds: - `computed_at`: when its run started, RFC 3339; - `age_seconds`: its age when served; - `run_seconds`: how long the run took. It is an upper bound on the report's own time, since it also covers the connection checkout and the divergence line. It is also the first production measurement of the report since 026. - **Failure is never shown as a report.** A failed, timed-out or cancelled run answers 503 (`integrity_report_unavailable`). The body gives the step that failed (its connection, the payout divergence line, or the report) and how, when that run started, and when the next run may start. - **An older run can't replace a newer outcome.** Each run carries its number, and publication refuses an older one. - **Cancellation and panics leave nothing stuck.** The run executes on a task of its own, spawned only after the state lock is released. A caller that disconnects leaves it running, bounded by its deadline, and its result serves the next caller. A run that times out drops its future, and its connection with it. A drop guard clears the in-flight slot however the task ends, a panic included, so the next request can always run. - **A stop never waits on a report.** `ApiState::with_shutdown` gives the routes the server's shutdown signal; `server.rs` passes it in. On a stop, the run in flight is abandoned and its waiters answer 503 at once, and no new run starts. The run's connection closes at once instead of going back to the pool to wait out the statement, and the stop's 503 says no other run will start. The run sets `client_connection_check_interval` to 1 s on its own connection, best effort, as `migration.rs`'s import writes already do: a server that can't check refuses it, and the error is ignored. As a result PostgreSQL ends the abandoned report within about a second rather than running it to its timeout. **Refresh policy: on demand with single-flight, not a background refresh.** - A frontend nobody asks runs no report. A background refresh would run the report on every frontend, forever, against the primary. - The report holds one snapshot for its whole run. #738 shows that a long snapshot on the primary slows the share append at high share rates, so periodic runs are a standing cost. - On demand, after a good report each frontend starts a run at most once per (run time + 5 min), however often it is polled. At the estimated 29 s that is under 10% of the time. - A failure is kept for as long as its run took, at most 5 min, with no floor. A brief one, such as a moment without a free connection, is retried soon. After a failure a poller starts the next run at most once per twice the failed run's time, so a run that keeps failing holds its connection at most about half the time; it can't be re-run back to back. I chose this over a floor (say 60 s) because a floor would delay the retry after a transient failure. The docs now state this case separately instead of claiming the 5-minute cadence for every outcome. - For a fresh report on demand, operators run `self-check`. No new environment setting. Both values are constants, and the tests set them through a `#[doc(hidden)]` `ApiState::with_integrity_report_timing`. `payout_divergence_line` (`ledger/divergence.rs`) now takes any executor instead of only a pool, so the routes read it in their transaction. Self-check and the tests still pass their pools, unchanged. ### Part B (#690): fatal-state clear asks the node once per height - The clear's observation loop asks `getblockhash` once per distinct height. Pool blocks share heights with each other and with the blocks that confirm deep fanouts. A small helper, `once_per_height`, keeps the loop's answers. - When the tip has moved, `Observed::still_hold` re-reads the observations once per height too. It keeps its own answers, so the re-read still asks the node afresh. - **Unchanged:** every refusal and its message, the tip-extension handling (#742), the observation semantics (each pass propagates errors the same way, and the re-read still maps -8 to "no block"), and the event's `blocks_checked` and `deep_fanouts_checked`. - **One answer per height, by design.** The fanout check now reuses the block loop's answer for a shared height, so a single pass sees one consistent block per height. If the tip moved, the re-read asks every height again, as before. A chain that leaves the captured tip and returns to exactly it was already the documented limit of #742's checks, and that limit is unchanged. - **No JSON-RPC batching.** It would need `rpc.rs`, which is out of scope here. Deduplication removes the repeated calls; distinct heights are still asked one at a time. ### Docs - `docs/prism-ledger-ops.md`: the paragraph that said the routes still run under the pool setting now describes the new behaviour and fields, the failure cadence, `run_seconds` as an upper bound, and the stop behaviour. Also updated: the `payout_divergence` section, and the fatal-state clear section (once per height). - `doc/mining.md`: the monitoring line now says the report is dated and cached, with the 5-minute cadence after a good report only. ## Tests run (minidev-alex1, PostgreSQL 16 private cluster, fsync on) - `cargo test --locked -p qbit-prism-server --lib api::integrity`: **9 passed**. These are deterministic, with paused time where timing matters: - concurrent requests share one run; - an outcome is reused until its window ends; - a run past its timeout fails, releases what it held and leaves nothing in flight, and the next request after the window runs and succeeds; - a failed run answers why, and is served for as long as it ran; - two runs published out of order leave the later outcome (EP-STATE); - a caller that disconnects mid-run leaves the run to finish and serve the next request; - a run that panics leaves nothing in flight; - a stop abandons the run in flight, drops its future at once, and starts no other; - a failure names the step that failed. - `cargo test --locked -p qbit-prism-server --test api_database`: **3 passed**, including the new gated `integrity_routes_run_one_report_at_a_time_under_their_own_timeout`. It runs against stub SQL functions, with every session's statement timeout at 1 s, a 0.5 s divergence line and a 1.5 s report: - three concurrent requests over both routes share one run; - that run used its own timeout, the time left to its 10 s deadline (at most 9.5 s, after the divergence line), in a read-only transaction; - a request in the reuse window starts no run; - a report longer than its own 2 s timeout is cancelled in the server and answers 503 with the cancellation reason, and no report statement is left in `pg_stat_activity`; - the next request runs again and succeeds; - on a stop during a 60 s report, the request answers 503 within 5 s, the pool closes within 5 s, and PostgreSQL ends the report within 10 s. - That stop phase **fails without `close_on_drop`**: PostgreSQL kept running the abandoned report for more than 10 s. In that variant `pool.close()` still returned within 5 s. - `cargo test --locked -p qbit-prism-server --lib api::`: 43 passed. - `cargo test --locked -p qbit-prism-server --test ledger_postgres fatal_state:: -- --test-threads=4`: **22 passed**. That is all 21 existing fatal-state tests (every refusal case: reorg, shorten, unknown, runaway, flap, pool block above, closing-walk, bound, …) plus the new `clear_asks_the_node_once_per_height`: - a counting RPC proxy shows one `getblockhash` per height (two pool blocks at 90, a mature block and two fanout confirmations at 10, one at 20); - with a tip that moved before the first check, two per height (loop plus re-read). - That new test **fails against the old clear**: `{10: 3, 90: 2}` calls instead of `{10: 1, 90: 1}`. - `cargo fmt --all -- --check`: clean. - `cargo clippy --locked -p qbit-prism-server --all-targets -- -D warnings`: clean except the three known vendored sqlx-core warnings. - `python3 scripts/check_prism_pool_acquires.py`: OK. The audit sites moved and `payout_divergence_line` takes an executor now, so `scripts/prism_pool_acquires.json` was updated: the run's `acquire` is `public`; its `begin` and the divergence line inside its transaction are `transaction`. - `python3 -m unittest tests.test_docs_lab_prism_references`: 147 OK. - New gated tests listed in `test/prism-gated-tests.txt`. ## What CI must cover - The full lib suite, `ledger_postgres`, the API suites (`api_2x`, `api_contract`, `artifact_admission`, `observability*`). - The "Prove every Rust PRISM gated test executed" job, for the two new gated tests. - The load presets (`run-load`). Not run locally, per the host rules: the full lib suite, the rest of `ledger_postgres`, the landing binaries, load presets. Refs #737 Refs #690 🤖 Generated with [Claude Code](https://claude.com/claude-code) Squashed commits: cb0750b 3.x.x: the /audit integrity routes run one report at a time under their own timeout and serve a dated result; fatal-state clear asks the node once per height (#737, #690) f914c40 3.x.x: a stopping frontend abandons its integrity report run, and a failed run names the step that failed (#737 follow-up) Co-Authored-By: Claude Opus 5.5 <[email protected]>
f914c40 to
59e044e
Compare
|
Closing and reopening to rerun CI: the previous run on this squash-signed head failed on GitHub's 2026-11-11 Actions outage (artifact uploads refused), not on the change. |
… their median tip, with the slowest tip at twice the budget (#842) Three PR load runs failed a tip-notify gate on 11-03, one preset each, on one tip each: 4,546 ms among tips whose nearest-rank median was 1,039 ms (tip-delivery, #833), 4,860 ms among 1,005 ms (mainnet-shape-130, #835) and 3,826 ms among 569 ms (rental churn's churn tips, #834). The gated "p99 over 6 or 8 tips" is the slowest tip, so one tip stalled on a contended runner failed the run. #790 hit the same on the real-node smoke, and #805 split its gate. The same split applies here. tip-delivery-2000-miners-400k-2fe-retarget and its 500-address variant gate the median of their 8 tips at 2500 ms and the slowest at 5000 ms; mainnet-shape-130-addresses and mainnet-shape-650-addresses the median of their 6 at 3000 ms and the slowest at 6000 ms; rental-churn-bursts-and-storms its 8 churn tips at 3000 and 6000 ms through a new optional key, churn_tip_last_notify_median_budget_ms, validated like #805's (finite and positive; absent or null is not gated). A preset whose median budget is above its p99 budget is refused, for either pair. Its 2 warm-up tips keep their 3000 ms p99 and no median: the nearest-rank median of 2 is the faster one. The churn rows now go through the same check as the run's own tip rows, and the report's preset block serialises every gate key. The trade-off: a nearest-rank median of n tips is the ceil(n/2)-th fastest, so a regression confined to fewer than half the tips (3 of 6, 4 of 8) that lands between 1x and 2x the budget now passes. One that slows most tips still fails the median, and a stall past twice the budget or an unserved tip still fails the slowest-tip row. The dispatch override still sets only the slowest-tip budget. A changed preset starts a new S6 baseline (preset_sha256 is in the series key), so these five series are judged again after min_baseline kept nightlies. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… PostgreSQL's English message (#824) The pre-migrate, the share-hash backfill and `fatal-state clear` now tell a statement timeout from an operator's cancel by SQLSTATE and elapsed time. They no longer depend on PostgreSQL's English message. Refs #824. ## The problem - `statement_timed_out` (`ledger/migration.rs`) required SQLSTATE 57014 **and** a message containing "statement timeout". `fatal_state.rs` had its own copy of the same check. - PostgreSQL translates that message under `lc_messages`, and nothing in the server pins it to English. - **The pre-migrate's retry (#791, #821):** - Each attempt set `lock_timeout` and `statement_timeout` both to 100 ms. The statement timer starts first, so a blocked `LOCK TABLE` nearly always ended with 57014. - On a non-English server, `gave_up` treated that 57014 as fatal. - `migrate`, or a start with `PRISM_POSTGRES_INIT_SCHEMA=1`, then failed at its first brief contention instead of retrying within the 600 s budget. - **Other paths that lost their timeout handling on such a server:** - the share-hash backfill's batch and double-credit halving; - its record-of-2 retry; - `fatal-state clear`'s "raise --timeout-seconds" advice. ## The change - **Pre-migrate (`table_locks.rs`):** - The up-front requests now run under `lock_timeout` = `LOCK_WAIT` (80 ms) and `statement_timeout` = `ATTEMPT` (100 ms). - A request blocked on one table, the usual contention, ends with 55P03 (`lock_not_available`), which is unambiguous. The statement gets a 20 ms margin before its first wait. - These are unchanged: - the documented 100 ms bound on the primary (the statement timeout is still the total); - #821's `DEADLOCK_CHECK` (50 ms, still within any one table's wait); - the backoff; - `BUDGET`. - `LockContention` now carries the SQLSTATE, and the retry warning logs it as `sqlstate=`. - The refusal now says each attempt "waited up to 100 ms for <tables>, 80 ms for any one". - The module docs and the `BUDGET` reasoning (about 290 attempts in 600 s) are updated. - **Everywhere else: `timed(timeout, statement)` in `ledger/migration.rs`.** - It runs one statement under the `statement_timeout` the caller set for it, and times it on this side's clock. - It marks the error `StatementTimedOut` only for a 57014 that arrived after at least nine tenths of that timeout. - Why a timeout qualifies: PostgreSQL starts its timer after the client starts its clock, and the error arrives after the timer fires. - Why the tenth of slack: PostgreSQL times the statement by the server's wall clock, which can run fast or step forward against the client's monotonic clock. Taking a timeout for a cancel would stop the run, the failure #824 is about; taking a cancel for a timeout only retries the statement. - Any 57014 sooner is a cancel request. sqlx 0.8 never sends one, so it is an operator's, and it stops the run as before. - `timed_out(&anyhow::Error)` reads the mark through any added context. - The only ambiguity: a cancel that lands in the last tenth of the timeout, or within the client's own overhead before it, is taken for the timeout and retried, as the timeout would have been. - **Callers converted:** - `gave_up`; - the backfill's batches and double-credit chunks, plus `smallest_timed_out`; - every statement of the record of 2, each timed on its own, with `waited_too_long`; - `integrity_report_bounded`, plus the `fatal-state clear` advice. - The unthrottled backfill batches run under the session's timeout, which `map_batches` reads once from `pg_settings`. - **Why not `lc_messages = 'C'`?** It is superuser-only (or needs `SET` on the parameter from PostgreSQL 15), so production migrate roles would need a fallback anyway. It also changes the session's server-log language. Timing works for every role. - **Docs:** - `docs/prism-rust-migration.md` (pre-migrate section): the 80/100 ms bounds, the SQLSTATE classification and the pre-3.1.2 behaviour; - `docs/prism-ledger-ops.md`: the backfill throttle and the fatal-state report timeout. ## Tests On minidev-alex1, against a private PostgreSQL 16 with fsync on: - **Unit tests (German messages from PostgreSQL 16's own `de` catalog):** - `ledger::migration::tests::a_statement_timeout_is_told_by_its_sqlstate_and_its_time_not_its_message` - `ledger::migration::tests::timed_marks_a_statement_its_timeout_cancelled_and_nothing_else` - `table_locks::tests::an_attempt_gives_up_by_sqlstate_and_time_whatever_the_language` - `share_hashes::tests::a_record_attempt_waited_too_long_by_its_sqlstate_and_time` - **New gated tests** (all four added to `test/prism-gated-tests.txt`): - `table_locks::postgres_tests::a_request_blocked_on_one_table_ends_with_the_lock_timeout_and_is_tried_again`: a held read makes the request end with 55P03 after at least `LOCK_WAIT`. `committed_within` warns `sqlstate=55P03` and never `57014`, then applies 27 and 28 once the read ends. - `table_locks::postgres_tests::on_a_server_whose_messages_are_german_a_timeout_is_still_told_from_a_cancel`: - Setup: a private cluster started with `LANGUAGE=de`, and `lc_messages` set to a host locale other than C or POSIX. The test checks that the server really answers in German. - Through `timed`, a real statement timeout is marked and a real `pg_cancel_backend` is not. - Through `lock_within_attempt`, the statement timeout (57014) and a lock timeout (55P03) give the attempt up, and the cancel does not. - The cancel is the statement's own `pg_cancel_backend(pg_backend_pid())`, which makes the test deterministic. - The German cluster needs a non-C locale on the host (`en_US.UTF-8` here) and PostgreSQL's German catalog (`postgres-16.mo`, shipped with `postgresql-16`). The test fails, naming which is missing, rather than pass without translation. - `share_hashes::postgres_tests::an_unthrottled_batch_past_the_sessions_statement_timeout_is_halved_and_a_cancel_stops_it`: - Runs on a minimal schema, so it migrates nothing and never takes the migration lock. - The unthrottled `map_batches` reads its 300 ms session timeout from the server and halves twice behind a slow trigger. - A batch that cancels its own backend stops the run, unmarked. - `share_hashes::postgres_tests::a_record_attempt_cut_by_its_statement_timeout_is_tried_again`: - An open read of the cursor holds the record's `DROP TABLE`. - The throttle's 300 ms statement timeout cuts each attempt, and the attempt is retried (the warning carries "cancelled by its 300 ms statement timeout"). - Once the read ends, 2 is recorded. - **The gated tests on a loaded host:** - A request whose backend is held up for the 20 ms margin before its wait gives up with 57014 instead of 55P03, which is still contention. - So `blocked_until_the_lock_timeout` requests again, up to five times, until it sees the 55P03. - In the German test, the self-cancelling statement is prepared first, so the measured request is a single round trip. - **The existing `deadlock_is_contention`** now sets its unlowered deadlock check to 60 ms. That is as far below `LOCK_WAIT` as #791's 80 ms check was below its 100 ms timeouts. The test asserts SQLSTATE 40P01 rather than the English message. Commands, every one through the host gate with `CARGO_PROFILE_DEV_DEBUG=line-tables-only`: - `cargo test --locked -p qbit-prism-server --lib -- --test-threads=4 ledger::migration::tests::a_statement_timeout ledger::migration::tests::timed_marks table_locks share_hashes fatal_state api::integrity` with `PRISM_TEST_DATABASE_URL`, `PRISM_TEST_PG_BIN_DIR` and `PRISM_TEST_REQUIRE_INTEGRATION=1`, on the tree merged with `3.x.x` (#833, #834): **56 passed**. The gate manifest shows all four new ids `executed`. - `cargo test --locked -p qbit-prism-server --test ledger_postgres --test api_database -- --test-threads=4 <the tests below>`, on the merged tree: - `a_batch_past_the_throttles_statement_timeout_is_retried_at_half_its_size` - `the_double_credit_check_runs_under_the_throttles_statement_timeout` - `backfill_share_hashes_runs_each_batch_under_its_statement_timeout_and_rests_between_batches` - `the_record_of_2_waits_out_a_reader_of_the_cursor_in_short_attempts` - `the_record_of_2_stops_cleanly_behind_a_held_migration_lock_and_records_once_released` - `clear_report_statement_ends_within_the_bound` - `migration_027_backs_off_instead_of_closing_a_lock_cycle_with_a_serving_frontend` - `clear_and_self_check_run_the_report_under_their_own_timeout` - #833's `api_database::integrity_routes_run_one_report_at_a_time_under_their_own_timeout`, which asserts `cancelled (canceling statement due to statement timeout)`. It still finds the SQLSTATE through the new `StatementTimedOut` context. - All passed except `clear_report_statement_ends_within_the_bound`. It failed only because it ran beside `clear_and_self_check_run_the_report_under_their_own_timeout`: - its last check counts every active `qbit_carry_forward_integrity_report` query in the whole database, and caught the other test's report; - alone, and with the two run serially, both pass; - both tests predate this change. - `cargo fmt --all -- --check`: clean. - `cargo clippy --locked -p qbit-prism-server --all-targets -- -D warnings`: clean, apart from the 3 known vendored sqlx-core warnings. - `python3 scripts/check_prism_pool_acquires.py` and `python3 scripts/check_gate_env_reads.py`: clean. An observation from the local runs: - An earlier version of the German test migrated a full ledger on its own cluster. Run beside the other schema-migrating tests on a loaded host (load average about 12), it slowed the shared database's migrations. - The result was two failures, neither seen when the test runs alone or on base: - `share_hashes::postgres_tests::a_record_whose_commit_reply_never_comes_is_read_afresh_at_its_deadline` hit its 100 s bound under the record's patient backoff; - `a_cursor_dropped_after_its_look_up_reads_as_nothing_pending` hit its 5 s lock timeout on the migration lock. - The German test now locks a table of its own instead of migrating a ledger. The same set then passes in 33 s, the same as base. - Even so, `a_record_whose_commit_reply_never_comes_is_read_afresh_at_its_deadline` varies between 30 and 83 s, within its 100 s bound, in this concentrated set at load average 7 to 10: - its record attempts' 300 ms timeout backs off up to 30 s whenever another test's fresh-schema migration holds the migration lock; - it was 83 s with this PR's record test skipped, so that test is not the cause. - This is pre-existing; the test's bound already allows a minute for it. ## Review Two local `/code-review xhigh` rounds (Opus). Most of what they found is fixed above. These are deliberate: - **Timing per call site:** `timed` wraps each statement where it runs, rather than in an executor wrapper. - `record_transaction`'s `BEGIN`/`set_config` and the double-credit check's first read are not timed. - Neither can meet the throttle's timeout, and that first read's failure stops the run, as before. - **The record transaction's timeouts stay equal:** its default statement timeout (2 s) still equals `RECORD_LOCK_TIMEOUT` (2 s), so a blocked record attempt usually ends with a timed 57014 rather than 55P03. - Its lock bounds are documented and feed the record's deadlines. - The tenth of slack covers the clock, and a gated test covers the retry. - **The German test fails rather than skips** when the host has no locale but C/POSIX or no German PostgreSQL catalog, so it can never pass without translation. ## What CI must cover - The full lib suite. - `ledger_postgres`. - The gated-test manifest proof, for the two new ids. - The dual-sim `r01-rc6-premigrate` scenario, which runs the pre-migrate with its new 80 ms lock wait beside rc.6 frontends. ## Not changed here - `ledger/window.rs` `refused_for_want_of_a_partition` also reads PostgreSQL's English message: 23514 plus "no partition of relation". That is the same class of problem and is outside this change's paths. - `api.rs` and `api/public_service.rs` classify 57014 by SQLSTATE alone, which this change does not touch. Refs #824 🤖 Generated with [Claude Code](https://claude.com/claude-code) Squashed commits: 6da4065 3.x.x: tell statement timeouts from cancels by SQLSTATE and time, not PostgreSQL's English message (#824) 9f3e558 3.x.x: review fixes for the #824 timeout classification dac583d 3.x.x: second review round for the #824 timeout classification f79ccb8 Merge remote-tracking branch 'origin/3.x.x' into orca/824-timeout-classification-lc-messages a8d40c3 3.x.x: the share-hash throttle's #738 comments name frontends before 3.1.1 Co-Authored-By: Claude Opus 5.5 <[email protected]>
… not the run's worst case (#859) The bound's doc comment said four times the 15 s each statement and checkout may take, but a run makes up to seven statements on the share writer's pool, each with up to 15 s of checkout wait and the statement timeout's 15 s of execution. Under a saturated writer pool, or with a raised statement timeout, a valid run can pass 60 s every time, and the route then answers 503 read_timeout until a run fits again, where before #859 it answered slowly. The bound stays fixed, as #833's integrity runs' is; the comment and docs/prism-ledger-ops.md now say what an operator sees in that state and why. docs/prism-deleted-test-map.md no longer calls /audit/latest a per-request query. docs/prism-share-ledger-partitioning.md's stale /audit/latest-evidence name is left to #848, which changes that line. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…the tip-delivery, mainnet-shape and churn presets gate their median tip (#842) ## The problem On 2026-11-03 three PR runs of the `run-load` set each failed a tip-to-last-notify gate, each on a different preset. No nightly failed one on the same code. The triage for #842 found the runner, not the code. The findings are drafted as a comment on #842. - **The trend tracks VM speed, not commits.** - No server or harness source changed between the 10-23 and 10-27 nightlies, or across 11-03, 11-04 and 11-11. - Each frontend's initial full refresh of the same seeded 416,260-row window took 6.5–17.9 s across the 39 preset runs examined. This is the frontend's `snapshot_ms` on its `trigger="initial"` refresh line. - Tip-delivery's median tip follows it over 13 runs at r = 0.87 (the gate's nearest-rank median), or r = 0.90 with the midpoint median. - Fast VMs give the same latency before 10-27 (572–624 ms) and after it (526–571 ms). - **Each failure was one stalled tip on its own VM.** Medians are nearest rank, as the gate computes them. | PR | Preset | Slowest tip / median tip | Where the time went | |---|---|---|---| | #833 | `tip-delivery-2000-miners-400k-2fe-retarget` | 4,546 / 1,039 ms | 1st tip: refresh 1.5 s plus 2.9 s of fan-out, on both frontends at once | | #835 | `mainnet-shape-130-addresses` | 4,860 / 1,005 ms | 3rd tip: refresh 4.1–4.6 s. A PostgreSQL check query took 1.1–1.8 s on both frontends, with no checkpoint running | | #834 | `rental-churn-bursts-and-storms` | 3,826 / 569 ms | 6th churn tip, after the 2,000-rental burst: refresh 2.1 s plus 1.7 s of fan-out | - **The share-ack path degraded on the same VMs.** In each failing run, the phase holding the slow tip had a share-ack p99 of 71, 207 and 380 ms. The other 36 preset runs had 2–38 ms. - **Nothing measured the VM itself.** No steal time, pressure stall or sampler gap was recorded, so a VM-level stall could only be inferred. - **One stall fails the whole run.** The gated "p99 over 6 or 8 tips" is the slowest tip, nearest rank. #790 had the same problem on the real-node smoke, and #805 split that gate. ## The change, in two commits and a follow-up ### 1. Measure the host The harness now reads `/proc/stat` and `/proc/pressure/{cpu,io,memory}` every `--process-sample-interval-ms` (new `contention` module). - **Where the figures go:** a `host_contention` block per phase, and per tip in `time_to_usable_work` and each churn section. - A tip's window runs from the node's tip stamp to its slowest session's first usable job. - When some session never got the tip, the window runs to the next tip instead, covering the time those sessions were starved. - **What each figure divides:** - `steal` and `iowait` are shares of the CPU time the kernel accounted. - The PSI figures (some and full) are shares of the harness's monotonic time from before one read of a file to after the next. That is the most the two totals can cover, so time the sampler loses around a read lowers a share and never raises it past what the kernel counted. - Each gives its share over the window and its worst interval. - **Unknown stays unknown:** a host without PSI or without a steal field reports that figure as null with a reason, never 0. - CPU `full` is not read, because the kernel reports it as zero at the system level. - The run-level block records the steal counter at start. A counter still at 0 cannot tell an idle hypervisor from one that doesn't report steal, so the gate's lines carry that caveat when it reads 0. - The sampler takes one last read as the run stops, so the final interval and a late tip have a read after them. - **Lock sampler:** it adds its longest gap between polls, with PostgreSQL's `clock_timestamp()` of the poll that ended it. A gap counts if its interval overlaps the phase, so a stall that began before the phase is still the phase's. - **Gate:** a failed tip row, main or churn, gets one informational row. It shows the host over the slowest tip, over its phase, and that phase's longest sampler gap. `gate::tip_timeline` prints each tip's line. All of it is additive to the report. An older report gates as before and simply gets no host row. A report without churn or a soak keeps its shape (the tips are reached with `pointer_mut`, not indexing). The top-level key is added to the load smoke's golden key list. ### 2. Gate the median tip and give the slowest tip room for a stall This applies #805's split to the nightly presets with tip budgets. | Preset | Median tip | Slowest tip (was) | |---|---|---| | `tip-delivery-2000-miners-400k-2fe-retarget` (and `-500-addresses`) | 2,500 ms | 5,000 ms (2,500) | | `mainnet-shape-130-addresses`, `mainnet-shape-650-addresses` | 3,000 ms | 6,000 ms (3,000) | | `rental-churn-bursts-and-storms` churn rows (8 tips) | 3,000 ms | 6,000 ms (3,000) | - **New key for churn tips:** `churn_tip_last_notify_median_budget_ms`, optional and validated like #805's key (finite and positive; absent or null means not gated). A preset whose median budget is above its p99 budget is refused, for either pair. - **Rental churn's warm-up row is not split.** Its 2 warm-up tips keep their 3,000 ms p99 and no median, because the nearest-rank median of 2 is the faster one. - **One check for both:** the churn rows now go through the same check as the run's own tip rows. - **The report records every gate:** its `preset.gates` block now serialises `preset::Gates` whole, so the median keys and `new_session_first_job_p99_budget_ms` are in it. - **Docs:** the README gate table, the workflow's dispatch description and the scenario criteria say the same thing. **The trade-off, plainly:** - **Now passes:** a regression confined to at most half the tips that lands between 1× and 2× the budget. A nearest-rank median of n tips is the ceil(n/2)-th fastest, so that is up to 3 of 6 or 4 of 8. Examples: only the first tip after a frontend start, or only churn's burst tip. - **Still fails:** - The median, when a regression slows more than half the tips. - The median, when the run delivered fewer tips than it planned (see the follow-up below). - The slowest-tip row, on a stall past twice the budget or a tip some session never got. - **Run against 11-03's three failures:** their medians (1,039 / 1,005 / 569 ms) and slowest tips (4,546 / 4,860 / 3,826 ms) all pass. - **The trend restarts for these presets:** a changed preset starts a new S6 baseline (`preset_sha256` is in the series key). These five series are judged again after `min_baseline` (5) kept nightlies. - **The dispatch override is unchanged:** the `tip_last_notify_p99_budget_ms` input still sets only the slowest-tip budget. The medians and churn budgets stay the preset's own, and the input's description now says so. The commits are ordered so the first can land without the second if the gate change is not wanted. ### 3. Follow-up: a split gate passes only a run that delivered every planned tip An independent verify found two gaps in commit 2. - **F1, a run with too few tips passed.** Nothing checked the tips delivered against the plan; `external_tips_unminted` was reported but never gated. The nearest-rank median of 2 tips is the faster one, so tip-delivery passed a run that delivered 2 of its 8 tips with one at 4,900 ms. The old single 2,500 ms budget failed it. - **F2, wording.** Exactly half the tips slow (4 of 8 at 4,900 ms) passes the median. This body said "fewer than half". The rule stays (it is #805's nearest rank) and the wording now says "at most half passes, more than half fails", as the README's table already did. **The rule:** where a median budget is gated, the median row is measured only over every tip the run planned. - **Main rows:** each phase now reports `external_tips_planned` beside `external_tips_unminted`. The gate sums them, and when the report holds fewer tips the row reads, for example, "unmeasured: 7 of 8 planned tips delivered, 1 held unminted behind a landing" and fails. - **Churn rows:** the same check, against the section's `plan.tips_at_seconds`, which reports have carried since #521. - **A report that does not record its plan** has an unmeasured median, which fails. - **Unchanged:** the p99 rows, and every preset without a median. **Why this rule:** it is the narrowest one that is exact. - `external_tips_unminted == 0` alone misses a real node's mint that failed or never reached the watcher, since `observed_mints` drops those without counting them. - A per-preset minimum tip count would add a key to keep in step with `--external-tips`. - The planned count catches every way a tip goes missing, adds no preset key, and applies only where a median can hide a missing tip. **The A/B summary:** it re-gates each base run on the candidate's preset. - A base harness older than this follow-up records no plan, so every base run would have failed a median-gated preset, and a candidate regression would have read "as does a base run". - When no phase records the plan, `compare` now fills it from the pinned `--external-tips`, which it already holds every counted run's tip list to. - **After landing:** add `external_tips_planned` to `legacy-flags.json`'s `report_fields`, with the landed squash commit as `introduced`, so a newer build that drops the key is caught rather than filled. The commit is not known until squash-sign, so it can't be done in this PR. **Not changed, by choice:** - p99-only presets don't check the plan. - The bridge script's tip p50 is reported over delivered tips only, and gates nothing. ## Tests run All on this branch, through the host's build gate: - `cargo fmt --all -- --check`: clean. - `cargo clippy --locked -p qbit-prism-load --all-targets -- -D warnings`: clean, apart from the three known vendored sqlx-core warnings. - `cargo test -p qbit-prism-load --test contention`: 15 passed. - Parsers against real and truncated lines, plus this host's own `/proc/stat`. - Unknown versus a real zero for a host without PSI or a steal field, and a counter that went backwards. - Window math, and the tip annotation, including an unserved tip whose window runs to its replacement. - The lock sampler's gap, including one that straddles a window's start. - The sampler's final read, and the steal caveat. - A sampler preempted around a pressure read (the share stays at or below what the kernel counted), and the stamps on both sides of a read. - The gate rows: shown only on a failed tip row, absent for an old report, and pointing at an unserved tip. - `cargo test -p qbit-prism-load --test realism`: 24 passed. #805's preset test is now `presets_gate_the_tip_median_only_where_they_split_it_from_a_stall_budget`, which covers both median keys, their refusals (including a median above its p99) and null. It is not cited in the deleted-test map, which covers 2.x.x files only. - `cargo test -p qbit-prism-load --test churn`: 7 passed. The new churn median test uses #834's eight churn tips. - `cargo test -p qbit-prism-load --lib --test harness --test compare --test legacy_flags --test soak_plan --test faults -- --test-threads=4`: 56, 155, 50, 3, 5 and 1 passed. Without `PRISM_TEST_PG_BIN_DIR`, the PostgreSQL-gated tests in `harness` pass without running. - `python3 scripts/check_e2e_scenarios.py` and `python3 scripts/check_prism_pool_acquires.py`: pass. - The first commit alone also passes clippy and the contention, realism and churn tests, so it can land without the second. - All of the above was rerun after merging `origin/3.x.x` (#833 and #834). No load preset was run locally. **For the follow-up (commits after d96b217):** - `cargo test --locked --offline -p qbit-prism-load --lib --test realism --test churn --test contention --test compare --test harness -- --test-threads=4`: 56, 26, 7, 13, 51 and 155 passed. The new tests: - `realism`: `a_tip_median_is_measured_only_over_every_tip_the_run_planned` (a 2-of-8 run with one tip at 4,900 ms fails, a tip held unminted fails, a report without the plan fails, a short run with an unserved tip names both reasons) and `a_tip_median_passes_a_slowdown_on_half_the_tips_and_fails_one_on_more`. - `churn`: 2 of 8 churn tips delivered fails the median, and a section without its plan fails it. - `compare`: `a_base_report_predating_the_tip_plan_is_held_to_the_pinned_tips`. - `harness`: the ordered-tips runs record `tips_planned` 3, including the run with one tip held unminted. - `cargo fmt --all -- --check`: clean. `cargo clippy --locked -p qbit-prism-load --all-targets -- -D warnings`: clean, apart from the three known sqlx-core warnings. ## Landing note: merging with #845 #845 (`orca/817-alerts-check-and-report-gates`) lands first. Merged with this branch, `cargo test -p qbit-prism-load --lib` fails to compile: E0063, a missing `churn_tip_last_notify_median_budget_ms` in #845's two `Gates` literals in `preset_report_tests` (run.rs, near L5876 and L5904). - **Don't use `None` in both literals.** With `None`, #845's `every_gate_set` still passes when the new key is dropped from the report. - **`every_gate_set` needs `Some(non-default)`** for the new churn median key, as its own doc says ("each value differs from its default"). `the_side_report_carries_every_gate_key` then catches a dropped key. - **The golden key file should also cover `preset.gates`.** `tests/golden/fake_side_report_keys.json` pins only the `top_level`, `node`, `topology`, `versions` and `window` keys, so it would not catch a regression in the gates block either. ## What CI must cover - **`load_smoke`** (PostgreSQL-gated) is the only end-to-end proof of the wiring in `run.rs`. Its golden key set now includes `host_contention`. It now asserts, against a real run, that: - every phase has host intervals, with steal and iowait measured on Linux; - each PSI figure is measured or unknown with a reason; - the lock sampler's gap is present; - every driven tip, main and churn, carries a `host_contention` block naming its phase. - **`cargo test --workspace --all-targets`** picks up the new `tests/contention.rs`. - **Not touched:** server code, settings and metrics. The workflow edit is the dispatch input's description only, which `main` picks up at its next sync of the nightly workflow. Refs #842 🤖 Generated with [Claude Code](https://claude.com/claude-code) Squashed commits: 6aac948 3.x.x: the load report says what the host was doing over each phase and each tip's delivery (#842) b428e5f 3.x.x: the nightly tip-delivery, mainnet-shape and churn presets gate their median tip, with the slowest tip at twice the budget (#842) d96b217 Merge remote-tracking branch 'origin/3.x.x' into orca/842-load-notify-latency b53688c 3.x.x: a split tip gate passes only a run that delivered every planned tip (#842) 6859982 3.x.x: the A/B summary holds an older base report's tip median to the pinned tips (#842) 189e1a2 3.x.x: the A/B tip-plan fill-in leaves a report without a phase list as it is (#842) 3dcce7e 3.x.x: a PSI share divides by the time from before its first read to after its second (#842) Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ed, for 10 s (#859) ## Problem `/audit/latest` rebuilt its evidence on every call (#859). Each request: - decoded the newest confirmed block's whole audit bundle, only to count its shares; - counted the share tail; - took a `UNION` over every daily miner rollup. All of it ran on the share writer's pool, with no route timeout and no limit on concurrent calls. `ApiState.latest_evidence` looked like the cache for this, but nothing ever wrote it. History (`git log -S latest_evidence`) shows it was never added rather than removed. The field arrived with the Python-to-Rust port (#244, 1398bbc), together with its reader in the handler, and no Rust writer has existed since. It mirrors the Python runtime's `_latest_evidence`, which that runtime's coordinator set on block confirmation. ## Change This follows #833's integrity routes (`api/integrity.rs`). The code stays in `api.rs` and `api/read_models.rs`, as this wave's file split requires, so it reimplements #833's pattern rather than sharing its code. Generalizing `IntegrityReports` would have meant editing `integrity.rs`. Its semantics also differ: it remembers failures, and it turns every failure into a 503 `integrity_report_unavailable`, while `/audit/latest` must keep its 404. - **One run at a time per frontend**, spawned, bounded by a fixed 60 s, as #833's integrity runs have a fixed bound. That is far beyond the run's usual time, but not its worst case: a run makes up to seven statements on the share writer's pool (the evidence key, the rollup check, the counts, the payout count, then, for new evidence, the bundle row and its canonical bytes, or its share snapshot and window), and each may wait up to the pool's 15 s for a connection and then run up to the statement timeout, 15 s by default. So while every writer connection is busy and checkouts queue for seconds (each under the 15 s at which one fails), with a raised `PRISM_DATABASE_STATEMENT_TIMEOUT_MS`, or with a slow decode of a new bundle (it runs last and untimed, after a wait for a decode permit), a valid run can pass 60 s every time. The route then answers every request, after up to 60 s, with 503 `read_timeout` and serves nothing until a whole run fits again, where before it answered slowly. Each abandoned run's statement in flight holds its writer connection until it ends, and an abandoned decode keeps its permit, while the next request starts the next run. The bound stays fixed by decision; the code comment and `docs/prism-ledger-ops.md` say all this. - Requests that arrive during a run wait for it. - A request that gives up (its client disconnects) leaves the run going for the next request. - A stopping frontend abandons its run in flight and starts none. It uses the same stop signal as the integrity routes. - Runs are numbered, and an older run's answer never replaces a newer one. A drop guard clears the run in flight on panic, abort or shutdown. - **Dated answer, reused for 10 s.** An answer is served for 10 s after its run ends. It carries `computed_at`, `age_seconds` and `run_seconds`, as #833's reports do. These keys are added; every existing key keeps its name and value. - **Why a short lifetime and not a freshness key:** no cheap key covers the lifetime share counts. `max(share_seq)` misses shares committed out of order, and counting is the very work being saved. - **How stale:** the counts can trail the ledger by up to 10 s plus the run's own time. A newly confirmed block shows up after at most as long. - **Polling:** after an answer, a poller starts a run on each frontend at most once per run time plus 10 s. - **The bundle is decoded once per new evidence.** A run reads the newest confirmed block with a bundle, then the counts, then the block's payout entries, then decodes the bundle last. It decodes only when the newest block, its bundle digest or its payout manifest differs from the previous answer's evidence. That evidence is keyed by what the decoded body itself says it is, so a row re-imported between the reads is decoded again by the next run. A run that fails before the decode decodes nothing. - **Failures are never remembered,** and each is logged (`latest evidence run failed`, with its code and run time). The request that waited for a failed run gets its error: - 404 "no PRISM evidence has been produced", as before; - 503 `read_timeout` when the run hits its 60 s; - 503 when the frontend stopped; - otherwise whatever the read returned, as before. The next request starts a run. Because the bundle is now decoded last, a request on which both the counts and the bundle would fail gets the counts' error. Before, the bundle's error won: for example a 404 for an unreadable legacy body, where now it can be a 503 after a slow counts statement. A request on which only one of them fails gets the same error as before. A frontend that has already decoded the evidence keeps serving it if the body later becomes unreadable under the same key, until the key changes or the frontend restarts. A fresh frontend reports the read failure, as before. - **The field is gone.** `ApiState.latest_evidence` is now the run state (private). `ApiState::with_latest_evidence_reuse` is a `#[doc(hidden)]` test hook, like `with_integrity_report_timing`. - **Docs:** `docs/prism-ledger-ops.md` describes the route as it now behaves, after the integrity routes' passage, including what an operator sees when runs pass the 60 s bound and why. It also corrects a stale route name (`/audit/latest-evidence` → `/audit/latest`). `docs/prism-deleted-test-map.md:90` no longer calls `/audit/latest` "a per-request query". ## Tests run All cargo commands ran through the host gate with `CARGO_PROFILE_DEV_DEBUG=line-tables-only`. - `cargo test --offline -p qbit-prism-server --lib -- api::read_models api::integrity`: 19 passed, including 8 new tests in `api/read_models/latest_evidence_tests.rs`, with runs injected: - `concurrent_requests_share_one_run` - `an_answer_is_dated_and_served_until_its_window_ends` (it also checks that the next run is handed the previous evidence) - `a_failure_is_not_remembered` - `an_earlier_run_never_replaces_a_later_answer` - `a_run_past_its_timeout_fails_and_leaves_nothing_in_flight` - `a_request_that_stops_waiting_leaves_its_run_to_finish` - `a_run_that_panics_leaves_nothing_in_flight` - `a_stop_abandons_the_run_in_flight_and_starts_none` - `PRISM_TEST_PG_BIN_DIR=/usr/lib/postgresql/16/bin test/prism-native-tests.sh cargo-args --offline -p qbit-prism-server --test share_partitions_postgres -- --test-threads=4 latest_evidence`: 2 passed, both recorded `executed`. - **New:** `latest_evidence_is_shared_dated_and_refreshed_after_its_window`. It checks that: - eight concurrent requests get one run's answer (same `computed_at`), with counts equal to the raw ledger's; - within the window, a new share does not change the served answer; - after the window, the counts include it, and the answer equals what a frontend that never answered computes; - a newly landed block becomes the answer; - with the newest bundle's share snapshot detached and its inline shares emptied (key unchanged), the next run still serves the share count it decoded, while a fresh frontend's decode reads 0; - a changed payout manifest makes the next run decode again. It is listed in `test/prism-gated-tests.txt`. - **Existing:** `latest_evidence_counts_lifetime_shares_across_the_rollup_watermark` now sets the reuse window to zero, so every request still reads the ledger it asserts on. - `cargo fmt --all -- --check`, `cargo clippy --offline --locked -p qbit-prism-server --all-targets -- -D warnings` (clean apart from the three known vendored sqlx-core warnings) and `python3 scripts/check_prism_pool_acquires.py`: all clean. The run keeps `latest_evidence`'s four acquire sites. Re-run on the follow-up commit (comments and docs only), with `python3 scripts/check_prism_settings.py`: all clean. - Follow-up (run bound and docs, comments and docs only): two `/code-review xhigh` rounds in an Opus 5.5 subagent; their findings on the new text's accuracy are fixed (abandoned statements hold their writer connection, the 15 s checkout failure's message, the decode as a second cause, `with_shutdown`'s comment). Their findings on the route's design are reported to the coordinator rather than changed here. - Local review: two `/code-review xhigh`-level rounds in an Opus 5.5 subagent, the second ending with nothing left worth fixing. Round one's findings, all fixed: - the doc passage sat inside the integrity report's guidance; - the bundle was decoded before the counts; - the evidence key came from another statement than the body; - no test showed evidence reuse. ## Other consumers of `/audit/latest`, with the 10 s reuse | Consumer | How it reads the route | With the 10 s reuse | | --- | --- | --- | | `tests/live_regtest.rs` | polls every 200 ms for up to 30 s | holds, with about 20 s to spare | | `scripts/prism_shipped_image_lane.py` quiesce | polls every 2 s for up to 90 s | holds | | `tests/support/ledger_2x.rs` | one first request on a fresh router | unaffected | | `tests/api_database.rs` | one first request on a fresh router | unaffected | ## Not in this PR `docs/prism-share-ledger-partitioning.md:260` still names the route `/audit/latest-evidence`. Open PR #848 changes that line to `/audit/latest`, so it is left to #848: `git merge-tree --write-tree` of this branch with #848's head (da36f25) merges cleanly, and the merged passages read correctly. Its line 249 (the `latest_evidence` lifetime counts row) describes how the counts are read, which this PR does not change. The other writer-pool operator routes (`/owed`, `/miners/{id}/status`) are #859's stated follow-up. ## What CI must cover The lib suite, `share_partitions_postgres`, `ledger_postgres`, `live_regtest` (polls `/audit/latest`) and the shipped-image lane. Refs #859 🤖 Generated with [Claude Code](https://claude.com/claude-code) Squashed commits: 39b8a91 3.x.x: /audit/latest is computed by one run at a time and served, dated, for 10 s (#859) dfccd9e 3.x.x: /audit/latest's 60 s run bound is documented as a fixed bound, not the run's worst case (#859) a298ec5 3.x.x: /audit/latest's docs say an abandoned statement holds its writer connection, and when a decode keeps runs failing (#859) 828690e 3.x.x: /audit/latest's docs describe a decode that keeps runs failing, and when a checkout queues (#859) 207ac1e Merge 3.x.x (fa8ac84) into orca/859-audit-latest-cache: take in the PostgreSQL 16.15 service pin (#866) b2b7c67 Merge 3.x.x (234ff1c) into orca/859-audit-latest-cache: take in the landed 3.1.2 PRs and the collate test fix (#874) Co-Authored-By: Claude Opus 5.5 <[email protected]>
Problem
The
/auditintegrity routes (#737, remaining part).GET /audit/carry-forward-integrityand/audit/ledger-integrity, on a frontend's operator listener, ranSELECT qbit_carry_forward_integrity_report()on the writer pool under the pool's statement timeout (PRISM_DATABASE_STATEMENT_TIMEOUT_MS, 15 s by default). They had no cache and no limit on concurrent runs. At production size (2.75M active carry-forward rows) the report took about 57 s before migration 026; since 026 it is estimated at about 29 s, never measured there. So every call:read_timeout.Concurrent calls each did the same.
self-checkandfatal-state clearalready run the report under a statement timeout of their own (#742).#690 (#737's F3).
clear_fatal_statecalledgetblockhashonce per pool block and once per deep-confirmed fanout. The calls ran one after another inside the recovery transaction, which holdsSETTLEMENT_LOCK,ORDER_LOCKand more. At mainnet's rate that is 65,000–130,000 calls per year of history; the rc.4 drill spent about 4.5 s idle in that transaction.Change
Part A: the routes run one report at a time and serve a dated result
New module
api/integrity.rs, held inApiState:close_on_dropso it is closed rather than returned to the pool when the run ends. On it the run opens one read-only transaction and reads thepayout_divergenceline, under the session's statement timeout as before, and then the report. The report runs under a statement timeout of its own: the time left to the run's 300 s deadline, which is self-check's allowance. Because the report is the run's last statement, the server cancels it by the deadline. There is no explicit ROLLBACK: the transaction ends when the connection closes. A client-side backstop 5 s after the deadline covers the report's last round trip (restoring the session timeout) and a server or network that doesn't answer.payout_divergenceandledger_backend, and adds:computed_at: when its run started, RFC 3339;age_seconds: its age when served;run_seconds: how long the run took. It is an upper bound on the report's own time, since it also covers the connection checkout and the divergence line. It is also the first production measurement of the report since 026.integrity_report_unavailable). The body gives the step that failed (its connection, the payout divergence line, or the report) and how, when that run started, and when the next run may start.ApiState::with_shutdowngives the routes the server's shutdown signal;server.rspasses it in. On a stop, the run in flight is abandoned and its waiters answer 503 at once, and no new run starts. The run's connection closes at once instead of going back to the pool to wait out the statement, and the stop's 503 says no other run will start. The run setsclient_connection_check_intervalto 1 s on its own connection, best effort, asmigration.rs's import writes already do: a server that can't check refuses it, and the error is ignored. As a result PostgreSQL ends the abandoned report within about a second rather than running it to its timeout.Refresh policy: on demand with single-flight, not a background refresh.
self-check.No new environment setting. Both values are constants, and the tests set them through a
#[doc(hidden)]ApiState::with_integrity_report_timing.payout_divergence_line(ledger/divergence.rs) now takes any executor instead of only a pool, so the routes read it in their transaction. Self-check and the tests still pass their pools, unchanged.Part B (#690): fatal-state clear asks the node once per height
getblockhashonce per distinct height. Pool blocks share heights with each other and with the blocks that confirm deep fanouts. A small helper,once_per_height, keeps the loop's answers.Observed::still_holdre-reads the observations once per height too. It keeps its own answers, so the re-read still asks the node afresh.blocks_checkedanddeep_fanouts_checked.rpc.rs, which is out of scope here. Deduplication removes the repeated calls; distinct heights are still asked one at a time.Docs
docs/prism-ledger-ops.md: the paragraph that said the routes still run under the pool setting now describes the new behaviour and fields, the failure cadence,run_secondsas an upper bound, and the stop behaviour. Also updated: thepayout_divergencesection, and the fatal-state clear section (once per height).doc/mining.md: the monitoring line now says the report is dated and cached, with the 5-minute cadence after a good report only.Tests run (minidev-alex1, PostgreSQL 16 private cluster, fsync on)
cargo test --locked -p qbit-prism-server --lib api::integrity: 9 passed. These are deterministic, with paused time where timing matters:cargo test --locked -p qbit-prism-server --test api_database: 3 passed, including the new gatedintegrity_routes_run_one_report_at_a_time_under_their_own_timeout. It runs against stub SQL functions, with every session's statement timeout at 1 s, a 0.5 s divergence line and a 1.5 s report:pg_stat_activity;close_on_drop: PostgreSQL kept running the abandoned report for more than 10 s. In that variantpool.close()still returned within 5 s.cargo test --locked -p qbit-prism-server --lib api::: 43 passed.cargo test --locked -p qbit-prism-server --test ledger_postgres fatal_state:: -- --test-threads=4: 22 passed. That is all 21 existing fatal-state tests (every refusal case: reorg, shorten, unknown, runaway, flap, pool block above, closing-walk, bound, …) plus the newclear_asks_the_node_once_per_height:getblockhashper height (two pool blocks at 90, a mature block and two fanout confirmations at 10, one at 20);{10: 3, 90: 2}calls instead of{10: 1, 90: 1}.cargo fmt --all -- --check: clean.cargo clippy --locked -p qbit-prism-server --all-targets -- -D warnings: clean except the three known vendored sqlx-core warnings.python3 scripts/check_prism_pool_acquires.py: OK. The audit sites moved andpayout_divergence_linetakes an executor now, soscripts/prism_pool_acquires.jsonwas updated: the run'sacquireispublic; itsbeginand the divergence line inside its transaction aretransaction.python3 -m unittest tests.test_docs_lab_prism_references: 147 OK.test/prism-gated-tests.txt.What CI must cover
ledger_postgres, the API suites (api_2x,api_contract,artifact_admission,observability*).run-load).Not run locally, per the host rules: the full lib suite, the rest of
ledger_postgres, the landing binaries, load presets.Refs #737
Refs #690
🤖 Generated with Claude Code