Skip to content

3.x.x: the collate tests' synthetic report records its planned tip, so #842's median gate measures it (3.x.x is red since #847 and #854 both landed) - #874

Merged
kiwidream merged 1 commit into
3.x.xfrom
orca/collate-tests-planned-tips
Nov 13, 2026
Merged

kiwidream merged 1 commit into
3.x.xfrom
orca/collate-tests-planned-tips

Conversation

@kiwidream

@kiwidream kiwidream commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

Problem

3.x.x is red since #847 and #854 both landed (CI run 43456385763 on 3d48a8f): "Rust tests" and "Rust PRISM PostgreSQL and multi-instance contracts (shard 3)" fail in qbit-prism-load --test collate, and every PR that takes the base in fails the same way.

test a_report_only_points_failed_budgets_are_shown_but_never_fail_the_suite ... FAILED
test a_report_only_run_sets_aside_only_its_commit_deadlines_refusals ... FAILED
test a_report_only_run_that_did_not_reconcile_fails_the_suite ... FAILED

Each PR was green on its own base. Together they are not:

It is a test-fixture gap, not a defect in the gate or the collation: a report without the key is rightly unmeasured.

Change

crates/qbit-prism-load/tests/collate.rs: the synthetic report's first phase records the one tip the report holds (external_tips_planned: 1), and the other phases record none. The report now says what a current harness says, and the median gate measures its one tip (600 ms against 3,000 ms).

No code outside the test changes.

Tests

  • cargo test --locked -p qbit-prism-load --test collate: 14 passed, 0 failed (on 3d48a8f without this change, CI has the three above failing).
  • cargo fmt --all -- --check: clean.

🤖 Generated with Claude Code

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-13T18:42:57.057933Z 53708e3 New commits
ℹ️ About Codex in GitHub

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

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

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

@qbit-reviewer qbit-reviewer Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved: a complete review with no bugs found.

No findings.

Reviewed by Claude Opus 5.5.

…#842's median gate measures it (3.x.x is red since #847 and #854 both landed)

## Problem

`3.x.x` is red since #847 and #854 both landed (CI run 43456385763 on 3d48a8f): "Rust tests" and "Rust PRISM PostgreSQL and multi-instance contracts (shard 3)" fail in `qbit-prism-load --test collate`, and every PR that takes the base in fails the same way.

```
test a_report_only_points_failed_budgets_are_shown_but_never_fail_the_suite ... FAILED
test a_report_only_run_sets_aside_only_its_commit_deadlines_refusals ... FAILED
test a_report_only_run_that_did_not_reconcile_fails_the_suite ... FAILED
```

Each PR was green on its own base. Together they are not:

- #854 gave `mainnet-shape-650-addresses` a median gate (`tip_last_notify_median_budget_ms: 3000`, #842). A median is only measured when the report says how many tips its phases planned (`external_tips_planned`), so a run that lost tips cannot pass on the ones it kept.
- #847 added tests that use that preset as the gated run beside a report-only point. Their synthetic report has one tip and no `external_tips_planned`, so the collation now reports the gated run as

  `tip to last session's notify, median over tips (unmeasured: phase warm_up does not record its planned tips (external_tips_planned))`

  and fails a suite the tests expect to pass.

It is a test-fixture gap, not a defect in the gate or the collation: a report without the key is rightly unmeasured.

## Change

`crates/qbit-prism-load/tests/collate.rs`: the synthetic report's first phase records the one tip the report holds (`external_tips_planned: 1`), and the other phases record none. The report now says what a current harness says, and the median gate measures its one tip (600 ms against 3,000 ms).

No code outside the test changes.

## Tests

- `cargo test --locked -p qbit-prism-load --test collate`: 14 passed, 0 failed (on 3d48a8f without this change, CI has the three above failing).
- `cargo fmt --all -- --check`: clean.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Squashed commits:
32c308d 3.x.x: the collate tests' synthetic report records its planned tip, so #842's median gate on the 650-address preset measures it

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@kiwidream
kiwidream force-pushed the orca/collate-tests-planned-tips branch from 32c308d to 53708e3 Compare November 13, 2026 18:41
@kiwidream
kiwidream merged commit 234ff1c into 3.x.x Nov 13, 2026
46 checks passed
kiwidream added a commit that referenced this pull request Nov 13, 2026
…ke in the landed 3.1.2 PRs and the collate test fix (#874)

Co-Authored-By: Claude Fable 5.2 <[email protected]>
kiwidream added a commit that referenced this pull request Nov 13, 2026
…landed 3.1.2 PRs and the collate test fix (#874)

Co-Authored-By: Claude Fable 5.2 <[email protected]>
kiwidream added a commit that referenced this pull request Nov 13, 2026
… in the landed 3.1.2 PRs and the collate test fix (#874)

Co-Authored-By: Claude Fable 5.2 <[email protected]>
kiwidream added a commit that referenced this pull request Nov 13, 2026
…3.1.2 PRs and the collate test fix (#874)

Co-Authored-By: Claude Fable 5.2 <[email protected]>
kiwidream added a commit that referenced this pull request Nov 13, 2026
…anded 3.1.2 PRs and the collate test fix (#874)

Co-Authored-By: Claude Fable 5.2 <[email protected]>
kiwidream added a commit that referenced this pull request Nov 13, 2026
…anded 3.1.2 PRs and the collate test fix (#874)

Co-Authored-By: Claude Fable 5.2 <[email protected]>
kiwidream added a commit that referenced this pull request Nov 13, 2026
…nded 3.1.2 PRs and the collate test fix (#874)

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

@qbit-reviewer qbit-reviewer Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved: a complete review with no bugs found.

No findings.

Reviewed by Claude Opus 5.5.

kiwidream added a commit that referenced this pull request Nov 13, 2026
…d the load harness's side report carries every gate (#817)

## Problem

#817 found two low-severity gaps in the review of #811:

1. The required lint job didn't run `scripts/generate_prism_alerts.py --check`, or `scripts/generate_prism_metrics.py --check`. On closer reading, both checks *do* run in CI already: the Rust observability tests (`crates/qbit-prism-server/tests/observability/inventory.rs`, `inventory_is_generated_from_registry` and `migration_covers_every_deployed_alert_and_all_46_historical_names`) shell out to them in `rust-tests`. A stale artifact therefore did fail CI, but only after a full Rust test build, and under an unrelated test name.
2. `load-harness-report.json`'s `preset.gates` was a hand-copied subset of the preset's `Gates`. It left out `tip_last_notify_median_budget_ms`, `churn_tip_last_notify_p99_budget_ms` and `new_session_first_job_p99_budget_ms`. A real-node-smoke report showed only `tip_last_notify_p99_budget_ms: 10000`, which reads as a 10 s gate. The gate's verdicts were correct, because they rebuild the budgets from the preset.

## Change

- **`.github/workflows/ci.yml`:** `lint-compile-compose` runs both generators' `--check` beside the alert UID check. A stale generated artifact now fails in seconds, under its own step name, in the job that already owns the alert checks.
- **`tests/test_prism_generated_artifact_checks.py`** pins:
  - both steps in `lint-compile-compose`, not commented out, with no `if:` on the step and no `continue-on-error` on the step or the job;
  - no `if:` on the job other than the same-tree skip (#839), which skips it only for a merge tree that already passed;
  - `lint-compile-compose` in the `needs` of the required aggregate check `Lint, compile, and test`;
  - that each `--check` refuses a hand-edited output, on a temp copy of exactly the files each generator reads: the migration tables, a reformatted rule file (each of the two), an edited rule value (via the patch's specification digest), and the metric inventory.
- **`crates/qbit-prism-load`:** `preset::Gates` derives `Serialize`, and the side report writes the whole struct (`run::preset_report`), so a gate key can't be left out again. Unit tests:
  - check that the report's block parses back (unknown keys refused) to the same `Gates`, with every gate set to a non-default value;
  - check that a preset with no optional gates reports the same keys, each ungated one as `null`.
  - Both tests fail against the old hand-copied subset.

Ungated keys now appear as `null` in the report. The side report's readers (compare, collate, A/B and `scripts/prism_load_probe.py`) read only `preset.name`, `preset.sha256` and `preset.gates.phases`, which are unchanged.

## Tests run (minidev, on 00001ae)

- `python3 scripts/generate_prism_alerts.py --check` and `python3 scripts/generate_prism_metrics.py --check`: exit 0 on the base tree and on this branch.
- `python3 scripts/check_prism_alert_uids.py`: OK.
- `python3 -m unittest tests.test_prism_generated_artifact_checks tests.test_check_prism_alert_uids`: OK.
  - The workflow pin also fails as it should when a step is commented out, when a step or the job gets `continue-on-error: true`, and when the job is dropped from the aggregate's `needs`.
- `cargo test --locked -p qbit-prism-load --lib`: 58 passed.
- `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.

## CI must cover

The full Python shards and `rust-tests`, including the observability inventory tests that also run both generators. Nothing PostgreSQL-gated was added.

## Left open (outside this PR's scope)

- Without `--snapshot`, `generate_prism_alerts.py --check` checks only that the qbit-tools patch contains the current specification digest, not the patch body. A hand edit to a `+` line that keeps the digest line passes. The step name says what is actually checked.
- That digest check is a bare `assert`, which `PYTHONOPTIMIZE` strips. CI doesn't set it.
- Dispatch overrides of the gate's budgets (`PRISM_LOAD_MAX_SHORTFALL`, `PRISM_LOAD_TIP_LAST_NOTIFY_P99_BUDGET_MS`) reach only the gate binary, so the side report shows the preset file's gates, and gate.md's Budget column shows what was applied. `preset_report`'s doc comment says so.

Refs #817

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Squashed commits:
7cb26dc 3.x.x: the lint job runs the alert and metric generators' --check, and the load harness's side report carries every gate (#817)
e68ecac Merge 3.x.x (3d48a8f) into the #817 branch: the side report keeps preset_report, and its tests name #842's churn median gate
5748aac Merge 3.x.x (234ff1c) into orca/817-alerts-check-and-report-gates: take in the landed 3.1.2 PRs and the collate test fix (#874)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
kiwidream added a commit that referenced this pull request Nov 13, 2026
## 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]>
kiwidream added a commit that referenced this pull request Nov 13, 2026
… set of node calls for a few seconds (#858)

## Problem

`network()` (`crates/qbit-prism-server/src/api/public.rs`) asks the node for `getblockchaininfo`, then `getblocktemplate` and `getnetworkinfo`, on every cache miss of the pool summary, the reward leaderboard and every miner page. Miner pages are cached per miner, so template requests grow with the number of distinct miners viewed, on the node that also serves the mining path's templates (#858).

Checked against the code at the base: as the issue says, all three callers call `network()` first on a miss, and every one of them discarded its second return value (the raw template).

## Change

- `network()`'s answer is remembered in the process and shared by the three routes, through the response cache's own slot (`response_cache::CacheSlot`, now generic over what it holds). No second cache implementation.
- **Single flight:** one set of node calls at a time. Every miss that arrives meanwhile waits for it.
- **Lifetime:** the shortest public cache lifetime and staleness budget among the three routes, from each route's own `CachePolicy` (default and aggregate TTLs) and `staleness_budget` (the leaderboard's 15 s caps it). That is 5 s by default and 15 s at most. It is read from the configuration the request is served with. It is zero, so every call asks the node as before, when the public cache is off or any of those TTLs is zero.
- **How stale:** a response that reads a remembered answer is dated and cached as before, from when the response was built. The answer's own age is input staleness that the response's `Age` does not count, as with the read replica's lag. It is less than the lifetime: the lifetime counts from when the answer's node calls started, before `getblockchaininfo` was asked, not from when they ended, so a slow `getblocktemplate` cannot stretch it. An answer whose calls took longer than the lifetime has expired by the time it arrives: it answers only the requests that waited for it, and the next miss asks the node again. Route entries keep their dating, from when the response was built. I tried dating route entries from the memo instead, in local review. It shrank the 5 s routes' HIT windows and let fresh MISS responses exceed their staleness budget, where they were counted as refusals, so I dropped it. As a consequence, a pool-summary response can pair a remembered `network.height`/`tip_hash` with a fresher `pool.latest_block` read from PostgreSQL, for up to the lifetime.
- **Failures are not remembered.** A failed `getblockchaininfo` (or no usable compact bits) fails the requests that waited for it, and the next miss asks again.
- **Degraded answers are not remembered either.** An answer may still fall back, as before, on any field: the chain's bits when the template failed or had no usable bits, zero peers, a zero height or tip, a default chain name or IBD flag. Such an answer goes only to the requests that waited for it, and the next miss asks the node again. So a failed call's fallback `network_difficulty` or `peers: 0` never reaches a later miss through the memo. It does reach every miss that joined that one flight, on any of the three routes, and each of those responses is then cached by its route for its TTL plus stale-while-revalidate, as any response is (pool summary 30 s + 30 s, miner pages 5 s + 30 s by default). Before #858 each of those misses made its own calls, and most would have succeeded. A route response built on a degraded answer stays cacheable, as before: making it uncacheable would turn a node hiccup into uncached database load.
- **Shared failure:** a miss that joins a call in flight shares its outcome, a failure included. That includes a miss that arrives late in a call that then times out, which before #858 would have made its own call. This is what single flight costs here. It is bounded by the flight's own deadline (below), each call within it by the node client's 10 s per-call timeout and its idle-connection handling (#759).
- **Deadlines:** a waiter keeps its own request deadline (`PRISM_PUBLIC_READ_STATEMENT_TIMEOUT_SECONDS`) and gets its `read_timeout` when that passes. The node calls run on a spawned task, so a waiter giving up, its client gone, does not cancel them: they finish and are remembered for the next request. The set of calls has a deadline of its own: the same public read timeout, counted from when the set started. A set past it fails with `read_timeout`, is dropped with its calls, is not remembered, and clears, so the next miss asks the node again instead of joining a stalled set. The request that started a set has a deadline no later than the set's, so the set's deadline never cuts short a request it could still have answered. Without it, a set was bounded only by two node timeouts in a row, about 20 s. With the read timeout at 0 (no whole-request deadline), only the node client's per-call timeout bounds it.
- **Ordering:** flights never overlap. The next one starts only after the previous one has written its result and cleared itself, so a slow earlier call cannot replace a newer answer.
- **Panics:** a computation that panics now fails its waiters with a 500 and clears its flight, instead of poisoning the slot. This applies to route responses too, where it used to leave that route's slot poisoned until eviction. The memo is a single process-wide slot, so this matters more there.
- **Return type:** `network()` now returns only the network object, because no caller used the template.
- **Unchanged:** the response bodies, and `public_response`'s behaviour apart from the panic case above. The refactor moves its flight into `CacheSlot::flight` and the cacheability test into one `cacheable` fn. The STALE path no longer spawns a second task to drive a flight that already has its own driver.

## Tests run

All cargo commands ran through the host gate with `CARGO_PROFILE_DEV_DEBUG=line-tables-only`.

- `cargo test --offline --locked -p qbit-prism-server --lib -- api::response_cache api::public::`: 18 passed, the four route-cache tests in `response_cache` unchanged. The new ones, all but the last four against a counting fake node over HTTP:
  - `concurrent_misses_wait_for_one_set_of_node_calls`
  - `a_failed_call_is_not_remembered`
  - `a_degraded_answer_is_not_remembered`
  - `a_waiter_times_out_by_its_own_deadline_and_a_set_past_it_is_not_remembered`
  - `a_waiter_that_gives_up_leaves_the_shared_calls_running`
  - `the_remembered_answer_expires_and_a_slow_call_is_never_overtaken`
  - `a_zero_lifetime_asks_the_node_every_time`
  - `the_lifetime_follows_the_configuration_a_state_serves_with`
  - `the_memo_lives_as_long_as_the_shortest_lifetime_of_its_routes` (no node)
  - `a_computation_that_panics_fails_and_leaves_nothing_in_flight` (response_cache, no node)
  - `a_stalled_set_of_calls_fails_at_the_read_timeout_and_the_next_miss_asks_again` (paused time, a socket-free node fake): a set stalls, the node recovers 1 s in, a miss 2 s in joins the stalled set; both fail with `read_timeout` at the set's 4 s deadline, not the node client's 10 s, the stalled calls are dropped, and the next miss asks the recovered node and is remembered.
  - `without_a_read_timeout_a_stalled_set_ends_at_the_node_clients_timeout` (paused time)
  - `an_answer_is_dated_from_when_its_calls_started`: with a 1 s lifetime, a set that took 1.1 s answers only its own request and the next miss asks again.
  - With the memo dated from its flight's end, or with no flight deadline, four of these fail (checked by reverting each fix locally).
- `PRISM_TEST_PG_BIN_DIR=/usr/lib/postgresql/16/bin test/prism-native-tests.sh cargo-args --offline -p qbit-prism-server --test api_2x -- concurrent_pool block_views public_service`: 3 passed, all recorded `executed` in the gate manifest.
  - The new test is `concurrent_pool_leaderboard_and_miner_misses_ask_the_node_for_one_template`. It sends seven concurrent misses (pool summary, two reward-leaderboard queries and four miner pages) against a counting node that holds `getblockchaininfo`. While they are held, all seven are still waiting and the node has seen one call. Once released, the node has seen exactly one `getblockchaininfo`, one `getblocktemplate` and one `getnetworkinfo`. The pool summary's `network` object equals the one an uncached state computes from the same node.
  - A later miss on another miner page reads the remembered answer without asking the node.
  - It is listed in `test/prism-gated-tests.txt`.
- `cargo fmt --all -- --check`: clean.
- `cargo clippy --offline --locked -p qbit-prism-server --all-targets -- -D warnings`: clean, apart from the three known vendored sqlx-core warnings.
- `python3 scripts/check_prism_pool_acquires.py`: passes. The change adds no database acquire sites.

- Local review: four `/code-review xhigh` rounds in an Opus 5.5 subagent. Its findings are fixed or listed above as decisions.
- Follow-up (memo dating, flight deadline, docs): two more `/code-review xhigh` rounds in an Opus 5.5 subagent. Fixed: a warning log when a set's deadline fires, test names and comments that claimed more than they showed, the README's worked example, an `ApiState` clone on every memo hit, a real-time assertion that could flake. Left as decided: slow sets (longer than the lifetime) are not usefully remembered; a set slower than the read timeout fails every request, as each request's own calls did before; with the default 20 s read timeout the deadline rarely fires before the node client's per-call timeouts; `read_timeout` is the code a set past its deadline answers.
- `cargo clippy --offline --locked -p qbit-prism-server --all-targets -- -D warnings` and `python3 scripts/check_prism_pool_acquires.py` on the follow-up: clean.

## Docs

`docs/public-dashboard-api/README.md`, "Staleness": the `network` object, and what its `network_difficulty` sizes (the pool summary's `reward_window` and `expected_time_to_block_seconds`, the reward leaderboard's window and rows, a miner page's `estimated_next_block` and `reward_window_percent`), can be older than the response's `Age` (and its build time) by up to the memo's lifetime, 5 s by default and 15 s at most, counted from when its node calls started. A response that waited for a set of node calls already running carries, in place of the lifetime, however long that set had been running when it joined: under 20 s, two node calls of at most 10 s each in a row. `network.hashrate_ths` is read afresh by every response.

## What CI must cover

The rest of the lib suite and the PostgreSQL-gated suites, in particular `api_2x`, `api_contract`, `api_database` and `artifact_admission`, which samples pool summaries through a cache-off view of a cached state.

Refs #858

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Squashed commits:
27d1384 3.x.x: the pool summary, reward leaderboard and miner pages share one set of node calls for a few seconds (#858)
e36aaaf 3.x.x: network() memo is dated from when its node calls started and its calls have the read timeout as a deadline (#858)
67eabf1 3.x.x: the memo's staleness docs cover a response that waited for a running set of node calls (#858)
089dff9 Merge 3.x.x (fa8ac84) into orca/858-network-memo: take in the PostgreSQL 16.15 service pin (#866)
77327cd Merge 3.x.x (234ff1c) into orca/858-network-memo: take in the landed 3.1.2 PRs and the collate test fix (#874)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
kiwidream added a commit that referenced this pull request Nov 13, 2026
#861)

## Problem

For each new job, each session built its own `serde_json::Value` for `mining.notify` (`Job::notify()` in `codec.rs`) and `write_json` serialised it: `coinb1`, `coinb2` and the hex merkle branch were copied into the value and copied again into the bytes, per session per job. `coinb2` carries the payout outputs, so at the 2,600-address shape that is a 225 KB message rebuilt 2,000 times per tip, on the runtime threads that also turn share appends around.

## Premise, checked against the code

Within one publication only the job ID and `clean_jobs` differ between sessions' notifies:
- `announce_job` announces only jobs from `prepare_job` → `Coordinator::build_job` → `materialize_wire`, which hands every session `prepared.base_wire.clone()` (built once by `shared_base_wire`, with a placeholder extranonce1 that `coinb1`/`coinb2` exclude), then `reassign`, which changes the job ID, extranonce1 and share target only. Jobs restored by `resume_job` are never announced.
- `announce_job` sets `clean_jobs` per session. The version mask (`mining.set_version_mask`) and the share difficulty (`mining.set_difficulty`) travel in their own messages; extranonce1 in the subscribe answer.
- One exception: before the first share (an empty window, no `base_wire`), each worker's coinbase is its own. Those sessions render their own body, as before.

## Change

`codec::NotifyBodies` (kept in `StratumConfig::notify_bodies`, shared by both listeners) renders the shared part of the params array once, `,prevhash,coinb1,coinb2,[branch],version,nbits,ntime,`, with serde_json itself, and each session's line is the constant head, its job ID serialised by serde_json, that body, `true`/`false`, `]}` and the newline, written with one `write_all` under the same send timeout as before.

- **Same bytes.** `id` < `method` < `params` is both the `BTreeMap` order and the insertion order (`preserve_order` is enabled nowhere), the strings go through the same serde_json escaping, and there are no numbers (`arbitrary_precision` does not apply). `Job::notify()` is unchanged and is the tests' reference.
- **A body belongs to its work.** A kept body is reused only for a job whose `coinb1` and `coinb2` are the very same allocations (the cache holds them, so their addresses cannot be reused while it keeps the body) and whose prevhash, merkle branch, version, bits and time are equal: every field the body holds.
- **Bounded.** The eight most recently used bodies. The cache keeps up to eight superseded works' coinbase halves (`coinb1`/`coinb2`, the allocations it compares by address) and their rendered bodies alive, about 3.6 MB at the 2,600-output shape, until eight newer works evict them; it is not cleared when idle, so the resident floor after a landing (`landing_malloc_trim_resident_bytes`) can be up to that much higher. Sessions that miss together at the start of a fan-out may each render it (at most one per runtime worker); the first kept is used.

## Measurement (2,000 sessions, single-threaded, `tests/perf/notify_render_fan_out.md`)

Optimised (`opt-level=3` for this crate, `serde_json` and `hex`; AMD Ryzen 9 9955HX, shared host):

| coinbase | message | before: fastest / median | after: fastest / median | before: allocations, bytes | after: allocations, bytes |
| --- | --- | --- | --- | --- | --- |
| 130 outputs | 12,405 bytes | 9.8 / 9.8 ms | 0.2 / 0.2 ms | 94,000, 100.5 MB | 2,025, 24.9 MB |
| 2,600 outputs | 224,829 bytes | 104.4 / 104.6 ms | 3.3 / 3.3 ms | 94,000, 1,799.9 MB | 2,025, 450.6 MB |

Unoptimised (CI's test build): 313 → 1.8 ms and 5,157 → 7.6 ms. The remaining cost is one copy of the body into each session's line, kept so the line is still one write.

## Load runs (`run-load`, two samples on b7adeaf) next to the scheduled nightlies

All presets passed their gates in both samples. Tip delivery is `tip-delivery-2000-miners-400k-2fe-retarget` (8 external tips, all in warm-up). The two nightlies are the ones whose artifacts are still available. Controls first: each frontend's initial-refresh `snapshot_ms` (VM speed over the same seeded window, #842), `pg_test_fsync` fdatasync (one 8 kB write), and client share-ack in the tip-free phases.

| run | commit | initial `snapshot_ms` fe0 / fe1 | fdatasync | share-ack p50 steady / reconnect | tip-to-last-notify median / slowest | refresh median / slowest | **fan-out after the refresh, median / slowest** | client share-ack p99 warm-up / steady |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| nightly 42994888106 (11-11) | 47ad4e1 | 7,250 / 6,519 | 75.0k ops/s | 1.03 / 0.80 ms | 571 / 632 ms | 440 / 483 ms | **129 / 174 ms** | 2.53 / 1.87 ms |
| nightly 43194821373 (11-12) | 3a23df9 | 8,084 / 8,517 | 69.0k ops/s | 0.68 / 0.84 ms | 675 / 704 ms | 486 / 552 ms | **160 / 194 ms** | 2.39 / 1.36 ms |
| this PR, sample 1 (43334915761) | b7adeaf | 7,224 / 7,363 | 50.4k ops/s | 1.09 / 1.21 ms | 883 / 1,312 ms | 609 / 1,136 ms | **216 / 291 ms** | 8.36 / 1.92 ms |
| this PR, sample 2 (43337976535) | b7adeaf | 8,325 / 7,674 | 65.0k ops/s | 1.00 / 1.35 ms | 614 / 934 ms | 442 / 670 ms | **161 / 305 ms** | 5.19 / 1.72 ms |

"Fan-out after the refresh" is each tip's per-frontend last-notify latency minus that frontend's `refresh_ms` for the tip (its `refresh published trigger="tip"` log line, which starts at the tip's mint): job build, issued-job persistence and the `set_difficulty`/`notify` writes, 16 values per run.

Per tip (fan-out after the refresh, fe0 / fe1, ms; refresh in brackets):

| tip | nightly 11-11 | nightly 11-12 | PR sample 1 | PR sample 2 |
| --- | --- | --- | --- | --- |
| h101 | 155 / 135 (444, 483) | 152 / 178 (552, 480) | 202 / 205 (506, 470) | 305 / 305 (618, 629) |
| h102 | 129 / 115 (405, 456) | 181 / 155 (478, 524) | 223 / 222 (486, 474) | 260 / 239 (605, 645) |
| h103 | 129 / 118 (440, 463) | 192 / 177 (496, 526) | 222 / 210 (528, 560) | 220 / 265 (670, 587) |
| h104 | 130 / 128 (425, 426) | 159 / 120 (464, 551) | 196 / 226 (543, 481) | 157 / 166 (456, 429) |
| h105 | 115 / 122 (438, 411) | 162 / 149 (461, 483) | 246 / 291 (750, 658) | 150 / 166 (465, 424) |
| h106 | 112 / 136 (440, 394) | 154 / 140 (450, 489) | 198 / 243 (1,000, 833) | 125 / 114 (348, 372) |
| h107 | 131 / 124 (432, 447) | 173 / 194 (508, 464) | 176 / 233 (1,136, 894) | 111 / 116 (379, 345) |
| h108 | 166 / 174 (466, 450) | 149 / 179 (505, 457) | 166 / 210 (1,048, 872) | 129 / 126 (365, 374) |

Reading it:
- **Sample 2 ran on a VM about as fast as the nightlies' by database speed.** fsync was 65.0k ops/s against 69.0k and 75.0k, and the initial snapshot matched 11-12's. Share-ack p50 was 1.00 / 1.35 ms in the tip-free phases, against 0.68–1.03 / 0.80–0.84.
- **On that VM the post-refresh fan-out is inside the nightlies' range: a 161 ms median against 129 and 160 ms.**
- **Tips 1–3 of sample 2 are the exception: 220–305 ms, above every nightly tip.** The refresh before them was also the slowest of any run's first tips (587–670 ms against 405–552), so both halves slowed together early in that run. Its last five tips, 111–166 ms, are as fast as or faster than either nightly's.
- **Sample 1 ran on a slower-disk VM: fsync 50.4k, share-ack p50 about 1.5× the nightlies'.** Its fan-out (216 ms) and, from tip 5, its refresh (up to 1,136 ms) were slow together; the refresh is a database read that this change does not touch.
- **The load runs are inconclusive at this sample size.** Two samples against two nightlies on different VMs can neither show nor exclude an effect of about 50 ms in either direction, and the slowest post-refresh fan-out in both PR samples (291 and 305 ms) is above both nightlies' (174 and 194 ms).
- **The conclusion rests on the mechanism, not on these runs.** Per session the change does strictly less work (one scan of at most eight kept bodies under the lock and one copy of the body, instead of building a `Value` tree and serialising it) and adds no await and no I/O. The per-session CPU it removes (about 5–50 µs per session by the measurement above) is smaller than the spread between runs of this preset, so no gain is measurable here either.

## Tests

New, `crates/qbit-prism-server/tests/notify_render.rs`:
- `every_session_gets_exactly_the_bytes_it_serialised_for_itself`: byte-for-byte against `notify()` serialised, over 1, 130 and 2,600 recipients, no merkle branch and a 12-level one, both `clean_jobs` values, job IDs at their limit (128-byte `PRISM_INSTANCE_ID` plus a UUID, 161 bytes) and at 256 bytes, and instance IDs with quotes, backslashes, slashes, multi-byte characters and U+2028.
- `a_body_belongs_to_the_work_it_was_rendered_from`: a second session of a work reuses the body (exactly one allocation, its line; mutation-checked), while equal coinbase text in another allocation and a change to each field the body holds, one at a time, each render their own, with the right bytes; eviction past eight works.
- `fan_out_cost_before_and_after` (`#[ignore]`d): the measurement above.

Run locally (through the host gate, `CARGO_PROFILE_DEV_DEBUG=line-tables-only`):
- `cargo test -p qbit-prism-server --test notify_render`: 2 passed, 1 ignored (the measurement, run separately with `-- --ignored --nocapture` as above). Mutation check: with `renders()` always false, `a_body_belongs_to_the_work_it_was_rendered_from` fails.
- `cargo test -p qbit-prism-server --test stratum_protocol`: 50 passed, 1 ignored (manual inspection).
- `cargo test -p qbit-prism-server --test stratum_properties`: 8 passed.
- `PRISM_TEST_PG_BIN_DIR=/usr/lib/postgresql/16/bin cargo test -p qbit-prism-server --lib -- stratum:: codec:: --test-threads=4` (private PostgreSQL 16 clusters): 31 passed.
- `cargo fmt --all -- --check`, `cargo clippy --locked -p qbit-prism-server --all-targets -- -D warnings`: clean (apart from the three known vendored sqlx-core warnings).
- `python3 scripts/check_prism_pool_acquires.py`: pass (no database site added).

## What CI must cover

The full lib suite and the other Stratum binaries (`stratum_rebuild_lane`, `vardiff_convergence`, `landing_metrics`, the fuzz build), which all read notifies off the wire.

Refs #861

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Squashed commits:
b7adeaf 3.x.x: render the shared part of mining.notify once per published work (#861)
396e323 Merge 3.x.x (fa8ac84) into orca/861-notify-render-once: take in the PostgreSQL 16.15 service pin (#866)
b54f138 Merge 3.x.x (234ff1c) into orca/861-notify-render-once: take in the landed 3.1.2 PRs and the collate test fix (#874)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
kiwidream added a commit that referenced this pull request Nov 13, 2026
…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]>
kiwidream added a commit that referenced this pull request Nov 13, 2026
… nobody serves (#857)

## Problem

The public dashboard queries run on the read pool on every cache miss, and several of them do work that nobody reads, or that the rollups and existing indexes already hold (#857). The issue's findings came from a code read. Each one was checked here against real plans and timings, and old and new SQL were compared on the same data.

## Measurements

Seeded data: 200,000 shares over 25 h from 500 miners, a 50,000-share reward window (difficulty 6,250,000,000), 5,000 blocks, rollups current. Each figure is the median of five `EXPLAIN ANALYZE` runs of the prepared statement, on PostgreSQL 16 on a shared dev host.

| Query (per cache miss) | 3.1.1 | Now | Ledger rows read |
| --- | --- | --- | --- |
| Miner page share summary | 4.83 ms | 0.22 ms | 24,774 → 783 |
| Miner page reward share | 93.8 ms | 58.5 ms | 106,496 → 106,496 (the window itself) |
| Pool summary snapshot + sums | 143.4 ms | 52.0 + 7.5 ms | 298,485 → 106,496 + 865 |
| Blocks page, `active`, 15 rows | 3.81 ms | 0.97 ms | none |

## Each finding

1. **Miner page: whole-pool 3-hour sum. Changed.** `pool_h3_difficulty` from `dashboard_miner_share_summary.sql` was read by nothing: `miner()` never reads it, it is not in any response, and nothing else in the repo reads it. The `pool` CTE and the key are dropped.

2. **Miner page: whole reward window grouped for one miner. Changed.** `miner()` reads three figures from `reward_leaderboard(…, Some(id))`: the miner's row's `share_percent` (null without a row), its `counted_share_difficulty`, and the window's `counted_window_weight`. The new `dashboard_miner_reward_share.sql` computes exactly those in one aggregate over the same `qbit_prism_window` rows, with the same numeric expressions. It skips grouping and ranking every miner and attributing blocks to them. Materialising the window is unavoidable, because the share is a fraction of the whole window's counted weight. So the saving is the per-miner work, about a third here. The leaderboard route itself is unchanged.

3. **Pool snapshot (`dashboard_pool_snapshot.sql`).**
   - **24 hours of raw shares. Changed**, following the chart rollups (`dashboard_hashrate_rollups.sql`). The sums now come from the new `dashboard_pool_hashrate_rollups.sql`, and the 3-hour participants from the miner rollups' `UNION` with the raw parts. For each window `[ended_at − span, ended_at]`, the query reads:
     - the 5-minute rollups for whole buckets before the current one;
     - raw shares at or below the watermark in the window's two partial buckets (its leading slice, and the current bucket up to `ended_at`);
     - raw shares past the watermark.

     The three spans are whole multiples of 5 minutes, so they share one current slice.
     - **No watermark, or a stale one:** when there is no watermark row, or the share at the watermark is older than the 24 hours (rollups disabled, stalled or still backfilling), the query reads the 24 hours' raw range instead. So a lagging watermark never turns the tail into a walk longer than the range it saves, at any share rate. Unlike the charts, which walk everything past their watermark.
     - **No rollup schema:** a database without it (a public replica may lack it) runs the old raw scan, now `dashboard_pool_hashrate.sql`, chosen as the charts choose.
     - **Separate statement:** the sums are read by `read_models::pool_hashrate_sums`, apart from the snapshot. Each takes its own `clock_timestamp()` and snapshot, milliseconds apart: the same answer on the same data, while under concurrent writes the two groups of fields can be milliseconds apart. That adds a `to_regclass` check and a pool acquisition per miss, as the charts have.
   - **Four `count(*)` over the blocks. Changed** to one pass with `FILTER`.
   - **`total_mined_bits` over all carry-forward history. Left alone.** No rollup or counter holds the total. An exact one needs a new table or trigger, which means a migration, and this change has none.

4. **Blocks page (`dashboard_blocks.sql`). Changed.**
   - **The rewrite:** the `public_blocks` CTE (`block.*`, referenced twice, so materialised over every block) and its `CASE` filter are gone. The page filters on plain columns, one `UNION ALL` branch per filter, each behind a one-time test of `$3`.
   - **Why it now uses the index:** the `active` branch's own predicate (`chain_state = 'confirmed'`) implies the index's (`chain_state <> 'reversed'`). So an `active` page is an ordered read of `qbit_pool_blocks_public_recent_idx` that stops at its page, under custom and generic plans alike. A single `$3`-dependent `OR` would keep generic plans off the index.
   - **Why `reversed` and `all` don't:** they include reversed rows, which the partial index excludes, so they still scan. The total count still counts the matching blocks.

## Same responses on the same data

`dashboard_queries_answer_what_their_3_1_1_queries_answer` (tests/api_2x.rs) runs the 3.1.1 SQL, kept verbatim as test fixtures under `tests/fixtures/dashboard_queries_3_1_1/`, and the new SQL on the same data, and compares the JSON.

**The clock:** every comparison runs on a pool whose sessions resolve `clock_timestamp()`, the only clock either side reads, to a function in a test schema placed before `pg_catalog` in their `search_path`. It is pinned at one fixed instant, 150 s into its 5-minute bucket and weeks before the wall clock. The phases the rollups can serve are compared at that instant and four more: bucket-aligned (every window's leading slice empty), a second into the bucket, its last second and a fractional one. The test asserts which path each phase reads: the rollups after they advance, at every instant, and the raw 24 hours before that and with the watermark a day behind. So the old and new statements answer at one instant, every window's first bucket is partial at the pinned instant, the shares placed on the exact 24-hour, 3-hour, 1-hour and bucket edges are on the edges they read on every run, no mismatch is retried, and a statement that read the real clock would fail every run.

### What can differ from 3.1.1

- **Shares younger than 24 hours that a detach removed.** `share-archive detach --retention-days 0`, on a network whose payout window is under a day of shares (signet, regtest), can detach a partition holding shares less than 24 hours old. 3.1.1's raw scan stopped counting them. The new sums keep counting them through the 5-minute rollups for whole buckets, as the hashrate charts already do; the partial buckets, read raw, drop them. Until the rollup sweep moves the watermark past the detached partition's newest share, the readiness check can find no attached share at or below it and read the raw 24 hours instead, which drops them too; the next sweep brings them back. So `h24` (and in the extreme `h3`, `h1` and `participants_3h`) can differ from 3.1.1 on the same database, and agree with the charts. Accepted. With any retention of a day or more a detached partition holds no share younger than 24 hours, so this cannot happen. `docs/prism-share-ledger-partitioning.md`'s reader inventory states it.
- **Concurrent writes:** the snapshot and the sums are separate statements, milliseconds apart (above).

**The data:**

- an empty database;
- shares on both sides of every window start and 5-minute bucket edge, others spread over 26 h, and one in the future;
- a miner with one share, and a miner with none;
- blocks in every chain state, including a reversed one, a disconnected-but-published one (public `reversed`), and two at one height;
- miners that tell the 3-hour participants from the 24-hour ones:
  - eve only older than 3 hours, in a whole bucket, just before the window and past the watermark;
  - frank, grace and henry only in the current, 3-hour or 24-hour partial slice;
- each with no rollup progress, with the rollups current, with shares past the watermark (in the current bucket, in each window's partial bucket, in an already rolled bucket, and from a miner the rollups have never seen), and with the watermark set a day behind while the rollups hold more than it.

Mutation checks:

- Four deliberate bugs in the participants CTE each fail the test:
  - the rollup bound widened to 24 hours;
  - the slice list widened;
  - the boundary branch dropped;
  - the tail time filter dropped.
- Reverting the watermark-age rule fails both the equivalence test and the plan test.
- Making the 24-hour slice's lower bound exclusive (`>` for `>=`) in `dashboard_pool_hashrate_rollups.sql` fails the equivalence test, which only a share on the exact window start can show. So does making the whole buckets' lower bound exclusive. Both fail in the "current watermark" phase, where the rollup path is read. Shares past the watermark sit on each side of every window's start, at the pinned instant and after it, and two miners sit only on either side of the 3-hour start: making the tail's 24-hour bound or its 3-hour participants bound exclusive, or dropping its upper bound, fails the test in the "lagging watermark" phase.

**What it compares:**

- the miner share summary, minus the dropped key, for four miners;
- the reward share at three difficulties, against the 3.1.1 leaderboard's row and totals;
- the pool snapshot plus sums, through both the raw and the rollups SQL, at two difficulties;
- the blocks page for every filter and six pages, including past the end.

The Rust that turns these into the public responses is unchanged, apart from reading the same three figures from the new query in `miner()`.

## Plan assertions

These follow the style of #849 and the chart rollups' plan test.

- `an_active_blocks_page_reads_the_public_recent_index_under_any_plan`: 5,000 blocks, with `force_custom_plan` and `force_generic_plan`, each at `random_page_cost` 4 and 1.1, for three pages. Every plan reads `qbit_pool_blocks_public_recent_idx`, and that read stops at the page.
- `pool_hashrate_sums_read_only_the_partial_buckets_and_the_lag`: 20,000 rolled shares over 25 h, at both page costs, in four states. With the watermark current, then with 300 shares past it, the rollups query reads at most 1,000 ledger rows plus the lag and makes no one-sided ledger scan, while the raw query it replaces reads over 19,000. With the watermark a day behind, and with no progress row, it reads the 24-hour range, no more than the raw scan, again with no one-sided scan.
- Mutation check: pointed at the 3.1.1 SQL, both tests fail.

## Tests run

All cargo commands ran through the host gate with `CARGO_PROFILE_DEV_DEBUG=line-tables-only`, against a private PostgreSQL 16 cluster.

- `PRISM_TEST_PG_BIN_DIR=/usr/lib/postgresql/16/bin test/prism-native-tests.sh cargo-args --offline -p qbit-prism-server --test api_2x --test window_multiplier_invariant`: 12 and 1 passed, the three new tests included.
- After the pinned clock: `PRISM_TEST_PG_BIN_DIR=/usr/lib/postgresql/16/bin test/prism-native-tests.sh cargo-args --offline --locked -p qbit-prism-server --test api_2x -- --test-threads=4 dashboard_queries_answer pool_hashrate_sums an_active_blocks_page`: 3 passed, all recorded `executed`; with either mutation above, the equivalence test fails. `cargo fmt`, `cargo clippy` and the pool-acquire guard as below: clean. The follow-up had two more `/code-review xhigh` rounds in an Opus 5.5 subagent; their findings are fixed (a wall-clock epoch that left the rollup path uncompared at bucket-aligned instants, missing timeouts on the pinned pool, the readiness fallback after a detach).
- The follow-up's last commit (more instants, tail edges, readiness assertions) applies the second review round's own findings and was not reviewed locally again; Codex reviews it.
- The same with `--test api_database --test api_contract -- --test-threads=4`: 3 and 6 passed.
- `cargo test --offline -p qbit-prism-server --lib -- api::`: 43 passed.
- `cargo fmt --all -- --check`: clean.
- `cargo clippy --offline --locked -p qbit-prism-server --all-targets -- -D warnings`: clean, apart from the three known vendored sqlx-core warnings.
- `python3 scripts/check_prism_pool_acquires.py`: passes. The new sites are `miner_reward_share` (1) and `pool_hashrate_sums` (2), both public.
- Local review: two `/code-review xhigh`-level rounds in an Opus 5.5 subagent. Their findings are fixed:
  - the invariant's missing site, which would have turned CI red;
  - test data that couldn't tell the participants' windows apart;
  - a tail walk unbounded without rollup progress or with a stale watermark;
  - tail shares placed by a stale clock.

## Docs

`docs/prism-share-ledger-partitioning.md`'s reader inventory no longer lists `dashboard_pool_snapshot.sql` as an `accepted_at`-range reader. It lists `dashboard_pool_hashrate.sql` with those readers, and `dashboard_pool_hashrate_rollups.sql` in a row of its own, with the detach case above. It merges cleanly with open PR #848, which changes a line further down the same file.

## Not in scope

`OFFSET` pagination and the `strpos(lower(...))` searches, as the issue says.

## What CI must cover

The PostgreSQL-gated suites, `api_2x` in particular, and the lib suite.

Refs #857

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Squashed commits:
1cce087 3.x.x: the miner page, pool summary and blocks page stop reading what nobody serves (#857)
ae57486 3.x.x: the dashboard equivalence test reads one pinned clock, and the partitioning doc lists the pool summary's new readers (#857)
387b570 3.x.x: the dashboard equivalence test pins one fixed mid-bucket instant, and the reader row covers the readiness fallback after a detach (#857)
7987d38 3.x.x: the dashboard equivalence test compares at five clock instants and on every tail edge, and asserts which path it reads (#857)
fb26a94 Merge 3.x.x (fa8ac84) into orca/857-dashboard-queries: take in the PostgreSQL 16.15 service pin (#866)
0cdbb30 Merge 3.x.x (234ff1c) into orca/857-dashboard-queries: take in the landed 3.1.2 PRs and the collate test fix (#874)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
kiwidream added a commit that referenced this pull request Nov 13, 2026
… in the six PRs landed after #874

Co-Authored-By: Claude Fable 5.2 <[email protected]>
kiwidream added a commit that referenced this pull request Nov 13, 2026
…nstead of awaiting it (#856)

## Problem

After an accepted share's acknowledgement (and after announcing a retarget), a Stratum session awaited `remember_difficulty` inline: `remember_worker_difficulty` (the evidence lookup, then the record, or the downward-only lowering) and the `worker_difficulty` read-back, on the shared ledger pool, under one 500 ms timeout. The session reads no request while it awaits, so a slow hint write held up the miner's next `mining.submit` by up to 500 ms, exactly when the pool is busy (#829), and the server's share-ack histogram never saw it.

Checked against the code at `55581716`: the issue's description holds. There were two callers, the accepted-share branch of `request` and the end of `announce_job` (a retarget's hint, the only `downward_only` one). Neither uses the write's result before it carries on, so both now queue the hint instead of awaiting it; nothing else calls it. The record itself is a transaction (`writable` check, upsert, commit), so a hint was up to about seven round trips, not three statements.

## Change

- **Sessions offer, never await.** `session.hints.offer(...)` queues the hint and returns at once. The checks that made a hint a no-op before (resume off, no evidence and not downward) still make it one. `session.last_hint` still limits a session to one hint per 30 s at an unchanged difficulty.
- **One bounded queue and one writer per listener** (`stratum/difficulty_hints.rs`). The queue holds one entry per worker, at most `StratumConfig::difficulty_hint_queue_capacity` (4096; not an environment setting). A hint for another worker when it is full is dropped and counted. The writer is the listener's own task (`beside`): it writes one hint at a time, oldest worker first, so hint writes in progress hold at most one ledger connection per listener instead of one per waiting session. A write that passes its 500 ms bound is the exception: its connection stays busy until PostgreSQL ends the statement (at most the server's `statement_timeout`, 15 s by default) while the writer moves on to the next hint, so a listener whose writes keep timing out can hold several connections at once. That is still fewer than one per waiting session, as before this change.
- **Each hint is written exactly as a session awaited it before** (bar a decrease past its wait bound, below): the same backend call, its own 500 ms bound (`difficulty_hint_timeout_seconds`, default 0.5; tests lengthen it), the evidence-ownership `ensure!` in the backend, the read-back and the retained-difficulty cache update from it, and the `downward_only` path. A queued hint is written against the worker and share it was made for, never against what the session holds later.
- **Coalescing by (listener, worker)**, combining hints into what their separate writes would have left: decreases fold into the lowest on their side of the evidence, and of two pieces of evidence the one this frontend accepted later is kept (by the session's own acceptance time, so a username shared by several sessions keeps its newest evidence whichever offered last). Each remaining step is still its own write, bound and count. Three narrow differences from separate writes remain: if the kept evidence's write fails, the evidence it replaced is not written either; two sessions of one username whose acceptances this frontend orders differently from the ledger keep the other one (the kept evidence is chosen by each session's own `Instant` at acceptance, so under the pool pressure this PR targets the two orders can disagree by tens to hundreds of milliseconds; harmless, since either result is one of that username's live difficulties); and the decrease-age case below.
- **A queued decrease ages out.** A `downward_only` hint carries no share, and `lower_worker_difficulty` lowers any higher row whatever evidence it holds, so a decrease written long after its retarget could pull down evidence another frontend recorded meanwhile (a worker reconnects through the balancer, proves a higher difficulty on the other frontend, then resumes at this frontend's stale lower one). Before this PR such a decrease reached the ledger within its 500 ms write bound; in the queue it could wait tens of seconds when the database is slow (one pass is about workers × per-write time). Now a decrease whose write would start more than `MAX_DECREASE_WAIT` (500 ms) after its offer is not written (checked as its write is about to run), touches neither the row nor the retained-difficulty cache, and counts as `aged_out`. The age is measured on tokio's clock, the one that timed the offer. Why 500 ms: it is one write's own (default) bound, so the time from retarget to the end of its write stays within about a second (500 ms wait plus the 500 ms write bound), against 500 ms when sessions awaited it. A healthy queue waits milliseconds, and a decrease offered during a single write waits at most the rest of that write's bound, even if it times out. The cost is under backlog: behind other entries (a reconnect storm, writes piling up on a slow database) or behind earlier hints in its own entry, decreases that wait longer age out, and the row keeps its older, higher difficulty until the miner's first share at the lowered difficulty records evidence; a miner that reconnects meanwhile resumes higher than this frontend last wanted (still clamped to `startup_difficulty × resume_max_start_factor`) and vardiff lowers it again. Evidence never ages out: the ledger keeps the row with the newer evidence, so late evidence cannot overwrite newer. The ledger's lowering itself still has no evidence guard (not in this pass), so the bound limits the window rather than closing it, as before #856.
- **A folded decrease's age.** The entry holds only the lowest decrease on each side of the evidence, and it keeps the time it was itself offered (the newer one's on a tie), so it ages as it would have alone. A held decrease already past the bound when another is folded into it is replaced by the newer one whatever their values (counted as `aged_out`), which is what their separate writes would have left. The one remaining difference: a held lower decrease, still within the bound when a higher one is folded into it, that passes the bound before the write. Neither is then written, although the higher one alone would have been; the fold errs toward leaving the row as it is, never toward a stale decrease.
- **Refused difficulties are never folded away.** A hint whose difficulty the ledger refuses (not positive and finite) is kept apart from the fold (`f64::min` would keep the other operand of a NaN, and the finite one beside an infinite decrease; newer evidence would replace it) and written after the entry's other hints (so its evidence probe cannot age them), whatever its age, so the fuzz backend's check still sees it; it changes no row (the ledger refuses it, `failed`, or, for evidence whose share it cannot find, records nothing). A second refused hint for the same queued worker is `superseded`. Production never offers one; valid hints beside it are combined exactly as before.
- **Another worker's share is not this worker's evidence.** A session that re-authorizes under another username and then has a share accepted on a job of its earlier one offers its next retarget with that share as the new worker's evidence. The ledger refuses it. Combined as the later-accepted evidence it would have replaced the worker's own queued evidence, and both would be lost, where separate writes lost only the mismatched one (Sixth Man's finding on 9a72501). It goes to the same refused slot: never folded, written last, counted `failed`. The slot holds one hint, and a refused difficulty takes it from another worker's share, so the fuzz backend's check still sees the difficulty.
- **Ordering.** Writes never overlap, so an older write's read-back always reaches the cache before a newer one's; a hint superseded in the queue is never written, so it never reaches the cache.
- **Stops with the listener.** When the listener's work ends, its writer drops what is queued (counted as abandoned), refuses later offers and starts no further write, but lets the write in flight finish within its own bound, as a session's awaited write did, rather than cancel it mid-statement; the rest of that write's entry is abandoned. (An earlier head aborted the writer here: CI's `refresh_liveness::every_session_disconnects_then_new_tip_work_serves_a_new_identity`, which closes its listener right after a share's ack, then caught the cancelled evidence probe still running on the server after its connection was gone. Locally, over 41 runs, the server logged 25 such orphaned statements, 2 deadlocks against the fixture's `DROP SCHEMA` and 1 failure; with this change, 40 runs logged none.) A listener aborted mid-flight (frontend stop, shutdown timeout) still cancels the write in flight through a drop guard, counted as abandoned (it may have committed). A writer that panics closes its queue: what it held, the entry it was writing (whose effect is unknown: it may have committed) and every later offer count as `writer_panicked`, never as a stopping listener's `abandoned`, so an operator can tell "the writer died" from "the listener is stopping". It is logged as an error, naming the listener, and not restarted, so that listener writes no resume hints until the frontend restarts; the listener itself carries on. A connection served on its own through `serve_connection` (fuzz targets, property tests) brings its own writer, which writes what the session queued before `serve_connection` returns and whose panic is the connection's, so the fuzz backend's checks still see every difficulty a session offers that the ledger would refuse (those are never combined or aged out).
- **Observability.** New counter `qbit_prism_stratum_difficulty_hints_total{outcome}`: `written`, `failed`, `timed_out` (effect unknown), `aged_out` (a decrease past its wait bound), `dropped` (queue full), `superseded` (combined into another hint), `abandoned` (listener or connection stopped) and `writer_panicked` (the writer task died). Each offered hint is counted exactly once; a dropped or aged-out hint is distinct from a failed write. Registry help, `docs/prism-metric-metadata.json` and the regenerated `docs/prism-native-metrics.md` describe it; the metrics contract and cardinality tests count the new family (107 families; 328 and 1,012 series). How long hints wait in the queue is not measured; a queue-depth or oldest-hint-age gauge is a follow-up.

Not done: folding the statements into one round trip. The record runs inside a transaction whose `writable` check is a Rust-side check of a row read in that transaction, and the evidence lookup falls back to an unbounded probe; one statement would have to reimplement both in SQL in the ledger. With the write off the session and one writer per listener, the round trips no longer reach the miner. No migration, no new dependency, nothing on the wire changes.

## Tests

New, in-crate (`stratum::difficulty_hint_tests`, no database):
- `a_full_queue_drops_new_workers_and_a_queued_worker_keeps_its_newest_hint_and_place`: the bound holds, the overflow is counted, a queued worker's newer hint replaces its older one in place.
- `an_offer_never_waits_for_a_held_write`
- `hints_for_a_queued_worker_combine_into_what_their_separate_writes_left` (the steps each combination writes; the ledger's evidence guard itself is exercised by CI's PostgreSQL suites, not here)
- `a_failed_record_still_lets_the_decrease_after_it_land`
- `writes_never_overlap_and_only_committed_read_backs_reach_the_cache` (EP-STATE: two writes for one worker, the second offered while the first is held; a superseded hint is never written, a failed newer write leaves the older committed value)
- `a_write_past_its_bound_is_timed_out_and_a_refused_one_failed_never_dropped` (paused clock: the 500 ms bound)
- `a_stopping_listener_lets_the_write_in_flight_finish_and_abandons_what_is_queued`
- `a_stopping_listener_waits_no_longer_than_the_write_bound` (paused clock: a hung write is cut at 500 ms, and the rest of its entry is abandoned, not started)
- `an_aborted_listener_still_stops_its_writer_and_counts_what_it_held`
- `a_writer_that_panics_closes_its_queue_and_the_listener_carries_on` (counted as `writer_panicked`, with `abandoned` at zero, also after the listener stops)
- `a_connection_served_on_its_own_writes_what_it_queued_before_it_returns`
- `a_writer_panic_is_a_connection_served_on_its_owns_panic`, `a_writer_panic_while_a_connection_drains_is_the_connections_panic` (the in-flight write and the hint queued behind it: `writer_panicked`)
- `offers_that_were_never_writes_queue_nothing`
- `a_decrease_is_written_within_its_wait_bound_and_aged_out_past_it_and_evidence_never_is` (paused clock: a decrease 1 ms inside the bound is written, one 1 ms past it is `aged_out` and leaves row and cache alone, evidence that waited as long is written)
- `a_decrease_past_its_bound_is_replaced_by_a_fresh_one_folded_into_it` (stale lower and stale higher decreases, each folded with a fresh one, directly or when newer evidence moves a fresh decrease onto a stale one: the fresh one is written)
- `a_folded_decrease_ages_from_the_lowest_ones_offer` (the documented residual: the held lower decrease passes the bound, neither is written)
- `a_difficulty_the_ledger_refuses_is_never_folded_away` (NaN after a finite decrease, infinity before one, negative evidence replaced by newer evidence: the backend sees each, and the valid hints are written)
- `a_refused_difficulty_is_written_however_long_it_waited` (paused clock: a NaN decrease past the bound still reaches the backend; mutation-checked, it fails if refused decreases age)
- `another_workers_share_never_replaces_the_workers_own_evidence` (both orders: the worker's own evidence is written, the other worker's share is written last and fails; mutation-checked, it fails without the ownership check)
- `a_refused_difficulty_is_seen_though_another_workers_share_was_refused_first` (mutation-checked, it fails if the refused difficulty does not take the slot)

`stratum/session_timer_tests.rs` now runs its sessions beside a hint writer, as a listener does, and the bare `Session` in `stratum/stale_grace_tests.rs` gets a closed queue, so no test leaves a hint queued forever uncounted.

New, over a real listener (`tests/stratum_protocol.rs`):
- `a_submit_is_answered_while_the_previous_shares_difficulty_hint_write_is_held`: the first share's hint write is held in the backend; the same session's next `mining.submit` is answered while it is pending, then the write lands.
- `a_full_difficulty_hint_queue_drops_and_counts_a_new_hint_without_blocking_its_session`: queue of one, the writer held in one write; a third worker's hint is dropped and counted and its session keeps answering shares.

The existing resume and retained-difficulty tests (`fast_arrival_retries_failed_paired_delivery_and_only_proven_difficulty_resumes`, `idle_retarget_lowers_reconnect_difficulty_without_renewing_evidence`, `resumed_difficulty_is_lane_scoped_ttl_bounded_and_explicit_requests_win`) pass unchanged.

Run locally (all through the host gate, `CARGO_PROFILE_DEV_DEBUG=line-tables-only`):
- `cargo test -p qbit-prism-server --lib difficulty_hint_tests`: 20 passed.
- `cargo test -p qbit-prism-server --test stratum_protocol`: 52 passed, 1 ignored (manual inspection).
- `cargo test -p qbit-prism-server --test stratum_admission_gate`: 6 passed. `--test vardiff_convergence`: 7 passed. (With `stratum_protocol`, these are shard 2 binaries that CI does not reach until #866 fixes the PostgreSQL image break; run here one at a time.)
- `cargo test -p qbit-prism-server --test observability`: 17 passed. `--test stratum_rebuild_lane`: 7 passed.
- Against a private PostgreSQL 16 (`PRISM_TEST_DATABASE_URL`): `--test refresh_liveness` 38 passed, and `every_session_disconnects_then_new_tip_work_serves_a_new_identity` 40 of 40 in a row; `--test landing_metrics` 41 passed.
- `cargo test -p qbit-prism-server --test stratum_properties`: 8 passed.
- `PRISM_TEST_PG_BIN_DIR=/usr/lib/postgresql/16/bin cargo test -p qbit-prism-server --lib -- stratum:: metrics:: --test-threads=4` (private PostgreSQL 16 clusters): 123 passed.
- `cargo fmt --all -- --check`, `cargo clippy --locked -p qbit-prism-server --all-targets -- -D warnings`: clean (apart from the three known vendored sqlx-core warnings).
- `python3 scripts/check_prism_pool_acquires.py` (no new site), `python3 scripts/check_prism_settings.py`, `python3 scripts/generate_prism_metrics.py --check`, `python3 scripts/generate_prism_alerts.py --check`: pass.

## What CI must cover

The full lib suite, `ledger_postgres` and the landing binaries (not run here), the fuzz build (`serve_connection`'s signature is unchanged; it now runs a per-connection writer), and the PRISM gated-test proof (no new PostgreSQL-gated test). Shard 2 of "Rust PRISM PostgreSQL and multi-instance contracts" stops at `migration_rollback` (the `pg_attver` image break) until #866 lands, so its later binaries, `stratum_protocol`, `stratum_admission_gate` and `vardiff_convergence` among them, need the rerun after #866.

Refs #856

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Squashed commits:
cabd0cb 3.x.x: a session hands its difficulty hint to its listener's writer instead of awaiting it (#856)
7871b92 3.x.x: a connection cancelled mid-drain aborts its hint writer instead of detaching it (#856)
3557797 3.x.x: a queued decrease ages out past 500 ms, a dead hint writer counts as its own outcome, and refused difficulties are never folded away (#856)
5fca388 3.x.x: the hint writer's docs say what an aged-out decrease and a dead writer leave, and each step is built from its own hint (#856)
aea3a25 3.x.x: a refused difficulty is written after its entry's other hints, and the hint writer's docs say exactly when a decrease ages out (#856)
c56d332 3.x.x: a stopping listener lets its hint write in flight finish instead of cancelling it mid-statement (#856)
8d8bc7c 3.x.x: a hint writer that already panicked when its listener stops keeps its writer_panicked count, and the stop docs name every cancelling path (#856)
1e73406 Merge 3.x.x (fa8ac84) into orca/856-difficulty-hint-off-session: take in the PostgreSQL 16.15 service pin (#866)
057e49b Merge 3.x.x (3d48a8f) into orca/856-difficulty-hint-off-session: the metric census counts #829's stage histogram and #856's hint counter together
ec33bc2 Merge 3.x.x (234ff1c) into orca/856-difficulty-hint-off-session: take in the landed 3.1.2 PRs and the collate test fix (#874)
9a72501 Merge 3.x.x (582849b) into orca/856-difficulty-hint-off-session: take in the six PRs landed after #874
74915e1 3.x.x: another worker's share offered as a worker's difficulty evidence is kept apart, so it never replaces evidence the ledger would take (#856)
a3032b9 3.x.x: a refused difficulty takes the refused slot from another worker's share, and the hint counter's docs say what is kept apart (#856)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant