Skip to content

3.x.x: cut the per-session checkouts on the new-tip fan-out (#275) - #499

Merged
djh58 merged 4 commits into
3.x.xfrom
djh58/prism-b275-fanout-a
Sep 23, 2026
Merged

djh58 merged 4 commits into
3.x.xfrom
djh58/prism-b275-fanout-a

Conversation

@djh58

@djh58 djh58 commented Sep 23, 2026 •

Copy link
Copy Markdown
Member

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:

  1. Idle-gated checkout probe (ledger/connect/acquire.rs): the pool's acquire-time ping runs only when a connection has been idle for at least PRISM_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.
  2. One clock+revision statement per issuance boundary (coordinator/work_ledger.rs::clocked_payout_revision): the boundary's now_ms and payout_revision come from one SELECT that also carries the live-cluster predicates, instead of two checkouts.
  3. Single-flight clock+revision read per frontend (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_epoch takes 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 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.

Gate manifest: test/prism-gated-tests.txt gains the ids of the new gated tests only (probe tests, clocked-revision test, fanout_revision_bump).

Performance (real processes)

Method: qbit-prism-load, two qbit-prism-server frontends, 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's time_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.

run endpoint median endpoint mean publish→first / p50 / last notify (median over tips) steady share-ack p99 hashrate loss at 60 s
base A/A 1 1143 1047 88 / 302 / 365 36 1.73 %
base A/A 2 1171 1070 92 / 327 / 392 40 1.77 %
base (A/B, first) 1157 1053 87 / 311 / 374 48 1.74 %
candidate (A/B, first) 1005 933 42 / 192 / 246 8 1.54 %
candidate (A/B, second) 999 928 48 / 189 / 243 6 1.53 %
base (A/B, second) 1165 1054 95 / 308 / 374 89 1.74 %
candidate (two later runs) 1015, 995 940, 922 44 / 189 / 242, 43 / 186 / 241 5, 9 1.55 %, 1.52 %
base (after review fixes) 1150 1046 87 / 306 / 378 29 1.73 %
candidate (after review fixes, the code in this PR) 996 925 38 / 182 / 231 12 1.53 %
base, 200 shares/s 1333 1154 98 / 353 / 493 35 1.90 %
candidate, 200 shares/s 1048 953 36 / 206 / 269 5 1.58 %

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 waitfornewblock long-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:

  • All 32 frontend backends terminated (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 bumped (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 test fanout_revision_bump proves the same refusal between build_job and persist_issued_job. Candidate 2.7 s to full re-serve vs base 3.5 s.
  • PostgreSQL primary fast-restarted on tip 3: frontends reconnected unaided and re-served every session 0.9–2.6 s after the primary returned; 0 anomalies; no revision changed.
  • Existing revision-retirement tests pass (coordinator lib suite, 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: 16 share_archive lock timeouts under 22 test threads (32/32 pass single-threaded), one load-sensitive poll test (3/3 isolated passes), and public_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


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

djh58 and others added 4 commits September 22, 2026 17:03
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]>
@djh58

djh58 commented Sep 23, 2026

Copy link
Copy Markdown
Member Author

@cursor review

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

Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

Fix All in Cursor

❌ 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)
})

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 22a9248. Configure here.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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

@djh58

djh58 commented Sep 23, 2026

Copy link
Copy Markdown
Member Author

Review ledger (final)

Lanes

  • Independent adversarial review (Claude, separate session, read-only, on the pre-publication candidate 7b78ea6..89717ce plus the Fan-out A patch): 1 blocker, 2 minor, 4 observations needing no change. All three fixed in 22a9248.
  • Coordinator delta check of the three fixes in 22a9248: clean.
  • Codex adversarial lane: NOT RUN (capacity unavailable).
  • Cursor Bugbot: requested; 1 finding (medium), rejected with a written refutation (see below).
  • Author inline pass: no new finding (not an independent lane).

Findings and dispositions

# source finding disposition
1 independent review PRISM_DATABASE_ACQUIRE_PROBE_IDLE_MS missing from the native-settings inventory; production start-up from compose.yaml refused the setting and scripts/check_prism_settings.py failed fixed in 22a9248 (inventory line; settings script and production-mode check-config verified)
2 independent review a clocked-revision flight whose only awaiter was cancelled parked its pool checkout until a later request replaced it fixed in 22a9248 (driver task runs every flight to completion; three interleaving tests)
3 independent review comments and PR text said the revalidation clock reads were dropped; the code still evaluates them from the shared read fixed in 22a9248 (wording corrected)
4 independent review, observations O1–O4 batch-path amplification bounded by pool size and definite; check-config value validation pre-existing; >= join rule under a frozen clock; revision-then-clock ordering covered by require_revision under the cluster FOR SHARE no change required
5 Bugbot a failed acquire ping returned as Err from before_acquire aborts the checkout instead of replacing the connection rejected: SQLx 0.8.6 check_idle_conn maps a hook Err to close_hard and a replacement connection, the same branch as the default ping; proven by the gated probe test on a terminated backend (thread reply: #499 (comment))
6 CI PostgreSQL contracts shard 1: candidate_storm::drained_rows_cost_the_same_statements_at_the_baseline_and_storm_cardinalities failed once ("a pooled connection opened inside the measured window") environmental: the test passes 3/3 on this head and 3/3 on the base under the same fixture and passed in the full-suite run; it is the flake fixed by #498 (merged into 3.x.x after this PR opened); rerun (attempt 2) passed

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.

@djh58
djh58 merged commit b61747e into 3.x.x Sep 23, 2026
39 of 42 checks passed
djh58 added a commit that referenced this pull request Sep 23, 2026
…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]>
djh58 added a commit that referenced this pull request Sep 24, 2026
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]>
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