Skip to content

3.x.x: wake every frontend's refresh when another moves the payout revision on the same tip, so new-tip work stops being refused stale-job (#752) - #795

Merged
kiwidream merged 4 commits into
3.x.xfrom
orca/752-wake-frontends-on-revision
Oct 28, 2026
Merged

kiwidream merged 4 commits into
3.x.xfrom
orca/752-wake-frontends-on-revision

Conversation

@kiwidream

@kiwidream kiwidream commented Oct 28, 2026 •

Copy link
Copy Markdown
Member

Fixes #752. Each pool block moves the payout revision twice on its new tip: once when a frontend first records the tip (ledger/window.rs), and again when the landing confirms the block (ledger/blocks.rs). Work published in between carries the first revision. Once the confirmation commits, every share on that work is refused stale-job until its frontend republishes. The landing frontend woke its own refresh. Every other frontend kept the old work until its next PRISM_BLOCKPOLL_SECONDS tick, up to about 2.6 s after each pool block.

What changes

This takes the issue's option (a), using PostgreSQL LISTEN/NOTIFY. The revision fence (#675) is unchanged: a share on superseded work is still refused. Frontends now just learn about the new revision right away.

  • Every same-tip bump announces itself in its own transaction: pg_notify('qbit_prism_payout_revision', <new revision>) is returned from the same UPDATE. That covers the settlement bump (confirmation, abandonment, orphan settlement, reorg reconciliation, maturity), ledger::bump_payout_revision (carry claims and transfers) and the fatal-state clear. A policy transition needs no announcement, because it requires every frontend stopped. PostgreSQL delivers NOTIFY only on commit, so a rolled-back bump wakes nobody.
  • Each frontend's refresh loop runs a listener (coordinator/revision_wake.rs) on its own one-connection pool, outside the ledger pool.
    • It reconnects with backoff (250 ms to 5 s) and wakes once after reconnecting. A 30 s probe catches a dead session, and wakes are spaced at most 4 per second.
    • The tick stays as the fallback.
    • A startup handshake makes sure a bump committed before the first LISTEN is not missed.
  • Dual writer: each node is woken by its own database's reconcile bump, because qbit_prism_cluster is not a peer-copied table.
  • Connection budget: +1 connection per frontend. This is documented in prism-storage-sizing.md, prism-ledger-ops.md, prism-configuration.md and mainnet-deployment.md. scripts/check_prism_pool_acquires.py now flags a PgListener on the run pool.
  • The async-promotion drill expects no stale-job refusal on new-tip work after the final block, and still waits one out if a later maturity or carry bump moves the revision. It also checks the fence deterministically: after its own announced bump, a share on superseded work must be refused and leave no ledger row.

Tests

  • New gated tests/revision_wake.rs:
    • The other frontend's landing wakes this one: it republishes within the bound (observed ~0.1 s against a 5-minute tick); on the base it fails.
    • A lost listener falls back to the tick and recovers.
    • A carry-gate bump wakes the other frontend; with the pg_notify dropped from bump_payout_revision, this case fails.
  • Unit test revision_wake::tests::announcements_fold_into_spaced_wakes.
  • An independent run of the full central set on the first commit was all green:
    • ledger_postgres 253/253 and the server lib suite 855/0;
    • candidate_storm_restart, ledger_single_execution, ledger_deadline_atomicity, jsonb_ceiling_gate, artifact_admission, audit_body_normalization, audit_reconstruction_permit, api_database, signing_transition, migration_rollback, share_partitions_postgres and share_archive.
  • On this head: revision_wake 3/3, the ledger_postgres fatal-state tests 23/23, carry_owner_postgres 9/9, carry_owner_adoption 7/7, equal_work_scheduler 6/6, refresh_liveness 38/38, and the live drill 1/1 with a real qbitd. fmt, clippy and the guard scripts pass.
  • An adversarial check made the fix break in six ways: dropping the notify, stopping on connection loss, putting the listener on the ledger pool, and others. Every correctness change is caught. The carry gap it found is now covered.

🤖 Generated with Claude Code


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

