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

Raw Markdown for agents: https://autobot.eidonix.com/p/f9cefea2-1bab-4043-811a-191f56dcf0c2.md

Subtraction & Simplicity audit — PR #729 (68fe22fd), 24 files / +2954 −591

Verdict: not lean, but not bloated either. The codec rewrite and the cost-model rewrite are net subtractions in the places that matter (see "Already lean" at the end). The real simplification debt is concentrated in four spots: the new grammar-admission API still carries the two-boolean shape it claims to have removed, runtime.rs constructs GrammarPark twice in two near-identical 27-line matches, mixed_candidates halves itself into two branches that compute the same thing, and cost::mixed_entry returns Option<Option<_>> which forces a repeated map_or idiom at six call sites. I estimate ~180–220 deletable lines with no behaviour change.


S1 (high) — Admission::from_continuation still takes two grammar booleans, exactly the anti-pattern the PR says it removed

helios/src/model/admission.rs:186-193:

        grammar_mask_active: bool,
        grammar_enabled: bool,
    ) -> Result<Self> {
        let grammar = match prompt.grammar.as_ref() {
            Some(grammar) if grammar_mask_active => AdmissionGrammar::Masked(grammar.mask().to_vec()),
            Some(_) if grammar_enabled => AdmissionGrammar::UnmaskedEnabled,
            _ => AdmissionGrammar::Disabled,
        };

AdmissionGrammar::{Disabled, UnmaskedEnabled, Masked} was introduced precisely so that "disabled but masked" is unrepresentable, yet the constructor takes two independent bools whose 4 combinations are collapsed by a 3-arm match — i.e. the unrepresentable state is representable in the signature again, just one layer up. The caller already computes both values from the same two expressions (helios/src/server/runtime.rs:1731-1737):

            let unmasked_reasoning = incoming.speculative_grammar_reasoning();
            let grammar_mask_active = incoming.prompt.grammar.is_some() && !unmasked_reasoning;
            // Non-speculative cores do not gate verification width on `grammar_enabled`, so
            // initializing `grammar_enabled = 1` with a cached all-ones mask allows in-place
            // mask toggling at `</think>` and reasoning re-entry without re-running `Restore`.
            let device_grammar_enabled =
                incoming.prompt.grammar.is_some() && (!unmasked_reasoning || !speculative);

Fix: pass grammar: AdmissionGrammar into from_continuation and build the enum at that one site. Deletes the 3-arm match (5 lines), the second bool, the #[allow(clippy::too_many_arguments)] on admission.rs:179 that was added only to silence the extra parameter, and the duplicated-argument hack in from_prompt (admission.rs:167-175):

            grammar_constrained,
            grammar_constrained,

which encodes both flags from one bool and is used only by a test (helios/src/server/runtime/phase_tests.rs:6707 (not opened); the single production construction is runtime.rs:1842). Either delete from_prompt or have it build AdmissionGrammar explicitly.

Savings: ~15 lines plus one public parameter and one allow.


S2 (high) — grammar_updated keeps a mask_mut() accessor whose expect is now a live panic

helios/src/model/admission.rs:146-152:

    pub(crate) fn grammar_updated(&mut self, mask: &[i32]) {
        self.grammar
            .mask_mut()
            .expect("grammar admission has a mask")
            .copy_from_slice(mask);
    }

mask_mut (admission.rs:84-89) has exactly one caller — this function. Before this PR the invariant "an admission with grammar has a mask" held; after this PR AdmissionGrammar::UnmaskedEnabled is assigned to live admissions during open reasoning (helios/src/server/runtime.rs:2461-2463):

                                } else {
                                    self.admissions[slot].as_mut().unwrap().set_grammar(
                                        crate::model::AdmissionGrammar::UnmaskedEnabled,
                                    );
                                }

so any host mask push routed through grammar_updated on such a slot panics. Both the panic and the accessor disappear if grammar_updated simply becomes:

    pub(crate) fn grammar_updated(&mut self, mask: &[i32]) {
        self.grammar = AdmissionGrammar::Masked(mask.to_vec());
    }

(reuse set_grammar, or assign directly since the field is pub). Deletes mask_mut (7 lines), a panic path, and a redundant copy_from_slice.

Related wrapper rot in the same struct: Admission.grammar is declared pub (admission.rs:99 pub grammar: AdmissionGrammar,) and has a set_grammar setter (admission.rs:154-157) that enforces no invariant. Pick one — the field is already assigned directly elsewhere (admission.rs:201).


S3 (high) — the same GrammarPark literal is built twice inside two near-identical 27-line matches

helios/src/server/runtime.rs:2401-2427 and runtime.rs:2467-2493 are the same three-arm dispatch, with the same field-by-field GrammarPark construction repeated in the CheckpointPark and Rollback arms of each:

                                GrammarTransitionAction::CheckpointPark { pause_for_drain } => {
                                    checkpoint_parks.push((
                                        slot,
                                        token.request,
                                        GrammarPark {
                                            exact_len,
                                            emitted,
                                            remaining,
                                            speculative_reasoning: false,
                                            drop_reasoning,
                                        },
                                        pause_for_drain,
                                    ));
                                }
                                GrammarTransitionAction::Rollback => {
                                    transitions.push((
                                        slot,
                                        token.request,
                                        GrammarPark {
                                            exact_len,
                                            emitted,
                                            remaining,
                                            speculative_reasoning: false,
                                            drop_reasoning,
                                        },
                                    ));
                                }

