Code correctness report · NVIDIA/hyperflare-inference #729

Raw Markdown for agents: https://autobot.eidonix.com/p/17b8ff2f-d3a2-498a-81c5-fc718c5f9770.md

Deep Code Correctness / Invariants / Hot-Path Audit — PR #729 @ 150f705

14 files, 3 distinct Helios subsystems → audited via 3 concurrent sub-agents (offload codec, scheduler Mixed cost-model, runtime grammar/park), then key findings independently re-verified by me against the files at 150f705.

Verdict: 2 Major defects (both unconditional, code-level), 4 Minor. No Blocker found. The rest of the slice — including the claims most at risk (partition_restore_pages batching correctness, paused_for_park never stuck, pending domain exhaustiveness, no semantic outlier in the Mixed cost model, no per-step NNLS re-solve) — I checked and found correct.


FINDING 1 — MAJOR: try_with_gpu_codec_locked blocks on CopyEngineGate before try_lock, so the foreground-restore CPU fallback is unreachable (and it burns a wave token)

Diff site — helios/src/offload/transfer/codec.rs:888-899 (re-verified by me):

/// Acquires `CopyEngineGate::enter_offload_batch` before `try_lock` on the GPU codec mutex.
/// Returns `None` when another thread currently holds the codec mutex, releasing the gate
/// immediately so foreground restores can fall back to CPU decoding without blocking.
fn try_with_gpu_codec_locked<T, R>(
    copy_gate: Option<&super::super::CopyEngineGate>,
    codec: &Mutex<T>,
    f: impl FnOnce(&mut T) -> Result<R>,
) -> Option<Result<R>> {
    let _ce = copy_gate.map(super::super::CopyEngineGate::enter_offload_batch);
    let mut guard = codec.try_lock().ok()?;
    Some(f(&mut guard))
}

Callee definition — helios/src/offload/copy_gate.rs:173-195: enter_offload_batch is an unbounded blocking condvar wait, not a try:

fn must_wait(&self, state: &GateState) -> bool {
    state.peer_graphs_active > 0
        || (state.peer_graphs_waiting > 0
            && !(state.turn == Turn::Offload && state.offload_wave_remaining > 0))
}
// ...
while self.must_wait(&state) {
    state = self.changed.wait(state).unwrap_or_else(|e| e.into_inner());
}

Defect. Line 896 is the blocking step and it runs before line 897's non-blocking try_lock. The doc comment at :888-890 — which states the helper releases the gate immediately so restores can fall back to CPU "without blocking" — is false: by the time try_lock is evaluated the thread has already parked on the gate. The whole purpose of the PR's fix (docs/PR body: "preventing background captures blocked on CopyEngineGate from forcing foreground restores onto CPU decoding") is defeated for the try variant: the restore stalls for the full peer-graph drain (bounded only by the 120 s PEER_GRAPH_GATE_TIMEOUT) instead of taking the CPU path.

Concrete counterexample. Background capture thread holds gpu.codec (via with_gpu_codec_locked, codec.rs:883-885) and a gate ticket; a pipelined peer-copy graph calls enter_peer_graph → peer_graphs_waiting = 1 (copy_gate.rs:127). A foreground restore reaches try_with_gpu_codec_locked (call sites codec.rs:605, :704) and blocks at :896 for the entire peer drain. The CPU-fallback branch it was supposed to reach (codec.rs:729-755, the None arm that decodes on CPU) is never taken.

The new test cannot catch it — helios/src/offload/transfer/codec.rs:1737-1748 (copy_engine_gate_before_codec_mutex_leaves_mutex_unheld_while_waiting_on_peer_graph) drops peer_guard before exercising the helper, so it only proves the mutex is unheld during f(), never that the try path is non-blocking.

Fix. Reverse the order, or add a genuinely non-blocking gate entry:

let mut guard = codec.try_lock().ok()?;              // cheap, non-blocking first
let _ce = copy_gate.map(CopyEngineGate::enter_offload_batch);
f(&mut guard)

or add CopyEngineGate::try_enter_offload_batch() -> Option<Guard> that returns None instead of waiting, and use it here.


FINDING 2 — MAJOR: a single decode-only Mixed sample permanently disables the upward extrapolation floor, letting partial fills discount full-chunk cost ~2x

Diff site — helios/src/scheduler/cost.rs:132-142 (re-verified by me):

fn upward_extrapolation_floor(&self, u: f64) -> f64 {
    if self.u_min > 0.0
        && (self.u_max - self.u_min) < 0.15
        && u > self.u_max
        && self.u_max > 0.0
    {
        self.t_at_umax * (u / self.u_max).min(PREFILL_MAX_UPWARD_EXTRAPOLATION)
    } else { 0.0 }
}

Callee / invariant — helios/src/scheduler/cost.rs:368-373 + :354-361 (re-verified by me). The new zero_fill bucket is recorded into the same u_min/u_max extent as the positive-fill strata, with u = 0.0:

