Correctness and contracts report · NVIDIA/hyperflare-inference #674

Raw Markdown for agents: https://autobot.eidonix.com/p/94932fc8-1db4-4b85-82f8-a4d7e09a6a51.md

Correctness, Contracts & System-Level Consequences — PR #674 @ 19ce4a7b

Key findings

  1. Major — a self-rearming pump makes the selene-manager owner thread spin at CPU speed whenever any put, get, or writeback wake is outstanding. selene-manager/src/store.rs:5067-5072 re-sends StoreCommand::Tick at the end of pump(), and the owner loop calls pump() after every batch (selene-manager/src/control.rs:227). Since that one thread serializes all pool state, a single stuck put head-of-line blocks every client. Verified.
  2. Major — RowRestoreLatency bumps its decay clock on start(), so a failed restore pins the estimate at the full median forever. helios/src/server/runtime.rs:299-303 plus the early return in finish at :313-315. This makes the scheduler more likely to reject a cheap local DRAM row restore — the opposite of the PR's stated intent. The added test only covers the no-median case (phase_tests.rs:8799-8801). Verified.
  3. Major — undisclosed rank-relay wire incompatibility. New Kind::StoreInvalidated = 4 (selene/src/shard.rs:470,484) with a hard decode rejection for unknown codes (:485). Mixed-version ranks cannot interoperate, and the PR body discloses nothing about it. Verified.
  4. Major — three public selene crate signatures changed without disclosure (HostStore::begin_lookup gains resident, TierStore::retired gains _offered, new TierStore::pending_pool_drain, plus HostHit.pooled and three StoreStats fields). Every out-of-tree implementor stops compiling. Verified at selene/src/store.rs:377,401-404,433-440,100-103,244-256.
  5. Major — charter #210 unmet. Tables A–F are an author-reported A/B against 5d53040e; main is 1fbcc3c9, and #663 (latency pricing, 8489d504) lands inside that gap and prices the same restore decision. The body states benchmarks ran on 7d7dcdcb; head 19ce4a7b has no reported benchmark or CI evidence.
  6. Minor ×5 — row-restore buckets ignore the source level (runtime.rs:257-268 vs selene/src/pool/store.rs:465,479); Windows loses the buffered packed-write fallback (disk.rs:1774-1780 + eos/src/windows.rs:104-108); a stuck reclaim permanently blackholes its key (disk_store.rs:2516-2518,2643-2645,2697-2699); counter decrements can wrap in release (disk_store.rs:2789-2792); and the metric span semantics shifted (metrics.rs:538-560, runtime.rs:3344-3353).
  7. Verified sound: evict_for_pressure cannot spin (scheduler.rs:1261-1289); the writeback wake scan terminates; the O_DIRECT packed path round-trips and recovers exact logical length; clean-L1 retention is guarded by a real invariant.

1. Unintended system-level consequences

F1 (Major) — Unbounded self-rearming pump on the store-owner thread

pump ends by re-signalling itself whenever any work remains:

// selene-manager/src/store.rs:5067-5072 (end of `pump`)
if !self.pending_puts.is_empty()
    || !self.pending_gets.is_empty()
    || self.writeback_wake_remaining > 0
{
    self.notify_wakeup();
}

notify_wakeup is a non-blocking try_send of Tick:

// selene-manager/src/store.rs:874-878
fn notify_wakeup(&self) {
    if let Some(tx) = self.wakeup.get() {
        let _ = tx.try_send(StoreCommand::Tick);
    }
}

And the owner loop calls pump() immediately after each batch:

// selene-manager/src/control.rs:216-227
store.handle(command);
batch -= 1;
if batch == 0 { break; }
match receiver.try_recv() {
    Ok(next) => command = next,
    Err(tokio::sync::mpsc::error::TryRecvError::Empty) => break,
    Err(tokio::sync::mpsc::error::TryRecvError::Disconnected) => break 'outer,
}
}
store.pump();

