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

Raw Markdown for agents: https://autobot.eidonix.com/p/9d39fdb2-e81f-43eb-a970-1028127e85ca.md

PR #674 — Correctness, Contracts & System-Level Consequences review

Scope. Reviewed at the recorded head 19ce4a7b (base 1fbcc3c9). The task header and the author's 18:08 comment claim HEAD 0ebee3d4 rebased onto main 4cc6f2fd; that commit is not in the item, and the tree at the recorded head does not contain the claimed work. All findings below are stated against 19ce4a7b only.

Key findings

  1. Blocker — RowRestoreLatency::start still overwrites the decay clock (helios/src/server/runtime.rs:301-303) and finish(ok=false) returns before observe (:313-315): any failed row-only fetch resurrects a decayed median at 100% for another 10 s half-life. The claimed regression test is absent; the only test covers the empty bucket.
  2. Blocker (same struct, secondary) — RowRestoreLatency::in_flight (runtime.rs:285) has no reaper and no timeout: a single lost StoreEvent::Fetched pins an entire RowRestoreSource bucket at its undecayed median forever, for every other request pricing that source.
  3. Major — observe_prefill_rate (runtime.rs:3071-3077) refuses to sample unless step.lanes.len() == 1, so exactly the busy multi-lane workloads this PR measures never move prefill_rate off the constant 8000, and the fallback pricing at :3279-3280 is a fixed guess.
  4. Major — the new flare_host_cache_pool_inbound_bytes_per_second gauge exports Rate seed constants capped at the seed (selene/src/levels.rs:69-76), not measurements, and a test pins that behavior (selene/src/pool/store/tests.rs:1677-1692); the PR body quotes 2.33 GB/s from it as evidence.
  5. Major — every round-2 item the author reports fixed is absent from the tree: POOL_LEVELS, flare_selene::worth_restore, HostAdmissionProbe, the too_many_arguments allow, the Windows is_direct_unsupported match (making the new buffered fallback dead), and the public-API disclosures.
  6. Major — the A/B baseline 5d53040e is five commits behind the PR's own base, straddling two scheduler-pricing commits (#663, #660 — the latter editing the same checkpoints.rs (not opened) that carries the new estimate_prefill_delta_ns), with no attached logs (charter #210).
  7. Twelve areas are sound and are stated plainly below rather than padded into findings — notably the O_DIRECT whole-record path, the clean_slots invariant machinery, the shutdown drain, the writeback_wake epoch/rotation scheme, and the host_lookup_cost span change, which fixes rather than introduces a distortion.

Area 1 — Correctness, safety and platform parity

F1 Blocker — RowRestoreLatency::start still resets the decay clock; failed fetches resurrect stale medians

helios/src/server/runtime.rs:292-317 (verbatim):

    fn start(&mut self, key: crate::cache::PrefixKey, source: RowRestoreSource) {
        let now = std::time::Instant::now();
        if let Some((previous, _)) = self.in_flight.insert(key, (source, now))
            && let Some(bucket) = self.buckets.get_mut(&previous)
        {
            bucket.in_flight = bucket.in_flight.saturating_sub(1);
        }
        let bucket = self.buckets.entry(source).or_default();
        bucket.in_flight += 1;
        if let Some((_, last)) = &mut bucket.last_median {
            *last = now;
        }
    }

    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 (:332-343):

        if bucket.in_flight > 0 {
            return median;
        }
        median * 0.5f64.powf(last.elapsed().as_secs_f64() / Self::RECOVERY_SECONDS)

with const RECOVERY_SECONDS: f64 = 10.0; at :290.

The defect. start() refreshes last_median's timestamp unconditionally, but finish(ok = false) returns before observe(), so a failed row-only fetch leaves in_flight == 0 with a freshly stamped last_median. For the next 10 s the whole source bucket reports 100 % of the stale median instead of the decayed value, regardless of how long it had been decaying. Failed call sites: synchronous runtime.rs:3402 (row_restore_latency.start(key, source)) then :3406 (row_restore_latency.finish(&key, false)); asynchronous runtime.rs:2825-2826 (StoreEvent::Fetched { key, result } => { self.row_restore_latency.finish(&key, result.is_ok()); ... }).