kiwidream and others added 2 commits October 28, 2026 09:55
…t revision on the same tip, so new-tip work stops being refused stale-job until the next blockpoll tick (#752)

Each pool block moves the payout revision twice on its new tip: when a
frontend first records the tip (ledger/window.rs) and when the landing
confirms the block (ledger/blocks.rs). Work published on the new tip in
between carries the first revision, and once the confirmation commits
every share on it is refused stale-job (cause payout_revision) until its
frontend republishes. The landing frontend woke its own refresh; every
other one kept that work until its next PRISM_BLOCKPOLL_SECONDS tick, up
to about 2.6 s after each pool block.

This takes the issue's option (a) with PostgreSQL LISTEN/NOTIFY. Option
(b), a same-tip lease, would loosen the revision fence #675 settled, and
the fence is unchanged here: a share on superseded work is still refused.
The other form of (a), a republish triggered by the refusal itself, only
starts once a miner has been refused, and a refresh that keeps failing
would turn every refused share into another refresh; announcements arrive
at the rate the revision moves, a few per block.

- Every same-tip bump announces itself in its own transaction: the
  settlement bump in ledger/blocks.rs (confirmation, abandonment, orphan
  settlement, reorg reconciliation, maturity) and
  ledger::bump_payout_revision (carry claims and transfers) return
  pg_notify('qbit_prism_payout_revision', <new revision>) from the same
  UPDATE, so nothing is added to the settlement transaction's round trips.
  NOTIFY is transactional: listeners hear only committed bumps. The tip's
  own bump is not announced: each frontend learns the tip from its own
  node, and a wake would only send a frontend whose node is behind to
  refresh against the older tip.
- coordinator/revision_wake.rs: refresh_loop spawns a listener beside
  itself, aborted when the loop ends. It holds one connection of its own,
  on a one-connection pool outside the ledger pool, named
  qbit-prism-revision-wake in pg_stat_activity, and calls the refresh's
  existing Notify on each announcement. A wake is only a hint: the refresh
  reads the durable revision itself, so a late, repeated or foreign
  announcement can never republish older work. Announcements fold into
  the Notify's single permit, and wakes are at least 250 ms apart, so a
  burst costs one refresh.
- A lost listener never holds the refresh up: the loop keeps its tick, as
  before. The listener reconnects with backoff (250 ms doubling to 5 s,
  starting over only after a connection lasted 30 s), wakes the refresh
  once after each reconnect for anything it missed, probes an idle
  connection every 30 s so a silently dead one is found, and warns at most
  once a minute while it is down. The first connection does not wake: the
  loop's first refresh runs at once.
- Dual writer (3.1): each node's frontends listen on their own database.
  The peer sync never copies the payout revision; a peer's block counts on
  this node only once this node's reconciler confirms it, and that
  confirmation's bump is announced on this node's database, so both nodes'
  frontends are woken by their own database's bump.
- No migration, setting or metric. The listener's connection is not a
  run-pool checkout (scripts/check_prism_pool_acquires.py unchanged); the
  acquire-metrics exclusions table and the storage-sizing connection budget
  name it, and the rejections and mining docs describe the wake.

Tests:
- tests/revision_wake.rs (PostgreSQL-gated, two coordinators on one
  database and a fake node): A lands a real block while B, whose tick is a
  minute, publishes new-tip work at the tip's revision; after the
  confirmation B republishes at the confirmed revision within 5 s (about
  0.1 s here), a share on the superseded work is still refused stale-job
  and a share on the work B just published is accepted and credited once.
  On the base it fails at the bound: B still publishes the tip's revision
  5 s after the confirmation. The second case cuts both listeners off with
  the database refusing connections: the 2 s-tick frontend republishes on
  its tick, the minute-tick one does not move until connections return, then
  its reconnected listener wakes it for the missed announcement and the
  next announcement wakes it again; a late announcement of an older
  revision republishes nothing older.
- A unit test pins the wake spacing.
- The async-promotion drill (live_pg_async_live_miners.rs) no longer
  expects a stale-job refusal on new-tip work: a session passes over a job
  on superseded work without a share, and a stale-job answer to its share
  on work at the ledger's revision now fails the drill instead of being
  waited out. The fence check it carried moves to tests/revision_wake.rs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…id not follow, announce fatal-state clear, cover carry announcements, and keep the drill's fence check (#752)

Fixes from the pre-push review of 0381129.

- revision_wake: the first LISTEN no longer goes unannounced. The refresh
  loop now starts its listener through revision_wake::start, which waits
  up to 1 s for the listener's first attempt before the loop's first
  refresh. Every successful LISTEN then wakes the refresh unless that
  first refresh had not started yet (and so reads the revision after the
  LISTEN): a bump that commits during initial connect failures, or while
  a slow first connect is still running, is no longer left to the tick.
  An unconditional first wake would be harmless in production, but it
  lands while the loop's first refresh is in flight and breaks
  equal_work_scheduler's pinned refresh cadence.
- revision_wake: the connect options are parsed once and the no-op
  idle_timeout/max_lifetime settings are gone. The one-connection pool
  stays per attempt: a dropped PgListener returns its connection to its
  pool only after an UNLISTEN, which never finishes on a connection that
  died without closing, so a shared pool's only connection could stay
  held until TCP gives up on it, minutes later.
- ledger/fatal_state.rs: fatal-state clear's same-tip bump is announced
  with revision_wake::ANNOUNCE. The module doc names every announced bump,
  and says why a policy transition's is not: it requires every frontend
  stopped.
- scripts/check_prism_pool_acquires.py counts PgListener::connect_with as
  a checkout, and the inventory classifies the listener's own pool
  (policy revision-listener), so a PgListener on the run pool, through
  any receiver, is an unclassified site. A negative control covers it.
- tests/revision_wake.rs: a third gated case opens a dual-writer node's
  carry gate (Ledger::set_carry_paying, whose fence is
  ledger::bump_payout_revision, the bump carry-owner release and transfer
  write) and requires another frontend, whose tick is 5 minutes, to
  republish within 10 s; with the pg_notify dropped from
  bump_payout_revision it fails at that bound. The frontend-without-a-
  listener case no longer bounds its tick republish tightly: it allows
  30 s and relies on the order of events (no listener session exists
  meanwhile). The wake bound is 10 s against a 5-minute tick, and each
  case may run 150 s.
- The async-promotion drill waits out a stale-job answer again when a
  later same-tip bump (maturity, carry) moved the revision after the
  session's check, and checks the fence deterministically: after every
  session is credited it moves the revision with an announced same-tip
  bump of its own, and one share on the work miner 0's session holds must
  be refused (stale-job, or unknown-job if pruned) with no ledger row.
- Connection budget: prism-ledger-ops.md, prism-configuration.md and
  mainnet-deployment.md count the listener's connection per frontend.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-28T18:22:36.186407Z 0a16e2a 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.

No findings.

…rill, one connection formula, no pool maintenance task per listener attempt (#752)

Hardening from the local review of fb7ed65.

- The async-promotion drill bounds only the superseded revisions below the
  revision the final block landed at (read once the block is confirmed).
  The restored stale-job wait-out arm records work a later same-tip bump
  (maturity, carry) superseded after the check; that work is at or above
  the landed revision, so it no longer trips the at-most-one bound when the
  same session already passed over first-revision work.
- The drill's own bump, and the test's, announce through
  revision_wake::ANNOUNCE (now pub, as CHANNEL is), so there is one form.
- revision_wake::subscribe builds its per-attempt pool with no idle or
  lifetime limit again: with either, sqlx starts a maintenance task per
  pool that sleeps for minutes, and the listener holds its connection.
- prism-storage-sizing.md, prism-ledger-ops.md, prism-configuration.md and
  mainnet-deployment.md give one formula: each frontend uses up to
  PRISM_DATABASE_MAX_CONNECTIONS + 1 database connections (its
  payout-revision listener), + 2 more in dual-writer mode (its health
  pool).
- tests/revision_wake.rs: a fourth gated case starts the refresh loop while
  the database refuses new connections, so the listener's first attempt
  fails and the loop's first refresh runs without a LISTEN; a same-tip bump
  then commits, and the first LISTEN once connections return must wake the
  refresh within 15 s against a 5-minute tick. With fb7ed65's
  first-LISTEN wake reverted to 0381129's rule, it fails.

Co-Authored-By: Claude Opus 5.5 <[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.

No findings.

@kiwidream

Copy link
Copy Markdown
Member Author

Closing and reopening to re-run CI (this token can't re-run workflows). Shard 1's only failure was coordinator::miner_submit::acquire_tests::block_only_poll_checkout_cancel_and_deadline_stay_unknown. That test group is flaky on 3.x.x itself: it also failed on 3.x.x's push CI after #793 (run 40726591893) and on #792's CI (run 40565379439), and it passes locally. A fix for the flake is coming in its own PR.

@kiwidream kiwidream closed this Oct 28, 2026
@kiwidream kiwidream reopened this Oct 28, 2026

@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.

No findings.

@kiwidream
kiwidream merged commit 2c9c95b into 3.x.x Oct 28, 2026
41 checks passed
kiwidream added a commit that referenced this pull request Nov 11, 2026
…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]>
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