if let Some((t, u, h)) = self.zero_fill.median()
    && t > 0.0 && t.is_finite()
{
    record_point(t, u, h);          // u == 0.0
}
...
if u < u_min - 1e-12 || ((u - u_min).abs() <= 1e-12 && h < h_at_umin) {
    u_min = u;                       // u_min becomes 0.0

Spec violated. docs/scheduling-runtime-design.md (cost-model section) requires the floor "when only a narrow positive fill regime (u_min > 0, spread < 0.15) has been observed, queries above u_max apply a bounded constant-throughput upward floor … so partial fills cannot discount full-chunk cost estimates or lock out a large capacity after TTL reset". The u_min > 0 wording is meant to exclude the decode-only point, but the zero-fill bucket is folded into the same u_min, so the guard is dead as soon as one decode-only Mixed step is observed. Note the gate is not needed for work == 0 anyway — predict returns before the floor at cost.rs:176-189, so u_min > 0.0 protects nothing there. This also creates a prefill/Mixed parity break: pure-prefill graphs never push a u=0 point, Mixed graphs always do.

Concrete counterexample. Mixed(4,1,2048) just after a TTL reset (buckets cleared, cost.rs:317-320):

2-point exact fit: theta_0 = 15 ms, theta_1 = 16 ms, u_min = 0, u_max = 0.0625 (spread 0.0625 < 0.15).

A 2.06x under-prediction of full-chunk cost, caused solely by the presence of an observation that carries no information about fill cost. Downstream this makes a full-chunk Mixed plan look cheap and win select_plan/service_rates comparisons against correctly-priced candidates.

Existing coverage misses it: cost.rs:1830-1840 (asserts guarded == 80_000_000) exercises only the no-zero_fill path, so the regression test passes while the guard is disabled in the Mixed case.

Fix. Track u_min_positive/u_max_positive/t_at_umax_positive over the self.strata loop only (cost.rs:374-385) and gate upward_extrapolation_floor on that extent; keep zero_fill in the NNLS pts vector (:372) so the intercept is still fitted. Update the doc sentence accordingly.


FINDING 3 — MINOR: degenerate fit clamped to 1 ns, which is the best possible score rather than "unknown"

helios/src/scheduler/cost.rs:182-188 and :198-200 (re-verified by me):

return if !base.is_finite() || base <= 1.0 {
    1
} else if base >= u64::MAX as f64 { u64::MAX } else { base.round() as u64 };
...
if !pred.is_finite() || pred <= 1.0 { 1 }

Callee — helios/src/scheduler/utility.rs:154-171: a duration_ns of 1 is not treated as the optimistic-exploration sentinel (that is duration_ns == 0); it gets score = expected_value / 1e-6 (1e6x), and is_unmeasured_candidate (policy.rs:546-549) returns false because duration_ns != 0, so it is dispatched as PlanOrigin::Ordinary with estimated_duration_ns = 1.

Counterexample. NNLS with a clamped small intercept — points (100 ns, u=0.25, h=0) and (395 ns, u=1.0, h=0) — can leave the enumerated active-set solution at theta_0 = 0.4, theta_1 = 0 (cost.rs:407-440 clamps theta[idx[pos]] = sol[pos].max(0.0)). predict(2048, 0) → 0.4 → 1 ns → that candidate wins max_by against every measured graph and is treated as a free execution window.

Fix. Clamp to t_at_umin (or the smallest observed stratum median); reserve the literal 1 for the no-sample case only.


FINDING 4 — MINOR: grammar toggle is non-atomic; caller and callee phase guards are different predicates, so a rejected toggle leaves host and device grammar state disagreeing

Diff site — helios/src/server/runtime.rs:2363-2380 (mirror at :2441-2454): mutates incoming.grammar_reasoning_mode, request.reasoning, admissions[slot].set_grammar_mask(...) and then calls self.scheduler.set_grammar_constrained(...)?.

Callee — helios/src/scheduler.rs:3240-3247 (re-verified by me):

if request.pending != 0
    || matches!(request.phase, RequestPhase::Inbound | RequestPhase::Finishing)
    || (request.phase == RequestPhase::Snapshot && request.boundary_capture.is_none())
{
    return Err("grammar constraint mode requires a live request with no pending GPU work".into());
}

The caller gate (runtime.rs:2357-2362, :2435-2440) accepts Snapshot && boundary_capture.is_some(), which the callee rejects; conversely the caller rejects Snapshot && terminal_snapshot.is_some(), which the callee accepts. Neither predicate implies the other. On the rejected path the ? aborts complete() after the admission mask and request.reasoning were already mutated while grammar_constrained stays true — device keeps Width = 1 while the host believes reasoning is unmasked. Not proven reachable across a completion boundary (phase Snapshot with neither capture is transient inside complete_inner, scheduler.rs:3106-3113), hence Minor.

Fix. Call set_grammar_constrained first (it is a pure check + flag write, idempotent), then mutate incoming/admissions; or have the caller reuse the callee's predicate.


FINDING 5 — MINOR (fairness/hot path): the try-wrapper consumes two gate wave tokens per restore unit

codec.rs:896 enters the gate, then GatedCopies::batch (helios/src/offload/transfer.rs:335-336) enters it again. enter_offload_batch decrements offload_wave_remaining and flips the turn back to Peer at zero (copy_gate.rs:187-192), while the wave is armed to exactly offload_batches_waiting (copy_gate.rs:62) with MAX_PEER_STREAK_WHILE_OFFLOAD_WAITING = 4 (copy_gate.rs:34). A restore that later fails try_lock thus burned 2 tokens for one page run, shortening offload's turn against peer graphs. Same fix as Finding 1.


FINDING 6 — MINOR (hot path): per-frame invariant recomputation and per-page allocation on the foreground path


Explicitly checked and found CORRECT (no defect)

Not verified / limits