PR #705: fix(selene,helios): stop service_store and CompositeStore Retry(Slabs) CPU storm

Raw Markdown for agents: https://autobot.eidonix.com/api/v1/cases/295e21b0-a526-43f3-aecb-f865a9bdcb08

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:

Full report · Notes

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

Priority

Type

Area

Model

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

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

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)

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"):

  1. "Worker::run … enforces a 2 ms idle poll cap so the retry_after expiry 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 when executor.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.
  2. "9 new unit tests (all deterministic, zero sleeps)" — enospc_retry_after_expiry_wakes_sole_deferred_store_deterministically contains a 10-second wall-clock loop (while Instant::now() < deadline { … std::thread::yield_now(); }) despite its "no sleeps!" comment. The injected poll_at clock makes the assertions deterministic, but the claim as written is inaccurate.
  3. 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 orphaned parked entry in disk_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:

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.

Full report

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)

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.

Full report

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:

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:

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:

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:

  1. runtime.rs:2882 → has_spillable_slots walks all 5,000 keys (:779) → returns true early only if the first records happen to cover short; in the saturated case they do not, so it walks all 5,000.
  2. writing_spills() (:1455) walks self.jobs (8 writes + any reads) and, in a debug build, two more full O(parked) passes of 5,000 records for the debug_assert_eq! at :765-769.
  3. → writing < MAX_SPILLS is false → returns false → runtime.rs:2884 requeues and continues.

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.

  1. Incremental counters. Keep parked_slots: usize and writing_slots: usize fields updated at the six parked mutation sites (:546 insert, :662/:689/:736/:1584 remove, :857-859 writing flip) and on memory record removal; then has_spillable_slots(need) is parked_slots >= need and writing_spills() is (writing_count, writing_slots) in O(1). Move the debug_assert_eq! at :765-769 behind #[cfg(debug_assertions)] and out of writing_spills(), into a single poll()-tick consistency check.
  2. Return the length, not the vector: add fn planned_tail_pages(&self, checkpoint: &PublishedCheckpoint) -> usize (or make plan_record take a &mut Vec<PageId> scratch buffer) so can_retry_slabs:1423 and store:1328 do not clone O(tail_pages) for a .len().
  3. Better still, have store() return the needed/short it computed so the worker's gate can consume the decision instead of recomputing it; or cache the last can_retry_slabs verdict per key on CompositeStore keyed by a progress generation stamp, which is exactly the "retry after store progress" contract in docs/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:

  1. The PR's "Narrow Metric and API Shifts" item 2 under-describes the change. It says held[0] "is now accounted on progress-gated poll() maintenance ticks rather than per rejected Retry(Slabs) call." But the poll() maintenance block is itself gated twice — on !self.disk.preserve_committed (:1662) and on self.maintenance_progress != progress (:1662) — so in a period where progress is genuinely flat (exactly the ENOSPC regime this PR targets, where disk_stored now suppresses progress at :687 and retry_after bumps 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.
  2. The new assertion in slab_retry_while_spills_saturated_does_not_inflate_held (:6564-6568) asserts progress is unchanged across eight store() calls. That is true only because nothing else in the fixture bumps progress. The assertion therefore encodes the compound invariant (no held inflation and no progress movement) but attributes both to the MAX_SPILLS gate; if a future change makes the gate call spill_parked() when writing == 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)


Not findings (deliberately excluded per scope)


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.

Full report · Notes

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

Walkthrough

Pre-merge Checks

Blockers

  1. 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 over main on a served workload") are hard requirements for this PR class. The only profile in evidence is issue #703's capture on the pre-fix flare 0.5.1 binary, and #703 states the storm was not reproduced on v0.5.3; there is no post-fix perf sample, no CPU% before/after, no latency number. Fix: attach one perf/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

  1. Planning work is duplicated per accepted publication. selene/src/composite.rs:1423-1428 + :1452 + :1455 (can_retry_slabs) and :1328-1334 (store) independently call self.disk.plan_record(checkpoint) — an O(tail_pages) Vec<PageId> clone (selene/src/disk_store.rs:2516-2531) — and independently call has_spillable_slots. When can_retry_slabs returns true the worker immediately re-enters store() (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, so plan_record's clone runs once per publication.
  2. Mandated Layer-1 profile was not run. docs/design-review.md:180-184 requires cargo test --locked --release on 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 as cargo test --manifest-path selene/Cargo.toml (not opened) with no feature, so neither the release profile nor the test-support-gated selene tests were exercised. Fix: attach cargo test --locked --release for selene (with and without --features test-support) and helios --features runtime-core,server.
  3. docs/prefix-cache-offload.md still documents the pre-PR contract. The HostStore interface listing at :272-284 omits the new can_retry_slabs operation; 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 the Slabs gate; the retention-metrics text at :1364-1372 still describes held_total{tier} per holding event and store_skipped "including duplicates and retries" — precisely the cadence the PR's own "Narrow Metric and API Shifts" changes (held[0] now accounted on progress-gated poll() ticks; deferred Slabs publications skipped by the gate never reach store()). AGENTS.md:52-58 requires 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

  1. 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(), and retry_after is written in exactly two places (disk_stored, :668; poll, :1658), neither reachable from spill() → thin_rows/reserve_capture/start_write; and backoff_active() is monotone for a fixed retry_after. Delete the three lines.
  2. Collapse the four dedup collections to one claim helper — helios/src/server/runtime.rs:2791-2873. publication_index, seen_waiting, seen_copyouts and the fresh/prior_retry pair answer one question ("has this CheckpointId already been claimed this pass?"); the Vacant/Occupied block at :2803-2819 and the copyout block at :2857-2873 are the same shape written twice. A struct Pending { list: Vec<..>, at: HashMap<CheckpointId, usize> } with fn claim(..) plus an enum Prior { Fresh, Copyout, Retried(StoreReason) } removes seen_copyouts entirely and makes the contradictory fresh && prior_retry.is_some() state unrepresentable.
  3. Nine fully-qualified collection paths shadow an existing import — helios/src/server/runtime.rs:2801,2802,2805,2821,2854,2856 write std::collections::HashMap::<…>::new(), std::collections::hash_map::Entry::Vacant, std::collections::HashSet::new() although :8 already has use std::collections::{HashMap, VecDeque};. Extending that import deletes all nine.
  4. Duplicated preamble between can_retry_slabs and store — selene/src/composite.rs:1416-1422 is character-for-character :1272-1275, and :1423-1431 mirrors :1328-1333. Extract one helper (see Should Fix 1); checkpoint.tail_pages > checkpoint.chain_pages.len() (:1406-1408) is an Err(invalid(..)) integrity check in store but "go ahead and retry" here, so divergence converts a corrupt publication into a retry loop.
  5. 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 && …, :1452 after :1429 if short == 0 { return true; }). Either drop it or drop the short > 0 at :1334 so the 0 case has one owner.

Nits

Dropped on verification

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

Apply labels

Applied: +triage:validation, -triage:review