Code correctness report · NVIDIA/hyperflare-inference #729

Raw Markdown for agents: https://autobot.eidonix.com/p/2040d8e0-f3a4-45ae-af5d-12a2950ab707.md

Deep Code Correctness, Invariants & Hot-Path Performance Audit — PR #729 @ 68fe22f

Scope note (partitioning): the PR is >1,900 changed lines across three distinct subsystems (scheduler/lifecycle/runtime state machine, GPU KV offload, and the cost model), so I partitioned into 3 disjoint slices and audited them concurrently, then re-verified every reported finding myself against the real files at pr/729 (I re-read cost.rs:340-470, copy_gate.rs:165-215, codec.rs:700-740 directly and confirmed each quote below).

Result: 1 Major finding (a real numeric/algorithmic regression in the new GraphKind::Mixed cost model), 2 Minor findings (hot-path allocation regression in the restore path, bounded wave-token barging in CopyEngineGate). No Blocker. Slice A (grammar-transition state machine) is clean.


FINDING 1 — Major: a single decode-only Mixed sample turns the (fill, kv_context) model into a constant predictor, so later full-chunk prefills are priced at decode-only latency and the 4x upward floor is disabled

Diff site 1 — the offending disjunct (helios/src/scheduler/cost.rs:451-456):

        let wide_or_full_positive =
            pos_u_max == 0.0 || pos_u_max >= 1.0 - 1e-9 || (pos_u_max - pos_u_min) >= 0.15;
        let constant_nanos = (best_theta[1] == 0.0
            && best_theta[2] == 0.0
            && wide_or_full_positive)
            .then_some(clamp_nanos(best_theta[0]));

Callee/enum resolution that makes this a bug:

This is a regression vs. pre-PR behaviour, not intended design. Pre-PR, the same decode-only sample produced u = work.clamp(1,cap)/cap = 1/2048, hence u_max - u_min = 0 < 0.15 → narrow → constant_nanos = None, and a later u = 1 query was caught by upward_extrapolation_floor at 4x. The new pos_u_max == 0.0 || disjunct converts "no positive-fill evidence" into "confidently constant".

Concrete counterexample. Mixed graph (batch=4, width=1, prefill=2048); true costs: decode-only 2,000,000 ns, full shallow prefill 95,000,000 ns.

  1. First submitted step for this catalog entry is decode-only → observe(nanos=2_000_000, work=0, …, fresh=true) → zero_fill = {2_000_000}, strata all empty → fit(): n == 1, pos_u_max == 0.0, pos_u_min == INFINITY, fallback_t = t_at_umin = 2_000_000, best_theta = [2e6, 0, 0], wide_or_full_positive == true → constant_nanos = Some(2_000_000).
  2. A prefillable request arrives; mixed_entry returns the constant predictor → mixed_duration(4, 1, 2048, work=2048, start=0) = 2_000_000 instead of ~95,000,000 (≈47x under-priced), and predict(2048,0) never sees the theta[1]*u or theta[2]*h terms. mixed_candidates also branches to the variable_cost == false path.
  3. The graph stays mispriced for the whole TTL (30 s of now_ns - observed_at_ns < ttl_ns), i.e. across many scheduling decisions.

Fix (three parts, all local):

  1. Drop the vacuous disjunct so "no positive-fill evidence" is never declared constant: let wide_or_full_positive = pos_u_max >= 1.0 - 1e-9 || (pos_u_max - pos_u_min) >= 0.15;
  2. Add pub fn has_positive_fill(&self) -> bool { self.pos_u_max > 0.0 } and, in mixed_entry (cost.rs:762-790), return Some(None) when prefill > 0 and the predictor has no positive-fill evidence, so a Mixed prefill candidate is treated as a discovery candidate instead of being priced at decode latency.
  3. Leave the work == 0 branch of predict unchanged — that path is correctly anchored by has_zero_fill (cost.rs:187-197).

(The two new tests — cost.rs:1762-1898 and policy_tests.rs:9510-9576 — both train a positive-fill sample before asserting anything about fill pricing, which is exactly why neither catches this.)


FINDING 2 — Minor (hot-path allocation): the GpuBatch restore arm still clones every per-page DeviceSpan vector, one allocation per page per restore

