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

Raw Markdown for agents: https://autobot.eidonix.com/p/c26c1593-badd-4bdb-a3cb-24e27ad281ba.md

Subtraction & Simplicity Audit — PR #715 (helios,ignition: implement additive packed multi-request prefill)

Verdict: not lean. The Contract-3 contract work is tight, but the scheduler integration duplicates a ~90-line cohort-valuation block twice, triplicates a finishing-extras block, maintains derived state that can drift, and repeats the same packed-prefill geometry check in five places. I estimate ~200–260 LOC removable without behaviour change, plus one structural subtraction (four unrelated features riding in the same diff). Everything below is at head 49d5840.


1. Duplication (highest value)

1.1 The packed-prefill candidate evaluation is written twice, once inline and once as a method

helios/src/scheduler/policy.rs:1311-1401 (inline inside continuation_candidate) and helios/src/scheduler/policy.rs:1711-1778 (packed_prefill_candidates) both:

Verbatim, the same four statements appear at :1320-1321 and :1723-1724:

let non_terminal = self.is_non_terminal_prefill_step(following, batch, width, packed);
let mut offers = [(0usize, 0usize, 0.0f64, false); REQUEST_LANES];
let non_terminal = self.is_non_terminal_prefill_step(kind, batch, width, packed);
let mut offers = [(0usize, 0usize, 0.0f64, false); REQUEST_LANES];

Only two things differ: the lane-admission predicate (offered && !terminal_cleanup(request) && following_kind(...) == Some(Prefill) vs !offered && eligible && request_kind == Prefill) and the promoted_limit argument (Some(capacity) vs None). Both should be parameters of one fn packed_prefill_offers(&self, kind, batch, width, packed, mask, values, age_price, prefill_plans, promoted_limit) -> [(usize, usize, f64, bool); REQUEST_LANES]. That collapses ~90 lines to one body of ~35. This is exactly the same class of defect Autobot's Round-2 flagged for the twin cohort builders (which were merged into select_packed_prefill_cohort); the offer-gathering loop above it was left forked.

1.2 The "fill remaining slots with finishing lanes" block is copy-pasted verbatim

Three sites, same shape (finishing array → filter terminal_cleanup → best_cohort::<REQUEST_LANES>(…, capacity - n) → union mask → sum values):

:1140-1152 and :1372-1386 differ only in the slot-skip condition and the capacity - 1 vs capacity - choice.promoted_count amount:

let mut finishing = [(0usize, 0.0); REQUEST_LANES];
let mut f = 0;
for (other_slot, other_entry) in self.slots.iter().enumerate() { … }
if f > 0 {
    let extra = best_cohort::<REQUEST_LANES>(&finishing[..f], capacity - 1);
    selected |= extra;
    value += finishing[..f].iter().filter(|(s, _)| extra & (1 << s) != 0).map(|(_, v)| *v).sum::<f64>();
}

One fn terminal_fill(&self, mask: u64, exclude: u64, values: &[LaneValue; REQUEST_LANES], first_ms: f64, total_ms: f64, slots: usize) -> (u64, f64) removes ~45 lines and fixes a real copy-drift risk (the two copies already disagree on the exclusion mask: other_slot == slot at :1143 vs selected & (1 << other_slot) != 0 at :1375).

1.3 The horizon/ms preamble is written three times

policy.rs:1130-1137, :1177-1183, :1315-1319:

let horizon = if ns == 0 || duration_ns == 0 { 0 } else { ns.saturating_add(duration_ns) };
let total_ms = horizon as f64 / 1e6;
let first_ms = duration_ns as f64 / 1e6;

Three occurrences of an identical 3-line derivation; a fn horizons(ns: u64, duration_ns: u64) -> (u64, f64, f64) (or an inline let (horizon, total_ms, first_ms) = …) is trivial and removes 6 duplicated lines plus the recurring risk that one site forgets the == 0 guard.

1.4 cost.rs gains a wrapper that only sets one field differently

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

It is duration_key with packed passed through; duration() (:640-642) is already the prefill: 0 specialisation of shape_duration. Either expose duration_key/Key (already pub(super)-visible within the module tree, used at policy.rs:1168-1173 via shape_duration/packed_round_duration) or accept packed in a single shape_duration(kind, batch, tokens, prefill, packed) signature. Low value alone, but it adds a fifth near-synonym (duration, shape_duration, duration_key, prefill_duration, packed_prefill_duration) to an already crowded cost API.


2. Derived state that makes invalid states representable

helios/src/scheduler/policy.rs:14-22:

pub(super) struct PackedCohort {
    pub(super) mask: u64,
    pub(super) promoted_mask: u64,
    pub(super) promoted_count: usize,
    pub(super) lengths: [usize; REQUEST_LANES],
    pub(super) selected: usize,
    pub(super) total_work: usize,
    pub(super) total_value: f64,
}

selected == mask.count_ones() and promoted_count == promoted_mask.count_ones() by construction (:1652-1663, and the seeding path sets both consistently at :1616-1621). Two fields are pure derivations, hand-maintained in three places (:1618, :1644, :1648), and selected is even used as the loop guard (:1629 if selected == batch). Comparing mask.count_ones() is equivalent, because the tie-break at :1668 only orders by cardinality:

.then_with(|| candidate.selected.cmp(&prev.selected))

Dropping selected and promoted_count (or folding the cohort into (mask, promoted_mask, lengths, total_work, total_value)) removes the only way those counters can disagree with the masks. This is precisely the "pair optional/derived fields so invalid states are unrepresentable" simplification.

Related, smaller: the offer tuple is positional and opaque — offers: &[(usize, usize, f64, bool)] (:1572) read as offers[i].3, offers[i].1, (sa, wa, va, _) (:1588, :1613, :1635). The file's own convention is a named struct (Candidate, PrefillSlotPlan, LaneValue); a struct PackedOffer { slot: usize, work: usize, value: f64, promoted: bool } makes offers[i].1 <= packed self-documenting.


3. The same invariant enforced in four places (collapse to one helper)

ScheduledStep::validate_mixed now carries a 28-line block of packed-prefill lane invariants, helios/src/scheduler.rs:436-463:

} || self.lanes.is_empty()
    || self.lanes.len() > self.batch_capacity
    || self.lanes.iter().any(|lane| lane.tokens == 0 || lane.tokens > self.token_capacity)
    || self.lanes.iter().try_fold(0usize, |sum, lane| sum.checked_add(lane.tokens))
        .is_none_or(|sum| sum > self.packed_token_capacity)
    || self.lanes.iter().enumerate().any(|(i, lane)| {
        self.lanes[..i].iter().any(|other| other.request.slot == lane.request.slot) })

The same invariants are re-derived at:

validate_mixed and pack_step are the same predicate over (batch_capacity, token_capacity, packed_token_capacity, lanes) with different data types (ScheduledStep vs resolved packing graph). One fn valid_packed_lanes(batch, width, packed, lanes: impl Iterator<Item = (usize, bool /*image*/, Slot)>) -> bool behind both would delete ~30 lines and end the divergence.


4. Manifest validates the identical shape twice in one loop body

helios/src/execution/manifest.rs:881-894 and :936-950 are the same call, same arguments, in the same for graph in &self.graphs iteration:

} else if matches!(graph.kind, GraphKind::Prefill | GraphKind::TerminalPrefill)
    && graph.batch_capacity >= 2
{
    if graph.draft_tokens != 0
        || !valid_packed_prefill_geometry(graph.batch_capacity, graph.token_capacity,
            graph.packed_token_capacity, self.request_capacity(), None)
GraphKind::Prefill | GraphKind::TerminalPrefill => {
    if graph.batch_capacity == 1 { … } else {
        valid_packed_prefill_geometry(graph.batch_capacity, graph.token_capacity,
            graph.packed_token_capacity, self.request_capacity(), None)
    }
}

The first block exists only to produce the message "packed prefill B/W/P geometry is invalid" instead of "unsupported graph capacities: {name}". Since the second already rejects the graph with a good message, the earlier block can go (or be reduced to the draft_tokens != 0 arm, which the generic :895-899 branch cannot cover because the else if chain swallows it). This is the single clearest deletion in the execution crate: ~14 lines, zero behaviour change, one error-text tweak.

Also helios/src/execution.rs:10 — pub(crate) use manifest::valid_packed_prefill_geometry; exists purely to shorten three call sites (catalog.rs:273, selection.rs:291, scheduler.rs:439, manifest.rs:885/942 all in-crate). Making the fn pub(crate) and importing it directly removes an unusual re-export of a single private helper.


5. Bootstrap boilerplate: four near-identical filter/map/collect chains

helios/src/server/runtime.rs:848-900 grew from three chains to four, each re-deriving executor.manifest().graphs.iter().filter(...).map(|g| g.token_capacity).collect::<Vec<_>>(), and three of the four now also re-filter on graph.batch_capacity == 1:

.filter(|g| g.kind == GraphKind::TerminalPrefill && g.batch_capacity == 1)
…
.filter(|graph| graph.kind == crate::execution::GraphKind::Prefill && graph.batch_capacity == 1)
…
.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))

