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):
- sample A: decode-only, 15 ms →
zero_fill = (15 ms, u=0, h=0) - sample B: partial fill
work=128,start_position=0, 16 ms → stratum 0 =(16 ms, u=0.0625, h=0)
2-point exact fit: theta_0 = 15 ms, theta_1 = 16 ms, u_min = 0, u_max = 0.0625 (spread 0.0625 < 0.15).
predict(2048, 0)=15 + 16·1.0= 31 ms (floor skipped, sinceu_min == 0.0)- Correct (floor over positive fills only:
u_min = 0.0625):t_at_umax · min(1/0.0625, 4)=16 ms · 4= 64 ms
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
helios/src/server/runtime.rs:2118-2120:sampling_graphs_bind_grammar_enabled(self.config)(walks every graph × every input binding,runtime.rs:526-543) runs on everyWorker::complete. It is invariant for the immutable model config (the phase tests have to mutateconfig.contract.graphsbefore constructing the worker,phase_tests.rs:8695-8716). Fix: compute once inWorker::newand storecan_toggle_grammar_in_place: bool.helios/src/offload/transfer/codec.rs:685-695,:713-714,:738,:764,:766-770:restore_windowmaterialisespages+routesfor the whole window, then clones spans and chunks again per run — ~2-3 allocations per page per 64-pageWINDOW_PAGESwindow on the foreground restore path, and eager work for pages a later error never touches. Fix: pass&[Vec<DeviceSpan>]/&Vec<&[u8]>instead ofch.clone().
Explicitly checked and found CORRECT (no defect)
partition_restore_pages/restore_single_unit(codec.rs:837-873): handles empty window, all-Literal, leading+trailingLiteral,[Gpu,Cpu,Gpu],[Gpu,Gpu,Literal,Gpu](the post-LiteralGPU run is genuinely oneGpuBatch, not split or dropped — the originalelse { break; }bug is really fixed), all-singleton, andcap == 1.GpuBatchis only produced forlen > 1, so theself.gpu.as_ref().unwrap()at:706cannot panic. Pure-Literalbatches contribute exactly 0transform_ns(:569-574,:643-645) — no divide-by-zero, stale accumulator or mis-attribution.stored/transferredadvance exactly once per page on every branch (:756-757,:779-780,:784-785, row at:805).try_lockfallback cannot drop or double-consume a page (None → CPU path for the same slice,Some(Err)propagates aftersync_on_err)._ceand theMutexGuardare RAII, so no ticket leaks on?, panic, or the try-Nonepath.- Lock order: only the two wrappers plus
RankCodec::new:125(before any gate) touchgpu.codec; no path takes the mutex before the gate on the capture side. The PR's lock-order inversion is fixed; Finding 1 is the remaining consequence of gating too early inside the try variant. - Runtime state machine (
scheduler.rs/runtime.rs):paused_for_parkis cleared on every drain-loop exit (scheduler.rs:3265-3295), including the overshoot case, which routes topark_with_tokens→cancel(handle)→retire(request removed entirely, not left excluded fromeligible()/has_starved_request()/refill_reservations()/preempt_newest()). No early-?between pause and resume leaves a per-request hang. Reservation cleanup on bothfinish_earlyexits is intact. pendingdomain exhaustiveness: at most 2 outstanding submissions globally (scheduler.rs:2530-2535), and apending > 0request is scheduler-eligible only ifpending < 2 && !grammar_constrained(policy.rs:342-353), sopending ∈ {0,1}at the transition block — the in-place (pending == 0) / checkpoint (pending > 0) arms partition the domain. No dead or always-true guard.- Partial
ValueSource::GrammarEnabledbinding is handled conservatively —runtime.rs:526-543is anall()with early return plus asaw_samplingguard, so a partially-bound contract yieldsfalse→ safe checkpoint path. - Device/host grammar disagreement is unreachable:
Admission::from_continuation(admission.rs:160-173) yieldsgrammar_mask = Someonly whengrammar_mask_active, andruntime.rs:1712-1715guaranteesmask_active ⇒ device_grammar_enabled, so the||inpacking.rs:803-805is purely defensive; the.expect("grammar admission has a mask")inadmission.rs:117-122is likewise unreachable. - Mixed cost model enum hygiene:
cost.rs:653-659attaches the stratified model only foris_prefill()kinds and forMixedwithprefill > 0;Init/Restore/Snapshot/Decode/Speculative/Resume/Visionstill use the flatReplayTimesmedian (cost.rs:1097-1099), so no semantic outlier (sampling/resume/projection step) can poisonu_min/u_max/the floor. The Mixed sample really is recorded at(work, start_position)(cost.rs:1081-1090;policy.rs:2202-2206;validate_mixedatscheduler.rs:451-476). - No half-updated model / no stale coefficients:
fit()is pure;observedoeslet predictor = self.fit(); self.predictor = Some(predictor)(cost.rs:339-341);n == 0→constant(capacity, 1)(:386-388);mixed_entryreturnsSome(None)whenestimate.nanos == 0(:756-758), so the pre-first-sample path can never produce a free Mixed step. - Peer slope borrowing is bounded and cannot cross-borrow:
borrowed_mixed_context_slope(cost.rs:883-899) requirespeer_batch == batch && peer_width == width && peer_prefill > prefill && slope > 0.0 && fresh; no peer → no borrow → slope 0.context_slope_per_tokenalready requirestheta[2] > 0andhas_deep_context(cost.rs:119-122). - Boundaries:
work == 0short-circuits before the floor;u = work.clamp(1, cap)/cap.max(1)has no divide-by-zero;mixed_candidates'score_decoders(slot_ns, batch - 1)(policy.rs:1836) andcontinuation_candidate'scapacity - preparing_prompt/batch - usize::from(...)(policy.rs:1272-1274) cannot underflow becausemixed_graphsrequiresbatch >= 2(scheduler.rs:1056) andREQUEST_LANES = 64(manifest.rs:18). - Polarity: lower duration → higher score →
max_byeverywhere (policy.rs:867,:949,:1840-1845,:1979) and1e6/nsinservice_rates(service.rs:375,:387). - No per-step NNLS re-solve:
fit()runs only insideobserve(cost.rs:339), never in a pricing path;mixed_candidatesisO(mixed_catalog × 64)with fixed stack arrays and zero heap allocation. - New tests are non-vacuous and would fail on the pre-change code:
phase_tests.rs:8592-8687assertsparked.is_empty()+ sameRequestHandle(the oldpark_with_tokens(..., publish_terminal: false)→cancelpath clears the active slot and pushes toparked);:8802-8996assertsconsumed_tokens == 5ofprompt_tokens == 6(partial KV reuse) andconsumed_tokens == prompt_tokens == 5after the drain (zero re-prefill), both impossible undercancel.
Not verified / limits
- No tests were executed (no build/GPU access); all findings are from reading files at
150f705. - Finding 3 requires NNLS to leave
theta_0 ∈ (0, 1]; I traced the enumerated active-set clamping (cost.rs:407-440) but no existing test produces that exact state, so it is proven reachable-by-construction rather than observed in practice. - Finding 1's production impact depends on how often
peer_graphs_waiting > 0overlaps a restore; the code-level defect (the documented non-blocking path is unreachable) is unconditional. - Not audited: non-grammar hunks in the same
runtime.rsdiff (RowRestoreLatency,close_store, pool-lookup-reissue,observe_prefill_rate), and the chat-template tests the PR lists as unrun.