Repository navigation
3.x.x: single-pass tee, chunk-parallel counted-share JSON and lean tip probes for the refresh (#275) - #502
Conversation
…p probes for the refresh (#275) The refresh's CPU path serialized the accepted-share array twice (audit prefix and WindowRef digest), the counted-share array twice (commitment leaf and audit suffix), folded it with two million string clones on one thread and hashed the slice digest with millions of tiny SHA updates; the two pipeline lanes were balanced, so neither could shrink alone. Builder-only, byte-identical cuts (verifiers stay serial and untouched): - qbit_prism::parallel: an ordered chunk pipeline on one process-wide worker pool (PRISM_REFRESH_BUILD_THREADS; default three quarters of the cores, at most four, the measured knee; 0 runs the builder serially), write_array/write_array_frames (exactly serde_json::to_writer of the slice, every element still written by serde_json, chunks concatenated in order) and StructSplice, a serializer that keeps a struct's derived field order and skip rules while one field's value bytes come from a chunk-parallel writer. PrismRewardManifest's derive and AuditBundleRef::serialize_suffix remain the only definitions of the audit bytes; u128 fields reach serde_json's own serialize_u128 as before. - CanonicalAuditHashPrefix::new_with_share_digest serializes the accepted shares once and feeds both SHA states, the WindowRef digest on its own thread over the same frames; finish_with writes the suffix with the reward manifest's shares in ordered chunks. - The commitment leaf and, with CTV, the fan-out precommitments digest the reward manifest once through the same chunked writer. - compute_prism_window_parallel decides the counted difficulties serially, builds the CountedShare chunks on the pool with their slice-digest bytes and entitlement partial sums, and streams the digest on its own thread. Eligibility, ordering and the per-share digest encoding are shared with the serial fold. - The compact-record capture no longer waits for the counted-share drop; it runs on the blocking pool under the same build admission. Lean tip probes: the ledger probe before the reuse check is skipped when the template fingerprint already differs, the probe under the build permit when the cached window's revision is below the one the chain-observation write returned (every revision write is an increment), and the landing metric takes the anchor transaction's revision. The same-template path, the in-transaction save fence and the lock-loop re-prove are unchanged. AUDIT_BUILDER_VERSION is unchanged. Property tests build randomized windows through both paths at six thread/chunk geometries and compare every byte and digest; golden vectors for a fixed window were recorded from the serial builders and re-derived on the base tree. At the #275 bar (two frontends, 2,000 sessions, 400k window, background shares, eight tips per run, balanced A/B on the merged 3.x.x with the fan-out work) the refresh drops from 736-747 ms to 397-403 ms and tip-to-last-notify from 955-973 ms to 588-624 ms, with the fan-out tail and share-ack latency unchanged; RSS per frontend after the tips rises by 100-240 MiB (the pool's allocator arenas; it does not grow with further tips) and peak RSS by about 70 MiB. Refs #275 Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
@cursor review |
… gating (#275) The builder-threads test asserted that the detected parallelism is never serial, which only holds on hosts whose pool has at least two threads: builder_threads() is three quarters of the cores clamped to 1..=4, so a two-core runner starts one thread and Parallelism::new(1, ..) is the serial path. The test now asserts the relationship: the detected worker count is the running pool's (at most eight) and it is serial exactly when that count is one. Reproduced with the lib tests pinned to one and two cores; the fixed test passes there and at the full core set. No other test in this change reads the host's core count. The coordinator's refresh probes were only covered indirectly. A new test counts them alone (the memory ledger keeps that counter next to the state reads that lease proofs and reuse fences also make): a same-template poll probes once, a new tip whose transition bumped the revision probes not at all and reads one snapshot, and a tip a peer already recorded probes once under admission and reuses the cached window without a snapshot read. Refs #275 Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
CI fix pushed as 74be188 (signed, on top; no amend). Failure: Fix (tests only): the test now asserts the relationship: detected workers Also in the commit: a test that pins the R5 probe gating by counting refresh probes alone in the memory ledger: a same-template poll probes once, a new tip whose transition bumped the revision probes not at all and reads one snapshot, and a tip a peer already recorded probes once under admission and reuses the cached window without a snapshot read. The gated-test manifest is unaffected (no gated test added, expected list unchanged); the gate job re-proves it on this run. |
|
@cursor review |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit 74be188. Configure here.
Review ledger for head 74be188 (final)CI 21/21 green on this head (the gated-test proof included); Cursor Bugbot reviewed 49f69bf and 74be188 and found no issues both times. What was reviewed
Findings and dispositionsFixed (in 74be188, tests only)
Rejected (with reasons) Deferred as follow-ups (approved by the maintainer; a follow-up issue collects them) No production code changes remain open on this PR. |
|
Post-merge workstream A review (read-only at |
…-paging Both sides add metric families. Conflicts resolved by hand in the census tests only: `tests/observability/cardinality.rs` re-derived from the merged registry (60 families; 241 startup and 675 populated series: #504's four families and six series plus this branch's three unlabeled gauges), and `tests/observability/contract.rs` keeps both sides' gauge names. #502 and #507 touch no metrics files. The auto-merged registry, metrics, coordinator, ledger, metadata, inventory and gated-test list were checked: every family and constant from both sides is present, the metadata names all resolve in the registry, the inventory is regenerated, and the gated list is byte-sorted with no duplicates. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ld, trigger precedence, retained memory (#509) (#512) * 3.x.x: #502 follow-ups: pool drain state in an Arc, prefix-only rebuild, trigger precedence, retained memory (#509) F1, soundness. ordered_chunks kept its drain state (the ready map, the error, the outstanding count and their condvar) on the caller's frame and lent it to every job through a lifetime-erasing transmute. A job's last actions are decrementing outstanding and unlocking the mutex, and the drain waiter can see zero and return between the unlock's swap and its futex wake, so that wake could run on a freed frame. The state now lives in an Arc<Shared> cloned into each job; only produce stays borrowed, and a job's last use of it is inside catch_unwind, before the decrement. The twelve parallel unit tests pass under Miri. F3, hot path. The reused-window rebuild (prepare_refresh_body_with) called new_with_share_digest and discarded the digest, spawning a hasher thread and hashing the whole share array a second time on every same-tip template churn. CanonicalAuditHashPrefix::new_with hashes the prefix alone; a thread-local probe counts the digests computed, and tests in both crates pin that the rebuild computes none and that its hashes are the pipelined refresh's. F4, observability. A new template on the same tip runs no ledger probe at entry since #502, so the refresh trigger label was always template there even when the revision, balances, reanchor, shares or fee changed. The label is now named on that path from the window the rebuild used, by the same precedence (classify_refresh) as the probed path; a coordinator test drives a same-tip template change with a revision bump and reads revision, then template alone, from the metric. F2, resources. docs/prism-storage-sizing.md records the per-frontend retained-memory change with #502's numbers and the knobs that bound it (PRISM_REFRESH_BUILD_THREADS, MALLOC_ARENA_MAX) and the build slot no longer bounding live counted-share bodies exactly. No code change. No artifact byte changes: the byte-identity suites, golden pins, frozen corpus and audit_cli goldens are untouched and pass. Closes #509 Co-Authored-By: Claude Fable 5.1 <[email protected]> * 3.x.x: drop the jobs' untaken chunks on the calling thread (#509 review) With the drain state in an Arc, a chunk the consumer never took (a producer or consumer error, or a consumer panic unwinding through the drain) stayed in the shared state and was dropped by whichever thread released the last Arc clone, which can be a pool thread after ordered_chunks has returned. C is generic and may borrow the caller's frame: the counted-share fold's chunks are keyed by &str into a caller local. No current chunk type dereferences its borrow on drop, but the SAFETY invariant that justifies the transmute did not hold for them. Drain::settle now waits for the jobs and takes the first panic, the first error and the untaken chunks under the lock, on the calling thread, on the return path (Drain::finish) and on the unwind path (Drop) alike, so a clone of the shared state that outlives the call owns only empty containers. Found independently by the adversarial and code-review lanes of the review. Co-Authored-By: Claude Fable 5.1 <[email protected]> --------- Co-authored-by: Claude Fable 5.1 <[email protected]>
Summary
The refresh's CPU path serialized the 400k accepted-share array twice (audit prefix and the WindowRef digest),
serialized the counted-share array twice (commitment leaf and audit suffix), folded it with two million
string clones on one thread and hashed the slice digest with four million tiny SHA updates; the two pipeline
lanes were balanced at ~606 and ~611 ms, so neither could shrink alone. This PR cuts both lanes without
changing a byte of any artifact, and trims two dead ledger probes on new tips.
Refs #275.
Byte-identical CPU cuts (builder only; verifiers stay serial and untouched):
qbit_prism::parallel(new): ordered chunk pipeline on one process-wide worker pool (¾ of the cores,at most 16 threads),
write_array/write_array_frames(exactlyserde_json::to_writer(&slice), eachelement still written by serde_json, chunks concatenated in order), and
StructSplice, a serializer thatkeeps a struct's derived field order and skip rules but supplies one field's value bytes from a chunk-
parallel writer.
PrismRewardManifest's derive andAuditBundleRef::serialize_suffixremain the onlydefinitions of the audit bytes; u128 fields reach serde_json's own
serialize_u128as before.CanonicalAuditHashPrefix::new_with_share_digestserializes the accepted shares once and feeds bothSHA states (prefix and
WindowRef.snapshot_sha256), the second on its own thread over the same frames.reward_manifest.sharesin orderedchunks (
reward_manifest_sha256,finish_with); with CTV the manifest is digested once for the leaf andthe fan-out precommitments instead of twice.
compute_prism_window_paralleldecides counted difficulties serially, buildsCountedSharechunkson the pool, encodes each chunk's slice-digest bytes and entitlement partial sums there, and streams the
digest on its own thread (one update per chunk). Eligibility/ordering and the per-share digest encoding
are shared with the serial fold (
eligible_window,update_slice_digest).under the same build admission.
Lean-tip I/O (R5): probe #1 is skipped when the template fingerprint already differs (it includes
previousblockhash), probe #2 when the cached window's revision is below the one the chain-observation write
returned (every revision write is an increment), and the landing metric takes the anchor transaction's
revision. The same-template path is unchanged (probe #1 still precedes the fee RPC). The in-transaction save
fence and the lock-loop re-prove are untouched.
AUDIT_BUILDER_VERSIONis unchanged.Method
Real processes: two
qbit-prism-serverfrontends launched byqbit-prism-loadat the production initial-jobadmission (128), 2,000 Stratum sessions, a 400,000-share payout window, background shares at 1/s, 8 external
tips per run, runtime workers 8, pool 16. Both binaries carry the same diagnostic spans (scratch copies of
the trees; nothing in this PR is instrumentation); spans are aligned to the harness node's
minted_at.Order: A/A pair (base, base), then base A, candidate A, candidate B, base B. Every row is the median over a
run's 16 refreshes (8 tips × 2 frontends); every refresh took the delta share-acquisition path and served
2,000/2,000 sessions on both frontends. The host (22 cores, SHA-NI) was shared with other work; every heavy
step ran under one lock, and the A/A pair bounds the remaining noise.
Timing (on top of the merged fan-out work)
Base =
origin/3.x.xb61747e (#499 fan-out C1+C2+A and #498 merged); candidate = this branch on b61747eat its default pool size (4 threads). The branch was then moved onto 03f6347 (#501, delta across
retargets; one conflict in the refresh-trigger label, resolved to label a skipped probe from the parent
alone); a confirmation pair on that base (one run each, busier host): refresh 777 → 417 ms, tip→last notify 1061 → 678 ms, mean miner latency 979 → 610 ms, p99 1061 → 686 ms, publish→last 251 vs 252 ms, peak RSS 557 → 669 MiB, RSS after the tips 328–342 → 568–608 MiB; #501's refresh log shows the same trigger/acquisition mix on both binaries. Balanced A/B, base A / candidate A / candidate B / base B, eight
tips per run, medians over each run's 16 refreshes (8 tips × 2 frontends); every refresh took the delta
share-acquisition path and served 2,000/2,000 sessions on both frontends with reconciliation equal in
every phase and no refusals. A/A noise on this host (two base runs, earlier pair): refresh 2.7 ms, tip→last
13.5 ms, mean 12.2 ms, p99 19.3 ms.
Hashrate loss at 60 s (1 − exp(−mean/60)): 1.5 % → 0.9 %. Share-ack latency (harness client_ack p99,
ms, warm-up / steady state): base 10.1 / 5.7 and 50.0 / 7.0, candidate 15.1 / 10.9 and 16.8 / 10.1: within
run-to-run spread. Lanes (ms, base → candidate): left (prefix + WindowRef digest) 309–311 → 121–125;
right body 388–396 → 215–220; finish (suffix) 225–227 → 90.
Pool-size trade-off (
PRISM_REFRESH_BUILD_THREADS, same base pair, RSS per frontend after the eightwarm-up tips from the harness's
rss_kib_last):The refresh stops getting faster above four threads (every stage is bounded by its consumer: the SHA-256
states and the fold's merge) while more threads retain more memory across allocator arenas, so four is the
default; eight saves almost nothing over sixteen, two starves the tee's producers. The retained excess over
base at the default is +100–240 MiB per frontend after the tips and converges (it does not grow with
further tips);
PRISM_REFRESH_BUILD_THREADS=0restores the serial builder.Fault injection (real processes, same configuration)
Pool backends terminated mid-fan-out on tips 2 and 5 (16–32 backends), three own-block landings bumping the
payout revision while work was built and persisted, and a PostgreSQL fast restart during tip 3, each on the
candidate and on the base: every tip served 2,000/2,000 sessions on both frontends; reconciliation
offered = acknowledged = committed in every phase with zero missing, unexpected, unknown-outcome or
no-response commits and zero durability findings; the only refusals were the three
stale jobrefusalsafter landings (the existing revision fence). One existing
offered candidate could not be processed … payout revision changed while observing chain statealert appeared once on a base run and once on acandidate run; it is independent of this change.
Tests
tests/parallel_builder.rs(new): randomized windows (sizes 0–2,000, every string escape edge, u128difficulties at both ends, ineligible shares, credit policy, three orderings, CTV) × six thread/chunk
geometries: identical body, canonical bytes, pipelined audit hash, share-array digest, reward-manifest
digest and commitment leaf; the serial verifier accepts every parallel body and rebuilds its window; chunk
boundaries 1–4,097; empty window; golden vectors for a fixed 2,048-share window recorded from the serial
builders and re-derived on the untouched base tree.
parallel::tests: framing equality for every chunking, ordered consumption with bounded look-ahead,first-error propagation from either side, producer panic re-raised after draining, writer failures,
struct splice equality and refusal of non-struct values, frames through the digest thread.
overlapped_body_preserves_exact_serial_audit_bytes, the compute-pipeline admission/cancellationtests (now with the prefix→left hand-off), and the refresh-window deferral tests pass; tests force
3 workers × 5-element chunks so the ordered path runs on any host.
cargo testfor qbit-prism and qbit-prism-server (lib and every integration test, including thePostgreSQL-gated ones with the gate manifest checked),
cargo clippy --workspace --all-targets -D warnings,cargo fmt --check: on the final tree (3.x.x 03f6347 plus this change) 3,948 passed, 0 failed, 60 ignored across the workspace (78 test binaries, PostgreSQL 16 and qbitd for the gated suites) with all 692 expected gated tests executed and the manifest check passing; clippy and fmt clean;scripts/check_prism_settings.pyclean.Independent review (no blockers, 8 minors) and dispositions
ordered_chunksinline(thread-local flag set on every pool thread), as does a disabled pool or one whose threads failed to
start; nested use cannot park the pool. Test: nested
ordered_chunksinside a producer completes withcorrect order and takes the serial path.
PRISM_REFRESH_BUILD_THREADS(0 = serial builder, 1–64 = poolthreads, empty = three quarters of the cores capped at 16) validated at startup, listed in the native
settings inventory (
scripts/check_prism_settings.pypasses), documented in PRISM.md and.env.example,rejected out of range by the config CLI test. The thread arithmetic in the code comments now states the
real shape: pool threads plus two lane threads and two digest threads per refreshing frontend, one pool
per frontend process. Pool threads keep the process's priority (not changed).
and revision) now uses the chunked fold, leaf, tee and suffix on its single lane; the benchmark's
new-tip path is unchanged.
revision_work_observedis fed right after reconcile from therevision the chain-observation write returned (the instant the ledger probe used to feed it), and again,
idempotently, from the anchor transaction and at window selection, so a bump between those points is still
recorded at the later instant.
before the counted-share drop is deferred.
submitted job finished before the unwind reached the caller, none runs afterwards, and the pool still
serves ordered work.
builders run serially instead of leaking a half-started pool.
ordered_chunksstates that producers must not block on the consumer ordepend on the pool;
BufferPool/spawn_hasherstate the buffer-return bound.Caveats
RSS retained after the tips is +100–240 MiB: glibc keeps freed memory per arena across the pool's threads;
per-stage threads instead ratcheted RSS every refresh, which is why the pool exists. It does not grow
across tips. The frontend that lands its own block peaks at 1.9–2.5 GiB while it publishes that block's
audit bundle on base and candidate alike (pre-existing).
unsafe(parallel::ordered_chunks): the per-chunk job's borrowed closure is lifetime-erased to runon the persistent pool; a drain guard waits for every submitted job on return and on unwind, and jobs never
block. Covered by the producer-panic and consumer-panic tests; the independent review read the argument
and added a 50-round unwind stress and a concurrent-callers test of its own (both passed).
(discarded at run end); the byte identity is proven by the property/golden tests and the PostgreSQL-gated
audit and landing tests.
🤖 Generated with Claude Code
Need help on this PR? Tag
@codesmith-botwith what you need. Autofix is disabled.