Diff site (helios/src/offload/transfer/codec.rs:716-717):

                            let run_spans: Vec<Vec<DeviceSpan>> =
                                slice.iter().map(|(_, _, _, sp)| sp.clone()).collect();
                            let res = guard.decode_pages_batch_to_device(
                                &self.cpu.gpu_page,
                                &packets,
                                &run_spans,

Callee resolution: slice is a sub-range of the pages vector built at codec.rs:685-693, which already owns exactly those Vec<DeviceSpan> values — the clone is pure overhead introduced to satisfy the &[Vec<DeviceSpan>] signature of decode_pages_batch_to_device (helios/src/offload/transfer/gpu_codec.rs:1693-1698). The PR already made the sibling helper generic for exactly this reason: copy_spans_batch takes impl AsRef<[DeviceSpan]> (codec.rs:1062). This partially contradicts the PR's own claim that the partitioning avoids "cloning per-page DeviceSpan vectors".

Concrete case: a 32-page GKV1 restore window with gpu_batch_cap = 8 and 4 planes per page ⇒ 32 extra Vec heap allocations and 128 DeviceSpan copies per foreground prefix-cache restore. restore_window is on the per-restore foreground hot path.

Fix: mirror the copy_spans_batch change — spans_per_page: &[impl AsRef<[DeviceSpan]>] (or &[&[DeviceSpan]]) in decode_pages_batch_to_device, and pass slice.iter().map(|(_,_,_,sp)| sp.as_slice()).collect::<Vec<_>>() (one outer allocation, zero per page). transfer_spans_batch (gpu_codec.rs:1175-1250) already only iterates the inner slice, so the change is local.


FINDING 3 — Minor (bounded fairness): try_enter_offload_batch can spend a wave token that was armed for blocked offload batches

Diff site (helios/src/offload/copy_gate.rs:177-186, :204-210):

    fn take_offload_lease(&self, state: &mut State) -> OffloadBatchGuard<'_> {
        if state.turn == Turn::Offload && state.offload_wave_remaining > 0 {
            state.offload_wave_remaining -= 1;
            if state.offload_wave_remaining == 0 {
                state.turn = Turn::Peer;
            }
        }
        state.offload_batches_active += 1;
        OffloadBatchGuard { gate: self }
    }
    pub fn try_enter_offload_batch(&self) -> Option<OffloadBatchGuard<'_>> {
        let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
        if Self::offload_must_wait(&state) {
            return None;
        }
        Some(self.take_offload_lease(&mut state))
    }

Invariant resolution: maybe_arm_offload_wave (copy_gate.rs:54-68) sizes the wave as offload_wave_remaining = offload_batches_waiting, i.e. one token per thread already parked in Condvar::wait. Because offload_must_wait (:171-175) returns false for turn == Offload && offload_wave_remaining > 0, an unrelated foreground restore can satisfy the guard and consume a token reserved for a parked batch.

Concrete counterexample: 4 offload batches are blocked (offload_batches_waiting = 4, peer streak at MAX_PEER_STREAK_WHILE_OFFLOAD_WAITING = 4, :34) ⇒ maybe_arm_offload_wave sets turn = Offload, wave_remaining = 4. Four foreground GPU restores call try_enter_offload_batch() back-to-back ⇒ wave_remaining reaches 0 and turn flips to Peer before any woken batch re-evaluates; the woken threads see turn == Peer and wait again.

Severity is Minor because starvation is bounded, not unbounded: the re-arm is unconditional — every peer-graph entry increments peer_entries_while_offload_waiting while offload_batches_waiting > 0 (:159-164) and PeerGraphGuard::drop retries maybe_arm_offload_wave (:225), so at most 4 peer admissions can be inserted between waves. I found no invariant break in should_yield_to_offload (:94-100), which keys off offload_batches_waiting/peer_entries_while_offload_waiting — counters the try path correctly leaves untouched.

Fix: don't spend waiter-reserved tokens from the try path —

    if Self::offload_must_wait(&state)
        || (state.turn == Turn::Offload && state.offload_batches_waiting > 0) {
        return None;
    }

which keeps the foreground fast path whenever nobody is queued.


Slice A (grammar transitions) — audited clean, with the proofs that mattered

No defect found in scheduler.rs {set_grammar_constrained, pause_for_park, finish_for_park, pause/eligible/refill_reservations gating}, model/admission.rs AdmissionGrammar, model/packing.rs, server/runtime.rs {complete, publish, park_*, decide_grammar_transition}, or the Lifecycle.tla/check.py additions. The non-obvious claims I verified rather than assumed:

One non-defect robustness note (not counted as a finding): Admission::grammar_updated's .expect("grammar admission has a mask") (admission.rs:147-152) is safe only because Disabled/UnmaskedEnabled never co-occur with grammar_reasoning_mode == Some(false) — a cross-file invariant now load-bearing across admission.rs, packing.rs and runtime.rs, unenforced by types. A debug_assert! there would make it non-fragile.


Slice B (offload, apart from Findings 2–3) — audited clean


Coverage summary

Caveats: no code was executed (read-only audit); the 9 HF chat-template and 39 checkpoint-gated tests the PR marks unrun were not assessed; the Python simulator does not model (fill, kv_context) curves so Finding 1's numeric impact is hand-computed from the code, not observed — but the defect requires only one decode-only Mixed sample, and service.rs:232-239 already issues exactly such a probe.