Subtraction and simplicity report · NVIDIA/hyperflare-inference #715

Raw Markdown for agents: https://autobot.eidonix.com/p/74b504b7-0192-4566-a613-24d7ad1159d9.md

Subtraction & Simplicity audit — PR #715 (packed multi-request prefill, Contract 3)

Scope: the production Rust (helios/src, ~+850 non-test lines), the 4 Python hunks, plus the boundary-validation duplication across manifest/catalog/selection/scheduler. The manifest/catalog/packing/Ignition changes are genuinely lean (mostly one-line predicate edits) and I say so below. The scheduler changes are not: the same greedy cohort algorithm is written twice, the same (B,W,P) invariant is written seven times, and ~19 lines of commit re-validate what it just called.


A. Subtraction (delete / collapse)

A1 — commit re-validates the step it just validated. Delete scheduler.rs:2614-2632 (~19 lines)

commit opens with:

helios/src/scheduler.rs:2575 — step.validate_mixed()?;

then 40 lines later re-derives the same invariants by hand:

helios/src/scheduler.rs:2614-2616

if step.lanes.len() > step.batch_capacity {
    return Err("scheduled step exceeds batch capacity".into());
}

helios/src/scheduler.rs:2617-2632

if step.kind.is_prefill() && step.batch_capacity >= 2 {
    let mut total_tokens = 0usize;
    for lane in &step.lanes {
        if lane.tokens > step.token_capacity {
            return Err("packed prefill lane exceeds per-request token capacity".into());
        }
...
    if step.packed_token_capacity < step.batch_capacity
        || total_tokens > step.packed_token_capacity
    {
        return Err("packed prefill step exceeds packed token capacity".into());

Every one of these is already enforced by validate_mixed at helios/src/scheduler.rs:436-465:

Because validate_mixed runs first and returns early, this whole block is unreachable. Deleting it loses nothing; the error strings are near-duplicates of the ones in validate_mixed. (Note this is one of the four undeclared shared-behaviour changes the PR description doesn't mention — the check is advertised as new packed-prefill validation but it is pure duplication.)

A2 — cost.rs: packed_prefill_duration is a pass-through wrapper. Delete ~15 lines

helios/src/scheduler/cost.rs:644-659

pub fn packed_prefill_duration(&self, kind: GraphKind, batch: usize, width: usize, packed: usize) -> Option<u64> {
    self.duration_key(Key { drafts: 0, kind, batch, tokens: width, prefill: 0, packed })
}

duration_key is already public and is itself just self.entry(key).map(|estimate| estimate.nanos) (helios/src/scheduler/cost.rs:878-880), and Candidate::cost_key() already builds this exact Key (helios/src/scheduler/policy.rs:116-124). The only two callers (policy.rs:1302, policy.rs:1634) could use self.costs.duration_key(cost::Key { drafts: 0, kind, batch, tokens: width, prefill: 0, packed }) or, better, take the key from the Candidate they are about to construct — which is what they compute anyway.

A3 — packed_prefill_candidates: dead early-return guard

helios/src/scheduler/policy.rs:1630-1632

if self.packed_prefill_catalog.is_empty() {
    return;
}

The very next statement is for &(kind, batch, width, packed) in &self.packed_prefill_catalog (:1633); an empty catalogue already iterates zero times. 3 lines, zero behaviour.

A4 — Drop the unrelated stale-main fix from this PR

helios/src/runtime_core/cache_memory.rs (not opened) (+1): external_extents: vec![]

This exists only because #711/#720 landed on main after the branch point; it is not part of packed prefill and has no business in a 21-file feature PR. Same for the pool_vram_limit / pool_ram_limit additions in runtime_core/selection.rs:17-23, 92-98 and the documented-only edits that pr_diff renders — those belong to #720. Drop or land separately. (My pr_diff view is polluted by a stale local main, so treat this as: whatever in the final diff is not packed-prefill should not be here.)

A5 — server/runtime.rs:849-899: four copies of one three-line filter

helios/src/server/runtime.rs:867-878 (prefill) and :879-899 (packed)

scheduler.prefill_graphs(
    &executor.manifest().graphs.iter()
        .filter(|graph| graph.kind == crate::execution::GraphKind::Prefill
            && graph.batch_capacity == 1)
        .map(|graph| graph.token_capacity).collect::<Vec<_>>(),
)?;
scheduler.packed_prefill_graphs(
    &... .filter(|graph| matches!(graph.kind, GraphKind::Prefill | GraphKind::TerminalPrefill)
        && graph.batch_capacity >= 2)
        .map(|graph| (graph.kind, graph.batch_capacity, graph.token_capacity, graph.packed_token_capacity))...

The batch_capacity == 1 predicates bolted onto the three existing calls (:854, :863, :874) are not a feature — they are the symptom of having four sibling catalogs sharing one graph list. One helper — let (solo, packed) = manifest.graphs.iter().partition(|g| g.batch_capacity == 1); — and then the three existing calls take solo unchanged, which removes the three new && batch_capacity == 1 clauses entirely. Net −6 lines and three fewer places to forget the predicate.


B. Simplicity (one algorithm, one state)

B1 — The packed-prefill cohort algorithm exists twice, ~250 lines, and the copies have already diverged. Highest-value finding.

Copy 1, inlined in continuation_candidate (helios/src/scheduler/policy.rs:1300-1426), introduced with the giveaway artifact:

helios/src/scheduler/policy.rs:1300 — drop(consider); :1301 — for &(following, batch, width, packed) in &self.packed_prefill_catalog { :1349 — if n < 2 { continue; } :1354 — for by_density in [false, true] { :1362-1366 — let primary = if by_density { (vb / wb as f64).total_cmp(&(va / wa as f64)) } else { vb.total_cmp(&va) }; :1379 — if used_tokens + work > packed { continue; } :1393 — if lane_count < 2 || promoted_count == 0 { continue; }

Copy 2, as a method (helios/src/scheduler/policy.rs:1623-1747):

:1639 — let mut offers = [(0usize, 0usize, 0.0f64); REQUEST_LANES]; :1672 — if count < 2 { continue; } :1676 — for by_density in [false, true] { :1684-1688 — identical primary construction :1704 — if total_work + work > packed { continue; } :1713 — if selected < 2 { continue; }

Same offers array shape, same density/value double pass, byte-identical comparator head, same budgeted greedy fill, two spellings of every local (n/count, lane_count/selected, used_tokens/total_work). 250 lines where one closure + two thin callers would be ~130.

The two copies are already inconsistent, which is exactly the risk:

Also, in both copies the by_density == false pass compares value twice:

helios/src/scheduler/policy.rs:1362-1367 / :1684-1689

let primary = if by_density { (vb / wb as f64).total_cmp(&(va / wa as f64)) } else { vb.total_cmp(&va) };
primary.then_with(|| vb.total_cmp(&va))...

When by_density is false, primary is vb.total_cmp(&va), so the .then_with(|| vb.total_cmp(&va)) is a guaranteed-Equal retry. Written as if by_density { density_cmp.then(value_cmp) } else { value_cmp } the intent is explicit and the dead retry disappears.

Recommendation: extract one fn packed_prefill_cohort(&self, ...) -> Option<(mask, lengths, work, value, rate)> parameterised by (horizon, require_promoted) and a single comparator, and have continuation_candidate call it — which also removes the drop(consider); hack, since the inlined block would leave the closure's borrow alone.

B2 — Candidate stores work and host_lengths that must agree. Make one of them derived.

helios/src/scheduler/policy.rs:103-112

pub batch: usize,
pub capacity: usize,
pub packed_token_capacity: usize,
...
pub work: usize,
...
pub host_lengths: Option<[usize; REQUEST_LANES]>,

For exactly the candidates this PR adds, work == host_lengths.iter().sum():

helios/src/scheduler/policy.rs:1731-1745

output.push(Candidate {
    host_lengths: Some(lengths),
    ...
    work: total_work,

total_work is accumulated as total_work += work in the same loop that fills lengths[slot] = work (:1707-1711). Two fields, one truth — and the invariant is silently broken by every other constructor (:1579, :1803, :1966, rounds.rs:818 all pass host_lengths: None, work: 0 or work: <something> and rely on inference). A enum LaneWidths { Scalar, PerLane([usize; REQUEST_LANES]) } next to a fn work(&self) would make work unrepresentable-as-wrong; at minimum drop work from the packed constructor and derive it.

The Option<[usize; N]> shape also produces a silent-zero hazard:

helios/src/scheduler/policy.rs:2056-2058

let work = candidate
    .host_lengths
    .map_or(0, |lengths| lengths[slot]);
if work == 0 || !self.packed_prefill_lane_compatible(...)

None and "lane carries 0 tokens" collapse to the same work == 0 rejection, so a future non-packed caller that reaches this branch silently rejects None-carrying candidates instead of tripping an assert. host_lengths is only meaningful when packed_token_capacity >= 2, so Option<(usize, [usize; N])> (capacity + lengths together) removes the pairing question at :2212:

helios/src/scheduler/policy.rs:2212-2215

let lengths = (candidate.packed_token_capacity != 0).then(||
    candidate.host_lengths.unwrap_or_else(|| self.round_lengths_optimistic(...)));

That .then(unwrap_or_else) chain only exists because "is this a packed round?" is encoded in two independent fields (packed_token_capacity for speculative and packed prefill, host_lengths only for the latter).

B3 — New dominates_padding clause is a shared predicate widened for one caller

helios/src/scheduler/policy.rs:169-171

if smaller.kind.is_prefill() {
    return smaller.work == larger.work && smaller.host_lengths == larger.host_lengths;
}

Before this PR the clause was return smaller.work == larger.work;. It now compares host_lengths, a field that is None for every solo prefill candidate (:1579), so the new conjunct is a no-op on the path this clause was written for and only matters for the packed candidates. That is a mutation of a shared pruning predicate in order to admit a new graph family — the safer shape is a separate arm keyed on packed_token_capacity != 0, leaving solo padding pruning provably unchanged.

B4 — Four validations of one (B,W,P) invariant, plus three re-derivations

The new geometry constraint set is spelled out at:

  1. helios/src/execution/manifest.rs:860-872 — draft_tokens != 0 || packed < batch || packed > batch*token || packed < 64 || !packed.is_multiple_of(64) || packed > i32::MAX
  2. helios/src/execution/manifest.rs:914-924 — (2..=request_capacity).contains(&batch) && token > 0 && token <= packed
  3. helios/src/model/catalog.rs:266-282 — batch >= 2 && tokens > 0 && tokens <= packed && packed >= batch && packed <= batch*tokens && packed >= 64 && packed <= prefill_chunk_size && packed.is_multiple_of(64)
  4. helios/src/runtime_core/selection.rs:260-275 — the same eight conjuncts, rewritten
  5. helios/src/scheduler.rs:902-912 — the same eight, rewritten again
  6. helios/src/scheduler.rs:436-446 — the same eight, rewritten a third time inside validate_mixed
  7. helios/src/scheduler.rs:2617-2632 — a seventh (deletable, see A1)

Sites 1 and 2 are two halves of one check within the same file, 40 lines apart. Sites 4/5/6 duplicate 3. One fn validate_packed_prefill(batch, width, packed, chunk, lanes) -> Result<()> — or better, one struct PackedPrefill { batch, width, packed } with a single validate — collapses seven copies of an eight-term conjunction into one. The only site that genuinely needs different inputs is catalog.rs (it has prefill_chunk_size and no lane list) and validate_mixed (it has lanes).

Evidence the copies already diverged: the same condition has three different error strings — "packed prefill B/W/P geometry is invalid" (manifest.rs:871), "packed prefill shapes must be distinct aligned multi-request capacities within the chunk size" (scheduler.rs:915), "packed prefill lanes exceed their captured geometry" (scheduler.rs:464) — and i32::MAX appears in exactly one of them (manifest.rs:869), while prefill_chunk_size appears in only three of the seven.

B5 — is_non_terminal_prefill_step uses a different search than its own batch-1 branch

helios/src/scheduler.rs:936-938

pub(super) fn is_non_terminal_prefill(&self, kind: GraphKind, capacity: usize) -> bool {
    kind == GraphKind::Prefill && self.terminal_prefill_catalog.binary_search(&capacity).is_ok()

helios/src/scheduler.rs:947-954

if batch <= 1 { self.is_non_terminal_prefill(kind, capacity) } else {
    kind == GraphKind::Prefill
        && self.packed_prefill_catalog.contains(&(GraphKind::TerminalPrefill, batch, capacity, packed))
}

The catalogue is sorted on exactly (kind as u8, batch, width, packed) (scheduler.rs:899-901), so the batch≥2 branch could binary_search the tuple too. Two lookups for one concept with two search strategies is the kind of divergence that later becomes a performance bug on the hot path (commit calls this at :2685, and checkpoints.rs:922-931 calls it per lane per step). Minor, but free to fix and free to keep aligned.

B6 — is_text_only_prefill_request carries a conjunct that both call sites already guarantee

helios/src/scheduler/policy.rs:1585-1590

fn is_text_only_prefill_request(&self, r: &LiveRequest) -> bool {
    !r.prompt_logprobs
        && r.image_slot.is_none()
        && r.vision_patches.is_empty()
        && r.conditioned_windows.is_empty()
}

Both call sites filter on a predicate that already maps prompt_logprobs → ScoredPrefill:

So !r.prompt_logprobs is unreachable-true at both sites. Keep it as a debug_assert! or fold it into the caller's Some(GraphKind::Prefill) ==, but don't let it read as a live constraint on the packing rules. Likewise, image_slot.is_none() already implies most vision state (scheduler.rs:2550 sets image_slot alongside vision_patches.extend), so three of the four conjuncts are measuring one thing — worth a single LiveRequest::is_text_only() next to the existing prompt_phase() (scheduler.rs:343-350) rather than a third private copy of the vision predicate.

B7 — checkpoints.rs Mixed special case defeats the helper it just added

helios/src/scheduler/checkpoints.rs:922-931

let non_terminal = if step.kind == GraphKind::Mixed {
    self.is_non_terminal_prefill(kind, step.prefill_capacity())
} else {
    self.is_non_terminal_prefill_step(kind, step.batch_capacity, step.token_capacity, step.packed_token_capacity)
};

is_non_terminal_prefill_step already dispatches batch <= 1 to is_non_terminal_prefill, so the Mixed arm exists only to substitute prefill_capacity() for token_capacity. A helper taking the prefill extent as an argument (is_non_terminal_prefill_step(kind, batch, prefill_extent, packed)) removes the branch; as written the reader has to know that Mixed's prefill width lives in a different field.

B8 — checkpoints.rs: two *_for helper pairs where one suffices

helios/src/scheduler/checkpoints.rs:172 — fn prefill_catalog_costs_for(&self, prompt_logprobs: bool) -> Vec<PrefillCatalogCost> helios/src/scheduler/checkpoints.rs:217-219

fn prefill_catalog_costs(&self, request: &LiveRequest) -> Vec<PrefillCatalogCost> {
    self.prefill_catalog_costs_for(request.prompt_logprobs)
}

and identically interval_prefill_ns / interval_prefill_ns_for (:196-215). The _for variants are the real functions; the non-_for ones are 2-line adaptors retained for callers that still hold a LiveRequest. This is a legitimate refactor — but it means the diff touches every prefill path's pricing, not just packed steps, so it belongs in the PR description (it isn't there) and the adaptors should be inlined at their call sites rather than kept as a second API surface.

B9 — Python: key arity is used as a type tag

ignition/direct/scheduler.py:197-200

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,)

ignition/direct/scheduler.py:290-293

return sorted({key[2] for key in self.graphs if len(key) == 3 and key[0] == kind and key[1] == 1})

The key now has three arities (3/4/5) and correctness depends on len(key) everywhere it is read (:290, :292). The and key[1] == 1 guard is redundant with len(key) == 3 for solo keys but is now load-bearing by accident — it silently becomes wrong the moment a second kind gains a 4th element. A uniform 5-tuple ((kind, batch, width, packed, drafts), unfilled slots None) makes capacities() a plain filter with no arity test.


C. What is already lean (no action)


Bottom line

Two deletions are worth doing before review:

  1. helios/src/scheduler.rs:2614-2632 — dead re-validation after step.validate_mixed()? at :2575. ~19 lines, zero risk.
  2. Collapse helios/src/scheduler/policy.rs:1300-1426 into :1623-1747 (one packed_prefill_cohort helper, one comparator, require_promoted as a flag). ~120 lines saved, and it removes three live divergences (comparator tie-break, promoted requirement, horizon) that no reviewer would otherwise notice. This is the single change that most reduces what future maintainers must keep in sync, in a file that four merged PRs touched in the five days before this one.

Then, in order: one shared validate_packed_prefill for the seven copies of the eight-term conjunction (B4); delete packed_prefill_duration (A2) and the empty-catalogue early return (A3); partition the graph list once in server/runtime.rs instead of adding three batch_capacity == 1 clauses (A5); and pair host_lengths with packed_token_capacity so the work field stops being independently assignable (B2).

None of these change the feature's semantics; A1, A2, A3 and B1 are pure subtraction. I found no speculative CLI flag, config knob, or supports_* boolean in this diff — the opt-in mechanism (core declares B >= 2 graphs, --max-concurrency 1 filters them) follows docs/design-review.md (not opened)'s "no per-model flags" rule, and that part is exemplary. The weight is entirely in the scheduler: ~250 of ~850 production lines are one algorithm written twice, sitting on top of a validation invariant written seven times.