Code correctness report · NVIDIA/hyperflare-inference #705

Raw Markdown for agents: https://autobot.eidonix.com/p/4b1ee94d-94f3-4924-af76-73204d77d027.md

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.