Skip to content

3.x.x: #502 follow-ups: pool drain state in an Arc, prefix-only rebuild, trigger precedence, retained memory (#509) - #512

Merged
djh58 merged 2 commits into
3.x.xfrom
djh58/prism-b509-refresh-pool-soundness
Sep 24, 2026
Merged

djh58 merged 2 commits into
3.x.xfrom
djh58/prism-b509-refresh-pool-soundness

Conversation

@djh58

@djh58 djh58 commented Sep 24, 2026 •

Copy link
Copy Markdown
Member

Implements #509 (which absorbed #508): the four low-severity findings that survived #502's review. No artifact byte changes: the byte-identity suites (parallel_builder.rs, golden pins, frozen corpus, audit_cli goldens) are untouched and pass.

F1: pool drain state in an Arc (soundness)

ordered_chunks kept its drain state (the ready map, the first error, the outstanding count and their condvar) on the caller's frame and lent it to every job through the lifetime-erasing transmute. A job's last actions are decrementing outstanding and unlocking the mutex; 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 (benign on Linux, undefined behaviour in Rust's model).

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, so the drain guard's wait still bounds every borrow. The SAFETY comment states the new invariant. The twelve parallel::tests pass under Miri (nightly cargo miri, -Zmiri-num-cpus=4 -Zmiri-disable-isolation -Zmiri-ignore-leaks; the last flag only allows the never-stopped global pool's threads to exist at exit). The module split into pool, ordered-pipeline and struct-splice modules is left for later, as the issue allows: the change is local to ordered_chunks.

F3: prefix-only rebuild (hot path)

The reused-window rebuild (prepare_refresh_body_with, every same-tip template churn) called CanonicalAuditHashPrefix::new_with_share_digest and discarded the digest: a hasher thread and a second full SHA-256 pass over the share array for nothing. CanonicalAuditHashPrefix::new_with(shares, parallelism) feeds the prefix alone, through the same ordered-chunk array writer, and the rebuild takes it. A thread-local probe (share_digests_computed_on_this_thread, #[doc(hidden)]) counts the digests new_with_share_digest computes; a qbit-prism test pins that new_with computes none at four geometries and that its prefix state equals the serial one, and a server test pins that the reused-window rebuild computes none and produces the pipelined refresh's hashes.

F4: trigger label precedence on the reused-window path (observability)

Since #502 a new template on the same tip runs no ledger probe at entry, so the label was always template there even when the revision, balances, reanchor, shares or fee had changed. The label is now named on that path from the window the rebuild used (its revision, balances digest and share sequence), once it is admitted, by the same precedence as the probed path; refresh_trigger now takes those three values and delegates to classify_refresh over a RefreshChanges record. A coordinator test drives a same-tip template change with a revision bump and reads revision (then template for a template change alone) from qbit_prism_refresh_seconds; a unit test pins the precedence. The metric inventory's description gains one sentence (edited in docs/prism-metric-metadata.json, regenerated). scripts/test_prism_alert_promql.py passes.

F2: retained memory (docs only)

docs/prism-storage-sizing.md gains "Refresh build memory per frontend": #502's confirmation-pair numbers (after the tips 328-342 to 568-608 MiB, peak 557 to 669 MiB), the independent 400k probe (251-254 MiB serial against 284-330 MiB at eight workers), roughly 0.5 GiB more retained on a two-frontend host, the knob that bounds it (PRISM_REFRESH_BUILD_THREADS, with MALLOC_ARENA_MAX guidance), and that the build slot (PRISM_JOB_BUILD_EXECUTOR_WORKERS) no longer bounds live counted-share bodies exactly.

Not done

The optional refresh_parallelism() cfg!(test) replacement is left as is: every server test relies on the forced (3, 5) geometry, so a fixture override is not a small change. The builder-options struct and the parallel.rs module split are left for later, as the issue allows.

Checks

  • qbit-prism lib (160 tests) and parallel_builder (4 tests, 1 ignored): pass, both plain and pinned to two cores
  • parallel::tests under Miri: 12 passed, no undefined behaviour reported
  • qbit-prism-server lib binary, whole run against a private PostgreSQL 16: 568 tests pass (the new F3 and F4 tests included); its gate manifest passes the checker against the binary's 134 gated ids
  • cargo clippy --locked -p qbit-prism -p qbit-prism-server --all-targets -- -D warnings: clean
  • cargo fmt --all --check: clean
  • scripts/test_prism_alert_promql.py (promtool 3.14.0): 38 expressions, 146 scenarios pass
  • scripts/generate_prism_metrics.py --check and scripts/generate_prism_alerts.py --check: clean
  • test/prism-gated-tests.txt: unchanged
  • Not run locally: the rest of the workspace test suite

Closes #509

🤖 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 2 commits September 24, 2026 13:13
…ld, 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]>
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]>
@djh58

