Repository navigation
3.x.x: a submitblock hyper hands back unwritten counts as not sent and is offered again, and the payout-revision listener reports its health (#816) - #834
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. |
There was a problem hiding this comment.
Approved: a complete review with no bugs found.
1 finding posted inline.
Findings without an inline location
2 nits
2. [low · nit] Claim-fenced transition row omits the #816 case for offer_reserved returning to pending
docs/prism-ledger-ops.md:2429
This table row still allows offer_reserved -> pending only after a submitblock that never established its connection (#522) or a warmup answer (#526).
After this PR, offer_not_executed (coordinator.rs:400-401) also returns Some for RpcNotSentError with stage Returned. Its caller (coordinator.rs:3394-3400) then calls release_unsent_offer, which moves the row back to pending.
The PR updated the state-table rows near line 225 and the #816 paragraph near line 787, but not this row. The doc now contradicts itself and the code, and an operator checking a Returned row against this table would conclude the transition is not allowed.
3. [low · nit] Inline comment at the release decision says only connect and warmup failures release; Returned does too
crates/qbit-prism-server/src/coordinator.rs:3388
The comment directly above if let Some(not_run) = offer_not_executed(&result) (coordinator.rs:3394) says only a call whose connection was never established, or that the node answered from its warmup, provably did not run. It says every other failure stays unknown.
Since this PR, offer_not_executed (coordinator.rs:385-401) also releases RpcNotSentError with stage Returned, where the connection did exist. That reservation goes back to pending, not to unknown as the comment says.
The PR updated the function's doc comment but not this comment, so it misdescribes the decision at the very point where it is made.
| it open and unread, and only within the 20-second idle bound. Since #816 it | ||
| also covers a request the HTTP client hands back unwritten because the | ||
| connection it was given closed or failed before the client wrote it: for | ||
| example a spare or pooled connection the node or a proxy closed after the |
There was a problem hiding this comment.
1. [low · nit] Runbook cites a pooled connection as a #816 not-sent example, but hyper-util retries that case instead
docs/prism-ledger-ops.md:790
The new #816 paragraph names "a spare or pooled connection the node or a proxy closed after the client checked it" as a case that fails with "the connection closed before the request was written".
The PR's own audit says otherwise (rpc.rs:74-77). hyper-util wraps a returned request as Canceled and retries it only on a reused connection, which the spare is not. The client never disables that retry (rpc.rs:669-687).
A pooled connection is a reused one. So hyper-util retries its returned request on another connection, from_returned (rpc.rs:151) never sees it, and last_error shows the retry's outcome. An operator who reads the runbook will expect that reason for pooled closes and will misread the evidence. The ConnectBoundLayer doc at rpc.rs:282 ("as it can a pooled connection") gives the same misleading impression.
…d is offered again, and the payout-revision listener reports its health (#816) Refs #816 (items 3 and 1; item 2, the lagging-node wake, is out of scope). Follow-up to #797/#762 and #795. One PR for both parts: they share no code, but each is small and both are 3.1.2 follow-ups to the same review (#811). Split commits would only cost the operator another hardware-key touch. ## Part A: a submitblock hyper hands back unwritten counts as not sent (#816 item 3) ### Problem `Rpc::call_timeout` mapped a send error to `RpcNotSentError` only when `error.is_connect()`. Suppose the node or a proxy closes the parked spare connection after `take_spare`'s kernel check but before hyper writes the request. hyper then hands the request back unwritten, and hyper-util doesn't retry it, because the spare is a new connection. The call failed as the plain `transport failed`, `classify_offer` recorded `OfferOutcome::Unknown`, and the block was never offered again although it never left the frontend. ### Change - `RpcNotSentError` is also returned when the send error's chain holds hyper-util's `Canceled` error (named by its `Display`, `client error (Canceled)`: the kind is private) directly over a canceled `hyper::Error`. Any other kind, source or text stays Unknown. Callers can tell the two cases apart through a new `stage: NotSentStage` (`Connect`, `Returned`). The connect message is unchanged. The new one reads `... transport failed before the request was sent: the connection closed before the request was written (<hyper's reason>)`. - **Source audit** (hyper 1.11.1, hyper-util 0.1.20, reqwest 0.12.28; no `h2` in `Cargo.lock`, so HTTP/1 only): - hyper's client builds a canceled error only with the request in hand, unwritten. There are three sites: `SendRequest::try_send_request` (connection not ready), the dispatch `Envelope` drop (the dispatcher went away with the request still queued), and `proto/h1/dispatch.rs` `recv_msg` (the dispatcher read a close or an error before it took the queued request). - The dispatcher takes a request out of the queue only to write it. Any failure after that is the connection's own error, never canceled. The only other canceled site, `OnUpgrade`, is not on the send path. - hyper-util wraps a canceled error as its `Canceled` kind only when `take_message()` returns the request, and retries it only on a reused connection. - reqwest's default retry policy acts only on HTTP/2 and HTTP/3 errors. - **Kept Unknown:** a close that hyper reads before hyper-util has handed the connection the request at all. hyper-util reports it as `SendRequest(IncompleteMessage)`, exactly like a close after a write, so it can't be proven unsent. - A tripwire test fails if hyper, hyper-util or reqwest change version, or `h2` enters the build, so the audit must be redone first. - Doc comments in `rpc.rs` (`RpcNotSentError`, `ConnectBoundLayer`), on `offer_not_executed` in `coordinator.rs` and on `release_unsent_offer` in `ledger/candidates.rs`, plus the #522 paragraph and the `offer_reserved` and `reconciliation` rows of `docs/prism-ledger-ops.md`, now describe the new case (prose only). - **Test seam:** a `#[doc(hidden)]` `SpareObserver` set through `Rpc::observe_spare`. It reports when a spare is parked and when one is handed out, before hyper has the request. When no observer is set, it costs one `OnceLock` read per spare hand-out. ### Tests (`tests/rpc_not_sent.rs`, `coordinator/offer_not_executed_tests.rs`) - `a_spare_the_node_closes_after_its_check_returns_the_submitblock_unsent`: - When the spare is handed out, the observer half-closes the node's end and waits for the kernel to report the FIN (a condition, not a sleep). The current-thread runtime's order then makes hyper's connection task read the close before it takes the queued request. - The call fails as `RpcNotSentError { stage: Returned }`, and the node's end reads 0 bytes before the client's own close. - The re-offer goes out on a new connection and the node takes the block exactly once. - It fails with the new rule disabled, and passed 30 of 30 repeats. - `a_spare_the_node_closes_after_reading_the_submitblock_may_have_been_sent`: the node reads the request off the spare and closes without replying. The outcome stays unknown (`transport failed`, not `RpcNotSentError`). - `the_not_sent_proof_covers_the_http_stack_in_the_lockfile`: the version tripwire above. - `land_a_cut_connect` now waits until the spare is actually parked instead of relying on a 100 ms sleep. `a_spare_the_node_closed_is_never_handed_out` also checks that the spare was never handed out. - `a_request_returned_unwritten_is_not_executed`: the offer path treats the new stage as not executed, so the reservation returns to `pending`. ## Part B: payout-revision listener health metrics (#816 item 1) ### Problem The #752 listener's only signal was a WARN, logged at most once a minute. A listener that is connected but hears nothing (for example through a transaction-pooling proxy) logged nothing at all. Such a frontend silently falls back to the blockpoll tick: after another frontend's block, its shares on new-tip work are refused `stale-job` until its next tick. ### Change - `qbit_prism_payout_revision_listener_up` (gauge): 1 from a successful LISTEN until the connection is lost or the probe fails. 0 before the first LISTEN, while reconnecting, and once the listener ends; a drop guard covers an aborted task. `Metrics` counts the listeners whose LISTEN holds, so a listener ending after a newer one began cannot clear the gauge. - `qbit_prism_payout_revision_announcements_heard_total` (counter): every notification the listener received, one per announced bump (a block's confirmation or settlement, a carry gate change, a fatal-state clear), so it is not a block count. - Both families are registered at 0 at startup and refreshed at every scrape, so a database outage that also stalls the health publisher still shows the listener down. - Documented in `docs/prism-native-metrics.md` (regenerated inventory plus a "Reading the payout-revision listener" section) and in `docs/prism-metrics-cardinality-privacy.md`. The pinned observability census is updated (106 families, 320 startup and 1004 populated series). - **No alert rule.** A frontend without its listener loses no block, credit or payout: each pool block costs it at most one tick of `stale-job` refusals. The gauge also drops to 0 on every reconnect, so a useful rule needs a dwell chosen from fleet data. The doc names a candidate (`listener_up == 0` for 10 m) for a later change through `generate_prism_alerts.py`. ### Tests - Lib: `the_listener_gauge_is_down_until_a_listen_holds_and_once_the_listener_ends` covers the guard and the counter. - `tests/revision_wake.rs`, `a_lost_listener_keeps_the_tick_and_wakes_again_once_it_reconnects`: - The gauge reads 1 with both listeners up, 0 once they are terminated, 1 after reconnecting, and 0 after the loops stop. - B's counter doesn't move for the announcement made while it was down, then moves by 1 for the next bump and by 1 for the late notification. - `a_bump_before_the_first_listen_still_wakes_the_refresh`: the gauge reads 0 before the first LISTEN and 1 after it. ### The CI failure of `a_lost_listener_keeps_the_tick_and_wakes_again_once_it_reconnects` (run 41467535602, 2026-11-02) - That run failed with `B republished at 2 without a listener or a tick`. - Cause: the test waited only for both LISTEN sessions, not for each loop's first refresh. B's first loop refresh could still be running when the "unheard" bump committed, read the new revision and publish it. - That run's log agrees: "A republished on its tick 66.9ms after the unheard announcement", although A's tick is 2 s. - The test now waits until each loop's first refresh has finished before it cuts the listeners. A's republish now comes on its real tick (2.00-2.03 s; once 8.0 s on this loaded host) in 6 local runs. ## Tests run locally (minidev-alex1, through the host gate) - `cargo test --locked -p qbit-prism-server --test rpc_not_sent`: 16 passed. The two new spare tests passed 30 of 30 repeats, and the not-sent test fails with the rule disabled. - `cargo test --locked -p qbit-prism-server --test rpc_idle_close --test rpc_deadlines`: 2 and 5 passed. - `test/prism-native-tests.sh cargo-args --locked -p qbit-prism-server --test revision_wake -- --nocapture` (private PostgreSQL 16): 7 passed. The two listener tests then passed 5 more times. - `test/prism-native-tests.sh cargo-args --locked -p qbit-prism-server --lib -- offer_not_sent_tests offer_not_executed_tests --test-threads=4`: 14 passed. - `cargo test --locked -p qbit-prism-server --lib -- revision_wake::tests offer_not_executed_tests metrics::registry::tests`: 12 passed. - `cargo test --locked -p qbit-prism-server --test observability`: 17 passed. - `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. - Guards: `python3 scripts/check_prism_pool_acquires.py`, `python3 scripts/generate_prism_metrics.py --check` and `python3 scripts/generate_prism_alerts.py --check` all pass. - No new PostgreSQL-gated test ids, so `test/prism-gated-tests.txt` is unchanged. ## CI must cover - The full lib suite, every gated shard (`revision_wake`, `offer_not_sent_tests`), and the gated-test manifest proof. This host runs in downgraded mode, so it can't prove the manifest. - Python tests. - The nightly load presets, through the `run-load` label. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Squashed commits: 332798a 3.x.x: a submitblock hyper hands back unwritten is not sent, and the revision listener gets a health gauge and counter (#816) ab9a006 3.x.x: revision_wake fills each frontend's ledger pool before the database refuses connections (#816) Co-Authored-By: Claude Opus 5.5 <[email protected]>
ab9a006 to
939d996
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]>
## Problem #834 (#816) added `qbit_prism_payout_revision_listener_up` and `qbit_prism_payout_revision_announcements_heard_total`, but no alert reads them. A frontend whose payout-revision listener (#752) is down republishes after most announced payout revision bumps (another frontend's block confirmation, for example) only at its next poll, a `PRISM_BLOCKPOLL_SECONDS` tick or a blockwait return, as before #752. Until then its miners' shares on work at the superseded revision are refused `stale-job`, after every such bump. The only signal today is a WARN line, logged at most about once a minute. ## Change One warning rule, `PrismPayoutRevisionListenerDown` (UID `qbit-prism-revision-listener-down`, severity `warning`, no page label). `scripts/generate_prism_alerts.py` generates its expression, `for` and text, and the deployed-rules patch is regenerated from them. The rule fires when: - `qbit_prism_payout_revision_listener_up` has read 0 for 10 minutes, - on a frontend that had an authorized miner in the last 15 minutes, - using the same `miner_gated` / `miners_recently()` helpers as the revision-work warnings (#758, #800). **Choices, and why:** - **`for: 10m`.** The listener waits at most 5 s between attempts, so it is back within seconds of the database answering. An ordinary reconnect reads 0 for a scrape or two. A database that keeps refusing the listener's connection holds it at 0 for good. Examples: `max_connections` not raised by one per frontend, or a role or database `CONNECTION LIMIT`. - Forty consecutive 15-second scrapes leave no reconnect behind. - A database outage already pages `PrismDatabaseUnavailable` after 2 minutes, so a short outage doesn't warn twice. - The cost of a down listener is bounded, as it was for every frontend before #752. It warns; it never pages. - **15-minute window.** This is the revision-work warnings' window, reused rather than redefined. - An idle standby's listener costs no miner anything, so the standby stays quiet. - When miners fail over to a frontend whose listener is down, the dwell starts as they arrive. - A miner count that is absent for the whole window closes the gate, as it does for those warnings. - **Missing gauge.** On a scraped frontend, a missing gauge counts as down, under the same gate and dwell. - Since #834 the gauge is a live overlay, present from startup, so a scraped target without it runs an older image. - Its listener's state is unknown, and unknown is not healthy. - Rollout consequence: re-vendor only once the frontends run an image with #834. Otherwise each serving frontend warns after 10 minutes. - **Failed scrapes.** The rule reads `last_over_time(…[2m])` and `max_over_time(up[2m])`, the #666 pattern, so a failed scrape neither restarts the dwell nor makes a healthy listener read as missing. A scrape that keeps failing belongs to `PrismMetricsEndpointDown`. - **No-data and evaluation errors are `OK`.** The expression keeps a present 0 for every scraped frontend, so no data means no target, which `PrismMetricsNoData` and `PrismMetricsEndpointDown` own. **Known limits, documented in the rule text and the runbook:** - **A listener that keeps reconnecting and dropping** can warn late or not at all. Each evaluation that finds the `LISTEN` holding restarts the dwell. Its WARN lines show it. - **A `LISTEN` that holds but hears nothing**, as through a transaction-mode pooler, reads 1. Compare `…_announcements_heard_total` across the node's frontends. - **After a restart** the gate still counts the previous process's miners for the window. **Docs:** - **Runbook.** A new section, "A payout-revision listener that stays down (#843)", sits at the end of "Snapshot and payout boundary" in `docs/prism-ledger-ops.md`, just before the block-candidate chapter and its #630 revision-race runbook. It covers: - the miner-visible effect; - a missing gauge; - a database outage; - `max_connections` headroom and reserved slots, with a query, and connection limits; - a transaction-mode pooler; - the listener's WARN, DEBUG and INFO lines; - a refresh loop that isn't running. - **Pointer.** The connection budget under "HA database and shutdown" now links to the runbook. - **Metrics guide.** The #816 section of `docs/prism-native-metrics.md` no longer says that no rule reads these families, and points to the runbook. Its WARN cadence and per-bump cost now match the code. - **Migration notes.** `docs/prism-alert-migration.md` gets an adoption note. Its generated evidence row comes from the generator. - **Drift check.** `generate_prism_alerts.py --check` now fails if these docs state a dwell other than `LISTENER_DOWN_MINUTES`. In the ops guide it reads only the runbook section. It also checks that section's recent-miner window. ## Tests run - `python3 scripts/generate_prism_alerts.py --check`: passes. Also passes after `--snapshot` regenerated the patch from the pinned qbit-tools a007a142 templates (sha256 matches `tests/fixtures/prism-deployed-alerts.json`). - `python3 scripts/generate_prism_metrics.py --check`: passes. - `python3 scripts/check_prism_alert_uids.py`: 46 rule UIDs, unique and within Grafana's limits. The new UID is 33 characters. - `python3 -m unittest tests.test_check_prism_alert_uids`: 10 tests OK. - `(cd scripts && python3 test_prism_alert_deployment.py --snapshot <a007a142 templates>)`: "Patch applies cleanly; 10 Jinja gate combinations passed; 78 original / 80 proposed rules". It now also checks the new rule's severity, missing page label, `for`, no-data and error states, expression and recent-miner gate. - `python3 scripts/test_prism_alert_promql.py --promtool <promtool 3.14.0>` (release tarball, sha256 checked as CI does): 46 expressions; 211 scenarios; 436 expression assertions; 331 alert assertions passed (run on 73a92d7; later commits change only rule text and docs, no expression or fixture). That is 200 scenarios before this change, plus 11 new `#843 …` scenarios: - fires after the dwell only with a recent miner, beside a healthy frontend, an idle standby and an absent miner count; - pending under the dwell; - recovery inside the dwell, and an evaluation that finds the listener holding restarts the dwell; - a listener that held for one evaluation fires 10 minutes after it dropped again, not before; - a failed scrape neither restarts the dwell nor reads as a missing gauge; - a missing gauge fires only with a recent miner, through a failed scrape; - keeps warning inside the miner window after the last miner leaves, and stops after it; - failover: the dwell starts when miners arrive; - a scrape that keeps failing is left to `PrismMetricsEndpointDown`. - **Mutation check:** a local script ran these scenarios against ten variants of the rule. Every variant fails at least one scenario: - no smoothing; - an absent gauge stays quiet; - no gate; - gated on miners now; - plain `up`; - `min_over_time` in place of `last_over_time`; - a 15-minute hold suppression; - a 9-minute dwell; - an 11-minute dwell. - **Inventory check (emulated):** a Python copy of the Rust check `native_rules_reference_only_inventory_families_for_their_role` passes for all 44 native rules. - `python3 scripts/check_prism_settings.py` and `python3 scripts/check_prism_pool_acquires.py`: pass (no settings or pool acquires changed). ## What CI must cover - **Not run locally:** `cargo test --locked -p qbit-prism-server --test observability`. Its inventory tests run `generate_prism_alerts.py --check` and require every family a rule reads to be in the inventory for the rule's role. No Rust code changed. - **Run by CI:** the promtool and UID steps in "Lint, compile, and Compose validation". ## Rollout - **Re-vendor.** The rule reaches the pair at qbit-tools' next re-vendor of the native rules (last at 442b7744 for v3.1.1). That is an operator step outside this repo. - **Delete list.** At that re-vendor, add `qbit-prism-revision-listener-down` to `qbit_monitoring_stack_prism_native_only_grafana_alert_rule_delete_uids`, so the rule is removed when native alerts are turned off. - **Ordering.** Re-vendor only once the frontends run an image that includes #834. Otherwise every frontend serving miners warns after 10 minutes, because it doesn't export the gauge. ## Left for a follow-up #834's WARN text (`revision_wake.rs`) and the gauge's HELP text say a down listener republishes "after another frontend's block" on its tick. Most announced bumps wait the same way, for the tick or a blockwait return. The runbook says so, but this PR doesn't change the code's text; `docs/prism-native-metrics.md`'s table row, generated from that HELP text, and `docs/prism-pool-acquire-metrics.md` keep the narrower wording until then. Refs #843 🤖 Generated with [Claude Code](https://claude.com/claude-code) Squashed commits: 69b0da2 Merge remote-tracking branch 'origin/orca/816-unsent-spare-submitblock' into orca/843-listener-down-alert 628356f 3.x.x: warn when a frontend's payout-revision listener stays down (#843) 6d462e8 3.x.x: listener-down warning: review fixes (#843) 04b373e 3.x.x: listener-down warning: second review fixes (#843) 73a92d7 3.x.x: listener-down warning: third review fixes (#843) f0ea95f Merge remote-tracking branch 'origin/3.x.x' into orca/843-listener-down-alert 5f02e7b 3.x.x: listener-down warning: fourth review fixes (#843) 48644ef 3.x.x: listener-down warning: fifth review fixes (#843) 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]>
…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]>
## Problem #834 (#816) added `qbit_prism_payout_revision_listener_up` and `qbit_prism_payout_revision_announcements_heard_total`, but no alert reads them. A frontend whose payout-revision listener (#752) is down republishes after most announced payout revision bumps (another frontend's block confirmation, for example) only at its next poll, a `PRISM_BLOCKPOLL_SECONDS` tick or a blockwait return, as before #752. Until then its miners' shares on work at the superseded revision are refused `stale-job`, after every such bump. The only signal today is a WARN line, logged at most about once a minute. ## Change One warning rule, `PrismPayoutRevisionListenerDown` (UID `qbit-prism-revision-listener-down`, severity `warning`, no page label). `scripts/generate_prism_alerts.py` generates its expression, `for` and text, and the deployed-rules patch is regenerated from them. The rule fires when: - `qbit_prism_payout_revision_listener_up` has read 0 for 10 minutes, - on a frontend that had an authorized miner in the last 15 minutes, - using the same `miner_gated` / `miners_recently()` helpers as the revision-work warnings (#758, #800). **Choices, and why:** - **`for: 10m`.** The listener waits at most 5 s between attempts, so it is back within seconds of the database answering. An ordinary reconnect reads 0 for a scrape or two. A database that keeps refusing the listener's connection holds it at 0 for good. Examples: `max_connections` not raised by one per frontend, or a role or database `CONNECTION LIMIT`. - Forty consecutive 15-second scrapes leave no reconnect behind. - A database outage already pages `PrismDatabaseUnavailable` after 2 minutes, so a short outage doesn't warn twice. - The cost of a down listener is bounded, as it was for every frontend before #752. It warns; it never pages. - **15-minute window.** This is the revision-work warnings' window, reused rather than redefined. - An idle standby's listener costs no miner anything, so the standby stays quiet. - When miners fail over to a frontend whose listener is down, the dwell starts as they arrive. - A miner count that is absent for the whole window closes the gate, as it does for those warnings. - **Missing gauge.** On a scraped frontend, a missing gauge counts as down, under the same gate and dwell. - Since #834 the gauge is a live overlay, present from startup, so a scraped target without it runs an older image. - Its listener's state is unknown, and unknown is not healthy. - Rollout consequence: re-vendor only once the frontends run an image with #834. Otherwise each serving frontend warns after 10 minutes. - **Failed scrapes.** The rule reads `last_over_time(…[2m])` and `max_over_time(up[2m])`, the #666 pattern, so a failed scrape neither restarts the dwell nor makes a healthy listener read as missing. A scrape that keeps failing belongs to `PrismMetricsEndpointDown`. - **No-data and evaluation errors are `OK`.** The expression keeps a present 0 for every scraped frontend, so no data means no target, which `PrismMetricsNoData` and `PrismMetricsEndpointDown` own. **Known limits, documented in the rule text and the runbook:** - **A listener that keeps reconnecting and dropping** can warn late or not at all. Each evaluation that finds the `LISTEN` holding restarts the dwell. Its WARN lines show it. - **A `LISTEN` that holds but hears nothing**, as through a transaction-mode pooler, reads 1. Compare `…_announcements_heard_total` across the node's frontends. - **After a restart** the gate still counts the previous process's miners for the window. **Docs:** - **Runbook.** A new section, "A payout-revision listener that stays down (#843)", sits at the end of "Snapshot and payout boundary" in `docs/prism-ledger-ops.md`, just before the block-candidate chapter and its #630 revision-race runbook. It covers: - the miner-visible effect; - a missing gauge; - a database outage; - `max_connections` headroom and reserved slots, with a query, and connection limits; - a transaction-mode pooler; - the listener's WARN, DEBUG and INFO lines; - a refresh loop that isn't running. - **Pointer.** The connection budget under "HA database and shutdown" now links to the runbook. - **Metrics guide.** The #816 section of `docs/prism-native-metrics.md` no longer says that no rule reads these families, and points to the runbook. Its WARN cadence and per-bump cost now match the code. - **Migration notes.** `docs/prism-alert-migration.md` gets an adoption note. Its generated evidence row comes from the generator. - **Drift check.** `generate_prism_alerts.py --check` now fails if these docs state a dwell other than `LISTENER_DOWN_MINUTES`. In the ops guide it reads only the runbook section. It also checks that section's recent-miner window. ## Tests run - `python3 scripts/generate_prism_alerts.py --check`: passes. Also passes after `--snapshot` regenerated the patch from the pinned qbit-tools a007a142 templates (sha256 matches `tests/fixtures/prism-deployed-alerts.json`). - `python3 scripts/generate_prism_metrics.py --check`: passes. - `python3 scripts/check_prism_alert_uids.py`: 46 rule UIDs, unique and within Grafana's limits. The new UID is 33 characters. - `python3 -m unittest tests.test_check_prism_alert_uids`: 10 tests OK. - `(cd scripts && python3 test_prism_alert_deployment.py --snapshot <a007a142 templates>)`: "Patch applies cleanly; 10 Jinja gate combinations passed; 78 original / 81 proposed rules" (81 since the branch took in #844's append-slot rule from `3.x.x`; 80 before). It now also checks the new rule's severity, missing page label, `for`, no-data and error states, expression and recent-miner gate. - `python3 scripts/test_prism_alert_promql.py --promtool <promtool 3.14.0>` (release tarball, sha256 checked as CI does): 46 expressions; 211 scenarios; 436 expression assertions; 331 alert assertions passed (run on 73a92d7; later commits change only rule text and docs, no expression or fixture). That is 200 scenarios before this change, plus 11 new `#843 …` scenarios: - fires after the dwell only with a recent miner, beside a healthy frontend, an idle standby and an absent miner count; - pending under the dwell; - recovery inside the dwell, and an evaluation that finds the listener holding restarts the dwell; - a listener that held for one evaluation fires 10 minutes after it dropped again, not before; - a failed scrape neither restarts the dwell nor reads as a missing gauge; - a missing gauge fires only with a recent miner, through a failed scrape; - keeps warning inside the miner window after the last miner leaves, and stops after it; - failover: the dwell starts when miners arrive; - a scrape that keeps failing is left to `PrismMetricsEndpointDown`. - **Mutation check:** a local script ran these scenarios against ten variants of the rule. Every variant fails at least one scenario: - no smoothing; - an absent gauge stays quiet; - no gate; - gated on miners now; - plain `up`; - `min_over_time` in place of `last_over_time`; - a 15-minute hold suppression; - a 9-minute dwell; - an 11-minute dwell. - **Inventory check (emulated):** a Python copy of the Rust check `native_rules_reference_only_inventory_families_for_their_role` passes for all 44 native rules. - `python3 scripts/check_prism_settings.py` and `python3 scripts/check_prism_pool_acquires.py`: pass (no settings or pool acquires changed). ## What CI must cover - **Not run locally:** `cargo test --locked -p qbit-prism-server --test observability`. Its inventory tests run `generate_prism_alerts.py --check` and require every family a rule reads to be in the inventory for the rule's role. No Rust code changed. - **Run by CI:** the promtool and UID steps in "Lint, compile, and Compose validation". ## Rollout - **Re-vendor.** The rule reaches the pair at qbit-tools' next re-vendor of the native rules (last at 442b7744 for v3.1.1). That is an operator step outside this repo. - **Delete list.** At that re-vendor, add `qbit-prism-revision-listener-down` to `qbit_monitoring_stack_prism_native_only_grafana_alert_rule_delete_uids`, so the rule is removed when native alerts are turned off. - **Ordering.** Re-vendor only once the frontends run an image that includes #834. Otherwise every frontend serving miners warns after 10 minutes, because it doesn't export the gauge. ## Left for a follow-up #834's WARN text (`revision_wake.rs`) and the gauge's HELP text say a down listener republishes "after another frontend's block" on its tick. Most announced bumps wait the same way, for the tick or a blockwait return. The runbook says so, but this PR doesn't change the code's text; `docs/prism-native-metrics.md`'s table row, generated from that HELP text, and `docs/prism-pool-acquire-metrics.md` keep the narrower wording until then. Refs #843 🤖 Generated with [Claude Code](https://claude.com/claude-code) Squashed commits: 52294bf 3.x.x: warn when a frontend's payout-revision listener stays down (#843) cce2295 Merge 3.x.x (3d48a8f) into the #843 branch: the listener warning and #844's append-slot warning are generated together 797f660 Merge 3.x.x (234ff1c) into orca/843-listener-down-alert: take in the landed 3.1.2 PRs and the collate test fix (#874) Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ing for PrismMetricsEndpointDown's whole dwell, so no minute is left uncovered (#869) Refs #869 ## Problem `PrismPayoutRevisionListenerDown` (#843, new in 3.1.2) carried a frontend's last reading for 2 minutes after its scrapes stopped (`LISTENER_SMOOTHING_MINUTES = 2`). `PrismMetricsEndpointDown` fires 3 minutes after the first failed scrape. So when a frontend stopped being scraped while its listener warning was firing or pending, the warning resolved (or the dwell restarted) about a minute before the endpoint alert took the frontend over. For that minute neither alert covered the frontend. ## Change - `scripts/generate_prism_alerts.py` no longer has a window constant. It reads `PrismMetricsEndpointDown`'s authored `for` (3m) and adds one standard-group evaluation interval (`STANDARD_EVALUATION_MINUTES = 1`, qbit-tools' default for `qbit_monitoring_stack_grafana_alert_standard_evaluation_interval`), so the window is now **4m**. The two rules can no longer drift apart. - **Why not "equal to the dwell":** the endpoint alert goes pending at the first evaluation that sees `up == 0`. That can be up to a scrape interval, a scrape timeout and an evaluation interval after the last good scrape, and the alert fires one dwell later. Range selectors drop a sample that is exactly one window old (left-open since Prometheus 3). - A 3m window therefore ends before the last evaluation ahead of the hand-off. promtool shows this even at 1s granularity: the new scenarios fail with a 3m window as well as a 2m one. - While the evaluation interval divides the dwell, the margin needed beyond the dwell is the scrape interval plus its timeout. The extra minute covers the 15-second scrape interval with any timeout Prometheus allows, with 30 s to spare. - **Regenerated artifacts:** - `docs/prism-native-alert-rules.json`: the two windows go from `[2m]` to `[4m]`, and the rule text states the window, what it is made of and its preconditions. - `docs/prism-alert-migration.md`: the evidence table. - `docs/prism-alert-rules-qbit-tools.patch`, regenerated with `--snapshot` against the pinned a007a142 templates. It changes only the specification digest and the listener rule's `expr` (`[2m]` to `[4m]` twice) and `description`. - `docs/prism-alert-migration.json` is not something the generator writes, and it does not state the window, so it is unchanged. - The rule count is unchanged: 45 native, 78 original / 81 proposed in the deployment check. No other rule's expression or dwell changes. - **Runbook** (`docs/prism-ledger-ops.md`, "A payout-revision listener that stays down"): states the 4-minute carry, measured from the last successful scrape, and the hand-off's preconditions. Those are: scrape interval plus timeout (plus any lag) within the 1-minute margin; an evaluation interval that divides the dwell; both rules evaluated on one tick (no within-group jitter). It also covers what the carry does not do: the dwell restarts after an outage longer than the carry, a target removed from Prometheus's configuration gets no endpoint alert for its instance, and the pre-#834 rollback case is delayed. - **Prose guard:** the generator's `--check` now also checks every number that runbook paragraph states against the constants: window, endpoint dwell, margin, scrape interval, miner window and listener dwell. - **Scenarios:** 11 new #869 scenarios in `tests/fixtures/prism-alert-scenarios.json`. - **Firing:** the listener still warns at the last evaluation before `PrismMetricsEndpointDown` fires. Because a resolve would need the full 10-minute dwell again, that proves it warned at every evaluation since the scrapes stopped. - **Hand-off:** the evaluation where the endpoint alert fires. - **Pending:** a dwell that completes at the last evaluation before the hand-off. - **Missing gauge:** a frontend without the listener gauge. - **Window end:** exactly 4 minutes after the last successful scrape. - **Outage longer than the carry:** the dwell restarts once scrapes resume (2 scenarios). - **Rollback to a pre-#834 image:** 2 scenarios. - **Removed target:** 2 scenarios. ## Cost - **Stale readings carried longer:** a stale listener reading is now carried 2 minutes longer after scrapes stop (4 minutes instead of 2): one minute to reach the endpoint dwell, and one for the evaluation-interval margin. A pending dwell can now complete on a reading up to 4 minutes old. Example: a frontend whose listener has read 0 for 6 minutes and then stops being scraped warns, and resolves when the carry ends. - **Missing-gauge warning later:** a frontend rolled back to an image from before #834 keeps its last reading of 1 for the carry, so the missing-gauge warning comes up to 4 minutes after the dwell (2 before). - **Removed targets:** a warning for a target removed from Prometheus lingers for the carry. ## Not changed (follow-ups for the coordinator) - `PrismBlockSubmissionHeld` (#666, paging) keeps the same 2-minute carry and has the same gap before `PrismMetricsEndpointDown` takes over. It is out of this PR's scope (no other rule's expression may change). - The 1-minute margin is a copy of qbit-tools' default standard evaluation interval. Nothing in this repository ties it to the deployed value or checks that both rules stay in the same Grafana group. - The harness runs at 1s scrape/evaluation granularity. A local review probe at 15s scrapes and 1m evaluations (not committed) found no gap with up to 60 s between the last good scrape and the first visible failure. ## Tests run (promtool 3.14.0 from the CI tarball, sha256 checked; snapshot sha256 matches the manifest) | Command | Result | | --- | --- | | `python3 scripts/test_prism_alert_promql.py --promtool <promtool>` (full suite, on `b79320de`; later commits change only rule text, runbook prose, guards and fixture additions) | exit 0: 47 expressions; 230 scenarios; 460 expression assertions; 355 alert assertions | | Same with `--scenarios` holding the 11 #869 scenarios, on the head | exit 0: 43 scenarios (with the pool-wait ones); 74 expression and 94 alert assertions | | Mutation: the window forced to 2m, then 3m (copy of the tree, rules regenerated), on the 11 #869 scenarios | exit 1 both times; the same 6 fail (firing, hand-off, pending, missing gauge, rollback, removed target); the window-end and resume scenarios pass, as expected | | `python3 scripts/generate_prism_alerts.py --check` and `--check --snapshot <dir>` | pass; each new prose guard rejects a mutated runbook number | | `python3 scripts/test_prism_alert_deployment.py --snapshot <dir>` | Patch applies cleanly; 10 Jinja gate combinations; 78 original / 81 proposed rules | | `python3 -m unittest tests.test_prism_generated_artifact_checks tests.test_check_prism_alert_uids` | 15 tests OK | | `python3 scripts/check_prism_alert_uids.py` | 47 UIDs unique | | `python3 scripts/generate_prism_metrics.py --check` | pass | Not run: Rust builds and tests (no Rust change), and the other Python shards (CI runs them). The full PromQL suite was not rerun on the final head, because only text and scenarios changed after `b79320de`; CI runs it. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Squashed commits: ee3e01e 3.x.x: PrismPayoutRevisionListenerDown carries a frontend's last reading for PrismMetricsEndpointDown's whole dwell, so no minute is left uncovered (#869) 0dbcecc 3.x.x: #869 review: the runbook states the window's limits, and the generator checks every number it states 2d12a3d 3.x.x: #869 review round 2: pin the missing-gauge branch's window, and state the carry's preconditions and limits 17f6f1e 3.x.x: #869 review round 3: state the hand-off's real precondition, and pin the carry's documented limits def88c3 3.x.x: #869 review round 4: the runbook states the same-tick assumption, the timeout bound and Grafana's missing-series resolve 8537cec 3.x.x: #869 review round 5: state the margin's real bound, the same-tick condition in the rule text, and a removed last target's no-data alert Co-Authored-By: Claude Opus 5.5 <[email protected]> Squashed-from: 8537cec
Refs #816 (items 3 and 1; item 2, the lagging-node wake, is out of scope). Follow-up to #797/#762 and #795.
One PR for both parts: they share no code, but each is small and both are 3.1.2 follow-ups to the same review (#811). Split commits would only cost the operator another hardware-key touch.
Part A: a submitblock hyper hands back unwritten counts as not sent (#816 item 3)
Problem
Rpc::call_timeoutmapped a send error toRpcNotSentErroronly whenerror.is_connect(). Suppose the node or a proxy closes the parked spare connection aftertake_spare's kernel check but before hyper writes the request. hyper then hands the request back unwritten, and hyper-util doesn't retry it, because the spare is a new connection. The call failed as the plaintransport failed,classify_offerrecordedOfferOutcome::Unknown, and the block was never offered again although it never left the frontend.Change
RpcNotSentErroris also returned when the send error's chain holds hyper-util'sCancelederror (named by itsDisplay,client error (Canceled): the kind is private) directly over a canceledhyper::Error. Any other kind, source or text stays Unknown. Callers can tell the two cases apart through a newstage: NotSentStage(Connect,Returned). The connect message is unchanged. The new one reads... transport failed before the request was sent: the connection closed before the request was written (<hyper's reason>).h2inCargo.lock, so HTTP/1 only):SendRequest::try_send_request(connection not ready), the dispatchEnvelopedrop (the dispatcher went away with the request still queued), andproto/h1/dispatch.rsrecv_msg(the dispatcher read a close or an error before it took the queued request).OnUpgrade, is not on the send path.Canceledkind only whentake_message()returns the request, and retries it only on a reused connection.SendRequest(IncompleteMessage), exactly like a close after a write, so it can't be proven unsent.h2enters the build, so the audit must be redone first.rpc.rs(RpcNotSentError,ConnectBoundLayer), onoffer_not_executedincoordinator.rsand onrelease_unsent_offerinledger/candidates.rs, plus the 3.x.x: a block found while qbitd refuses the connection is never offered again and is lost #522 paragraph and theoffer_reservedandreconciliationrows ofdocs/prism-ledger-ops.md, now describe the new case (prose only).#[doc(hidden)]SpareObserverset throughRpc::observe_spare. It reports when a spare is parked and when one is handed out, before hyper has the request. When no observer is set, it costs oneOnceLockread per spare hand-out.Tests (
tests/rpc_not_sent.rs,coordinator/offer_not_executed_tests.rs)a_spare_the_node_closes_after_its_check_returns_the_submitblock_unsent:RpcNotSentError { stage: Returned }, and the node's end reads 0 bytes before the client's own close.a_spare_the_node_closes_after_reading_the_submitblock_may_have_been_sent: the node reads the request off the spare and closes without replying. The outcome stays unknown (transport failed, notRpcNotSentError).the_not_sent_proof_covers_the_http_stack_in_the_lockfile: the version tripwire above.land_a_cut_connectnow waits until the spare is actually parked instead of relying on a 100 ms sleep.a_spare_the_node_closed_is_never_handed_outalso checks that the spare was never handed out.a_request_returned_unwritten_is_not_executed: the offer path treats the new stage as not executed, so the reservation returns topending.Part B: payout-revision listener health metrics (#816 item 1)
Problem
The #752 listener's only signal was a WARN, logged at most once a minute. A listener that is connected but hears nothing (for example through a transaction-pooling proxy) logged nothing at all. Such a frontend silently falls back to the blockpoll tick: after another frontend's block, its shares on new-tip work are refused
stale-jobuntil its next tick.Change
qbit_prism_payout_revision_listener_up(gauge): 1 from a successful LISTEN until the connection is lost or the probe fails. 0 before the first LISTEN, while reconnecting, and once the listener ends; a drop guard covers an aborted task.Metricscounts the listeners whose LISTEN holds, so a listener ending after a newer one began cannot clear the gauge.qbit_prism_payout_revision_announcements_heard_total(counter): every notification the listener received, one per announced bump (a block's confirmation or settlement, a carry gate change, a fatal-state clear), so it is not a block count.docs/prism-native-metrics.md(regenerated inventory plus a "Reading the payout-revision listener" section) and indocs/prism-metrics-cardinality-privacy.md. The pinned observability census is updated (106 families, 320 startup and 1004 populated series).stale-jobrefusals. The gauge also drops to 0 on every reconnect, so a useful rule needs a dwell chosen from fleet data. The doc names a candidate (listener_up == 0for 10 m) for a later change throughgenerate_prism_alerts.py.Tests
the_listener_gauge_is_down_until_a_listen_holds_and_once_the_listener_endscovers the guard and the counter.tests/revision_wake.rs,a_lost_listener_keeps_the_tick_and_wakes_again_once_it_reconnects:a_bump_before_the_first_listen_still_wakes_the_refresh: the gauge reads 0 before the first LISTEN and 1 after it.The CI failure of
a_lost_listener_keeps_the_tick_and_wakes_again_once_it_reconnects(run 41467535602, 2026-11-02)B republished at 2 without a listener or a tick.Tests run locally (minidev-alex1, through the host gate)
cargo test --locked -p qbit-prism-server --test rpc_not_sent: 16 passed. The two new spare tests passed 30 of 30 repeats, and the not-sent test fails with the rule disabled.cargo test --locked -p qbit-prism-server --test rpc_idle_close --test rpc_deadlines: 2 and 5 passed.test/prism-native-tests.sh cargo-args --locked -p qbit-prism-server --test revision_wake -- --nocapture(private PostgreSQL 16): 7 passed. The two listener tests then passed 5 more times.test/prism-native-tests.sh cargo-args --locked -p qbit-prism-server --lib -- offer_not_sent_tests offer_not_executed_tests --test-threads=4: 14 passed.cargo test --locked -p qbit-prism-server --lib -- revision_wake::tests offer_not_executed_tests metrics::registry::tests: 12 passed.cargo test --locked -p qbit-prism-server --test observability: 17 passed.cargo fmt --all -- --check: clean.cargo clippy --locked -p qbit-prism-server --all-targets -- -D warnings: clean, apart from the 3 known vendoredsqlx-corewarnings.python3 scripts/check_prism_pool_acquires.py,python3 scripts/generate_prism_metrics.py --checkandpython3 scripts/generate_prism_alerts.py --checkall pass.test/prism-gated-tests.txtis unchanged.CI must cover
revision_wake,offer_not_sent_tests), and the gated-test manifest proof. This host runs in downgraded mode, so it can't prove the manifest.run-loadlabel.🤖 Generated with Claude Code
Open in [code]smith · Need help on this PR? Tag
@codesmith-botwith what you need.