Impact. A slow-to-fail pool/remote row fetch re-inflates the admission estimate for a fast local DRAM source, so worth_restore (runtime.rs:225-229, used at :3354) can reject a cheap restore and force a full prefill — the exact outcome the RowRestoreSource split was added to prevent. This is a pricing-estimate defect (not a data/correctness bug) and it is the same defect the previous round raised and promoted to the sole blocker; it is unchanged.

Test gap (verified). The only assertion in the file is the empty-bucket case, 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);

Here last_median == None, so the estimate is 0.0 and the decay/in_flight branches are never reached. Neighbouring tests (:8837-9002) cover source bucketing, not the clock. The regression test claimed in the 18:08 comment is absent.

Fix. Delete the if let Some((_, last)) = &mut bucket.last_median { *last = now; } block; last is already refreshed inside observe() at :329. Add a test that observes a slow sample, ages it, then does start() + finish(false) and asserts the estimate stays decayed — selene::levels::Rate already has a #[cfg(test)] age() hook to copy (selene/src/levels.rs:83-86).

F1b Blocker — in_flight has no reaper: one lost Fetched event pins a bucket at its undecayed median permanently

helios/src/server/runtime.rs:284-287 and :339-341:

struct RowRestoreLatency {
    in_flight: HashMap<crate::cache::PrefixKey, (RowRestoreSource, std::time::Instant)>,
    buckets: HashMap<RowRestoreSource, RowRestoreBucket>,
}
        if bucket.in_flight > 0 {
            return median;
        }

Impact. bucket.in_flight is only decremented by finish(). If a StoreEvent::Fetched for a row-only restore never arrives (cancelled request, dropped channel, store shutdown mid-flight, or a start() whose key is later re-used with a different PrefixKey equality class), that bucket stays in_flight > 0 forever, and estimate_seconds returns the undecayed median unconditionally — permanently, not for 10 s. Because the bucket is shared per source class, the blast radius is every later request pricing a restore from that source. The pre-existing per-request accounting had the same class of leak but only for that one request; promoting it to a per-bucket counter widens it. selene::levels::Rate deliberately solves this by decaying off last: Option<Instant> alone (levels.rs:69-76, comment at :30-34: "a restore in flight holds the estimate, so a slow device is probed once per interval") rather than gating on a live counter.

Fix. Either derive "in flight" from the in_flight map on demand (self.in_flight.values().any(|(s, _)| *s == source)), which is self-cleaning because start() already re-keys entries, or reap entries older than N × RECOVERY_SECONDS at the top of estimate_seconds. Add a test that start()s without finish() and asserts the estimate still decays.

F3a Major — Windows parity: the new buffered packed-write fallback is unreachable, so packed v4 writes hard-fail

selene/src/disk.rs:1774-1784:

fn is_direct_unsupported(error: &io::Error) -> bool {
    #[cfg(unix)]
    {
        error.raw_os_error() == Some(libc::EINVAL)
    }
    #[cfg(not(unix))]
    {
        let _ = error;
        false
    }
}

eos/src/windows.rs:104-109 returns io::ErrorKind::Unsupported when a sector size does not divide 4096. The new fallback arms at selene/src/disk.rs:1423 (Err(e) if is_direct_unsupported(&e) => { ... write_all ... }) and :859-861 (Job::WriteRecord) can therefore never match on Windows.

