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:
helios/src/scheduler/cost.rs:365-374—pos_u_maxis raised only underif u > 0.0:if u > 0.0 { if u < pos_u_min - 1e-12 { pos_u_min = u; } if u > pos_u_max + 1e-12 || ((u - pos_u_max).abs() <= 1e-12 && h < pos_h_at_umax) { pos_u_max = u; pos_t_at_umax = t; pos_h_at_umax = h; } }helios/src/scheduler/cost.rs:321-324— awork == 0(decode-only) Mixed sample is recorded only inzero_fill, withu = 0.0, h = 0.0:if work == 0 { self.zero_fill .observe(PrefillSample { nanos, u: 0.0, h: 0.0 }); } else {work == 0is a legal, routine Mixed step:validate_mixedacceptsprefill_row == None(helios/src/scheduler.rs:455-479), andservice.rs:232-239already prices a decode-only Mixed probe viamixed_duration(batch, width, prefill, 0, 0).helios/src/scheduler/cost.rs:413-414— with no positive-fill sample,pos_u_max == 0.0, sofallback_t = t_at_umin= the zero-fill median (decode latency), andbest_theta = [decode_ns, 0, 0].helios/src/scheduler/cost.rs:183-186—predictshort-circuits on the constant, so the fill/context terms are never evaluated:pub fn predict(&self, work: usize, start_position: u64) -> u64 { if let Some(nanos) = self.constant_nanos { return nanos; }helios/src/scheduler/cost.rs:144-153— the 4x upward floor cannot rescue it, because it requirespos_u_max > 0.0:fn upward_extrapolation_floor(&self, u: f64) -> f64 { if self.pos_u_max > 0.0 && (self.pos_u_max - self.pos_u_min) < 0.15 && u > self.pos_u_max { self.pos_t_at_umax * (u / self.pos_u_max).min(PREFILL_MAX_UPWARD_EXTRAPOLATION)- Downstream,
helios/src/scheduler/policy.rs:1872usesvariable_cost = predictor.is_some_and(|p| !p.is_constant()), so the predictor being constant also disables per-candidate fill/KV-context scoring for that graph, andis_unmeasured_candidate(policy.rs:546-549, viacosts.observation()→nanos != 0) no longer classifies the graph as discovery, so exploration never learns the true prefill cost.
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.
- First submitted step for this catalog entry is decode-only →
observe(nanos=2_000_000, work=0, …, fresh=true)→zero_fill = {2_000_000},strataall 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). - A prefillable request arrives;
mixed_entryreturns the constant predictor →mixed_duration(4, 1, 2048, work=2048, start=0) = 2_000_000instead of ~95,000,000 (≈47x under-priced), andpredict(2048,0)never sees thetheta[1]*uortheta[2]*hterms.mixed_candidatesalso branches to thevariable_cost == falsepath. - 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):
- 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; - Add
pub fn has_positive_fill(&self) -> bool { self.pos_u_max > 0.0 }and, inmixed_entry(cost.rs:762-790), returnSome(None)whenprefill > 0and 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. - Leave the
work == 0branch ofpredictunchanged — that path is correctly anchored byhas_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:
set_grammar_constrainedcannot fail on aToggleInPlacepath. Its rejection predicate (scheduler.rs:3238-3253:pending != 0 || phase ∈ {Inbound, Finishing} || (Snapshot && boundary_capture.is_none())) is dominated by thedecide_grammar_transitiongate (runtime.rs:529-538:skipped == 0 && pending == 0 && extra == 0 && error_code.is_none() && can_toggle_in_place && !phase ∈ {Inbound,Finishing} && !(Snapshot && terminal_snapshot.is_some())).?on the scheduler call precedes the request/admission mutation (runtime.rs:2390-2399), so the two sides cannot diverge on a partial failure.pending_grammar_parkcannot leak / wedge a slot. Written atruntime.rs:2534(and kept at:2517), cleared at:2514(drained-frame error),:2519-2524(rollback),:2566(publishtake), plusclear_active_sloton failure (:2574). I enumerated all fivepublishexits for a slot holding a park (finish+last_use <= completed, finish+fence pending, still paused,Snapshotterminal-capture arm, drained error) and each either finalizes or re-parks; thecontinueat:2588cannot strand a terminal slot because the grammar branch always ends inpark_with_tokens(which pushes toself.parked) orfail+finish+clear_active_slot.ToggleInPlacecannot run with a frame in flight:pendingis decremented insidecomplete_with_survival(scheduler.rs:~2875) before the token loop readslive.pending()atruntime.rs:2376.consumed_tokens > exact_lenis handled on everyCheckpointParkbranch::2516requires<=for keep-park; otherwise:2518-2525truncates viapark_grammar_transition→live.tokens()[..exact_len](:2828), covered byphase_tests.rs:9050-9070(consumed 6 > exact 5).paused_for_parkgenuinely blocks further frames on all three gates:policy.rs:334-341(eligible),scheduler.rs:1430-1440(has_starved_request),scheduler.rs:1448-1459(refill_reservations, so it is neither grown nor chosen aspreempt_newestvictim).AdmissionGrammarsemantics are consistent in packing:UnmaskedEnabled→GrammarEnabled = 1(packing.rs:802) and all-ones mask (packing.rs:797-801,0xffon the int32 fast path at:603-637), withunconstrained_masks.retain(...)(:616-618) correctly invalidating the cached all-ones row when aMaskedupload follows — verified againstmodel/tests.rs:1886-1968.- Hot path: the only per-transition heap cost added is the mask clone
grammar.mask().to_vec()(~vocab/32i32) atruntime.rs:2382-2389, once per</think>/re-entry rather than per step; the new drain scan is O(REQUEST_LANES= 4) with an earlycontinue. No per-step O(N) or O(vocab) regression.
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
try_enter_offload_batchreturnsNoneunder exactly the blocking conditions:offload_must_wait(copy_gate.rs:171-175) is a verbatim lift of the old inline closure, andenter_offload_batch(:190-200) was refactored to call the same two helpers, so its behaviour is unchanged.- Skipping
offload_batches_waiting += 1on the try path is correct: every reader of that counter (should_yield_to_offload:97,maybe_arm_offload_wave:58,:62,PeerGraphGuard::drop:225,enter_peer_graph_timeout:160-164) only adds obligations for waiters; a caller that never waited must not arm a wave or notify. - Lock order is acyclic: only two functions take both locks —
with_gpu_codec_locked(codec.rs:881-889, gate-blocking → codec-blocking) andtry_with_gpu_codec_locked(:895-906, codec-try_lock→ gate-try_enter, neither blocking). The old capture path's codec-then-blocking-gate sites are gone, so no cycle exists. - No silent KV drop on failure: a GPU batch decode error propagates via
.transpose()?(codec.rs:729) and aborts the window; per-page CRC verification happens before the scatter (gpu_codec.rs:1729-1732,:1971-1981, scatter at:1984). Atry_locksuccess followed by gate contention drops theMutexGuardvia?(codec.rs:902) and falls back to CPU decode with the route rewritten toGpuOnCpu(codec.rs:624-628,:730-758) — no lease leak, no stream desync. - Boundary cases walked correct: 0/1-page windows, all-CPU, all-
GKV1, alternatingLiteral/GKV1(the regression this PR fixes), trailing singleGKV1, matrix pages (correctly forced toSinglebecausegpu_batch_capcollapses to 1 whennum_mats() != 0,codec.rs:677-683, since the batch kernel rejects mats atgpu_codec.rs:1707), codectry_lockcontended, gate contended by an active peer graph.
Coverage summary
- Slice A:
decide_grammar_transition,Worker::{complete, publish, park, park_if_preempted, park_grammar_transition, park_with_tokens, admit},RequestScheduler::{set_grammar_constrained, pause_for_park, finish_for_park, finish_early, retire, finish, cancel, eligible, refill_reservations, preempt_newest},AdmissionGrammar/Admission::*,packing.rsgrammar binding paths,Lifecycle.tla,check.py(all 6 new mutation strings diffed char-by-char against head sources), and the new tests. ✔ - Slice B: all of
copy_gate.rs;codec.rsRankCodec::new/run/capture_window/decode_route/decode_pages_cpu_batch/restore_single_unit/restore_window/partition_restore_pages_by/with_gpu_codec_locked/try_with_gpu_codec_locked/copy_spans_batch; cross-checkedtransfer.rsGatedCopies/RankWorker. ✔ - Slice C:
PrefillPredictor::{predict, upward_extrapolation_floor, is_constant, has_deep_context, with_borrowed_context_slope},clamp_nanos,PrefillCostModel::{observe, fit, reset_with_full},ActionCosts::{get, observe/record, prefill_entry, mixed_entry, mixed_duration, borrowed_mixed_context_slope, refresh_prefill_context_slopes},mixed_candidates/continuation_candidate/resize_prefillscoring, and both new tests. ✔
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.