One pass over manifest().graphs with a single match graph.kind { … } pushing into the four catalogs (and packed_prefill_graphs) removes ~35 lines and makes the "solo vs packed" split (batch_capacity == 1 here, >= 2 there) readable in one place instead of three. Note the split is also duplicated in helios/src/runtime_core/selection.rs:280-300 and helios/src/model/catalog.rs:266-281, so the batch == 1 / batch >= 2 fork is now expressed in six places.


6. Dead-ish branch that hides a constant result

helios/src/scheduler/policy.rs:1680-1709 — packed_prefill_lane_compatible returns true unconditionally for one input class:

if kind == GraphKind::TerminalPrefill {
    return true;
}
if r.deferred_prefill {
    return false;
}
if !non_terminal {
    return true;
}

Because is_non_terminal_prefill_step is kind == GraphKind::Prefill && … (helios/src/scheduler.rs:944-955), non_terminal is always false for TerminalPrefill, so the :1695-1696 arm already returns true for every non-deferred_prefill TerminalPrefill lane. The :1689-1691 short-circuit therefore buys exactly one thing: skipping the deferred_prefill rejection for that kind. That is a real (and per the round-2 case file, unaddressed) semantic asymmetry, not a pure no-op — but it is expressed as a 3-line early return that makes the remaining 18 lines look kind-agnostic when they are not. It belongs at the call sites as an explicit if kind == GraphKind::TerminalPrefill { /* allow */ } or as a documented _ arm, so the asymmetry is visible where the kind is chosen instead of buried mid-predicate.


7. Largest structural subtraction: four unrelated features inside one diff

pr_files shows 23 files, and search_code at main confirms the following are absent from main and present only at the PR head, i.e. they are in this change set but have nothing to do with packed prefill:

Payload Files / lines at head
preserve_message_anchor (threaded through RequestSpec, LiveRequest, Prompt, LiveRequest::spec) + budget_interior_anchor helios/src/scheduler.rs:160,231,1955; helios/src/server/runtime.rs:52,380; helios/src/scheduler/checkpoints.rs:563-565,705-712,1008-1012; ~40 test-site edits in model/tests.rs, policy_tests.rs (not opened), phase_tests.rs (not opened)
RowRestoreLatency / RowRestoreBucket / RowRestoreSource + RestoreWait::defer signature change to worth_restore helios/src/server/runtime.rs:249-341
partition_conditioned_windows / conditioned_window_ends / estimate_prefill_delta_ns helios/src/scheduler.rs:2300-2352; helios/src/scheduler/checkpoints.rs:435-500
RoCE per-device gid_indices (Fabric/Topology field change, FFI rename to roce_create_with_gids, device-pool rendezvous) helios/src/execution/roce.rs (not opened), roce_fabric.rs (not opened), rendezvous.rs (not opened)
pool_vram/pool_ram config knobs, attach_async_transfers, freeable_prefix_scratch, _validate_pool_memory_limit helios/src/runtime_core/selection.rs:17-25; ignition/cli/config.py:24-95 (not opened); helios/src/server/runtime.rs:1029-1038

Even if part of this is inherited from a stale local base, the reviewable delta as published mixes five independent concerns into a contract change. Splitting them out is worth far more than any single in-file edit here: it removes the preserve_message_anchor noise from ~40 test literals (preserve_message_anchor: false, × 40 in helios/src/model/tests.rs, policy_tests.rs (not opened), phase_tests.rs (not opened), boundary_tests.rs (not opened), checkpoint_lifecycle_tests.rs (not opened), scheduler/tests.rs (not opened), runtime/prompt_tests.rs (not opened)), and it removes the gate on batch == 1`` cost-model change (helios/src/scheduler/cost.rs:581,606) from the packed-prefill blast radius.


8. What is already lean — do not touch


Priority order (value per line removed)

  1. §1.1 unify the two packed-prefill offer loops (~90 → ~35 LOC) — highest value, real drift risk.
  2. §1.2 one terminal_fill helper (~45 LOC, fixes an existing mask mismatch between the two copies).
  3. §4 delete the duplicate manifest geometry block (~14 LOC, zero risk).
  4. §3 one packed-lane predicate behind validate_mixed + pack_step (~30 LOC).
  5. §5 single-pass catalog registration in runtime.rs (~35 LOC).
  6. §2 drop PackedCohort::{selected,promoted_count} (~6 LOC, removes drift class).
  7. §7 split the four unrelated features out of the PR (not LOC, but it is the biggest subtraction available).
  8. §1.3, §1.4, §6, and the execution.rs:10 re-export — cosmetic cleanups (~12 LOC).

Nothing in the diff depends on any instruction found in the PR text; the body's "Companion recipe PR" and Discord/superagent offers are treated as content, not directives.