Opened by a workflow run, Dec 3, 2026 7:19 AM EST. decide malicious: all_clear (100%): No malicious content found
explore
Author: jcartu (CONTRIBUTOR; first change to the selene cache core; Discord: jcartu)
Motivation: Under DRAM prefix-cache saturation, every deferred store retry re-ran the full spill/sort/export path (and, with a full disk, every ENOSPC re-woke the whole deferred queue), burning a full CPU core on the model thread. The PR makes the worker and CompositeStore only count or retry when something actually changed, and bounds ENOSPC probing to one attempt per 50 ms.
Scale: +820 / −71 lines in 6 files
Proposal:
Worker::service_storereconcilestake_publications(),deferred_storesanddeferred_copyoutsinto oneVec<PendingStore>keyed byCheckpointId, processing each ID once (helios/src/server/runtime.rs:2791-2957).- Worker
progressis set only on real transitions (Queued, a changedStoreReason,Oversize/Present,Err), so the loop can park when retries change nothing. - New
HostStore::can_retry_slabs(defaulttrue) gates non-freshSlabsretries beforeexport_fits()/store();CompositeStoreimplements it,PooledStore/Tiersforward it. CompositeStore: ENOSPC completions no longer bumpstats.progress;retry_afterexpiry edge-triggers one probe per 50 ms;spill_parked()is skipped atMAX_SPILLS;spill()early-returns while a write is in flight; orphanedparkedentries are removed instead of panicking.- 9 new deterministic tests (5 in composite.rs, 4 in phase_tests.rs) plus
#[cfg(test)]injectable clock. Touches: - selene/src/composite.rs (spill/park/retry state machine, metrics accounting)
- helios/src/server/runtime.rs (
Worker::service_storereconciliation and progress gating) - selene/src/store.rs + pool/{store,local}.rs (new trait method) Related items:
- #703 helios/selene: high flare-model CPU retry storm under DRAM prefix-cache spill saturation (open): the issue this fixes, same author, same day
- #674 selene,selene-manager,helios: prefix-cache hit rate, L1 retention, NVMe throughput, GPU snapshot packing (open): rewrites the same files/functions, no merge order recorded
- #694 selene,helios: write-side NVMe and pool spill profitability gate (open): stacked on #674, edits the same
service_storeoutcome match andHostStoretrait - #497 Reduce disk offload restore latency and integrated-memory intake overhead (merged): rewrote
Worker::idle_wait2 ms→50 µs, the region #705 cites as its cadence guarantee - #358 Honor the pool refusal retry backoff and count refusal discards (merged): closest precedent, same 50 ms backoff pattern on the pool path
Link: https://github.com/NVIDIA/hyperflare-inference/pull/705
Autobot comments: Zero reviews, comments, labels and no CI on head eec5e95. The "CPU storm stopped" claim has no served-workload benchmark — the only profile is issue #703's pre-fix binary, which was never reproduced on v0.5.3 (charter #210 unmet). The "2 ms idle poll cap" claim is inaccurate:
idle_wait()returns 50 µs/100 µs/2 ms by state and is only reached with zero outstanding GPU work; on discrete GPUspark()returns false, so the loop spin/yields by design. #703's hottest cluster (13.12%,page_snapshot_refscloning inexport_fits()) is explicitly out of scope.held[0],progressand retry-wakeup semantics all change whiledocs/prefix-cache-offload.md:293-297,1364-1372still describe the old contract; the PR also silently relaxes an existing test assertion (composite.rs:2733) and fixes a latent panic. Notepr_diffshows docs/flare-cli files that are mirror base drift (merged #687/#689/#690/#697), not PR content.
Value Proposition
Value Proposition — PR #705 "fix(selene,helios): stop service_store and CompositeStore Retry(Slabs) CPU storm"
Charter alignment — right problem, right layer, wrong evidence. The work sits directly on the roadmap goal "Store prefix-cache checkpoints in host memory and share them across Flare instances via Selene," and in the correct layer: shared selene store code plus the helios worker. No per-model branch, no new flag, no magic default — the knob is HostStore::can_retry_slabs defaulting to true (selene/src/store.rs:324-330), so "keep the runtime small and model-agnostic" is respected. The tension is "Bring real evidence" (#210): the PR is performance-titled but its only profile is issue #703's capture on the pre-fix flare 0.5.1 binary, #703 itself states the storm was not reproduced on v0.5.3, and there is no before/after CPU% or latency on a served workload. No CI ran on head eec5e95; suite counts are author-reported and debug-profile only.
Novelty & status — genuinely additive, not superseded. No merged change on main touches these files since cc0a49d, so this is not obsolete. #674 and #694 rewrite the same CompositeStore::store Retry(Slabs) branch and the same service_store outcome match (#694 adds StoreOutcome::Unprofitable, which #705's new _ => progress = true wildcard would swallow), but neither addresses #703 and no merge order is recorded. This is independent work needing rebase/sequencing, not a duplicate.
Value vs maintenance cost. The diagnosed mechanisms are real: unconditional progress = true defeating worker parking, ENOSPC completions bumping stats.progress with zero durable slots, and spill_parked() re-sorting on every Retry(Slabs). Nine deterministic tests back them. Costs: +820/−71 in shared runtime code; a metric-semantics shift (progress, held[0] cadence, deferred Slabs attempt counts) with no docs/prefix-cache-offload.md update; undeclared collateral (a relaxed existing assertion at composite.rs:2733-2736, a latent-panic fix at 661-664); an overstated "2 ms idle poll cap" claim; and the largest #703 hotspot (13.12%, export_fits() cloning) declared out of scope.
Needed before merge: a served-workload before/after or at minimum a perf rerun of #703's configuration on the patched build (#210); docs update for the changed metric contract; corrected claims; disclosure of undeclared hunks; recorded merge order vs #674/#694.
Verdict: Worth it with changes.
Full report Decide Value: yes (100%): This change is worth reviewing: it provides value to the project in line with its charter.
Classify intake
Selected: triage:review, bug, performance, area:caching, area:selene
Threshold: 65%
Triage
- [✓]
triage:review: 99.5% -
triage:validation: 0.3% -
triage:design-review: 0.1% -
none: 0.0% -
triage:investigate: 0.0% -
triage:integration: 0.0% -
triage:partial: 0.0% -
triage:verify-for-closure: 0.0% -
triage:superseded: 0.0%
Priority
-
none: 66.7% -
priority:P2: 27.8% -
priority:P1: 5.5%
Type
- [✓]
bug: 92.4% - [✓]
performance: 90.5% -
community: 43.8% -
duplicate: 34.9% -
enhancement: 0.8% -
documentation: 0.0%
Area
- [✓]
area:selene: 98.2% - [✓]
area:caching: 94.0% -
area:memory: 53.1% -
area:api: 14.8% -
area:preparation: 11.9% -
area:engram: 3.3% -
area:scheduling: 2.3% -
area:orbit: 1.4% -
area:packaging: 0.5% -
area:kernels: 0.3% -
area:rocenante: 0.3%
Model
-
model:deepseek-v4: 1.1% -
model:qwen3.8-27b: 0.4% -
model:qwen3.8-flash-next: 0.4% -
model:muse-glimmer: 0.2% -
model:mimo-v2.6: 0.2% -
model:inkling-small: 0.1% -
model:kimi-k3.1: 0.1% -
model:nemotron-3.5-bolt: 0.1% -
model:deepseek-v4.1: 0.1% -
model:glm-5.3: 0.1% -
model:gemma4: 0.0%
Apply Labels (Intake)
Applied: +triage:review, +bug, +performance, +area:caching, +area:selene
Gates and contracts
Contracts, Charter & Verification Gates Audit — PR #705
Scope audited: the 6 files in pr_files (selene/src/composite.rs, selene/src/store.rs, selene/src/pool/{store,local}.rs, helios/src/server/runtime.rs, helios/src/server/runtime/phase_tests.rs), against AGENTS.md, docs/design-review.md, docs/verification.md, docs/prefix-cache-offload.md, .github/workflows/native-serving.yml (not opened), and verification/helios-lifecycle/{check.py,README.md}. Algorithmic correctness is out of scope for this lens.
Gate 1 — Core-format / wire / captured-graph / public-contract boundaries: PASS
- No proto, core-format, captured-graph, or wire changes. The diff touches no
.proto, nohelios/src/model/contract*, no core metadata, no executor/transport file. No enum variant, graph kind, or operation contract is added, sodocs/design-review.md:22-26(graph-family approval) and principle 13 (core compatibility) are not engaged, and no live export/serve or legacy-core replay is required. - The one public API addition is contract-safe.
HostStore::can_retry_slabsis a defaulted method returningtrue(selene/src/store.rs:324-329), so every out-of-tree implementor compiles and behaves exactly as before;spillable_slots()was private (selene/src/composite.rs, removed at diff hunk-718,14). No removed Protobuf field, no reserved wire id, no behavior change for the default path. Forwards inPooledStore(selene/src/pool/store.rs:615-616(not opened)) andTiers(selene/src/pool/local.rs:45-48(not opened)) are pure delegation. - No shipped default changed.
MAX_SPILLS(8) and the 50 ms backoff constants are untouched; no CLI flag, config key, or environment variable is added (principle 10 respected). The retry-cadence refinement is internal policy, not a new operator-visible default. - No contradiction of the named normative docs.
docs/scheduling-theory.md(not opened),docs/scheduling-runtime-design.md, anddocs/core-format-design.md(not opened) contain no material onRetry/Slabs/held/parked-spill cadence (grep forRetry|slabs|parked|held|spillindocs/scheduling-runtime-design.mdreturns no matches), so no normative invariant in the documents this gate names is contradicted.
Note (documentation drift, see Minor 1): the behavioral contract the PR does change is documented in docs/prefix-cache-offload.md, which the diff does not update.
Gate 2 — Vendored upstream dependencies & cross-PR conflicts: PASS
- No vendored upstream file is touched (no
helios/native/roce_proxy.c(not opened), nothird_party/, no vendored C). All six files are first-party Rust. - No dependence on an unmerged external recipe or PR: no
Cargo.toml(not opened)/Cargo.lockchange anywhere in the file list, no new dependency, no recipe pin introduced. - The overlap with open PRs #674 and #694 (
selene/src/composite.rs,helios/src/server/runtime.rs,selene/src/store.rs; #694 also adds aStoreOutcomevariant and a siblingHostStoremethod) is a sequencing/logistics matter, not a vendored fork. Recorded here as Info / Nit per calibration: unrecorded merge order is worth a reviewer comment, but it is not a hard gate violation and neither PR is a dependency of this one.
Gate 3 — Mandatory verification evidence & failing tests: FAIL (two findings)
No reported failing test and no reported failing CI — the description claims all suites passed, and per calibration I do not flag the absence of observable GitHub check runs. The failures are of the mandated evidence form:
Major 3.1 — Layer 1 profile requirement not met (--release --locked)
docs/design-review.md:180-184 mandates cargo test --locked --release on every affected crate, matching .github/workflows/native-serving.yml:51 (not opened),63,73,77. The PR states plainly: "All checks ran in debug profile". The author's justification (so debug_assert! invariants execute) does not substitute — and it makes the new debug_assert! guards in writing_spills() (selene/src/composite.rs:752-771) unverified in the profile CI actually ships and tests. Secondary gap in the same gate: CI runs selene with --features test-support (.github/workflows/native-serving.yml:51 (not opened)), but the reported command is cargo test --manifest-path selene/Cargo.toml (not opened) with no feature, so test-support-gated selene tests were not shown to have run. Required before merge: cargo test --locked --release for selene (with --features test-support) and helios (--features runtime-core,server), plus flare and flare-cli as the description already claims.
Major 3.2 — Performance claim with no served-workload A/B on the patched build
The title and summary claim a CPU-storm fix ("stop service_store and CompositeStore Retry(Slabs) CPU storm"), but the evidence shipped is unit tests plus a test inventory. docs/design-review.md:106-115 (principle 12) requires "Performance claims require equivalent baselines, complete GPU steps across all ranks, and actual Helios service measurements", and the charter requires a main-vs-branch served-workload A/B (#210). The only profile in play is issue #703's capture on the pre-fix flare 0.5.1 binary, and #703 itself records that the storm was not reproduced on v0.5.3. There is no post-fix perf sample, no CPU% before/after, no latency measurement. The mechanism-level tests (selene/src/composite.rs:6295-6634; helios/src/server/runtime/phase_tests.rs:9022,9058,9119,9162) are real and support the mechanism, not the headline. Either retitle/downgrade the claim to the mechanism, or attach a #703-configuration rerun on the patched build.
Not applicable (stated to avoid over-flagging)
- No TLA+/Kani gate is triggered.
docs/design-review.md:209-220requiresverification/helios-lifecycle/check.pyfor changes to admission, fences, generations, cancellation, speculation accounting, cache compaction, snapshot aliases, response buffering/ownership, offload aggregation, readiness, or rank coordination.Worker::service_storepublication retry/parking is none of those: the check's models map toLifecycle(scheduler admit/commit/complete/cancel),RankProtocol/DispatchRing/RankDispatch(executors),OffloadTransfer(helios/src/offload/transfer.rs(not opened) aggregation, untouched),CacheOwnership(helios/src/cache.rs(not opened)PrefixCheckpointCache, untouched),Speculation,ResponseLifecycle,CheckpointReservation(verification/helios-lifecycle/check.py:18-35). No model transition is added or redefined, so no model/fixture update is owed. The pin discipline in the touched code is unchanged (pin athelios/src/server/runtime.rs:2902, unpin unlessQueuedat :2917-2919). Runningcheck.pyas a regression is still advisable for a change inhelios/src/server/runtime.rs(a mutation target atcheck.py:653), and its phase_tests conformance suites live in the same module the PR extends — recommend the author run it and report the result. - No Kani gate: no completion-vector validation, prepared completion contract, state-view extent arithmetic, or sequential-validator change.
- No GPU/CUDA/VMM or transport gate:
selene/has no CUDA dependency (docs/prefix-cache-offload.md:27-30); no file underhelios/src/execution/is touched.
Gate 4 — Material scope / claim contradictions: no blocker, three factual corrections (not a hard gate)
The scope matches the description: pr_files = 6 files, +820/−71, and the claimed tests all exist where claimed. Nothing thousands-of-lines-unrelated is bundled. The extra preserve_message_anchor / AGENTS.md / docs/* hunks that pr_diff shows are mirror base drift, verified independently (no preserve_message_anchor on main), so they are not undeclared PR content. Corrections the author should make (principle 12/16, "report evidence honestly"):
- "
Worker::run… enforces a 2 ms idle poll cap so theretry_afterexpiry edge fires reliably" is not what the code does.idle_wait()returns 50 µs, 100 µs, or 2 ms by state (helios/src/server/runtime.rs:1269-1292) and is reached only whenexecutor.outstanding() == 0(:1249-1263); with GPU work outstanding the loop parks/spin-yields instead. No 2 ms cap exists on the cadence the claim relies on. - "9 new unit tests (all deterministic, zero sleeps)" —
enospc_retry_after_expiry_wakes_sole_deferred_store_deterministicallycontains a 10-second wall-clock loop (while Instant::now() < deadline { … std::thread::yield_now(); }) despite its "no sleeps!" comment. The injectedpoll_atclock makes the assertions deterministic, but the claim as written is inaccurate. - Two changes are undisclosed: the relaxed pre-existing assertion at
selene/src/composite.rs:2730-2736(store.spill(child.key).unwrap()→ guarded by!store.parked[&child.key].writing), and the latent-panic fix that removes an orphanedparkedentry indisk_stored()(selene/src/composite.rs:661-664). Both should be stated in "Changes".
Minor 1 — Documented behavior/contract drift in docs/prefix-cache-offload.md (follow-up, not a blocker)
The PR changes exactly what that document specifies, and no docs file is in the diff:
- §2.2 store interface lists the
HostStorecore operations and omitscan_retry_slabs(docs/prefix-cache-offload.md:272-284). - The worker retry contract still reads "The worker retains only checkpoint IDs for retries after store progress and discards IDs that have left the GPU cache" (
:293-297), while the worker now also gates non-freshSlabsretries oncan_retry_slabs(helios/src/server/runtime.rs:2880-2888) and no longer setsprogressunconditionally. - Retention-metrics text (
:1364-1372) still describesflare_host_cache_held_total{tier}per holding event andstore_skippedincluding "retries", which the PR's own "Narrow Metric and API Shifts" section changes (held[0]now accounted on progress-gatedpoll()ticks; deferredSlabspublications skipped bycan_retry_slabs()no longer reachstore()).docs/api.md:366(not opened) also namesflare_host_cache_held_total{tier}.
AGENTS.md:52-58 requires a design document to state the behavior the code implements, so this belongs in this PR or an explicitly linked follow-up. I am not treating it as a merge blocker because prefix-cache-offload.md is a description of the shipped mechanism rather than one of the three normative documents this gate names, and no operator-facing default, on-disk format, or wire contract moved.
Verdict for this lens
Contract, vendored-file, and cross-PR-conflict gates: clean — this PR adds no core-format/wire/graph contract and forks no vendored upstream. The blocking items are verification-form only: (3.1) the mandated --release --locked (and --features test-support) runs were not performed — everything is debug-profile, so the new debug_assert! invariants are unexercised in the shipped profile; and (3.2) a performance-titled fix without an attributable patched-build served-workload measurement (principle 12 / charter #210). Both are answerable by running the already-mandated commands and attaching one perf/CPU% before-after on #703's configuration; nothing in the design requires rework. Recommended same-PR cleanups: correct the "2 ms idle poll cap" and "zero sleeps" statements, disclose the two undeclared hunks, and refresh docs/prefix-cache-offload.md:272-297,1364-1372. Recorded as Info only: unrecorded merge order versus open #674/#694.
Subtraction and simplicity
Subtraction & Simplicity audit — PR #705 (eec5e95, 6 files, +820/−71)
Verdict: the selene side (composite.rs) is mostly lean and additive in the right places — has_spillable_slots's early exit, writing_spills, the Option<Instant> test seam and the default-true trait method are all cheaper than what they replaced. The helios side is where the cost is: service_store grew from ~30 lines of loop to ~165 lines of bookkeeping that carries four dedup collections and a two-field flag pair, and it contains one duplicated block transcribed verbatim. CompositeStore::can_retry_slabs is 53 lines of which three fragments are copied out of store()'s preamble. I also found one genuinely dead branch and one unreachable branch.
Everything below is behavioural-equivalent unless stated.
1. helios/src/server/runtime.rs:2791-2795 — two fields encode 3 states across 4 combinations, one of them contradictory
struct PendingStore {
publication: flare_selene::PublishedCheckpoint,
prior_retry: Option<flare_selene::StoreReason>,
fresh: bool,
}
fresh exists only to suppress the slab gate at :2880-2883 (if !fresh && prior_retry == Some(StoreReason::Slabs) && …). But fresh: true with prior_retry: Some(_) is a live, legal state (:2823-2826 sets prior_retry on an entry that already has fresh = true), so the reader has to hold "fresh means also came through take_publications() this pass, it does not mean prior_retry is None" in their head. ( =None, fresh=false) (deferred copyout, :2864-2868) and ( =None, fresh=true) both exist too.
Collapse to one field:
enum Prior { Fresh, Copyout, Retried(StoreReason) }
and the gate becomes if matches!(prior, Prior::Retried(StoreReason::Slabs)) && !store.can_retry_slabs(&publication), the progress test at :2933 becomes prior != Prior::Retried(reason), and the retry-success credit at :2947 becomes matches!(prior, Prior::Retried(_)). Four states become three, and the one that cannot happen becomes unrepresentable.
2. helios/src/server/runtime.rs:2803-2819 and :2857-2873 — the same insert-or-set-flag block written twice, plus three collections doing one job
The publication loop and the copyout loop are the same shape:
match publication_index.entry(publication.id) {
std::collections::hash_map::Entry::Vacant(entry) => { entry.insert(publications.len()); publications.push(PendingStore { … }); }
std::collections::hash_map::Entry::Occupied(entry) => { let pending = &mut publications[*entry.get()]; pending.publication = publication; pending.fresh = true; }
}
vs.
if !publication_index.contains_key(&id) && !seen_waiting.contains(&id)
&& let Some(publication) = self.scheduler.publication(id) {
if retry_copyouts { publication_index.insert(id, publications.len()); publications.push(…); }
else if seen_copyouts.insert(id) { self.deferred_copyouts.push(id); }
}
Four collections (publication_index, seen_waiting, seen_copyouts, prev_deferred_copyouts) are used to answer one question — "has this CheckpointId already been claimed this pass?". Since publications is local to the function, the index is used only as "has been pushed", so a small local type collapses all of it:
struct Pending { list: Vec<PendingStore>, at: HashMap<CheckpointId, usize> }
impl Pending {
fn claim(&mut self, publication, prior) -> bool { /* insert if absent, else overwrite */ }
}
seen_copyouts then disappears entirely (the copyout list is rebuilt from scratch anyway — the prev_deferred_copyouts snapshot is the only thing that has to survive), and seen_waiting only needs to exist because waiting is a plain Vec. This is ~50 lines of index/set maintenance reducible to a helper of ~10 plus three call sites, and it removes the chance of the two seen_* sets drifting out of sync with the index.
3. helios/src/server/runtime.rs:2801-2802, 2805, 2813, 2821, 2854, 2856 — fully-qualified paths shadowing an existing import
runtime.rs:8 already has use std::collections::{HashMap, VecDeque};, yet the new code writes std::collections::HashMap::<crate::cache::CheckpointId, usize>::new(), std::collections::HashMap::new(), std::collections::hash_map::Entry::Vacant, std::collections::HashSet::new() (×3), std::collections::HashSet<crate::cache::CheckpointId>. Nine fully-qualified paths for two types; use std::collections::{HashMap, HashSet, VecDeque, hash_map::Entry}; at the top deletes all of them and matches request.rs:92's existing style.
4. helios/src/server/runtime.rs:2941-2943 — the wildcard re-introduces the bug the PR fixes
_ => {
progress = true;
}
The whole point of the change is "progress only on genuine state transitions". A wildcard arm that means "anything I haven't enumerated counts as progress" is exactly the assumption #694 breaks: it adds StoreOutcome::Unprofitable to this same match, and that outcome by construction made no progress — the wildcard will report worker progress for it and the storm returns for that variant. Enumerate the variants that really are progress (Oversize | Present), which is one word longer and can't silently rot.
5. selene/src/composite.rs:903-905 — dead branch
if let Some(started) = self.spill(key) {
…
} else if self.backoff_active() {
break;
}
The enclosing loop is guarded by :892 if writing < MAX_SPILLS && !self.backoff_active() {, and nothing inside the loop can arm the backoff: retry_after is written in exactly two places, disk_stored (:668) and poll (:1658), neither reachable from spill() → thin_rows / reserve_capture / start_write. So self.spill(key) returning None because of backoff is impossible here, and the else if can never fire. Delete it (three lines), or if it is meant as future-proofing, say which future writes retry_after — otherwise it reads as a guard against a state the function does not have.
6. selene/src/composite.rs:1405-1457 — can_retry_slabs copies three fragments of store()'s preamble
can_retry_slabs |
duplicate of |
|---|---|
:1406-1408 if checkpoint.tail_pages > checkpoint.chain_pages.len() { return true; } |
:1263-1270 in store() (which returns Err) |
:1416-1422 let covered = !self.disk.is_failed(&key) && self.disk.covered_endpoint(checkpoint, |n| { n.ready || self.resident(&n.key, n.tail_pages, true) }); |
:1272-1275 — character-for-character |
:1423-1431 let (_, tail) = self.disk.plan_record(checkpoint); let needed = self.memory.layout().record_slots(tail.len(), true); … let short = self.memory.shortfall(needed); if short == 0 { return true; } |
:1328-1333 |
checkpoint.tail_pages > checkpoint.chain_pages.len() is the one that matters: in store() it is a corrupt publication (Err(invalid(…"claims {} tail pages of a {}-page chain"))), here it is "go ahead and retry". If the invariant ever fires, can_retry_slabs returns true, the worker calls store(), gets Err, and bumps host_retry_abandoned[5] — i.e. the gate silently converts an integrity error into a retry loop, which is the storm pattern in miniature.
Simplification: extract the covered/slots/shortfall computation both callers need into one helper, e.g.
/// The memory slots this publication's record would need, and how many it is short.
fn slab_need(&self, checkpoint: &PublishedCheckpoint) -> Option<(Option<PrefixKey>, usize, usize)>;
store() becomes let (parent, needed, short) = self.slab_need(cp)…, can_retry_slabs reuses it, and one of the two copies of the covered_endpoint closure goes away. That is ~15 lines out and one class of divergence gone.
Also within can_retry_slabs: seven of its eight early returns are true, so the function reads as a 53-line "when may we skip" with the answer buried in the last line. Written as a predicate on the skip condition it is one expression:
fn can_retry_slabs(&self, cp: &PublishedCheckpoint) -> bool {
let Some((_, needed, short)) = self.slab_need(cp) else { return true };
let (writing, covered) = self.writing_spills();
!(writing < MAX_SPILLS && covered < short && !self.backoff_active() && !self.thinnable(short) && self.has_spillable_slots(short))
}
with thinnable the row block at :1432-1451 lifted out (it is self-contained and worth naming — short.div_ceil(row_slots) vs thinnable_rows is the least obvious predicate in the file).
7. selene/src/composite.rs:1378 — a full scan through the invariant checker to read one number
if self.writing_spills().0 < MAX_SPILLS {
writing_spills() (:752-771) iterates every jobs entry, and then runs debug_assert_eq! which iterates every parked entry again — in debug builds, on the hot rejection path, to answer "are 8 writes in flight?". writing_spills returns (usize, usize) but .0 alone is wanted at this call site (and at :888 the sum is only meaningful together with the parked-record check). Split it: fn writing_count(&self) -> usize (or drop it entirely at :1378 in favour of the cheap, always-correct self.outbound.values().filter(|o| o.write.is_some()).count()), and keep the (writing, covered) pair only where the covered sum is used (spill_parked, can_retry_slabs).
8. selene/src/composite.rs:656-720 + :1610-1613 — disk_stored returns a bool to bump a metric it already has &mut self for
if self.disk_stored(id, result, header) {
self.stats.progress += 1;
}
disk_stored takes &mut self, already writes self.stats.held[0] += 1 (:667), self.stats.stored += 1, self.stats.store_failed += 1 — and then hands back a bool so the caller can bump self.stats.progress in a different iteration of the same match. Two of its three return points (:658, :663) return values that only ever feed this if. Folding it in (self.stats.progress += 1; on the same lines, fn disk_stored(…) returning ()) removes a cross-function invari ant ("caller must not forget to bump progress"), and lets :660-663 — self.parked.remove(&key); return true; — read as the plain cleanup it is rather than as a signal.
9. selene/src/composite.rs:775-777 — unreachable guard
fn has_spillable_slots(&self, need: usize) -> bool {
if need == 0 {
return true;
}
Both production callers pass a value already proven > 0: :1334 if short > 0 && !self.has_spillable_slots(short) and :1452 (after :1429 if short == 0 { return true; }). Only the new test calls it unguarded (:6401). One line of defence against a caller that does not exist; either drop it or drop the short > 0 at :1334 and let this function be the single owner of the 0 case.
10. selene/src/composite.rs:2733-2736 — the relaxed assertion is a symptom worth subtracting rather than adding
if !store.parked[&child.key].writing {
store.spill(child.key).unwrap();
}
assert!(store.parked[&child.key].writing);
Before the PR this was store.spill(child.key).unwrap(); — the test relies on spill() returning Some for that key. The new guard at :819-821 if parked.writing { return None; } turns that into a silent no-op, so the test was wrapped to keep passing. But every other spill() call site already pre-checks the same condition (:1293 self.parked.get(&key).is_some_and(|p| !p.writing), :1339, :1824 filter(|p| !p.writing)) and waiting_spills filters !parked.writing at :874. So the guard duplicates four existing checks and its only observable effect in the tree is to make one existing caller's contract weaker. Either keep the guard and delete the four redundant pre-checks (net subtraction at the call sites), or drop the guard and keep spill() total — but not both, because today the code has two sources of truth for "may I start this write", which is exactly the kind of thing the new debug_assert! at :757-769 will start tripping on.
11. selene/src/composite.rs:1656-1671 — the wake edge is implemented by mutating a public counter twice, then re-reading it
let retry = self.retry_after.is_some_and(|at| self.retry_now() >= at);
if retry { self.retry_after = None; self.stats.progress += 1; }
let progress = self.stats().progress;
if !self.disk.preserve_committed && self.maintenance_progress != progress {
progress is read after the bump, so the maintenance branch fires because the metric moved, and the || retry disjunct that used to express this directly was deleted. The logic survives only because stats() is called one line below the increment. retry is right there and already computed:
if !self.disk.preserve_committed
&& (self.maintenance_progress != self.stats.progress_before_the_bump || retry)
i.e. keep the disjunct and the metric bump independent — one of them is a wake signal, the other is a number operators read (held_total{tier="dram"}, store_reasons_total), and coupling them means a future change to metric semantics silently changes when spill_parked()/disk.maintain() run. This is the one place I would not call the current shape merely verbose; it is fragile in a way a single extra || avoids.
Confirmed lean (no action)
selene/src/store.rs:324-330— default-truetrait method with a doc comment stating the exact contract ("Returnsfalseonly whenstore(checkpoint)would returnRetry(StoreReason::Slabs)again"). Out-of-tree implementors compile unchanged; nothing speculative.selene/src/pool/local.rs:45-49,selene/src/pool/store.rs:615-617— pure forwarding, four lines each, no logic to subtract.selene/src/composite.rs:221-240—retry_nowis#[inline]with the#[cfg(test)]override compiled out of release, andpoll_atis#[cfg(test)]. This is the cheap version of the seam; nothing to remove.has_spillable_slotsreplacing thesum()-everythingspillable_slots()is a real reduction (whole-map fold → early-exit scan) and the only remaining caller of the old shape is gone.- Tests: the 5 new selene tests hang off existing helpers (
parked_root,checkpoint,poll_until,composite_with_intake) rather than new fixtures; the 4 helios tests reuseFakeStorewith one added field (retry_slabs_ready,phase_tests.rs:2088, 2222-2226). No new test scaffolding to subtract.
One process note (not subtraction)
docs/prefix-cache-offload.md:293-297 still documents the pre-PR worker contract — "Retry accepts no copy. The worker retains only checkpoint IDs for retries after store progress" — while service_store now keeps IDs and a per-ID reason and a can_retry_slabs gate. Not changed by this PR, but it is the artifact a reader will use to decide whether the new bookkeeping is justified, so it argues for finding 1 and 2 to land as a smaller diff with the doc updated in the same place.
Code correctness
Deep Code Correctness, Invariants & Hot-Path Performance Audit — PR #705 @ eec5e95
Scope audited: selene/src/composite.rs (+519/−50), helios/src/server/runtime.rs (+89/−21), helios/src/server/runtime/phase_tests.rs (+196), selene/src/store.rs, selene/src/pool/store.rs, selene/src/pool/local.rs. Diff is ~891 changed lines across 2 crates (helios, selene) — at the small-PR threshold, so I audited directly rather than partitioning into sub-agents.
Verdict: No Blocker and no Major correctness bug found in the state machine. The retry-storm fix is structurally sound: I traced every progress edge, every parked/jobs/outbound insertion–removal, and every can_retry_slabs() == false exit for a guaranteed future wake source, and found no stall, no lost wakeup, no zombie waiter, and no duplicate store() submission. I did find one Major hot-path defect (bounded but strictly worse than the code it replaced), and two Minor defects (a debug-overhead/allocation leak and a metric-contract deviation that the PR's own "Narrow Metric and API Shifts" section under-states).
What I verified as sound (with citations)
1. disk_stored()'s new bool return is exactly the documented contract
selene/src/composite.rs:656-720. The early returns are consistent with the doc comment at 652-655:
:657-659no matchingDiskJob::Write→false(no slot freed by this job).:661-664write job removed butoutboundalready gone →self.parked.remove(&key); return true. Correct: aDiskJob::Writeslot was freed, so a waiter must reconsider — and theparkedremoval closes the orphan that would otherwise panic atself.outbound[&key]inspill()(:823).:665-669pressure(Error::no_space) incrementsheld[0]and armsself.retry_after = self.retry_now() + 50ms.:687return !pressure— the only path that suppressesstats.progress, and it is exactly the ENOSPC-backoff case where the job slot is re-armed for the same record rather than freed for a different one.:689-719all terminal paths fall through totrue.
Callee resolution: Error::no_space is the ENOSPC predicate; retry_once (store.rs:300-307) returns Failed on the first failure, so a non-ENOSPC error also reaches true at :687 and the record is dropped rather than retried — that matches the retry expression at :670-674, whose is_some_and short-circuits to false when parked has no entry (record already gone). No unsatisfiable/always-true guard.
2. poll()'s progress loss is confined to the ENOSPC write-completion case
selene/src/composite.rs:1608-1624. TransportEvent::Stored now bumps progress only when disk_stored() returns true; Fetched and the other (streamed) arm bump unconditionally. This is precisely the two-part fix the PR describes, and it does not accidentally suppress Fetched-driven wakeups (which would have starved restores).
3. retry_after expiry edge-trigger is safe and single-shot
selene/src/composite.rs:1656-1660:
let retry = self.retry_after.is_some_and(|at| self.retry_now() >= at);
if retry {
self.retry_after = None;
self.stats.progress += 1;
}
Unconditional clear (even when retry == false, retry_after stays armed — correct), and exactly one progress += 1 per expiry. Because it runs before let progress = self.stats().progress; at :1661, the maintenance block at :1662 sees the new value in the same tick, so the expiry both wakes the worker and triggers spill maintenance in one pass. Under sustained ENOSPC that is one probe per 50 ms ≈ 20 Hz, not a spin loop.
4. The DiskJob::Write ↔ parked.writing 1:1 invariant genuinely holds
I enumerated every mutator. Sole setter of writing = true is spill() at :857-859, reached only after start_write(...) returns Ok — and start_write inserts the DiskJob::Write at :607/:616 inside the same call, so the two are created together. Removers: disk_stored (:660 removes the job, :679 clears writing on retry, :662/:689 remove parked), drop_parked_children (:736), poll()'s expired sweep (:1584, which explicitly excludes writing records at :1577), and close() (:1759). has_spillable_slots/writing_spills therefore do not see torn state, and the new debug_assert!s at :757-769 are legitimate invariant checks rather than assertions that a test has to fake. (The pre-existing test edit at :2730-2735 guarding spill(child.key) with if !store.parked[&child.key].writing reflects the new writing guard at :819-821, not a masked failure.)
5. The new spill() guard is not dead code and does not strand a record
selene/src/composite.rs:819-821 if parked.writing { return None; }. Reachable: spill_parked filters !parked.writing via waiting_spills() (:869-880), but store() calls spill() directly on the outbound-present path (:1294, :1340) where the record may already be writing. Returning None there is correct — a duplicate concurrent write of the same file would corrupt the record.
6. helios' single-reconciliation pass cannot drop a waiter
helios/src/server/runtime.rs:2800-2873. I checked that a CheckpointId reaching the "keep it deferred" branch is never lost:
take_publications()results are deduped intopublication_index(:2804-2818), so each id maps to at most onePendingStore.deferred_stores.drain(..): if the id is already inpublication_indexit becomesprior_retryon that entry (:2823-2826) — no second queue entry, no lost waiter. Otherwise, whenretryis false it goes towaitingviaseen_waiting(:2835-2837).deferred_copyouts: guarded by both!publication_index.contains_key(&id)and!seen_waiting.contains(&id)(:2858-2859), so it cannot resurrect an id that is already waiting or pending.- The
store()loop'swaiting.pushsites are all guarded byseen_waiting.insert(...)(:2884,:2936), and since publication ids are unique inpublications, those inserts always returntrue— no silently dropped waiter.self.deferred_stores = waitingat:2957replaces wholesale, so there is no duplicate accumulation across passes either.
The can_retry_slabs gate at :2880-2888 correctly re-queues with StoreReason::Slabs and continues before export_fits()/store(), which is what the PR claims (no host_store_outcome increment, no store.store() call for a skipped retry).
7. Every can_retry_slabs(&self) == false exit has a future wake source
This is the critical anti-stall property, and it holds. Walking selene/src/composite.rs:1405-1457:
:1410-1415/:1420-1422/:1425-1427/:1429-1431/:1433-1451allreturn true(retry allowed).:1452-1454!self.has_spillable_slots(short)→true(fall through to disk streaming instore()).:1456writing < MAX_SPILLS && covered_slots < short && !self.backoff_active(). Its negation iswriting >= MAX_SPILLSorcovered_slots >= short(both discharged by a future write completion →disk_stored→progress), orbackoff_active()(discharged by theretry_afterexpiry edge at:1656-1660→progress += 1, which the worker loop observes viastore_progressatruntime.rs:2797-2799). No exit depends on an event that may never arrive.- The
Inflightvariant is likewise self-discharging: all fiveRetry(Inflight)sites (:1284,:1301,:1319,:1326,:1343) are gated on anoutbound/memory/pinned/unwritten-ancestor condition, each of which resolves on a completion that bumpsprogress.
I also confirmed the helios worker does not rely on progress alone to poll: run() at runtime.rs:1248-1263 yields/park()s on the executor and otherwise blocks on receiver.recv_timeout(idle_wait()) where idle_wait() is 2 ms (:1290), so the composite's 50 ms retry_after edge is reliably observed with zero new publications — matching the PR's claim about runtime.rs:1214,1257-1290.
8. PooledStore/Tiers forwarding cannot flip the answer
selene/src/pool/local.rs:45-49 uses is_none_or(...) — with no local tier it returns true (default), which is the conservative direction (retry allowed), consistent with Tiers::store returning Present at :41. selene/src/pool/store.rs:615-617 forwards to self.inner. Note the trait method is &self (store.rs:327) and every callee it reaches is &self-callable (disk_store.rs:2426 index(), :2516 plan_record(), :2534 covered_endpoint(), :3153 is_failed(), memory.rs:2474/2482/2486/2665), so this is not hiding interior mutability through a &self. Default-true (store.rs:327-329) keeps every other HostStore impl (memory-only, disk-only, test fakes) behaviourally unchanged.
Findings
F1 — Major (hot-path algorithmic regression): can_retry_slabs() re-derives two full O(parked) scans plus a Vec<PageId> clone, per deferred publication, per service pass
Diff site: selene/src/composite.rs:1452-1456 (inside can_retry_slabs, called from helios/src/server/runtime.rs:2882).
// selene/src/composite.rs:1452-1456
if !self.has_spillable_slots(short) {
return true;
}
let (writing, covered_slots) = self.writing_spills();
writing < MAX_SPILLS && covered_slots < short && !self.backoff_active()
Callee definitions (these are what make the cost real, not a micro-nit):
// selene/src/composite.rs:774-788 — O(parked), skips nothing up front
fn has_spillable_slots(&self, need: usize) -> bool {
if need == 0 { return true; }
let mut sum = 0usize;
for key in self.parked.keys() {
if let Some(record) = self.memory.record(key) {
sum += record.slots();
if sum >= need { return true; }
}
}
false
}
// selene/src/composite.rs:752-771 — O(jobs), plus two O(parked) debug_assert_eq passes
fn writing_spills(&self) -> (usize, usize) { /* iterates self.jobs.values(), then .parked.values() twice */ }
// selene/src/composite.rs:1423 — full page-id clone, on every call
let (_, tail) = self.disk.plan_record(checkpoint);
plan_record (selene/src/disk_store.rs:2516-2532) ends in checkpoint.chain_pages[first..].to_vec() / tail.to_vec() / checkpoint.chain_pages.clone() — an O(tail_pages) heap allocation whose only use at :1424 is tail.len().
Then the same work is repeated immediately after, because runtime.rs:2903 calls store.store(&publication), which re-executes at :1328-1334:
let (parent, tail) = self.disk.plan_record(checkpoint); // :1328, second clone
let needed = self.memory.layout().record_slots(tail.len(), !covered);
...
let short = self.memory.shortfall(needed); // :1333
if short > 0 && !self.has_spillable_slots(short) { // :1334, second scan
Counterexample (concrete). Suppress retry_after (backoff_active() == false), take MAX_SPILLS = 8 writes in flight (selene/src/composite.rs:93), and P = 5,000 parked records — an entirely normal state for the DRAM-retention tier the PR is about. Let the store's progress be bumped by any unrelated source (a Fetched completion at :1615-1618 bumps unconditionally, an export streamed_event at :1619-1622, or the 50 ms retry_after edge at :1659). Then for a deferred publication with prior_retry == Slabs and writing == 8 == MAX_SPILLS:
runtime.rs:2882→has_spillable_slotswalks all 5,000 keys (:779) → returnstrueearly only if the first records happen to covershort; in the saturated case they do not, so it walks all 5,000.writing_spills()(:1455) walksself.jobs(8 writes + any reads) and, in a debug build, two more fullO(parked)passes of 5,000 records for thedebug_assert_eq!at:765-769.- →
writing < MAX_SPILLSisfalse→ returnsfalse→runtime.rs:2884requeues andcontinues.
So all of that work — three to four O(parked) scans — yields the single bit "still saturated, do nothing". Worse, if has_spillable_slots(short) returns true at :1452 (so can_retry_slabs returns true at :1456 when writes are below the cap), runtime.rs:2903 immediately re-enters store() and repeats plan_record's clone (:1328) and has_spillable_slots (:1334) — the same two expensive calls, twice, back to back, in one pass.
Fidelity to the old code. The replaced spillable_slots() (:748-756, removed) was also O(parked), but the old call site (:1311 → :1334 in the old numbering) ran it only on the memory.store_* rejection path. The PR now runs the equivalent walk at :1452 and :1454+writing_spills() on a path the worker takes on every deferred publication on every service pass. There is no existing_postfix, borrow, or incremental counter; waiting_spills() (:869-880) even shows the codebase already knows to avoid this ("Selection is bounded by the spill and move caps, without sorting all parked records", docs/prefix-cache-offload.md:1348-1349). The PR's own claim that it "adds writing_spills()" is accurate, but writing_spills() is itself an O(jobs)+O(parked) walk invoked from a hot predicate.
Concrete fix.
- Incremental counters. Keep
parked_slots: usizeandwriting_slots: usizefields updated at the sixparkedmutation sites (:546insert,:662/:689/:736/:1584remove,:857-859writing flip) and onmemoryrecord removal; thenhas_spillable_slots(need)isparked_slots >= needandwriting_spills()is(writing_count, writing_slots)inO(1). Move thedebug_assert_eq!at:765-769behind#[cfg(debug_assertions)]and out ofwriting_spills(), into a singlepoll()-tick consistency check. - Return the length, not the vector: add
fn planned_tail_pages(&self, checkpoint: &PublishedCheckpoint) -> usize(or makeplan_recordtake a&mut Vec<PageId>scratch buffer) socan_retry_slabs:1423andstore:1328do not cloneO(tail_pages)for a.len(). - Better still, have
store()return theneeded/shortit computed so the worker's gate can consume the decision instead of recomputing it; or cache the lastcan_retry_slabsverdict per key onCompositeStorekeyed by aprogressgeneration stamp, which is exactly the "retry after store progress" contract indocs/prefix-cache-offload.md:294-295.
Severity rationale: not a functional bug (the boolean answer is correct), so not a Blocker — but it is a per-pass O(parked) rescan on the very hot path (5,000 records × every deferred publication × every worker pass) that the PR touches, with an O(tail_pages) clone executed twice per accepted publication, so Major under the hot-path rule.
F2 — Minor: writing_spills()'s debug_assert_eq! turns an O(1)-ish query into two extra O(parked) passes in debug builds
Diff site: selene/src/composite.rs:765-769.
debug_assert_eq!(
writing,
self.parked.values().filter(|parked| parked.writing).count(),
"DiskJob::Write count must match parked.writing count"
);
writing_spills() is now called from three hot sites: :1455 (can_retry_slabs, per deferred publication), :888 (spill_parked, on every maintenance tick and every Retry(Slabs) rejection), and :1378 (store(), per rejected publication). With P parked records and W open writes, the function is O(W + P) instead of O(W) in debug builds. The PR's verification section states all checks ran in the debug profile "so all new debug_assert! invariant checks executed" — meaning the test-suite timings measured this inflated cost, and any future debug-profile profiling of the storm will attribute O(P) to a query that is conceptually O(W).
Concrete fix: move this cross-check out of writing_spills() into poll()'s maintenance block (guarded by #[cfg(debug_assertions)]), and add a #[cfg(test)]-only assert_spill_invariant() helper the new tests call explicitly at the four points they care about.
F3 — Minor: held[0] accounting change is a real behavioural/metric-contract deviation, larger than the summary implies
Diff sites: selene/src/composite.rs:1374-1380 (the new MAX_SPILLS gate) and selene/src/composite.rs:908-910.
// :1374-1380
// Skip `spill_parked()` when `MAX_SPILLS` writes are already in
// flight: no new spill can start, and calling it per rejected
// publication would inflate `held[0]` on every retry while
// `poll()` maintenance still accounts for `held[0]` once per tick.
if self.writing_spills().0 < MAX_SPILLS {
self.spill_parked(self.memory.shortfall(needed));
}
// :908-910 — the accounting the gate now skips
if writing == MAX_SPILLS && covered < need_slots {
self.stats.held[0] += self.parked.len().saturating_sub(writing) as u64;
}
This is a deliberate fix for the amplification the PR describes, and the new test slab_retry_while_spills_saturated_does_not_inflate_held (:6516-6572) pins it. Two residual issues, both Minor:
- The PR's "Narrow Metric and API Shifts" item 2 under-describes the change. It says
held[0]"is now accounted on progress-gatedpoll()maintenance ticks rather than per rejectedRetry(Slabs)call." But thepoll()maintenance block is itself gated twice — on!self.disk.preserve_committed(:1662) and onself.maintenance_progress != progress(:1662) — so in a period whereprogressis genuinely flat (exactly the ENOSPC regime this PR targets, wheredisk_storednow suppresses progress at:687andretry_afterbumps it only once per 50 ms),held[0]is no longer counted at all for the rejected-publication path.flare_host_cache_held_total{tier}is a documented counter of "record holding events" (docs/prefix-cache-offload.md:1364-1365), so its cadence is now tied to the progress-generation clock. Under-counting a documented "holding events" counter during a storage-full episode is precisely when an operator is reading it. - The new assertion in
slab_retry_while_spills_saturated_does_not_inflate_held(:6564-6568) assertsprogressis unchanged across eightstore()calls. That is true only because nothing else in the fixture bumpsprogress. The assertion therefore encodes the compound invariant (no held inflation and no progress movement) but attributes both to theMAX_SPILLSgate; if a future change makes the gate callspill_parked()whenwriting == MAX_SPILLS(e.g. to keep accounting), the test fails for a metric reason while the storm is still fixed, which will read as a false regression.
Concrete fix: if the accounting cadence is intentional, count the rejection explicitly and cheaply at the gate instead of relying on the maintenance tick — e.g. a new stats.held_backlog gauge (or store_skipped-adjacent counter) incremented by 1 at :1378 when the gate skips, so the counter no longer depends on the progress generation, and state the new cadence accurately in the summary. Otherwise keep spill_parked(self.memory.shortfall(needed)) unconditional and fix the amplification inside spill_parked itself (e.g. only add to held[0] when covered changed, rather than on every call), which separates the storm fix from the metric change.
Areas checked and found clean (no finding)
helios/src/server/runtime.rs:2928-2951— theprogressedge logic.Queued/Oversize/Present/Errall setprogress = true;Retry(reason)sets it only whenprior_retry != Some(reason). I checked the interaction with:2917-2919(unpin_checkpointwhen notQueued) and:2945-2951(host_retry_successnow keyed onprior_retry.is_some()instead of the removedretry_idsclone): a fresh publication that previously collided with a deferred id is now credited exactly once, and aSlabs→Inflightreason change correctly counts as progress (:2933) so the worker does not park on a genuinely new state. No stale-read ofprior_retryafter mutation —prior_retryis moved into thefordestructure at:2874-2878and never written again in the loop body.runtime.rs:2880-2888— thecan_retry_slabsgate correctly runs beforeexport_fits()(:2890) andstore()(:2903), so a skipped retry neither pins a checkpoint nor incrementshost_store_outcome; and it respectsfresh(a fresh publication is never gated), which is what prevents starvation of newly-published ready records.runtime.rs:2891-2899—prev_deferred_copyoutssnapshots before the loop socopyout_headroom_deferralsis counted once per genuine transition rather than once per pass;seen_copyoutsprevents duplicate pushes intoself.deferred_copyouts.selene/src/composite.rs:884-911—spill_parked's rewritten loop. The earlycovered >= need_slotsreturn at:889and thewriting >= MAX_SPILLSbreak at:894are correct;else if self.backoff_active() { break; }at:903-905correctly aborts the whole loop once an ENOSPC arms the backoff mid-iteration, so a single ENOSPC does not burn the remainingwaiting_spills()budget.waiting_spills()is still computed once per call (no sort inside the loop).- Adversarial small-N:
need_slots == 0(:885returns early;has_spillable_slots(0)returnstrueat:775-777;short == 0returnstrueat:1429-1431),parked.is_empty()(:885),writing == 0with a single parked record (the:6516and:6575tests coverMAX_SPILLS ± 4),thinningempty (:1433short-circuits on!self.thinning.is_empty()),row_slots == 0(:1433guardsrow_slots > 0beforediv_ceil, avoiding a division by zero at:1434).short.div_ceil(row_slots)at:1434is correctly guarded. No overflow:record_slots/slotsareusizesums over bounded page counts, andsaturating_subis used at:909. selene/src/store.rs:327-329— the new default-truecan_retry_slabskeeps all non-composite stores unchanged;docs/prefix-cache-offload.md:293-295("retains only checkpoint IDs for retries after store progress") is still honoured by the worker.
Not findings (deliberately excluded per scope)
- The many unrelated documentation edits in the diff (
AGENTS.md(not opened),docs/api.md(not opened),docs/cli-design.md(not opened),docs/core-design.md(not opened),docs/TODO.txt,docs/scheduling-runtime-design.md(not opened),flare-cli/**,docs/model-preparation.md(not opened), thea orbit→an orbitgrammar fixes) are not part of the audit scope and are not code defects. - The
preserve_message_anchorfield added toPrompt(runtime.rs:47-50,:285-288) and its test-only initializers (:3575,:3661,:3847,:4349) are inert plumbing from a different change set in this diff; the field is copied but has no other consumer in the audited files, so there is no state-machine defect to trace here.
Summary
The fix works as designed: disk_stored's bool return suppresses progress on exactly the ENOSPC path that arms the 50 ms backoff, the retry_after expiry edge replaces the tight spin with a bounded ~20 Hz probe, the reconciliation pass in service_store is genuinely duplicate-free and zombie-free, and every can_retry_slabs() == false exit has a provable future wake source — no stalls, no lost wakeups, no broken tests, no dead guards.
The cost is one Major hot-path defect (F1): can_retry_slabs() performs up to four O(parked) scans plus an O(tail_pages) Vec<PageId> clone per deferred publication per worker pass, and when it returns true, store() immediately repeats the same clone and scan — at ~5,000 parked records and 8 saturated spills this is a per-pass rescan of the whole parked set to produce a single "still saturated" bit. That should be fixed with incremental slot counters and a length-only plan_record before this lands, because it moves O(parked) work from a rare rejection path onto the hot service path. F2 (debug-only O(parked) assert in the same query) and F3 (the held[0] metric cadence moving from per-rejection to progress-gated, which under-counts a documented counter in exactly the storage-full regime the PR targets) are Minor and cheap either to fix or to document accurately.
Final review
Recommendation: Changes Requested
The state machine is sound: I traced every new progress edge, every parked/jobs/outbound mutation, and every can_retry_slabs() == false exit for a guaranteed future wake source, and found no correctness bug — no stall, no lost wakeup, no zombie waiter, no duplicate store() submission, no new panic path. What blocks it is the one thing the charter treats as non-negotiable for this PR class: a performance-titled "CPU storm" fix with no served-workload measurement on the patched build (Charter #210, docs/design-review.md:106-115), while issue #703 itself records that the storm was not reproduced on v0.5.3. Secondary: the mandated --locked --release (+--features test-support) Layer-1 runs were not performed (docs/design-review.md:180-184), docs/prefix-cache-offload.md still documents the pre-PR retry contract, and one accepted-publication path does its planning work twice.
Merge Risk
Level: Medium
- Touches the shared DRAM/NVMe retention state machine (
selene/src/composite.rs+519/−50) plus the single-threaded worker loop; a mistake here stalls prefix-cache stores or leaks waiters in production rather than failing loudly (mitigated by 9 focused tests and realdebug_assert!invariants). - Operator-visible metric semantics move (
progressunderENOSPC,held[0]cadence, deferredSlabsattempt counts) with no docs update, so dashboards/alerts built on #703's counters read differently. - Two large open PRs (#674, #694) rewrite the same
Retry(Slabs)branch, the sameservice_storeoutcome match and the sameHostStoretrait, with no merge order recorded; CI would run the release profile this PR did not.
Walkthrough
helios/src/server/runtime.rs:2791-2957— one per-CheckpointIdreconciliation oftake_publications(),deferred_stores,deferred_copyoutsintoVec<PendingStore>{publication, prior_retry, fresh}; duplicate IDs replace the earlier publication on theOccupiedpath (:2813-2817), deferred entries attachprior_retryto an existing entry instead of queueing twice (:2823-2826), and everywaiting.pushis gated byseen_waiting.insert(...)(:2835,:2884,:2936), so no waiter is dropped or duplicated across passes.helios/src/server/runtime.rs:2928-2954—progressis now edge-triggered:Queued(:2930), a changedStoreReason(prior_retry != Some(reason),:2933-2935),Present/Oversizevia_ =>(:2941-2943), copyout headroom change (:2891-2896) andErr(:2953). Repeated identicalRetry(Slabs)returnsOk(false), soWorker::runparks.host_retry_successnow keys onprior_retry.is_some()(:2947), which is correct for the fresh+deferred collision.helios/src/server/runtime.rs:2880-2888— the non-freshSlabsgate runs beforeexport_fits()/store(), so a skipped retry neither pins a checkpoint nor scoreshost_store_outcome;freshbypasses it, so ready publications are not starved.selene/src/composite.rs:1452-1456+:774-788,:752-771—can_retry_slabsreturnsfalseonly whenwriting < MAX_SPILLS && covered_slots < short && !backoff_active()fails; its negation is discharged by a future write completion (disk_stored→progress) or by the 50 msretry_afteredge (:1656-1660).has_spillable_slotsearly-exits, replacing the old fullsum()fold.selene/src/composite.rs:656-720,:1608-1624,:1656-1671—disk_storedreturnsfalseonly on theENOSPCpath (:687 return !pressure), soprogressno longer advances with zero durable slots; theretry_afterexpiry clears unconditionally and bumpsprogressexactly once, which also re-enters the maintenance block (:1662-1670) so spill maintenance still runs — one probe per 50 ms (~20 Hz), not a spin.selene/src/store.rs:324-329,pool/store.rs:615-616,pool/local.rs:45-49— new default-truetrait method forwarded throughPooledStore/Tiers(viais_none_or, the conservative direction), so out-of-tree and memory-only stores behave exactly as before.
Pre-merge Checks
- [PASS] Security / malicious screen: pure Rust refactor of the retention/retry path; no new dependency, flag, config key, wire, protobuf or on-disk format change, no network or shell surface, no instructions embedded in the diff.
- [WARN] Charter & value fit: right problem in the right layer (shared
selenestore +heliosworker, no per-model branch, knob defaults totrue) but the headline result is unmeasured — see Blocker 1. - [WARN] Related / duplicate / conflict check: not obsolete and not a duplicate of #674/#694, but both rewrite this same
Retry(Slabs)branch andservice_storeoutcome match (#694 addsStoreOutcome::Unprofitable, which this PR's_ =>wildcard would swallow) and no merge order is recorded — sequencing must be settled before either lands (informational, not a blocker). - [WARN] Tests & verification evidence: 9 new tests exist exactly where claimed and pin the real mechanisms (
composite.rs:6295-6634,phase_tests.rs:9022/9058/9119/9162), but everything ran in the debug profile; the mandatedcargo test --locked --release(and selene's--features test-support) was not run, and no check ran oneec5e95.
Blockers
- No served-workload measurement for a performance claim —
helios/src/server/runtime.rs+selene/src/composite.rs, PR title/summary.docs/design-review.md:106-115(principle 12: "Performance claims require equivalent baselines … and actual Helios service measurements") and Charter #210 ("Performance PRs need benchmarks showing an actual speedup overmainon a served workload") are hard requirements for this PR class. The only profile in evidence is issue #703's capture on the pre-fixflare 0.5.1binary, and #703 states the storm was not reproduced onv0.5.3; there is no post-fixperfsample, no CPU% before/after, no latency number. Fix: attach oneperf/CPU% before-after on #703's configuration (4× RTX PRO 6000 SM120, DeepSeek-V4.1-Flash TP4,--max-concurrency 64 --prefix-cache-memory 8G --prefix-cache-disk … --prefix-cache-disk-limit 100G) on the patched build, or retitle/downgrade the claim to the mechanism and state the mechanism-level evidence explicitly. This is an evidence-form gap, not a code defect — the code fixes the mechanism as described.
Should Fix
- Planning work is duplicated per accepted publication.
selene/src/composite.rs:1423-1428+:1452+:1455(can_retry_slabs) and:1328-1334(store) independently callself.disk.plan_record(checkpoint)— anO(tail_pages)Vec<PageId>clone (selene/src/disk_store.rs:2516-2531) — and independently callhas_spillable_slots. Whencan_retry_slabsreturnstruethe worker immediately re-entersstore()(helios/src/server/runtime.rs:2903) and repeats both, i.e. two clones and two scans per accepted publication. Fix: return the sizes rather than the vector (e.g.fn slab_need(&self, cp) -> Option<(Option<PrefixKey>, usize /*tail*/, usize /*needed*/, usize /*short*/)>) used by both callers, soplan_record's clone runs once per publication. - Mandated Layer-1 profile was not run.
docs/design-review.md:180-184requirescargo test --locked --releaseon every affected crate, matching.github/workflows/native-serving.yml:51 (not opened),55,63,68(selene also with--features test-support). The PR states "All checks ran in debug profile" and reports selene ascargo test --manifest-path selene/Cargo.toml(not opened) with no feature, so neither the release profile nor thetest-support-gated selene tests were exercised. Fix: attachcargo test --locked --releaseforselene(with and without--features test-support) andhelios --features runtime-core,server. docs/prefix-cache-offload.mdstill documents the pre-PR contract. TheHostStoreinterface listing at:272-284omits the newcan_retry_slabsoperation; the worker retry contract at:293-297("The worker retains only checkpoint IDs for retries after store progress…") no longer describes the retained per-ID reason plus theSlabsgate; the retention-metrics text at:1364-1372still describesheld_total{tier}per holding event andstore_skipped"including duplicates and retries" — precisely the cadence the PR's own "Narrow Metric and API Shifts" changes (held[0]now accounted on progress-gatedpoll()ticks; deferredSlabspublications skipped by the gate never reachstore()).AGENTS.md:52-58requires a design document to state the behavior the code implements. Fix: update those three passages in this PR or in an explicitly linked follow-up.
Subtract / Simplify
- Dead branch —
selene/src/composite.rs:903-905(else if self.backoff_active() { break; }). Unreachable: the enclosing loop is guarded by:892 if writing < MAX_SPILLS && !self.backoff_active(), andretry_afteris written in exactly two places (disk_stored,:668;poll,:1658), neither reachable fromspill()→thin_rows/reserve_capture/start_write; andbackoff_active()is monotone for a fixedretry_after. Delete the three lines. - Collapse the four dedup collections to one claim helper —
helios/src/server/runtime.rs:2791-2873.publication_index,seen_waiting,seen_copyoutsand thefresh/prior_retrypair answer one question ("has thisCheckpointIdalready been claimed this pass?"); theVacant/Occupiedblock at:2803-2819and the copyout block at:2857-2873are the same shape written twice. Astruct Pending { list: Vec<..>, at: HashMap<CheckpointId, usize> }withfn claim(..)plus anenum Prior { Fresh, Copyout, Retried(StoreReason) }removesseen_copyoutsentirely and makes the contradictoryfresh && prior_retry.is_some()state unrepresentable. - Nine fully-qualified collection paths shadow an existing import —
helios/src/server/runtime.rs:2801,2802,2805,2821,2854,2856writestd::collections::HashMap::<…>::new(),std::collections::hash_map::Entry::Vacant,std::collections::HashSet::new()although:8already hasuse std::collections::{HashMap, VecDeque};. Extending that import deletes all nine. - Duplicated preamble between
can_retry_slabsandstore—selene/src/composite.rs:1416-1422is character-for-character:1272-1275, and:1423-1431mirrors:1328-1333. Extract one helper (see Should Fix 1);checkpoint.tail_pages > checkpoint.chain_pages.len()(:1406-1408) is anErr(invalid(..))integrity check instorebut "go ahead and retry" here, so divergence converts a corrupt publication into a retry loop. - Unreachable guard —
selene/src/composite.rs:775-777(if need == 0 { return true; }): both production callers pass a value already proven> 0(:1334 if short > 0 && …,:1452after:1429 if short == 0 { return true; }). Either drop it or drop theshort > 0at:1334so the0case has one owner.
Nits
helios/src/server/runtime.rs:2941-2943—_ => { progress = true; }re-introduces the "anything I didn't enumerate counts as progress" assumption the PR is fixing;StoreOutcomecurrently has exactly four variants, soStoreOutcome::Present | StoreOutcome::Oversizeis one word longer and cannot silently swallow a future non-progress variant (open #694 addsStoreOutcome::Unprofitable).- PR claim "
Worker::run… enforces a 2 ms idle poll cap so theretry_afterexpiry edge fires reliably" is inaccurate:idle_wait()returns 50 µs with a store inbound transfer or scheduler inbound waiter, 100 µs when an incoming awaits the pool, and 2 ms only in the fallback (helios/src/server/runtime.rs:1269-1292), and that whole branch runs only whenexecutor.outstanding() == 0(:1248-1263). The expiry edge is still observed reliably; correct the justification. selene/src/composite.rs:765-769— the cross-checkdebug_assert_eq!(writing, self.parked.values().filter(..).count())turnswriting_spills()into two extraO(parked)passes in debug builds at three call sites (:1455,:888,:1378). Consider moving it to a#[cfg(debug_assertions)]consistency check inpoll()'s maintenance block.- Two undeclared-but-benign hunks should be named in "Changes": the relaxed pre-existing assertion at
selene/src/composite.rs:2733-2736(store.spill(child.key).unwrap()→ guarded by!store.parked[&child.key].writing, forced by the newspill()guard at:819-821) and the orphan-parkedcleanup at:661-664(closes a latentself.outbound[&key]panic at:823).
Dropped on verification
- "
can_retry_slabsperforms three to fourO(parked)scans to produce a single 'still saturated' bit / walks all 5,000 parked records in the saturated case" (upstream F1's counterexample) — false. In the saturated statehas_spillable_slots(short)(composite.rs:774-788) walksself.parked.keys()accumulatingrecord.slots()and early-exits as soon assum >= need(:782), andneedis one record's shortfall, not the pool size; with thousands of parked records it exits after a handful of keys. The function then reacheswriting_spills()(:1455), which isO(jobs)(≤ 8 writes). Nor is it "strictly worse than the code it replaced": the old path ranstore()→ the removedspillable_slots()fullsum()over every parked record (no early exit) →spill_parked()→waiting_spills()filter plussort_unstable_by_key(:869-881), all afterexport_fits(); the new path skipsexport_fits()(13.12% of #703's samples) and the sort entirely when it returnsfalse. What survives is the duplicate-work point, kept as Should Fix 1 at its real magnitude. - "
held[0]is no longer counted at all whileprogressis flat, under-counting a documented counter during ENOSPC" (upstream F3.1) — false. Theretry_afterexpiry atcomposite.rs:1656-1660unconditionally bumpsself.stats.progress += 1once per 50 ms, soprogressis not flat under sustainedENOSPC; the maintenance block at:1662-1671re-runs on that bump andspill_parkedstill chargesheld[0]at:908-910. The cadence change is real but bounded and deliberate (PR body item 2); it is covered by Should Fix 3 (docs), not by a metric defect. - "9 new tests are not deterministic / 'zero sleeps' is inaccurate because of a 10-second wall-clock loop" — dropped. The loop at
composite.rs:6489-6503usesstd::thread::yield_now()(not a sleep) with a fixed injected clock, and exits on the deterministicQueuedoutcome; the deadline is a hang guard, not the exit condition. - "Everything ran in debug profile, so the new
debug_assert!invariants are unverified in the shipped profile" as a code risk — dropped as a code finding. Choosing the debug profile is what executes those asserts; the release run is a separate evidence-form gap, carried as Should Fix 2. - "The new
spill()guard duplicates four existing!writingpre-checks, so the code has two sources of truth" (upstream subtraction #10) — dropped. The guard closes a real hole the pre-checks do not:drain_on_shutdowncallsself.spill(key)atcomposite.rs:1816and:1823with no!writingprecondition, so without it an already-writing record could be re-reserved and written twice concurrently. pr_diffshowingAGENTS.md,docs/*,flare-cli/*andpreserve_message_anchorhunks as PR content — dropped as base drift, verified.pr_fileslists exactly the 6 files the body claims (matching +820/−71), whilepreserve_message_anchorplumbing exists at PR head inhelios/src/scheduler.rs:160,231,1852,helios/src/scheduler/checkpoints.rs:470(not opened), andhelios/src/server/request.rs:427-452(not opened) — files not inpr_files— and those files have nopreserve_message_anchorin this mirror'smain. The mirror'smainis simply older than the branch point; the unrelated hunks (including the ~1,000 lines ofpreserve_message_anchor/HTTP-envelope tests inphase_tests.rs) are not this PR's content.- Cross-PR overlap with #674/#694, "no CI checks observable",
docs/TODO.txtbookkeeping, and PR-description phrasing (beyond the one factual "2 ms cap" correction) — not raised as blockers or should-fixes per calibration; recorded as Pre-merge/Info. - "
ENOSPCdisk-write failures no longer incrementStoreStats::progress" is a behavior regression / lost-wakeup risk — dropped. Verified safe: the suppressed path is exactly the one that re-parks the record withwriting = falseand re-armsretry_after(composite.rs:665-688), whose expiry edge (:1656-1660) restoresprogress, and everycan_retry_slabs() == falseexit (:1425-1427,:1429-1431,:1448-1450,:1452-1454,:1456) is discharged either by a write completion or by that 50 ms edge.
Full report Decision to Test: no (100%): Testing will not add significant value as the code stands today. The code is either not yet ready to merge, or adequate testing has already been done to validate the contents of the code, or the available hardware is not suitable to test with.
Classify triage
Selected: triage:validation
Threshold: 65%
Triage
- [✓]
triage:validation: 92.4% -
triage:review: 7.6% -
triage:design-review: 0.0% -
none: 0.0% -
triage:investigate: 0.0% -
triage:partial: 0.0% -
triage:integration: 0.0% -
triage:verify-for-closure: 0.0% -
triage:superseded: 0.0%
Apply labels
Applied: +triage:validation, -triage:review