Deep Code Correctness, Invariants & Hot-Path Audit — PR #715 @ 84f789a
Partitioned per the large-PR rule (21 files, ~2,070 changed lines, 2 subsystems: helios/ Rust + ignition/ Python) into 3 concurrent sub-agents:
- s1:
execution/manifest.rs,execution/tests.rs,model/{catalog,packing,testing,tests}.rs,runtime_core/{cache_memory,selection}.rs - s2:
scheduler{,/cost,/policy,/checkpoints,/policy_tests}.rs,server/runtime.rs - s3:
ignition/preparation/execution.py,ignition/cli/serve.py,ignition/direct/scheduler.py,tests/preparation/test_execution.py
Every finding below was re-verified by me directly against the files at 84f789a (sub-agent claims that did not survive verification are dropped; several s2/s3 citations were corrected against the real line numbers).
F1 — Major: packed-prefill continuation values "ready" lanes that the emitted step can never run (double-counted value, suppressed legal cohorts)
Diff site: helios/src/scheduler/policy.rs:1324-1348 (offer construction) and helios/src/scheduler/policy.rs:1374-1395 (budget loop)
Callees resolved: fill() policy.rs:1068-1082; Candidate.mask consumer materialize policy.rs:2206-2247; ValueRate::new/compare helios/src/scheduler/utility.rs:155-172; caller add_candidate policy.rs:1793-1802 (the returned (mask, rate) replaces the candidate's mask/rate).
// policy.rs:1320-1348
let offered = mask & (1 << slot) != 0;
let promoted = offered
&& !terminal_cleanup(request)
&& self.following_kind(request, kind) == Some(GraphKind::Prefill);
let ready = !offered
&& self.eligible(request)
&& self.request_kind(request) == Some(GraphKind::Prefill);
if !promoted && !ready {
continue;
}
...
let val = self.lane_value_for_tokens(request, following, work, horizon, values[slot]);
offers[n] = (slot, work, val, promoted);
// policy.rs:1374-1396
for &idx in &order[..n] {
if lane_count == batch { break; }
let (slot, work, val, promoted) = offers[idx];
if used_tokens + work > packed { continue; }
if promoted && promoted_count == capacity { continue; }
used_tokens += work;
lane_count += 1;
value += val; // <-- ready (non-offered) lanes add value
if promoted { selected_promoted |= 1u64 << slot; promoted_count += 1; }
}
if lane_count < 2 || promoted_count == 0 { continue; }
let mut selected = selected_promoted; // <-- only promoted lanes enter the mask
selected seeds from selected_promoted only, and fill(selected) (policy.rs:1068-1082) can top up only from first_offers, i.e. the current step's mask. A ready lane (not in the current mask, request_kind == Prefill) therefore contributes value and consumes lane_count/used_tokens/batch budget but can never appear in the returned mask. The sibling solo path in the same function does it correctly — it prices exactly the lanes it selects (policy.rs:1128 let mut selected = 1u64 << slot;, policy.rs:1142-1148 adds only the extra bits it ORs into selected); so do Decode/Speculative via best_two_stage_cohort (policy.rs:1251-1267) and Mixed.
Concrete counterexample (value double-count / wrong step selection): Init(4) just committed mask {a,b,c,d} (capacity 4, measured 2 ms); queued Prefill-phase e,f,g,h; packed shape (TerminalPrefill, B=8, W=128, P=1024) measured 20 ms. promoted = {a,b,c,d} ⇒ promoted_count == 4 == capacity ⇒ the promoted_count < capacity top-up block is skipped; ready = {e,f,g,h} ⇒ lane_count = 8, value = V(a..h), horizon = 22 ms ⇒ rate V/22 attached to a Candidate whose mask is {a,b,c,d} and which materializes as four Init lanes with tokens == 0 (materialize, policy.rs:2233-2245). V(e..h) is priced here and again when the packed prefill actually executes next step.
Second counterexample (legal cohort silently dropped): packed (TerminalPrefill, B=2, W=128, P=256); current Init(2) mask {a,b}; promoted Prefill lanes p1,p2 (val 10.0 each, 6 tokens) and ready Prefill lanes r1,r2 (val 30.0 each, 6 tokens, lower slots). Sorted by value r1,r2 come first, lane_count hits batch == 2 and breaks, promoted_count == 0 ⇒ continue. The perfectly legal all-promoted cohort {p1,p2} (12 ≤ P) is never evaluated in either by_density pass, so Init loses its packed continuation — the exact chat_w65_c4/c8 scenario the PR reports.
Fix: delete ready from this loop — if promoted { offers[n] = ...; n += 1; } only. Ready-only cohorts are already produced correctly by packed_prefill_candidates (policy.rs:1641-1671, which requires request_kind(r) == Some(GraphKind::Prefill) for every offered slot), so no scheduling capability is lost.
F2 — Major: packed_prefill_lane_compatible short-circuits TerminalPrefill, so mid-prompt lanes run on terminal graphs and lose deferred_prefill
Diff site: helios/src/scheduler/policy.rs:1601-1620
Callees resolved: solo reference semantics RequestScheduler::resolve_prefill_kind_from helios/src/scheduler.rs:975-1006; deferred_prefill write helios/src/scheduler.rs:3065-3067; checkpoint consequence helios/src/scheduler/checkpoints.rs:935-936; design invariant docs/packed-prefill-design.md:96-111.
// policy.rs:1592-1621
fn packed_prefill_lane_compatible(
&self, r: &LiveRequest, kind: GraphKind, non_terminal: bool,
terminal_only: bool, work: usize, cut: Option<usize>,
) -> bool {
if kind == GraphKind::TerminalPrefill {
return true; // <-- no geometry check at all
}
if r.deferred_prefill { return false; }
if !non_terminal { return true; }
if terminal_only { return false; }
let start = Self::prefill_cursor(r);
let next_stop = cut.unwrap_or(r.prompt_tokens).min(r.prefill_limit()).min(r.prompt_tokens);
let end = start.saturating_add(work);
let window = self.terminal_prefill_window();
!(end >= next_stop || (window > 0 && next_stop.saturating_sub(end) <= window))
}
The Prefill branch faithfully mirrors resolve_prefill_kind_from (scheduler.rs:986-1005: needs_terminal = end >= next_stop || (window > 0 && next_stop - end <= window)). The TerminalPrefill branch bypasses it entirely, so a packed TerminalPrefill graph may be applied to a lane that stops well short of next_stop with more than window tokens remaining — a combination the solo planner provably never produces (scheduler.rs:1001-1005 returns Prefill in that case).
Concrete counterexample: prompt P = 300, prefill_catalog == terminal_prefill_catalog == [128,256,512,1024] ⇒ terminal_prefill_window == 0 (scheduler.rs:957-958, recompute_terminal_prefill_window); packed shape (TerminalPrefill, 4, 256, 512). prefill_work_through(r, 256, None) = 256, next_stop = 300, end = 256 < 300, remaining 44 > window 0. =⇒ solo resolve_prefill_kind = Prefill; packed accepts TerminalPrefill(4,256,512). This is exactly the PR's own test policy_tests.rs:9712-9726 (lane h1, 300 tokens, TerminalPrefill) which must then hand-patch the completion record at policy_tests.rs:9730-9733 (recs[h1.slot].generated_tokens = 0; token_id = -1;) instead of letting the real path produce it.
Two provable consequences, both of which solo semantics forbid:
helios/src/scheduler.rs:3065-3067—if kind == GraphKind::TerminalPrefill && record.status != 3 { request.deferred_prefill = false; }. A mid-prompt lane that is stilldeferred(multi-chunk prompt that needs terminal replay) hasdeferred_prefillcleared after a non-terminal chunk, so its next chunk becomes eligible for a non-terminalPrefillgraph — precisely the statepacked_prefill_lane_compatible's ownif r.deferred_prefill { return false; }guard exists to prevent, and whatscheduler.rs:2685-2700(if non_terminal_prefill { request.deferred_prefill = true; }) is trying to maintain.helios/src/scheduler/checkpoints.rs:935-936—deferred_after = (request.deferred_prefill || non_terminal) && kind != GraphKind::TerminalPrefill, so a mid-prompt terminal chunk is treated as capture-eligible whileplan_checkpointsprices it with terminal cost (checkpoints.rs:937-941).
Whether a mid-prompt terminal replay also corrupts the sliding-window KV tail is recipe/kernel-side (hyperflare_recipes, outside this repo), so I state that as a risk, not a proven miscompute; findings 1–2 above are proven in-repo.
Fix: replace the early true with the same geometry check minus the terminal requirement, e.g. for TerminalPrefill accept only lanes with end >= next_stop || (window > 0 && next_stop - end <= window) (i.e. reuse resolve_prefill_kind via self.resolve_prefill_kind(r, width, work, cut) == GraphKind::TerminalPrefill), and keep if r.deferred_prefill handling to TerminalPrefill only.
F3 — Minor: Ignition accepts packed_token_capacity > prefill_chunk_size, which the Helios loader rejects at load time
Diff site: ignition/preparation/execution.py:80-89
Callee that disagrees: helios/src/runtime_core/selection.rs:260-274 (max_chunk = config["prefill_chunk_size"]), rejection at selection.rs:304.
# ignition/preparation/execution.py:80-89
if self.kind in ("prefill", "terminal_prefill") and self.batch_capacity >= 2:
if (not 2 <= self.batch_capacity <= MAX_CONCURRENCY
or self.packed_token_capacity < 64
or self.packed_token_capacity % 64
or self.packed_token_capacity >= 1 << 31
or self.token_capacity > self.packed_token_capacity
or not self.batch_capacity <= self.packed_token_capacity <= self.batch_capacity * self.token_capacity):
raise ValueError(...)
// helios/src/runtime_core/selection.rs:265-274
(2..=REQUEST_LANES as u64).contains(&graph.batch_capacity)
&& graph.token_capacity > 0
&& graph.token_capacity <= graph.packed_token_capacity
&& graph.packed_token_capacity >= graph.batch_capacity
&& graph.packed_token_capacity <= graph.batch_capacity.saturating_mul(graph.token_capacity)
&& graph.packed_token_capacity >= 64
&& graph.packed_token_capacity.is_multiple_of(64)
&& graph.packed_token_capacity <= max_chunk // <-- no counterpart in Python
grep prefill_chunk ignition/ shows it only in ignition/direct/scheduler.py:206, ignition/preparation/bootstrap.py:45 (not opened), ignition/parameters.py, ignition/planning.py — never in GraphSignature validation, so the Python contract cannot see it.
Counterexample: prefill_chunk_size = 2048; GraphSignature("terminal_prefill", 16, 256, P=4096) ⇒ 16 <= 4096 <= 16*256 = 4096, aligned, 256 <= 4096 ⇒ accepted by Ignition; Helios selection.rs:273 requires 4096 <= 2048 ⇒ rejected, and flare run refuses the freshly prepared core. Also inconsistent with helios/src/execution/manifest.rs:914-924 and scheduler.rs:891-921 (packed > self.limits.prefill_chunk_size rejected), so two of the three validators disagree with Ignition.
Fix: thread prefill_chunk_size into GraphSignature validation (or re-check every packed prefill signature in PreparedExecution.__init__ against server_config["prefill_chunk_size"]) and add or self.packed_token_capacity > prefill_chunk_size, mirroring selection.rs:273.
F4 — Minor: direct-mode Layout registers packed prefill keys that no code path can ever select
Diff site: ignition/direct/scheduler.py:200-201, with the companion filter at scheduler.py:291
Consumers resolved: graph() scheduler.py:320-327, prefill_kind() scheduler.py:302-314, packed_shapes scheduler.py:316-318, plan() scheduler.py:731-735, Step.shape scheduler.py:491-494.
# scheduler.py:197-202
key = (signature.kind, signature.batch_capacity, signature.token_capacity)
if signature.kind == "speculative":
key += (signature.packed_token_capacity, signature.draft_tokens)
elif signature.kind in ("prefill", "terminal_prefill") and signature.batch_capacity >= 2:
key += (signature.packed_token_capacity,) # 4-tuple, never looked up
# scheduler.py:290-291
if kind in ("prefill", "terminal_prefill"):
return sorted({key[2] for key in self.graphs if len(key) == 3 and key[0] == kind and key[1] == 1})
# scheduler.py:731-735 (the only prefill path)
if prefilling:
request = min(prefilling, key=lambda r: r.ident)
tokens = min(len(request.prompt) - request.consumed, self.layout.prefill_chunk)
kind = self.layout.prefill_kind(request.consumed, tokens, len(request.prompt))
return self._step(kind, tokens, [Lane(request, request.consumed, tokens)])
capacities() returns only B == 1 capacities, graph() always builds (kind, 1, capacity) (scheduler.py:325), packed_shapes filters len(key) == 5 so 4-tuples are not packed rounds, and plan() always emits exactly one lane ⇒ Step.shape == (kind, 1, tokens) with packed_tokens = 0. A core whose only B >= 2 prefill graphs were declared therefore runs every prefill lane-at-a-time in --direct mode; the new keys exist only so bindings/buffer_specs/state_rows_per_request (scheduler.py:212-227) still cover the P-sized buffers.
Fix: add a packed_prefill_shapes property over the len == 4 keys plus a cohort builder mirroring packed_prefill_candidates, or (smaller) stop emitting those keys and take their buffer_specs from signatures, documenting that --direct ignores packed prefill. The len(key) == 3 and key[1] == 1 filter at line 291 is itself a necessary fix — without it graph() could KeyError on a capacity that came only from a B >= 2 graph.
Also verified (reported so it is not re-litigated)
manifest.rs:860-884, 914-924,catalog.rs:266-289,selection.rs:260-278,scheduler.rs:891-921,scheduler.rs:436-473— theB >= 2geometry rule sets are complete and mutually consistent:draft_tokens == 0,P >= 64, 64-aligned,B <= P <= B*W(saturating_mul, no overflow),W <= P,B == 1 ⇒ P == 0,P <= prefill_chunk_size.GraphKind::is_prefill()=Prefill | TerminalPrefill | ScoredPrefill(manifest.rs:85-87);ScoredPrefillis excluded from every packed path, correctly, since it is the prompt-logprobs outlier.selection.rs:283-296max_concurrencyfilter is scoped exactly tokind ∈ {prefill, terminal_prefill} && B >= 2;ScoredPrefill,Vision, andB == 1prefill keepmax_batch, andmax_batchderives only fromdecode/speculative(selection.rs:330-340), so--max-concurrency 1still leaves a loadable, serveable core.packing.rs:422-439— the new packed validation runs beforeself.staging.clear()(line 440) and before anystaging.put/write_*, so no half-populated buffer can survive a rejected lane;total_tokensuseschecked_add.packing.rs:169-188PackedTokenextent =Mixed → prefill_capacity+(B-1)*W, elseP != 0 → P, elsetoken_capacityforB==1prefill, elsepacked_tokens(); consistent with what the packer fills (packed_offset ≤ Σ lane.tokens ≤ P) and bounded byP <= B*W, so no under/over-sized buffer.packing.rs:113-126vision rejection —ImageFeatureSlotnow requiresVision | Mixed | (is_prefill() && B == 1);ImageFeatureIndex/Left/Rightrejectis_prefill() && B >= 2.B == 1prefill andScoredPrefillstill accept vision bindings, so single-request and vision prefill are unchanged.- Array bounds / div-by-zero / sort totality in both packed loops —
REQUEST_LANES == 64(manifest.rs:18) boundsslots.len()(scheduler.rs:749-751),offers[n]/order[..n]/finishing[f]cannot overflow;order[..n]correctlyoffers[a];vb/wbnever divides by zero (work == 0filtered atpolicy.rs:1333/1656); both comparators terminate on a uniqueslot(policy.rs:1367,1692) so they are total orders andsort_unstableis deterministic. prefill_slot_state(policy.rs:508-515) caches(cut, terminal_only)per slot per candidate array with results independent of(kind,B,W,P), so re-invocation across catalog shapes and bothby_densitypasses is idempotent — no double-advance or stale cut.cost.rsgating —PrefillCostModelis created only forkind.is_prefill() && batch == 1(cost.rs:606-607,581-583), so packed shapes cannot poison the per-capacity prefill predictor;packed_prefill_duration(cost.rs:644-659) is an exactHashMap<Key,_>lookup on(kind,B,W,prefill=0,P)and cannot collide with solo keys;ReplayTimes::observe(cost.rs:497-511) is the shared 9-sample ring with a correct lower-is-better even-count median index.checkpoints.rs:925-936— theMixedarm now keys onstep.prefill_capacity()and the packed arm on the full(kind,B,W,P)identity;is_non_terminal_prefill_step(scheduler.rs:940-955) is order-independent (containsover the sorted catalog validated inpacked_prefill_graphs). No checkpoint loss or duplication for non-terminal packed chunks.server/runtime.rs:846-905— soloPrefill/TerminalPrefill/ScoredPrefillcatalogs are filtered toB == 1andB >= 2shapes go only topacked_prefill_graphs, so theB == 1paths are untouched.runtime_core/cache_memory.rs:1397external_extents: vec![]— matches the pre-existing test literal and the non-test construction inruntime_core/format.rs;external_extentsfeeds only async-transfer channel validation, so an empty vec is semantically correct for these alias/granule tests and the compile fix is genuine.- Hot path (protocol 4) — no new heap allocation in the packed scheduler paths (all
[(..); REQUEST_LANES]are stack arrays);packed_prefill_candidatesis one pass of |packed catalog| × slots plus two ≤64-element sorts per shape (policy.rs:1633-1727). Thecontinuation_candidatepacked copy is re-executed inside theconsiderclosure once per prefill/terminal/scored capacity (policy.rs:1274-1282), i.e. O(|prefill catalog| × |packed catalog| × slots) with a 64-element array copy per shape — measurable but bounded (~3 × 20 × 64 at the PR's own 6-shape/4-capacity scale), so not filed as a defect; if the catalogs grow, hoist the packed loop out ofcontinuation_candidateintocandidates()next topacked_prefill_candidates.
No prompt-injection content was present in the PR body, code, or comments. No test in the changed files was found broken; the one fidelity weakness worth noting is that policy_tests.rs:9730-9733 hand-patches the mid-prompt lane's completion record rather than exercising the real SampleEnabled-driven record (F2 explains why it has to).