djh58 commented Sep 24, 2026

Copy link
Copy Markdown
Member Author

Review ledger (head 0994c69, CI green)

Scope. #509 in full: F1 (pool drain state in an Arc, only produce borrowed), F3 (prefix-only rebuild, no share digest), F4 (trigger precedence restored on the reused-window path), F2 (sizing doc). No artifact byte changes; the identity suites, golden pins, frozen corpus and CLI goldens pass unchanged.

Coordinator review. Reviewed the staged diff (Shared in an Arc per job, only produce borrowed, SAFETY comment matches). Approved.

Local lanes.

  • /code-review medium: one Low finding, chunks the consumer never took stayed in the shared state and were dropped by the last Arc holder, possibly a pool thread after the caller's frame was gone, while C may borrow that frame (the counted-share fold's chunks do). Fixed in 0994c69: Drain::settle waits for the jobs and takes the first panic, the first error and the untaken chunks on the calling thread, on the return and the unwind path alike. Everything else verified: drop order, both refresh_trigger call sites, the late label reading the same published work as the equivalence check, new_with writing the identical prefix bytes, the thread-local probe, and the docs.
  • Adversarial (Fable): found the same leftover-chunk gap independently (cross-lane, must-address, fixed as above); no further refutation across the transmute's remaining borrow, Arc<Shared>: Send enforcement, the prefix bytes at four geometries, the probe's thread scoping, and the entry-time reanchor capture.
  • Thermo-nuclear: two notes, both kept as is: the doc-hidden probe accessor (the server-side pin needs cross-crate visibility; a feature for one counter would be heavier) and refresh_trigger taking three values instead of PayoutState (the two call sites source them from different types; the comparison lives in classify_refresh over a named record).
  • Codex lane: not run (this lane is Claude-only).

Verification. qbit-prism lib (160) and parallel_builder (4) pass plain and pinned to two cores; parallel::tests under Miri: 12 pass, no undefined behaviour; server lib binary (568) passes against a private PostgreSQL 16 with the gate checker green on its 134 ids; clippy -D warnings and fmt clean on both crates; PromQL alert test and both generator checks pass; gated-test manifest unchanged.

Bots. CI green; tenki and codex-on-github posted nothing.

Closes #509

@djh58
djh58 merged commit 14f9b06 into 3.x.x Sep 24, 2026
21 checks passed
djh58 added a commit that referenced this pull request Sep 25, 2026
Brings in #470, #512, #513, #514 and #515. #515 opens the share append's
transaction through AppendConnection::begin, which records BEGIN completion
so that a future cancelled before the reply retires the connection instead
of returning it to the pool; this branch opens the same transaction with
"BEGIN; SET LOCAL plan_cache_mode = force_generic_plan" so the share_id
probe is planned once per connection.

Resolution keeps both: AppendConnection::begin takes the opening statement
and the append passes APPEND_TRANSACTION_BEGIN. SQLx reads every reply of
that simple query through its ReadyForQuery before begin returns, so the
guard records completion only once the whole batch is in.

ledger_cancelled_begin now cancels the append on the custom BEGIN, and a
new case holds only the batch's closing ReadyForQuery (the execution proxy
gains pause_statement_ready) and proves the connection is still retired.
The pool-acquire inventory, the gated-test manifest and the #482 ops notes
follow the new call sites.

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