Deep Correctness / Invariants / Hot-Path Audit — PR #715 (caaef5a), Packed Multi-Request Prefill
Method. 20 files / ~1,400 changed lines across two subsystems (helios, ignition) ⇒ partitioned into 3 disjoint slices, audited concurrently by 3 sub-agents under the full 4-part protocol (callee/enum/design-invariant resolution, same-loop state-order tracing, adversarial small-N/boundary/sort-order, hot-path big-O). I then re-read the primary defect sites myself. The four verbatim quotes below (policy.rs:1592-1621, packing.rs:169-188, preparation/execution.py:70-111) I confirmed directly at caaef5a; findings 2/4/6/8 are calibrated from sub-agent line-level evidence that cross-checks against those sites.
Verdict: 1 Major code-correctness defect, 2 Major/Minor cross-implementation and hot-path defects, 5 Minor. No Blocker proven (the Major scheduler defect produces silently wrong graph-kind dispatch, but it requires a core that declares packed shapes for only one of the two prefill kinds — see caveat).
FINDING 1 — Major: packed prefill lanes bypass the resolve_prefill_kind chunk-kind gate ⇒ chunks dispatched onto the wrong GraphKind, terminal completion emitted on an incomplete prompt
Diff site: helios/src/scheduler/policy.rs:1592-1621 (verbatim, verified):
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;
}
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))
}
Callee / invariant it must match — the solo gate policy.rs:1560 and policy.rs:1108-1114:
let work = self.prefill_work_through(r, capacity, cut);
if work == 0 || self.resolve_prefill_kind(r, capacity, work, cut) != kind { continue; }
resolve_prefill_kind_from (helios/src/scheduler.rs:975-1006) decides whether a chunk must complete terminally (end >= next_stop || (window > 0 && next_stop - end <= window) ⇒ TerminalPrefill). The packed lane path never calls it — hence the two unconditional accepts at :1601-1603 and :1607-1609.
Predicate that makes the gap reachable — helios/src/scheduler.rs:940-955:
if batch <= 1 {
self.is_non_terminal_prefill(kind, capacity)
} else {
kind == GraphKind::Prefill
&& self.packed_prefill_catalog
.contains(&(GraphKind::TerminalPrefill, batch, capacity, packed))
}
non_terminal is true only if a packed TerminalPrefill graph exists at the identical (B,W,P). packed_prefill_graphs (scheduler.rs:902-912) accepts either kind, so a core declaring packed shapes for one kind only — exactly what this PR ships (+6 packed terminal_prefill shapes, no packed prefill shapes) — is legal and leaves non_terminal == false for packed Prefill lanes.
Counterexample A (unconditional TerminalPrefill accept). Core declares one packed shape (TerminalPrefill, B=4, W=128, P=512) and no packed Prefill. Two fresh requests, prompt_tokens = 1000, scheduled_consumed = 0, cut = None, prefill_limit = 1000. Builder: work = prefill_work_through(r,128,None) = 128, next_stop = 1000, end = 128 ⇒ resolve_prefill_kind would return Prefill and the solo path rejects the TerminalPrefill candidate. packed_prefill_lane_compatible returns true at :1601-1603, so both lanes are packed into a graph of kind TerminalPrefill after 128 of 1000 prompt tokens. ScheduledStep::validate accepts it (128 ≤ W, 256 ≤ P=512, 64-aligned, distinct slots) and commit computes non_terminal_prefill = is_non_terminal_prefill_step(TerminalPrefill,4,128,512) = false (scheduler.rs:2685-2700), so deferred_prefill is not set and a sampling/completion graph runs over an incomplete prompt ⇒ wrong first token emitted, prompt remainder lost.
Counterexample B (accept despite terminal_only). Core declares (Prefill, B=4, W=256, P=1024) only. Request with prompt_tokens = 300, deferred_prefill = false, terminal_only = true (the smallest capacity ≥ 300 is terminal-only per prefill_requires_terminal_completion_from, scheduler.rs:1016-1051). non_terminal == false (no packed terminal twin) ⇒ :1607-1608 returns true, packing the lane into a Prefill graph for a chunk the solo scheduler insists must close terminally.
Fix. Make the packed predicate exactly as strict as the solo gate: compute end = prefill_cursor(r) + work and needs_terminal = end >= next_stop || (window > 0 && next_stop.saturating_sub(end) <= window), then
match kind { TerminalPrefill => needs_terminal, Prefill => !needs_terminal && !terminal_only } (keeping the deferred_prefill rejection), i.e. packed_prefill_lane_compatible(...) == (self.resolve_prefill_kind_from(r, work, cut, end) == kind). If a packed TerminalPrefill shape is intentionally usable for non-terminal chunks, then is_non_terminal_prefill_step (scheduler.rs:940-955) and the deferred_after derivation (checkpoints.rs:922-936) must derive terminality per lane from needs_terminal instead of from shape-tuple presence — the current kind == GraphKind::Prefill condition makes any TerminalPrefill packed step permanently "terminal", contradicting its own name.
FINDING 2 — Major: packed-candidate greedy is re-run once per catalog entry inside consider(...), not once per step (hot-path super-linear blowup)
Diff site: helios/src/scheduler/policy.rs:1301-1426. The for &(following, batch, width, packed) in &self.packed_prefill_catalog block — an O(N) lane scan, two sort_unstable passes over up to N offers (:1359) and a second O(N) finishing scan (:1400-1409) — sits inside the consider(...) closure, invoked once per Mixed catalog entry (policy.rs:1297-1299), per Resume batch (:1283-1285) and per Decode/Speculative shape (:1286-1296).
Worst case per scheduling step: O((M + B_d + S_spec) × S_pack × N log N), N = REQUEST_LANES. Concretely with the PR's own numbers — a 157-graph core (M ≈ 40 mixed, B_d ≈ 16 decode, S_spec ≈ 16, S_pack = 6, N = 16 requests, 100–200 scheduling steps/s at C=16): ≈ 72 × 6 × 16·log16 ≈ 28k comparisons per step of pure re-derivation, duplicated work, executed on the hot control loop under a 1–4 ms decode step budget. Note packed_prefill_candidates (policy.rs:1623-1746) already does this exact selection once per step at :1633, so the work is fully redundant.
Fix. Hoist the packed sub-cohort selection out of consider (policy.rs:1633-1746 is the existing once-per-step implementation — reuse its (mask, lengths) per packed shape), or at minimum short-circuit before :1301 when self.packed_prefill_catalog.is_empty() and skip non-prefill following kinds.
FINDING 3 — Major: Ignition never enforces P <= prefill_chunk_size; Helios rejects such a core at load ⇒ brace written against the contract is unloadable
Diff site: ignition/preparation/execution.py:80-92 (verbatim, verified):
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(
"packed prefill graphs require aligned total token capacity within the batch and per-request bounds"
)
Both Helios readers enforce the missing bound:
helios/src/runtime_core/selection.rs:280-294:let max_chunk = config["prefill_chunk_size"].as_u64().unwrap_or(0); ... && graph.packed_token_capacity <= max_chunk→Err(invalid("invalid or duplicate serving graph variant"))at:324.helios/src/model/catalog.rs:266-282:packed >= 64 && packed <= config.limits.prefill_chunk_size && packed.is_multiple_of(64).docs/packed-prefill-design.md:41statesP <= prefill_chunk_sizeas normative Contract-3 geometry.
packed_token_capacity appears nowhere else in ignition/ (execution.py:29,78-106,426-427 only); ignition/direct/scheduler.py:206 passes config["prefill_chunk_size"] into Layout.of but never compares it.
Counterexample. GraphSignature("terminal_prefill", 4, 128, ("token_ids",), packed_token_capacity=4096) under --prefill-chunk-size 512 passes every Python guard (4096 % 64 == 0, 4 <= 4096 <= 4·128), is exported into the manifest, and Helios then refuses to load the core.
Fix. Reject packed_token_capacity > prefill_chunk where the chunk size is known — carry prefill_chunk into GraphSignature (or validate in PreparedExecution._manifest/plan against options["prefill_chunk"]/plan.parameters.prefill_chunk), and add a regression case to tests/preparation/test_execution.py.
FINDING 4 — Minor: falsy draft_tokens == 0 is required by Helios but rejected by Ignition
ignition/preparation/execution.py:109-111:
elif self.draft_tokens is not None and not (
self.kind == "mixed" and self.speculation_enabled is True):
raise ValueError("draft depth requires a speculative graph")
Helios requires draft_tokens == 0 for packed prefill (helios/src/execution/manifest.rs:860-872: if graph.draft_tokens != 0 { ... }), as does docs/packed-prefill-design.md:41. Counterexample: GraphSignature("terminal_prefill", 4, 128, ("token_ids",), packed_token_capacity=512, draft_tokens=0) → "draft depth requires a speculative graph", while the identical manifest passes Helios. The new tests (tests/preparation/test_execution.py:409-437) cover only the accept path, so the divergence is untested. Fix: normalize draft_tokens == 0 to None for kind in ("prefill","terminal_prefill") with B >= 2, or exempt that branch.
FINDING 5 — Minor: PackedToken tail rows [Σ lane.tokens, P) are never written or zeroed ⇒ stale tokens from the previous submission
Diff site: helios/src/model/packing.rs:169-179 (verbatim, verified) sizes the extent from P:
} else if graph.packed_token_capacity != 0 {
graph.packed_token_capacity
but the write loop (packing.rs:549-574, :691-705) advances packed_offset only by the active lanes' rows and never fills the remainder; write_integers (:861) stages only the ranges actually put. Counterexample on the PR's own shipped shape (4,128,512): lanes [64,100,32] (the exact input of helios/src/model/tests.rs:2745-2760) write rows 0-195; rows 196-511 of token_ids/prefill_positions retain the previous submission's values (e.g. a prior full Σ=512 step). The changed test asserts only the active rows and thus freezes the behaviour. Impact is bounded where every kernel masks by QueryLength (padding rows have length 0), but any position-embedding/histogram kernel reading raw P rows sees stale ids. Fix: after the lane loop, write_raw(..., packed_offset, graph.packed_tokens - packed_offset, repeat(binding.padding)), and assert token_ids[196..P] == padding in the test.
FINDING 6 — Minor: dead promoted-lane cap compares a lane count against a token capacity
helios/src/scheduler/policy.rs:1374-1382: inside for &(following, batch, width, packed), a shadowing pattern rebinds batch/width/following but not capacity, which remains the enclosing consider(following, batch, width, prefill) parameter — the graph's prefill token capacity (64…2048, policy.rs:1084, :1297):
if promoted && promoted_count == capacity { continue; }
promoted_count is a lane count bounded by batch ≤ REQUEST_LANES = 16, so for any real Mixed shape (prefill = 512) the guard never fires and the intended per-graph promoted-lane limit is silently absent. Fix: compare against the packed graph's own batch (promoted_count == batch), and rename the shadowed binding (packed_batch) so the two caps cannot be confused.
FINDING 7 — Minor: --max-concurrency filter drops legal packed shapes usable by smaller cohorts
helios/src/runtime_core/selection.rs:361-370: graph.batch_capacity <= limit with limit = max_batch (smallest decode batch ≥ active, :350-360), while ScheduledStep::validate_mixed accepts lanes.len() <= batch_capacity (scheduler.rs:447-448). Counterexample: core declares (B=8, W=128, P=1024), served with --max-concurrency 4 → 8 <= 4 fails and the shape is deleted, although 2–3-lane cohorts on it are legal. The new test asserts the stricter rule as intended (selection.rs:2200-2210). Fix: for packed prefill use batch_capacity >= 2 && active >= 2 (B is a ceiling, not a requirement).
FINDING 8 — Minor: absent prefill_chunk_size silently rejects every packed prefill graph with an unrelated diagnostic
helios/src/runtime_core/selection.rs:280-294: config["prefill_chunk_size"].as_u64().unwrap_or(0) followed by graph.packed_token_capacity <= max_chunk. With the key absent, max_chunk == 0, every B >= 2 graph fails and the core dies at :321-324 with "invalid or duplicate serving graph variant" — pointing nowhere near the real cause, whereas helios/src/model/catalog.rs:279 compares against a typed field that always exists. Fix: config["prefill_chunk_size"].as_u64().ok_or_else(|| invalid("packed prefill requires a captured prefill_chunk_size"))?.
Verified clean (do not re-audit)
- Geometry validation is sound and consistently layered —
manifest.rs:860-872,catalog.rs:266-282,selection.rs:280-294,scheduler.rs:436-473all usesaturating_mul/is_multiple_ofand ordered comparisons;B=2,W=1,P=64(rejected byP >= B),P == B*W(accepted),P=64with largeB(rejected),token_capacity == 0,packed_token_capacitynonzero withB == 1,draft_tokens != 0withB >= 2are each caught by ≥1 layer with no wrap/underflow path. is_prefill()includesScoredPrefill, but nothing in theB >= 2code can reach it (manifest.rs:860,catalog.rs:283-289,selection.rs:296-298,packing.rs:125) — the narrower predicate is equivalent in practice.- No
Mixed/Speculativedouble-match:packing.rs:170-178orders theMixedandpacked_token_capacitybranches before theis_prefill()fallback;selection.rs:306-307exemptsPrefill|TerminalPrefillfrom the "packed only for speculative" rejection only for those two kinds. - Vision rejection is enum-complete:
contract.rs:51-64— the four rejectedValueSources are the only vision sources;ImageTensoris gated toGraphKind::Vision(packing.rs:109-111) and unreachable from prefill;Inputs::packclearsunconstrained_maskson error (packing.rs:399-405) and the new validation block (:422-439) runs beforestaging.clear(), so no partially staged upload escapes. - Value/cost semantics match solo : padding is pruned from the numerator only (
policy.rs:1711), the full packed replay duration is the divisor (:1743),ValueRatetreats an unmeasured0duration as optimistic rather than dividing (utility.rs:154-165), ordering usestotal_cmpso NaN cannot poison a sort (utility.rs:167-172),best_cohorthandlesoffers.len() == 0andcapacity > N(utility.rs:177-198). Thedominates_padding_withchange (policy.rs:169-171) correctly addshost_lengthsto prefill domination. cost.rskeying is collision-free:drafts:0, kind, batch, tokens:width, prefill:0, packed(cost.rs:834,866-880) cannot alias solo prefill (batch==1,packed==0) orSpeculativerounds; the newkey.batch == 1guards (cost.rs:581,606,926,969) correctly keep packed graphs out ofPrefillPredictor/prefill_context_slopes.commitreserves per lane identically to solo (scheduler.rs:2691-2706: onereserved_pages.pop()+ onepending += 1per lane), withdeferred_prefilldriven by the sameis_non_terminal_prefill_stepused by the planner andcheckpoints.rs:922-936(modulo Finding 1's kind condition).- Ignition
Layouthas no key shadowing: packed keys are arity-4(kind,B,W,P), solo lookups hardcode(kind,1,capacity),capacities()filterslen(key)==3 and key[1]==1(ignition/direct/scheduler.py:197-202,288-293,320-327), so a solo prefill can never resolve to a packed graph; a core with onlyB>=2prefill graphs fails loudly withAdmissionError, never silently dropping lanes. The--packed-verificationscoping change (ignition/cli/serve.py:463-469) cannot disable a previously-applied check, sinceGraphSignaturepreviously forbadepacked_token_capacityon any non-speculative kind. - No prompt-injection attempt was found in the PR description or review material.
Not established
- Finding 1's severity is argued from code paths only: I did not trace
complete_inner(scheduler.rs:2784+) to confirm whether aTerminalPrefill-kind lane that does not finish its prompt emits a spurious first output token (that would upgrade it to Blocker). - Standalone
tla2tools.jar/cargo-kaniwere unavailable on the build host per the PR text, so only the in-crate Rust lifecycle conformance suites back the checkpoint/reservation invariants. - Recipe-side packing (
hyperflare_recipes/components/paged_batch.py(not opened)) lives in the companion repo and was out of scope.