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.