Repository navigation
3.x.x: cut the per-session checkouts on the new-tip fan-out (#275) - #499
Conversation
Every pool checkout pinged the connection before use, on top of the unconditional ping SQLx runs when the connection is returned. Under a work fan-out the pool never idles for more than a few milliseconds, so the acquire ping was one of three PostgreSQL round trips per checkout that proved nothing the release ping had not proved moments earlier. The checkout probe now runs only when the connection has been idle for at least PRISM_DATABASE_ACQUIRE_PROBE_IDLE_MS (default 100 ms; 0 restores a probe on every checkout). A connection that dies inside that window fails its first statement with the same I/O error any mid-statement disconnect already produces and is discarded by the release ping; no payout, authority, deadline, digest, fence or admission path changes. Gated tests cover both sides of the threshold against a terminated backend and the setting's bounds. Co-Authored-By: Claude Fable 5.1 <[email protected]> (cherry picked from commit 6770d670b6104510d3e35afd573d856bebb13e0e)
…-probe window (#275) End-to-end against a real coordinator and PostgreSQL: with the probe window wide open, terminating the pool's idle backends makes the next job build fail once with a Stratum error, and the following attempt serves work for the same tip. The pool discards the dead connection on release, so recovery is one retry on the session timer, never a wait for the next refresh. Co-Authored-By: Claude Fable 5.1 <[email protected]> (cherry picked from commit 812a7bdd94129bbccb0725dbdf409513330e14d3)
…ce boundary (#275) Every issuance revalidation with an absolute expiry read the database clock and the payout revision as two statements on two pool checkouts, six PostgreSQL round trips for two values of one snapshot, at up to two boundaries per delivered job. The work ledger now reads both in one statement on one checkout, with the same row guards as payout_revision. The expired-clock branch still returns before the revision is used, a database failure still precedes every local check, and no deadline, authority, fence, payout or digest semantics change. The in-memory test ledger keeps its clock gate in the same order for the cancellation tests. Co-Authored-By: Claude Fable 5.1 <[email protected]> (cherry picked from commit cb15a7ac55a519db6ecc1ffa541a4f2c6de83b76)
…suance boundaries (#275) Concurrent issuance boundaries on a frontend now share a single in-flight clocked_payout_revision read (coordinator/clocked_flight.rs) under a join-after-request rule: a caller joins only a read that started after its own request instant, so a deadline derived from the shared value can only be shorter than a private read would give, never stale; a failed read is shared and the next request reads again, and a driver task runs every flight to completion so a leader cancelled with no joiner cannot park the read on its pool checkout. work_authority_in_epoch takes both values from the flight at every boundary, including each revalidation, where the clock is still evaluated against the recorded expiry and can only shorten the deadline fixed by the first read; the issued record's deadline clock comes from the same flight. The post-save revalidation and the PAYOUT_REVISION_SQL row guards are unchanged. WorkLedger::payout_revision became unused and is removed from that trait; the submit path keeps its own. Also registers PRISM_DATABASE_ACQUIRE_PROBE_IDLE_MS (from the checkout-probe commit) in the native-settings inventory, without which production start-up rejected the Compose-provided setting as unread, and fixes the probe-delivery test's backend reference (&*coordinator). New: five unit tests on the flight rule (join-after-request, shared failure, later request does not join an in-flight read, a joiner completes a read whose leader was cancelled, an abandoned read still completes) and the PostgreSQL-gated tests/fanout_revision_bump.rs (a payout revision bump between build_job and persist_issued_job is refused and writes no row), registered in the gate manifest. Measured with two real frontends, 2,000 sessions, 400k window, admission 128: node tip to last usable notify 1150-1165 -> 996-1005 ms median against a 28 ms A/A delta; publish-to-last-notify 374 -> 245 ms; steady share-ack p99 29-89 -> 6-12 ms; -285 ms at 200 shares/s. Fault injection (backend kills, revision bumps and a primary restart inside the fan-out) served every session on the next attempt with the revision guards firing as before. Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
@cursor review |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit 22a9248. Configure here.
| sqlx::Connection::ping(connection).await?; | ||
| } | ||
| Ok(true) | ||
| }) |
There was a problem hiding this comment.
Failed probe aborts checkout
Medium Severity
A failed acquire ping is returned as an error from before_acquire, so SQLx forwards it to the checkout caller instead of discarding the socket and opening another. After an idle gap the first use of a dead backend fails the whole acquire rather than silently replacing the connection as test_before_acquire did and as the hook documents.
Reviewed by Cursor Bugbot for commit 22a9248. Configure here.
There was a problem hiding this comment.
Rejected after re-reading SQLx 0.8.6's acquire path. An Err from before_acquire is not forwarded to the caller: pool/inner.rs::check_idle_conn matches Err(error) from the hook, logs it, calls close_hard() on the connection and returns the DecrementSizeGuard; acquire then takes that guard and falls through to self.connect(deadline, guard), opening a replacement. That is the same branch the default test_before_acquire ping takes on failure (Err(conn.close_hard().await)), so a failed probe replaces the socket silently exactly as before.
The gated test ledger::connect::acquire::probe_tests::a_dead_idle_connection_is_replaced_when_the_idle_gap_reaches_the_threshold exercises this against a real PostgreSQL backend: the idle backend is pg_terminate_backend-ed, the next checkout probes (threshold 0), and the statement runs on a fresh backend with a different pid and no error returned to the caller. The sibling test covers the inside-the-window case (first statement fails once, release ping discards, next checkout recovers).
Review ledger (final)Lanes
Findings and dispositions
CI: 19 checks green on 22a9248 (formatting, lints, Rust tests, PostgreSQL contract shards 0/2/3, Python shards, Compose validation, image builds and smoke, dependency audit, Dockerfile lint, ckpool live suite, deleted-test map); shard 1 failed once on that flake and passed on rerun (attempt 2), so every check is green. Not merging from this session. |
…ltas (#275) (#501) * 3.x.x: keep the refresh delta path across retargets and multi-page deltas (#275) RetainedShares::eligible refused any change in scaled network difficulty and any delta over 4,096 sequence slots, so with a per-block retarget every tip's refresh paid the serial full scan (about 100 pages at 400k). The harness hid it: constant bits and a timed tip with no new shares. snapshot_delta::advance now replays the full reader's newest-first saturating fold for the fresh target over the delta above the retained cutoff (ascending pages, up to 262,144 slots), the retained rows, and, for a heavier target, a bounded margin below the retained first row (up to 16 pages; a per-block retarget moves the crossing row by a fraction of a percent of the window). The merged window must be strictly ascending and cross exactly at its first row (the fold reaches zero and the fold without the first row does not); a walk that runs out of history is refused as partial, because the count proof cannot vouch for rows older than the first row. WindowRef is the digest of exactly the merged window, and the leaf, partition and WAL-timeline witness is unchanged: re-read over the merged range without the count, then with it. The reads are READ COMMITTED like the full scan's; consistency comes from immutable rows, the anchored predicate and the anchor's update of the singleton every append updates, and the final count catches what can still appear between statements. Memory at both bounds is stated next to the constants (about 640 MB at 400k, 720 MB at 500k). Measure it: qbit_prism_refresh_window_acquisitions_total{outcome} counts every snapshot's acquisition decision, qbit_prism_refresh_seconds {trigger,acquisition} times every published rebuild, and one "refresh published" line per rebuild carries the row and page counts. The load harness gains opt-in --retarget-bits (different bits on every tip, and a tenth more seeded history below the window) and --background-shares-per-second; per-tip client latency gains min, p90 and a per-frontend breakdown. Defaults are unchanged. Differential tests against the full reader cover retargets in both directions, multi-page deltas and margins, both size bounds, seeded random walks over target and inserts, and landing re-derivation of a delta-assembled window with its superset and subset refused; the independent review's adversarial differential over a legacy-style fixture is adopted, and a coordinator-level test lands a found block, through the coordinator's own submit loop, on a window the delta path built after a retarget. Two real frontends, 2,000 sessions, 400k window, admission 128, every tip retargeting with 133 shares/s, base b61747e (with #499's fan-out cut) against this branch rebased onto it: the candidate advances by the delta path on every tip (refresh 0.80 s) where the base full-scans (about 1.7 s); the last session holds fresh work 1.03-1.04 s after the tip instead of 1.86-1.92 s (829 and 886 ms in the AB and BA pairs, the two base runs 55 ms apart), and hashrate loss at 60 s drops from 3.0% to 1.6%. On 7b78ea6 the same pair saved 887 and 830 ms against an A/A noise of 3 ms. Backend kills mid-fan-out, revision bumps between build and persist, and primary restarts during a tip all keep every session's work correct with exact receipt reconciliation and landed blocks. Refs #275 Co-Authored-By: Claude Fable 5.1 <[email protected]> * 3.x.x: rekey the snapshot delta advance call in the pool-acquire census (#275) The delta path's advance call dropped its network_difficulty argument in 3f75d27, and scripts/prism_pool_acquires.json still keyed the old call text, so the pool-acquire guard reported the new call unclassified and the old key stale. Rekey the entry to the new text with the same classification (one transaction-scoped checkout); no code changes. Refs #275 Co-Authored-By: Claude Fable 5.1 <[email protected]> --------- Co-authored-by: Claude Fable 5.1 <[email protected]>
ledger::connect::acquire::probe_tests::a_dead_idle_connection_inside_the_probe_window_fails_one_statement_then_recovers failed in CI with "a statement on the terminated backend N returned pid M". The test terminates the pool's one backend right after a statement, but sqlx returns a dropped PoolConnection from a spawned task that pings the server before making the connection idle. When the backend is terminated while that ping is in flight, the ping fails, sqlx discards the connection on the spot, and the checkout under test opens a fresh connection instead of receiving the dead socket, so the statement succeeds on a new pid. On a two-core host with the runtime and the server competing for CPU this happened in 21 of 100 runs. Both probe tests now wait, bounded, until the pool reports the connection idle before terminating its backend, and assert it is still idle when the checkout starts, so the dead socket is deterministically the one handed out. The sibling threshold-zero test could pass for the wrong reason in the same race (a connection discarded at release, not by the probe); it gets the same synchronization. No assertion was weakened; the acquire code is untouched. Refs #499 Co-authored-by: Claude Fable 5.1 <[email protected]>


Refs #275.
What changes
Delivering a new tip to 2,000 sessions spends most of its time in per-session database checkouts. This stack cuts the checkouts on the fan-out path without touching payout, authority, deadlines, durability or the required population:
ledger/connect/acquire.rs): the pool's acquire-time ping runs only when a connection has been idle for at leastPRISM_DATABASE_ACQUIRE_PROBE_IDLE_MS(default 100 ms; 0 probes every checkout as before; documented in README,.env.example,compose.yaml, mainnet deployment). A connection killed inside the window fails one statement and the next checkout replaces it; tested at the unit level and end to end (tests/checkout_probe_delivery.rs). The setting is registered in the native-settings inventory so production start-up accepts it.coordinator/work_ledger.rs::clocked_payout_revision): the boundary'snow_msandpayout_revisioncome from oneSELECTthat also carries the live-cluster predicates, instead of two checkouts.coordinator/clocked_flight.rs): concurrent boundaries share one in-flight read under a join-after-request rule (a caller only joins a read that started after its own request instant, so a deadline derived from it can only be shorter, never stale); a failed read is shared and the next request reads again.work_authority_in_epochtakes both values from the flight at every boundary, including each revalidation: the clock is still evaluated against the recorded expiry every time and can only shorten the deadline fixed by the first read, never renew it; what changes is that the fan-out shares these reads instead of repeating them. A driver task runs every flight to completion, so a leader cancelled with no joiner (session gone, initial-job timeout) cannot leave the read parked on its pool checkout. The post-save revalidation and thePAYOUT_REVISION_SQLrow guards are unchanged.WorkLedger::payout_revisionbecame unused and is removed from that trait; the submit path keeps its own.Gate manifest:
test/prism-gated-tests.txtgains the ids of the new gated tests only (probe tests, clocked-revision test,fanout_revision_bump).Performance (real processes)
Method:
qbit-prism-load, twoqbit-prism-serverfrontends, 2,000 sessions, 400k-share window, admission 128 (harness default), pool 16, 8 external tips per run, 1 share/s background traffic plus one 200 shares/s pair. Fresh A/A pair, then base / candidate / candidate / base, then a further candidate / candidate pair from a constants experiment that is not part of this PR. Boundary: the harness'stime_to_usable_work(node tip stamp to the last session's usable notify). Every tip in every run served all 2,000 sessions. Times in ms.Paired: −152, −166 and (after the review fixes) −154 ms on the median (13–14 %), −120 ms on the mean, against an A/A delta of 28 ms; −285 ms under 200 shares/s. The last-notify tail (374 → 245 median, 416 → 263 max) and the share-ack p99 both improve; refresh itself is unchanged (≈ 750 ms median in every arm), so the remaining gap to sub-second is the refresh.
Host caveats: a shared development VM (other jobs ran concurrently; timing runs were serialized under an exclusive lock, and the load average was 2–7 at the start of some runs), a simulated node (fake
waitfornewblocklong-poll) and simulated miners; the numbers compare arms on the same host, not production latency. Benchmarked binaries are frozen release builds pinned by SHA-256 in every run's artifact.Fault injection (real processes, two frontends)
Injected from the first persisted cohort of a tip's fan-out (≈ 800 ms after the tip), candidate and base:
pg_terminate_backend) on tips 2 and 5: every session received work for the tip on the first or next attempt; in-flight deliveries failed with "terminating connection due to administrator command" and were re-served within about a second; 0 client failures, 0 ack/commit divergences, 0 unknown-outcome commits. Endpoints 1694 / 1974 (candidate) vs 1836 / 1208 (base); the one slow frontend on the candidate had the kill land inside its refresh reserve step and recomputed the window, a path this PR does not touch.payout_revision + 1) on tips 4 and 7: the cohort transaction's guard refused persistence ("payout revision changed while observing chain state"), later builds were deferred as "payout snapshot stale" until the refresh republished at the new revision, and all 2,000 sessions were re-served at the new revision (2,002 rows per tip at the new revision; a timestamp census shows every row created after the bump carries the new revision and the only old-revision rows predate it). The in-process gated testfanout_revision_bumpproves the same refusal betweenbuild_jobandpersist_issued_job. Candidate 2.7 s to full re-serve vs base 3.5 s.clocked_revision_tests,lost_race_pin,candidate_dispatch_probe,append_admission).Verification
An independent adversarial review of the candidate found one blocker (the new setting was missing from the native-settings inventory, so a production coordinator launched from the Compose file refused to start), one minor cancellation gap in the flight (fixed with the driver task, with three interleaving tests) and one comment inaccuracy (fixed); all addressed in this change.
cargo test -p qbit-prism-server(lib, all integration binaries incl. PostgreSQL-gated) and-p qbit-prism-load,cargo clippy --workspace --all-targets -- -D warnings,cargo fmt --check,scripts/check_gate_manifest.py. Locally 18 tests failed in the first full run and all were fixture effects: 16share_archivelock timeouts under 22 test threads (32/32 pass single-threaded), one load-sensitive poll test (3/3 isolated passes), andpublic_database_config's "absent password" case under a trust-auth fixture (5/5 pass against a password-authenticated fixture like CI's).🤖 Generated with Claude Code
Need help on this PR? Tag
@codesmith-botwith what you need. Autofix is disabled.