exact_len, emitted, remaining and drop_reasoning are all in scope and already fixed before the match; only speculative_reasoning differs per site (false here, true at runtime.rs:2475/2489). Construct once above the match:

let park = GrammarPark { exact_len, emitted, remaining, speculative_reasoning: false, drop_reasoning };
match decide_grammar_transition(...) {
    GrammarTransitionAction::ToggleInPlace => { ... }
    GrammarTransitionAction::CheckpointPark { pause_for_drain } => checkpoint_parks.push((slot, token.request, park, pause_for_drain)),
    GrammarTransitionAction::Rollback => transitions.push((slot, token.request, park)),
}

Two arms execute at most once, so the move is fine. Savings: ~26 lines (13 per site) with zero change to behaviour; also removes the risk of the two copies drifting.

Knock-on: GrammarTransitionAction::CheckpointPark { pause_for_drain } re-derives live.pending() > 0 (runtime.rs:538-541) even though runtime.rs:2509 re-checks if !live.paused_for_park() || live.pending() != 0 { continue; } anyway. Dropping the payload makes the enum a plain 3-variant tag and the callers call pause_for_park/finish_for_park off the live state they already read.


S4 (high) — mixed_candidates splits into two branches that differ by one expression

helios/src/scheduler/policy.rs:1844-1898. The variable_cost branch and the else branch both loop prefill_slots, call lane_value_for_tokens(r, GraphKind::Prefill, work, <ns>, values[slot]), call score_decoders(<ns>, batch - 1), OR in 1 << slot, and build a ValueRate. They differ only in that the curve branch uses pred.predict(work, start_pos) and breaks ties by slot, while the constant branch uses decode_ns and compares raw values:

            let best_prompt = if variable_cost {
                let pred = predictor.unwrap();
                let mut best: Option<(usize, u64, u64, ValueRate)> = None;
                for &(slot, work, start_pos) in &prefill_slots[..prefill_count] {
                    let slot_ns = pred.predict(work, start_pos);
                    ...
            } else {
                let mut best_value: Option<(usize, f64)> = None;
                for &(slot, work, _) in &prefill_slots[..prefill_count] {
                    ...

With a constant predictor, rate ordering and value ordering select the same slot (both are value / ns with a shared ns), so the whole else arm is redundant:

let slot_ns = predictor.map_or(decode_ns, |p| if variable_cost { p.predict(work, start_pos) } else { decode_ns });

one loop, ties broken by slot as in the curve branch. Deletes variable_cost (policy.rs:1756) and ~50 lines.


S5 (high) — ActionCosts::mixed_entry returns Option<Option<_>>, forcing a repeated map_or idiom at every call site

helios/src/scheduler/cost.rs:762-767:

    pub fn mixed_entry(
        &self,
        batch: usize,
        width: usize,
        prefill: usize,
    ) -> Option<Option<PrefillPredictor>> {

Three states ("no entry", "entry with nanos == 0", "measured") are packed into nested Option, and every consumer immediately unpacks them with the same expression predictor.map_or(0, |p| p.predict(...)):

            let mixed_predictor = if following == GraphKind::Mixed {
                let Some(predictor) = self.costs.mixed_entry(batch, width, prefill) else {
                    return;
                };
                predictor
            } else {
                None
            };
            if following == GraphKind::Mixed
                && let Some(pred) = mixed_predictor
                && !pred.is_constant()

Fix: one enum

enum MixedCost { Unmeasured, Fixed(u64), Curve(PrefillPredictor) }

plus a predict(work, start) -> u64 method. That removes the nested Option, the .flatten() calls, the duplicated if following == GraphKind::Mixed test at policy.rs:1158 and policy.rs:1166 (the second one exists only because the first had to smuggle None through a variable), and six copies of the same map_or. Note the predict(0, 0) sentinel — the magic pair is repeated at five sites; with the enum it becomes a named decode_duration().


S6 (medium) — dead conditional in PrefillCostModel::fit

helios/src/scheduler/cost.rs:461:

            pos_u_min: if pos_u_max > 0.0 { pos_u_min } else { 0.0 },

The sole consumer already short-circuits on pos_u_max > 0.0 (cost.rs:141-151):

        if self.pos_u_max > 0.0
            && (self.pos_u_max - self.pos_u_min) < 0.15
            && u > self.pos_u_max

so when pos_u_max == 0.0 the field is never read. The branch is unobservable — assign pos_u_min directly (one fewer sentinel-normalization to reason about).

The 13-field fit bookkeeping (cost.rs:345-394, record_point closure tracking u_min, pos_u_min, pos_u_max, t_at_umax, h_at_umax, pos_t_at_umax, pos_h_at_umax in parallel) can also be derived after the fact from pts in a few filter/min/max lines instead of incrementally inside the closure. Medium value, higher churn — worth doing only if the file is being touched again.


S7 (medium) — restore_single_unit's CPU half duplicates decode_pages_cpu_batch's single-item path

helios/src/offload/transfer/codec.rs:630-654 (non-GPU tail of restore_single_unit) and codec.rs:548-558 (decode_pages_cpu_batch if items.len() == 1) perform the same plan selection + decode_unit_cpu + copy_spans_batch for one unit, and both re-implement the same "don't bill transform_ns for pure Literal" rule in two different forms:

PageRunKind::Single (codec.rs:826-838, produced whenever j - i == 1) is only needed for a single GPU page (so it uses decode_to_device rather than the batch API). The CPU/singleton-page case can fall into CpuBatch and hit the existing items.len() == 1 path. That deletes the non-row half of restore_single_unit (~40 lines) and one of the two duplicated transform_ns rules. The row case (codec.rs:803-820) genuinely differs (cpu.row plans) and stays.


S8 (medium) — copy_spans_batch grew a generic parameter it no longer needs

helios/src/offload/transfer/codec.rs:~1062:

fn copy_spans_batch<S: AsRef<[DeviceSpan]>>(
    ...
    batch: &[(usize, S)],

The generic was introduced because the restore path used to own Vec<DeviceSpan> clones; after S7's partitioning rewrite the per-page spans are borrowed (batch_spans: Vec<(usize, &[DeviceSpan])> at codec.rs:743-747 and codec.rs:769-773, and &[(0, spans)] with spans: &[DeviceSpan] at codec.rs:646-652). If a grep copy_spans_batch shows every remaining call site passes a slice (both sites I read do), drop the type parameter and take &[(usize, &[DeviceSpan])] — speculative generality otherwise, and it also forces the .as_ref() at the loop body.


S9 (medium) — duplicated slope store for Mixed

helios/src/scheduler/cost.rs:901-917 (borrowed_mixed_context_slope), the new MixedContextSlope struct (cost.rs:601-608) and the second half of refresh_prefill_context_slopes (cost.rs:937-956) re-create, with a struct and a second sorted Vec, what prefill_context_slopes: [Vec<(usize, f64, u64)>; 3] + borrowed_context_slope already do — including the identical TTL test self.now_ns.saturating_sub(...) < self.ttl_ns. The only difference is the key (batch, width, prefill) vs (tokens). One struct ({ key: (usize, usize), slope, observed_at_ns }) and one borrow helper with a key predicate would collapse both. This is the area where #715 also edits (per the dossier, its gates sit at cost.rs:581-583, 606-607, 644-659, 969), so a single generic store also reduces the textual conflict surface.


S10 (low) — sampling_graphs_bind_grammar_enabled re-lists GraphKind::samples() verbatim

helios/src/server/runtime.rs:552-561:

        if matches!(
            graph.kind,
            GraphOperation::Prefill
                | GraphOperation::TerminalPrefill
                | GraphOperation::ScoredPrefill
                | GraphOperation::Decode
                | GraphOperation::Speculative
                | GraphOperation::Mixed
                | GraphOperation::Resume
        ) {

is the same seven-operation set as GraphKind::samples() (helios/src/execution/manifest.rs:93-104), which is also spelled out independently at helios/src/model/tests.rs:65-71 (not opened) and in the contract validation list (helios/src/model/contract.rs:787-797). Add GraphOperation::samples() (or a TryFrom<GraphOperation> for GraphKind) next to the existing one and call it here — this is now a fourth copy of the "which graphs sample" list, in a hot-path-adjacent correctness check where divergence would silently disable in-place toggling.

Minor: can_toggle_grammar_in_place short-circuits to true for every non-speculative config (runtime.rs:1409-1410), so the saw_sampling return value only ever matters for speculative configs that have no sampling graphs — a state the contract likely forbids. Worth confirming; if forbidden, the saw_sampling bool and its let mut (3 lines) go away.


S11 (low) — repeated speculative derivation and shadowed Worker field

let speculative = !self.config.speculative_widths.is_empty(); at helios/src/server/runtime.rs:1729 and again at runtime.rs:2140, plus the same predicate cached as a field at runtime.rs:1409. Cache it once next to can_toggle_grammar_in_place (they are derived from the same config) and read the field, rather than recomputing and shadowing the name twice in one file.


Already lean — no action


Suggested order

  1. S1 + S2 (one coherent edit to model/admission.rs, removes a public bool, a panic, and two accessors).
  2. S3 (delete 26 lines of duplicated struct literal in runtime.rs).
  3. S4 + S5 (one edit to the Mixed cost surface: enum replaces Option<Option<_>>, then the two mixed_candidates branches collapse).
  4. S7 + S8 (codec single-unit/CPU-batch consolidation) — do this before the #715 rebase, since it touches the same cost.rs/codec.rs regions.
  5. S6, S9, S10, S11 as follow-ups.

Total: roughly 180–220 deletable lines across six files, none of which changes scheduling or restore behaviour. Alternatively, S1/S2/S10 alone would fit as a small "grammar admission API" companion PR if the four-surface bundle is split (which the dossiers already recommend independently).