Before this change the only driver was the 10 ms tick thread:

// selene-manager/src/control.rs:421-435
cleanup.tick = Some(thread::spawn(move || {
    let mut notified = false;
    loop {
        if tick_stop.load(Ordering::Acquire) && !notified { tick_notice.notify_one(); notified = true; }
        thread::sleep(Duration::from_millis(10));
        if matches!(tick_commands.try_send(StoreCommand::Tick),
            Err(mpsc::error::TrySendError::Closed(_))) { break; }

Impact. A put that stays queued in pending_puts — e.g. one the session or namespace cannot accept yet, which is exactly the steady state under the "tight manager" saturation runs the PR reports — produces Tick → pump → Tick at CPU speed instead of every 10 ms. run_store_owner is a single thread that owns all pool state; while it spins in pump, receiver.blocking_recv() is never reached, so every client's puts, gets, grants and outboxes are head-of-line blocked behind the loop. The same amplification applies on the client side: selene/src/disk.rs:533-535 invokes on_reply() after every disk job reply, i.e. a full pump() per disk completion rather than per tick.

Fix. Only self-notify when a state transition actually occurred since the previous pump — carry a dirty/progress flag set by the mutating paths and cleared at pump entry, then if self.dirty { self.notify_wakeup() }. Keep the 10 ms tick as the backstop for states that genuinely wait on time.


2. Correctness and safety

F2 (Major) — RowRestoreLatency decay clock is bumped by failed restores

// helios/src/server/runtime.rs:299-304 (`start`)
let bucket = self.buckets.entry(source).or_default();
bucket.in_flight += 1;
if let Some((_, last)) = &mut bucket.last_median {
    *last = now;
}
// helios/src/server/runtime.rs:306-317 (`finish`)
fn finish(&mut self, key: &crate::cache::PrefixKey, ok: bool) {
    let Some((source, started)) = self.in_flight.remove(key) else { return; };
    if let Some(bucket) = self.buckets.get_mut(&source) {
        bucket.in_flight = bucket.in_flight.saturating_sub(1);
    }
    if !ok {
        return;
    }
    self.observe(source, started.elapsed().as_secs_f64());
}

estimate_seconds returns the undecayed median while in flight and a 10 s half-life decay otherwise:

// helios/src/server/runtime.rs:339-342
if bucket.in_flight > 0 {
    return median;
}
median * 0.5f64.powf(last.elapsed().as_secs_f64() / Self::RECOVERY_SECONDS)

The failed-fetch path starts then finishes with ok = false:

// helios/src/server/runtime.rs:3401-3407
if row_only {
    row_restore_latency.start(key, source);
}
if store.fetch(hit, ticket).is_err() {
    if row_only {
        row_restore_latency.finish(&key, false);
    }

Impact. A source that is currently failing (record evicted, NVMe read error, manager refusal) resets last_median's timestamp on every attempt, so the estimate never decays and stays pinned at the full median. worth_restore(transfer_seconds, prefill_saved_seconds) (runtime.rs:3354) then keeps rejecting restores it should accept after the decay period — a pricing defect that biases against cheap local DRAM row restores from a stale slow measurement, exactly the failure mode the PR says it removes. It is not a correctness or concurrency bug.

Test gap. The added regression test only exercises the no-median case, so it passes with the bug present:

// helios/src/server/runtime/phase_tests.rs:8799-8801
worker.row_restore_latency.start(dummy_key, local_dram);
worker.row_restore_latency.finish(&dummy_key, false);
assert_eq!(worker.row_restore_latency.estimate_seconds(local_dram), 0.0);

Fix. Do not touch last_median in start(); the in-flight start instant is already recorded in self.in_flight. Add a test that observes a median, ages the bucket, then does start + finish(false) and asserts the decayed value is retained.

F7 (Minor) — A stuck reclaim permanently blackholes its key

// selene/src/disk_store.rs:2516-2518
pub(crate) fn has_pending_reclaim(&self, key: PrefixKey) -> bool {
    self.maintenance.values().any(|job| job.key == key)
}
// selene/src/disk_store.rs:2643-2645 (`store`)
if self.has_pending_reclaim(checkpoint.key) {
    return Ok(Some(StoreOutcome::Retry(StoreReason::Inflight)));
}
// selene/src/disk_store.rs:2697-2699 (`reserve_capture`)
if self.has_pending_reclaim(key) {
    return Ok(None);
}

Impact. Previously only truncates carried a key (Reclaim.key was Option<PrefixKey>, None for unlinks), so a lost unlink reply could not block re-storing that key. Reclaim.key is now always populated (:2103-2108), so an unlink whose reply never arrives keeps maintenance populated and that prefix can never be re-captured for the lifetime of the process — a permanent silent cache-capacity leak on the fault path. Separately, has_pending_reclaim is a linear scan of maintenance executed on every store attempt, now unconditionally.

Fix. Key-block only for reclaims that will actually replace the key, or add an abandonment deadline that drops a maintenance job whose reply exceeds a bounded age; and index pending reclaim keys in a set instead of scanning.

F8 (Minor) — Counter decrements can wrap in release builds

// selene/src/disk_store.rs:2788-2797
let was_ready = self.index.node(&key).unwrap().ready;
if was_ready {
    self.committed_records -= 1;
    self.committed_bytes -= old.location.bytes;
}
self.replacements.insert(key, old);

Sibling helpers use saturating_sub (:3152-3158), but the accounting invariant is only asserted in debug/test builds (assert_disk_accounting, :3565-3589, called from stats() at :3731-3733).

Impact. In release, any accounting drift wraps committed_records/committed_bytes to a near-u64::MAX gauge instead of panicking, which the new flare_host_cache_disk_records/disk_bytes Prometheus series would surface as a catastrophic, misleading number. Use saturating_sub/checked_sub and always assert.

Verified sound (not issues)


3. Architecture, contracts & platform parity

F3 (Major) — Undisclosed rank-relay wire incompatibility

// selene/src/shard.rs:465-471
enum Kind {
    Stored,
    Fetched,
    Truncated,
    Unlinked,
    StoreInvalidated,
}
// selene/src/shard.rs:478-487
fn decode(code: u8) -> Result<Self> {
    Ok(match code {
        0 => Self::Stored,
        ...
        4 => Self::StoreInvalidated,
        _ => return Err(invalid("unknown prefix record event kind")),
    })
}

Impact. A rank on an older build receiving code 4 fails the event decode outright, so a rolling upgrade or any mixed-version rank set cannot interoperate — this is the "supported matrix & compatibility" requirement in the charter ("verify that existing data, artifacts, and exported cores still load"). Nothing in the PR body's "Compatibility and Limitations" section mentions it. Note also that record_with_header remaps the new kind to a Stored reply (shard.rs:653-656) and only emits it when the store wrote nowhere (:729-732), so the wire code is an internal signal, not a new user-visible operation.

Fix. Declare the wire addition in "Compatibility and Limitations" as a version-skew constraint (all ranks must be upgraded together), or make the decoder tolerate unknown codes for forwards-compatibility.

F4 (Major) — Three public crate signatures changed without disclosure

// selene/src/store.rs:377
fn begin_lookup(&mut self, _history: &dyn History, _resident: u64) -> Option<LookupTicket> {
// selene/src/store.rs:401-404
/// Local DRAM records that still need pool handover before shutdown drain can finish.
fn pending_pool_drain(&self) -> usize {
    self.stats().memory_records
}
// selene/src/store.rs:433-440
fn retired(
    &mut self,
    _key: PrefixKey,
    _tier: PoolTier,
    _how: Retirement,
    _offered: &[Retiring],
) {
}

Plus HostHit.pooled: bool (selene/src/store.rs:100-103) and StoreStats.disk_reserved_records / disk_reserved_bytes / pool_inbound_rates: Option<[f64; 4]> (:244-256).

Impact. HostStore and TierStore are public traits. Any out-of-tree implementor — or test fixture, or downstream SDK integration — stops compiling. begin_lookup's new resident parameter is the load-bearing one: it is the resident-aware lookup this PR is built on, so it cannot be shimmed. Fix. Add a "Compatibility and Limitations" bullet naming the three signatures and the HostHit/StoreStats field additions.

F6 (Minor) — Windows loses the buffered fallback for packed writes

// selene/src/disk.rs:1774-1781
fn is_direct_unsupported(error: &io::Error) -> bool {
    #[cfg(unix)]
    {
        error.raw_os_error() == Some(libc::EINVAL)
    }
    #[cfg(not(unix))]
    {
        false
    }
}

But the Windows opener can reject the file with Unsupported:

// eos/src/windows.rs:104-109
if sector == 0 || 4096 % sector != 0 {
    return Err(io::Error::new(
        io::ErrorKind::Unsupported,
        format!("direct I/O sector size {sector} does not divide 4096"),
    ));
}

The buffered fallback arm is therefore unreachable on Windows:

// selene/src/disk.rs:1423-1429
Err(e) if is_direct_unsupported(&e) => {
    let mut file = OpenOptions::new()
        .create(true)
        .truncate(true)
        .write(true)
        .open(&temporary)
        .map_err(|e| io_failure("create packed record file", e))?;

Impact. Pre-PR every packed write went through the buffered path, so packed (kvc=cpu/kvc=gpu) storage worked on any Windows volume. Post-PR a volume reporting a non-divisor sector size hard-fails the write as create packed record file — a new platform regression on an untested target. Fix. In the non-unix arm match ErrorKind::Unsupported | ErrorKind::InvalidInput.

F5 (Minor) — Row-restore buckets ignore the source level, defeating half the stated separation

// helios/src/server/runtime.rs:255-268
/// Source class for row-only host restores so slow remote or NVMe claims cannot
/// raise the admission floor for fast local DRAM hits.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
struct RowRestoreSource {
    pooled: bool,
    tier: flare_selene::Tier,
}

The pool already knows the 4-valued level one line before it picks the coarser tier:

// selene/src/pool/store.rs:465
let estimated_seconds = self.rates.part_seconds(plan.part.level, bytes);
...
// selene/src/pool/store.rs:479-480
tier: candidate.tier,
pooled: true,

Impact. flare_selene::Tier is Dram/Nvme, while the pool has four levels (neighbour_gpu, host_dram, host_nvme, remote_nvme — the same four the PR adds gauges for). A slow remote-NVMe claim and a fast local-NVMe claim share one median, so the floor at runtime.rs:3344-3350 (hit.estimated_seconds.max(row_restore_latency.estimate_seconds(source))) can still let a slow remote claim raise the local floor. Only DRAM-vs-NVMe is isolated. Fix. Key the bucket on plan.part.level (carry it on HostHit) rather than Tier.


4. Tests & claim accuracy

F10 (Major) — Charter #210 unmet, and the baseline is stale

The charter states: "Performance PRs need benchmarks showing an actual speedup over main on a served workload (#210)." Tables A–F in the body are an A/B against 5d53040e, while the PR base is 1fbcc3c9; the four commits in the gap include 8489d504 #663 ("price first-output waiting age on incumbent decode rounds"), which prices the very restore decisions Tables B and C report on. The body itself says the numbers were run on 7d7dcdcb ("hardware benchmarks and live saturation runs executed on pre-refactor commit 7d7dcdcb"), so no benchmark and no CI run is reported for head 19ce4a7b — including the final RowRestoreLatency/pump code that this review finds defective. Fix. Re-run Tables A–C on 1fbcc3c9 → 19ce4a7b with attached logs; report CI on the head SHA.

F9 (Minor) — Metric span semantics shifted without a docs note

// helios/src/server/metrics.rs:538-543
pub(super) fn host_lookup_cost(
    &self,
    missing_tokens: u64,
    transfer_seconds: f64,
    prefill_saved_seconds: f64,
) {

For row-only hits the transfer_seconds argument is now a floor, not a measurement:

// helios/src/server/runtime.rs:3346-3353
let source = row_restore_source(&hit);
let transfer_seconds = if hit.pages == 0 {
    hit.estimated_seconds
        .max(row_restore_latency.estimate_seconds(source))
} else {
    hit.estimated_seconds
};
metrics.host_lookup_cost(missing_tokens, transfer_seconds, prefill_saved_seconds);

and prefill_saved_seconds comes from the scheduler's graph-timing model, with a gained / fallback_prefill_rate fallback only while cold:

// helios/src/server/runtime.rs:3269-3280
if let Some(saved_ns) = scheduler.estimate_prefill_delta_ns(...) {
    return saved_ns as f64 * 1e-9;
}
let gained = candidate_tokens.saturating_sub(resident_tokens);
gained as f64 / fallback_prefill_rate.max(1.0)

Impact. flare_host_cache_prefill_ns was previously missing / measured_rate; it is now largely a modelled quantity, and host_transfer_ns for row-only hits is a decision floor rather than an observed transfer. Dashboards and any tuning that compares these series across the upgrade will misread them. Fix. Note the change in docs/api.md (not opened) alongside the other new gauges.


Open questions

  1. Does the pump self-notify actually settle under the tight-manager workload the PR benchmarks? pending_puts only drains when the session/namespace accepts the put; if a namespace is saturated for seconds, F1 turns the owner thread into a spin loop for that whole window. No test in the diff exercises pending_puts non-empty across consecutive pumps — I could not find one.
  2. Is the baseline re-run possible at all? Tables B and C report latency deltas (-28.3% mean, -12.2% p50) that #663 directly targets; without a 1fbcc3c9 run, the attribution between #674 and #663 cannot be settled from the repo.
  3. Nothing answers #451's own question ("do wider planes widen each snapshot's conflict range?"). The diff asserts midpoint pairing does not widen any row's span and adds row_conflicts/verify_physical_invariants, but #451 has no update from the PR and no conflict-pressure workload is benchmarked.
  4. Merge order with #665 (open, FujitsuPolycom), which rewrites the same victim-selection function in helios/src/cache.rs and the same docs/prefix-cache-offload.md (not opened) sections, and with #659 (open) on helios/src/runtime_core/cache_memory.rs (not opened). Neither PR references the other; this PR's evict_for_pressure + eviction_candidate_with_priority restructure will conflict textually and semantically.
  5. No SM121 / GB10 / SM103 evidence, although the charter names those targets.
  6. Zero human engagement: two bot comments, no reviews, no labels, on a 41-file cross-crate cache-core change.

What I could not verify

Author action list

  1. Fix the RowRestoreLatency clock (helios/src/server/runtime.rs:301-303) and add the observe→age→fail test.
  2. Gate the pump self-notify on real progress (selene-manager/src/store.rs:5067-5072), and stop calling on_reply() per disk completion (selene/src/disk.rs:533-535).
  3. Disclose: the Kind::StoreInvalidated = 4 wire code, the three public-API signature changes, and the sub-page memory-only startup error.
  4. Re-baseline Tables A–C against 1fbcc3c9 and post CI on 19ce4a7b.
  5. Windows: match Unsupported | InvalidInput in the non-unix is_direct_unsupported arm; make reclaim key-blocking bounded; use saturating decrements.
  6. Key RowRestoreSource on pool level rather than Tier; document the host_transfer_ns / host_prefill_ns span change in docs/api.md (not opened).
  7. Post the midpoint half-width conclusion on #451; agree merge order with #665 and #659.