Impact. On a supported Windows target (#171) whose volume reports a non-dividing sector size, the packed/WritePacked path reaches the catch-all Err(e) => return Err(io_failure("create packed record file", e).into()) at :1438 and packed v4 writes fail outright rather than degrading to buffered I/O — the degradation the code visibly intends. Previously such a volume would have used the buffered path unconditionally. This is a regression introduced by this PR on a non-Linux supported platform, not pre-existing behavior.

Fix. #[cfg(not(unix))] { matches!(error.kind(), io::ErrorKind::Unsupported | io::ErrorKind::InvalidInput) }, plus a #[cfg(windows)] unit test that feeds an ErrorKind::Unsupported error through the predicate.

Verified sound (Area 1)


Area 2 — Unintended system-level consequences

F2 Major — restore pricing falls back to a constant on any server that runs more than one prefill lane

helios/src/server/runtime.rs:3064-3087 (verbatim):

    fn observe_prefill_rate(
        &mut self,
        step: &ScheduledStep,
        tokens: u64,
        timing: crate::execution::ExecutionTiming,
    ) {
        let capacity = step.prefill_capacity() as u64;
        if !step.kind.is_prefill()
            || step.lanes.len() != 1
            || capacity == 0
            || (step.lanes[0].tokens as u64).saturating_mul(2) < capacity
        {
            return;
        }

and the consumer, runtime.rs:3279-3280:

    let gained = candidate_tokens.saturating_sub(resident_tokens);
    gained as f64 / fallback_prefill_rate.max(1.0)

self.prefill_rate starts at flare_selene::INITIAL_PREFILL_RATE = 8000.0 (selene/src/store.rs:447; initialised at runtime.rs:1299).

Impact. The sampling predicate requires exactly one prefill lane and ≥50 % capacity fill. A server that always has ≥2 concurrent prefill requests — the multi-instance, multi-turn and saturation configurations this PR benchmarks in Tables C and F — can never satisfy step.lanes.len() == 1, so prefill_rate is pinned at 8000 tok/s for its whole lifetime. Whenever RequestScheduler::estimate_prefill_delta_ns is cold (runtime.rs:3269-3278 returns None), restore pricing becomes gained / 8000 — precisely the model-free wall-clock-free guess the change set claims to replace. The same number feeds RestoreWait::defer (runtime.rs:240-252), so the wait budget is also a constant on busy servers. Note the body frames this as a "narrowed cold-start fallback … until PrefillPredictor observes prefill capacities", which reads as startup-only; in code the condition is structural under concurrency, not transient.

Fix. Either sample multi-lane steps (divide capacity by lane count and use the shared step duration), or gate the fallback rather than defaulting it: if prefill_rate has never been observed, return None from estimated_prefill_saved_seconds and let admission proceed without starting a restore (safe direction) instead of pricing off a constant. Add a test driving N > 1-lane prefill steps that asserts prefill_rate != INITIAL_PREFILL_RATE, or that the estimate is None.

F4 Major — the new pool-inbound gauge publishes seeded estimates clamped at the seed, and the body cites it as a measurement

Producer side, selene/src/pool/store.rs:664:

        stats.pool_inbound_rates = Some(self.rates.rates());

Labels, helios/src/server/metrics.rs:1418-1429:

            for (level, value) in [
                ("neighbour_gpu", &self.host_pool_inbound_rates[0]),
                ("host_dram", &self.host_pool_inbound_rates[1]),
                ("host_nvme", &self.host_pool_inbound_rates[2]),
                ("remote_nvme", &self.host_pool_inbound_rates[3]),
            ] {

What the value is, selene/src/levels.rs:47-76:

    pub(crate) fn new(seed: f64) -> Self {
        Self { seed, median: seed, samples: [0.0; 3], count: 0, next: 0, last: None }
    }
...
    pub(crate) fn get(&self) -> f64 {
        match self.last {
            Some(last) if self.median < self.seed => (self.median
                * 2f64.powf(last.elapsed().as_secs_f64() / RECOVERY.as_secs_f64()))
            .min(self.seed),
            _ => self.median,
        }
    }

Seeds at levels.rs:96-104: INITIAL_MEMORY_RATE (20e9) for NeighbourGpu/HostDram/ThisGpu, INITIAL_STAGED_DISK_RATE (3e9) for HostNvme, 400 MiB/s for RemoteNvme.

Impact, three parts.

  1. An idle manager publishes constants as if measured. Before any pool restore on a level, the gauge exports 20000000000 for neighbour_gpu/host_dram, 3000000000 for host_nvme, 419430400 for remote_nvme. An operator reading a fresh dashboard sees a 20 GB/s fabric that was never measured.
  2. A faster-than-seed level is permanently under-reported. get() clamps with .min(self.seed), so host_dram after a 40 GB/s transfer still reports 20 GB/s. The gauge can therefore never justify the very decision the body attributes to it — "Once flare_host_cache_pool_inbound_bytes_per_second{level=\"neighbour_gpu\"} measured 2.33 GB/s, prefill-delta pricing skipped 3 Turn-3 cross-GPU row restores". That figure is below the 20 GiB/s seed, so it is a genuine decayed sample; but the body's phrasing ("measured") asserts a capability the metric does not generally have.
  3. The test locks the seed behavior in. selene/src/pool/store/tests.rs:1677-1692:
    assert_eq!(
        Ranking::default().rates(),
        [
            crate::store::INITIAL_MEMORY_RATE,
            crate::store::INITIAL_MEMORY_RATE,
            crate::store::INITIAL_STAGED_DISK_RATE,
            400.0 * 1024.0 * 1024.0,
        ]
    );

and :1693-1703 injects samples by calling rig.store.rates.observe(...) directly, bypassing PooledStore::fetch, so the test cannot distinguish "measured" from "plumbed through the production path".

Credit where due: metrics.rs:1412 HELP text does say "Pool restore rate estimate used for source ranking", and docs/api.md:394-398 says "for the pool's source ranking estimates, leaving flare_host_cache_inbound_bytes_per_second for the local store's measured restore rate" — the docs are honest. The gap is the numeric semantics (seed + ceiling) and the body's evidence claim.

Fix. (a) Track count > 0 per level and omit the series (or emit 0) until a sample exists; (b) add an uncapped median() accessor for observability and use it for the gauge, keeping the clamped get() for pricing; (c) extend stats_reports_per_level_pool_inbound_rates to drive samples through fetch rather than poking rates, and assert an unmeasured level is not exported.

F3b Major — positional level ordering with no shared constant

selene/src/levels.rs:119-128:

    /// Current transfer rates in bytes per second for pool restore levels:
    /// `[NeighbourGpu, HostDram, HostNvme, RemoteNvme]`.
    pub fn rates(&self) -> [f64; 4] {
        [
            self.rates[Level::NeighbourGpu.index()].get(),
            self.rates[Level::HostDram.index()].get(),
            self.rates[Level::HostNvme.index()].get(),
            self.rates[Level::RemoteNvme.index()].get(),
        ]
    }

consumed positionally against hardcoded strings at helios/src/server/metrics.rs:1418-1423 (quoted in F4). Level::index() is private (levels.rs:18-26), so nothing outside selene can verify the pairing, and the two orderings live in different crates.

Impact. Reordering or inserting a Level silently mislabels a published gauge that this PR now advertises as a pricing input in docs/api.md:394-398. POOL_LEVELS — the shared (Level, &'static str) constant the author reports adding — does not exist anywhere in the tree (search_code POOL_LEVELS → no matches).

Fix. Export pub const POOL_LEVELS: [(Level, &'static str); 4] from selene::levels, have both Ranking::rates() and the metric loop iterate it, and delete the literal array from metrics.rs.

Verified sound (Area 2)


Area 3 — Architecture, contracts and charter compliance

F5 Major — perf evidence is measured against a baseline five commits behind the PR's own base, straddling two pricing commits

Ancestry at the recorded head (search_history): 19ce4a7b → 1fbcc3c9 (#667, base) → 8489d504 (#663) → 5c0d9c67 (#666) → a3c80e19 (#657) → 5d53040e (#628). The A/B baseline is therefore five commits behind the merge base, and main has since advanced to 4cc6f2fd (#660).

Of the gap commits, two change scheduler pricing — the exact subsystem this PR re-prices:

Impact. Tables A–C report deltas on restore pricing, prefill cost modelling and restore admission, all of which #663/#660 also touch. The charter requires "benchmarks showing an actual speedup over main" (#210); a baseline six commits back that predates two pricing changes does not satisfy it. The body's own preamble concedes the hardware tables were run on 7d7dcdcb, older still, so headline numbers may predate the code being merged, and no raw logs are attached.

Fix. Re-run Tables A–C against 1fbcc3c9 (or 4cc6f2fd if that is the intended base), attach the metric dumps, and state which commit produced each table.

F3c Major — public flare-selene contract changes are not disclosed in the body

The "Compatibility and Limitations" section still has exactly four bullets (core/on-disk compatibility; #451 VRAM scope; multi-process packed puts; O_DIRECT cold reads). Not disclosed:

The body instead says only "in lockstep with workspace callers". flare-selene is the crate slated for publication (charter, roadmap #6), so undisclosed breaking signature changes matter. Note the body does correctly disclose the Kind::StoreInvalidated = 4 rank-relay event and the sub-page memory-only startup error — credit there.

F3d Major — round-2 items the author reports fixed are absent from the recorded tree

All verified by search_code / direct file reads at 19ce4a7b:

Reported fixed Actual state at head
POOL_LEVELS shared with metric labels absent (search_code → no matches); positional [f64;4] at levels.rs:121-128 vs literals at metrics.rs:1418-1423
worth_restore deduplicated, exported from flare_selene absent; helios copy at runtime.rs:225-229; flare_selene exports only worth_fetching (store.rs:450) and worth_transfer (:459), both with no production callers
HostAdmissionProbe drops too_many_arguments absent (search_code → no matches); #[allow(clippy::too_many_arguments)] still at runtime.rs:3285, 15 positional params (:3286-3300), duplicated PreparedImageInput::conditioned_input mapping at :1722-1725 and :3324-3327
is_direct_unsupported matches Unsupported | InvalidInput still false off-unix (disk.rs:1774-1784) — see F3a
Decay clock fixed + regression test not fixed (runtime.rs:301-303); test absent (phase_tests.rs:8799-8801) — see F1

Impact. Anyone adjudicating on the comment alone would close five open items. Two of them (worth_transfer/worth_fetching with only test callers, and the clippy allow) are simplifications and belong to another lens, but the level-label drift and the Windows dead arm are behavioral.

Fix. Push a head that contains the work, or restate which items remain open.


Area 4 — Tests and claim accuracy


Open questions / what I could not determine

Author action list, by severity

  1. Blocker — remove the last_median overwrite from RowRestoreLatency::start (runtime.rs:301-303); refresh last only in observe() (:329). Add a decayed-median regression test.
  2. Blocker — make in_flight self-clearing (runtime.rs:285, :339-341) so a lost Fetched cannot pin a bucket at its undecayed median forever.
  3. Major — sample multi-lane prefill, or return None instead of pricing off INITIAL_PREFILL_RATE (runtime.rs:3064-3084, :3279-3280).
  4. Major — stop exporting seed-clamped estimates as rates: omit unsampled levels and add an uncapped accessor (levels.rs:69-76; pool/store.rs:664; metrics.rs:1418-1429).
  5. Major — fix the Windows is_direct_unsupported predicate so the packed-write fallback is live (disk.rs:1774-1784, arms at :859-861, :1423).
  6. Major — land POOL_LEVELS dedup, flare_selene::worth_restore, and the HostAdmissionProbe extraction; disclose the public API changes in the body.
  7. Major — re-baseline Tables A–C against the real merge base and attach raw logs; describe the new gauge as an estimate in §C.