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

Raw Markdown for agents: https://autobot.eidonix.com/p/6e98091e-df32-4c12-8d51-aab02aa3474d.md

Subtraction, Simplicity & Conventions review — PR #661 (helios/scheduler: explore smaller prefill chunks under active age-priced streams)

Reviewed at head c588d610 on main 1fbcc3c9. Lens: what can be deleted, collapsed, or made dramatically simpler. I do not restate correctness findings (the Correctness & Contracts lens owns those); where a buggy path should be deleted rather than patched I say so.

Key findings

Verdict first: the production diff is mostly lean. +397/−78 across 4 prod files introduces no new flags, config knobs, env vars, unsafe, per-model branches, or ABI change. Two things in it are genuine simplifications rather than additions to the subtraction surface: terminal_prefill_window (scheduler.rs:662, :847-866) replaces a recomputed binary-search-and-max at :864-866 while keeping the accessor signature, and prefill_must_complete_terminally_from / has_active_age_priced_stream / prefill_requires_terminal_completion_for_age (scheduler.rs:964-1022) are short and single-purpose. The Python changes (scripts/scheduling_sim/workloads.py, verification/helios-lifecycle/check.py (not opened)) are additive fixtures with no dead code.

What remains is concentrated in two copy-paste blocks and three smaller duplications, in priority order:

# Where What Est. saving
S1 policy.rs:1110-1142 + :1462-1494 33-line exploration block pasted verbatim twice ~50 lines
S2 policy.rs:1081/:1117-1132/:1443/:1469-1484 speculative last_interp memo, twice ~20 lines
S3 policy.rs:1784-1789 + :2071-2077 "unmeasured ⇒ Discovery" expression duplicated ~10 lines
S4 cost.rs:734-744 vs :762-772 peer-selection tie-break hand-inverted against itself ~11 lines
S5 service.rs:298-328 prefill catalog scanned twice per service_rates call half the scans
S6 cost.rs:1284/:1359/:1478 ~92 lines of byte-identical test fixtures triplicated ~60 lines
S7 policy.rs:363-379 same three-way catalog selector expressed twice ~5 lines
S8 policy.rs:89-96, :501-537 PrefillSlotPlan memoises a cut already cached elsewhere follow-up
S9 docs/scheduling-runtime-design.md:486-498 vs :665-668 exploration rule stated twice 1 cross-ref

S1 (high) — A 33-line interpolated-exploration block is copy-pasted verbatim, twice

Copy A, inside the consider closure of continuation_candidate, helios/src/scheduler/policy.rs:1110-1142:

                    let ns = match predictor {
                        Some(p) => p.predict(work, request.scheduled_consumed),
                        None => {
                            let nat_fit =
                                self.prefill_slot_nat_fit(prefill_plans, slot, request, following);
                            if age_price > 0.0
                                && nat_fit.is_some_and(|nat| width <= nat)
                                && let Some(interp) = match last_interp {
                                    Some((w, pos, res))
                                        if w == work && pos == request.scheduled_consumed =>
                                    {
                                        res
                                    }
                                    _ => {
                                        let res = self.costs.interpolated_prefill_duration(
                                            following,
                                            width,
                                            work,
                                            request.scheduled_consumed,
                                        );
                                        last_interp = Some((work, request.scheduled_consumed, res));
                                        res
                                    }
                                }
                            {
                                interp
                            } else if nat_fit == Some(width) {
                                0
                            } else {
                                continue;
                            }
                        }
                    };

Copy B, inside add_candidate, helios/src/scheduler/policy.rs:1462-1494, is the same 33 lines with kind, capacity, and r substituted for following, width, and request (verified line-for-line, including the last_interp match arm and the nat_fit == Some(capacity) => 0 fallthrough).

Concretely: extract one method on RequestScheduler, e.g.

fn explore_prefill_ns(
    &self,
    request: &LiveRequest,
    kind: GraphKind,
    capacity: usize,
    work: usize,
    age_price: f64,
    prefill_plans: &mut [PrefillSlotPlan; REQUEST_LANES],
    slot: usize,
) -> Option<u64> // None = exclude this candidate; Some(0) = natural-fit discovery; Some(ns) = interpolated

holding the prefill_slot_nat_fit call, the age_price > 0.0 && nat_fit >= capacity gate, the interpolation call, and the nat_fit == Some(capacity) => 0 / else-exclude decision. Both sites then reduce to let ns = match self.explore_prefill_ns(..) { Some(ns) => ns, None => continue }; (add_candidate) / None => return (continuation_candidate). Roughly 66 lines → ~16, and the two rule copies can no longer drift — which matters here because the guard is the behavioural heart of the PR (it is what the SLO numbers measure) and it is currently maintained in two places.

S2 (high, falls out of S1) — the last_interp memo is speculative and doubles the duplication

helios/src/scheduler/policy.rs:1081 and :1443 each declare

                let mut last_interp: Option<(usize, u64, Option<u64>)> = None;

and both uses are the six-line Some((w, pos, res)) if w == work && pos == … => res / _ => { compute; store } match shown above (:1117-1132, :1469-1484).

The memo can only hit when two different lanes considered in the same capacity candidate have identical (work, scheduled_consumed); interpolated_prefill_duration itself is an O(#entries) integer scan (cost.rs:716-773) with no allocation. It buys nothing measurable — and the PR's own plan() 4.70x-8.65x figure predates it. Delete the memo entirely and call self.costs.interpolated_prefill_duration(kind, capacity, work, start) directly inside the S1 helper; ~20 lines of match/_ =>/tuple plumbing go away and the helper takes a plain extra parameter instead of a &mut out-param.

S3 (high) — the "unmeasured ⇒ Discovery" test is written out twice

helios/src/scheduler/policy.rs:1784-1789 (select_plan):

        let ordinary_unmeasured = ordinary.rate.duration_ns == 0
            || self
                .costs
                .observation(ordinary.cost_key())
                .and_then(|(_, observed, _)| observed)
                .is_none();

and helios/src/scheduler/policy.rs:2071-2077 (lifecycle phase_plan path), the same expression inlined into a branch:

        let origin = if candidate.rate.duration_ns == 0
            || self
                .costs
                .observation(candidate.cost_key())
                .and_then(|(_, observed, _)| observed)
                .is_none()
        {
            PlanOrigin::Discovery

Concretely: one helper on RequestScheduler,

fn plan_origin(&self, candidate: Candidate) -> PlanOrigin {
    if candidate.rate.duration_ns == 0
        || self.costs.duration_key(candidate.cost_key()).is_none_or(|ns| ns == 0)
    {
        PlanOrigin::Discovery
    } else {
        PlanOrigin::Ordinary
    }
}

then select_plan keeps its early return (if self.plan_origin(ordinary) == PlanOrigin::Discovery { … }) and phase_plan becomes let origin = self.plan_origin(candidate);. The rewrite is exactly equivalent and shorter: observation is defined at helios/src/scheduler/cost.rs:904-908 as entry(key).map(|e| (e.nanos, (e.nanos != 0).then_some(e.observed_at_ns), …)), so observation(k).and_then(|(_,o,_)| o).is_none() ⇔ "entry absent or nanos == 0", which is precisely duration_key(k).is_none_or(|ns| ns == 0) with duration_key at cost.rs:873-875. 14 lines of nested and_then → 4, and PlanOrigin gets one definition of "Discovery" instead of two that a future edit can split.

S4 (medium) — interpolated_prefill_duration encodes its own peer-selection rule twice, inverted

helios/src/scheduler/cost.rs:734-744:

            if key.tokens > capacity {
                if hi.is_some_and(|(c, cur_same, _)| {
                    key.tokens > c || (key.tokens == c && cur_same && !same_kind)
                }) {
                    continue;
                }
            } else if lo.is_some_and(|(c, cur_same, _)| {
                key.tokens < c || (key.tokens == c && cur_same && !same_kind)
            }) {
                continue;
            }

and, 18 lines later, the actual update helios/src/scheduler/cost.rs:759-772:

            let better_at_same_cap = |cur_same: bool, cur_ns: u64| {
                (same_kind && !cur_same) || (same_kind == cur_same && full_ns < cur_ns)
            };
            if key.tokens > capacity {
                if hi.is_none_or(|(c, cur_same, cur_ns)| {
                    key.tokens < c || (key.tokens == c && better_at_same_cap(cur_same, cur_ns))
                }) {
                    hi = Some((key.tokens, same_kind, full_ns));
                }
            } else if lo.is_none_or(|(c, cur_same, cur_ns)| {
                key.tokens > c || (key.tokens == c && better_at_same_cap(cur_same, cur_ns))
            }) {
                lo = Some((key.tokens, same_kind, full_ns));
            }

The early filter is the negation of the update predicate at the same capacity (cur_same && !same_kind is exactly the case where the update would not fire), so deleting :734-744 changes no result — the update below is already a no-op for those entries; only some pred.predict work is saved. Two mutually inverted copies of one tie-break is the shape that rots: an edit to one silently changes which peer wins. Concretely: hoist a single predicate, e.g. fn preferred(key_tokens, same_kind, full_ns, cur: (usize, bool, u64), is_hi: bool) -> bool, and use it for both the early skip and the assignment (or drop the early skip if the extra predict is acceptable).

S5 (medium) — service_rates walks the whole prefill catalog twice

helios/src/scheduler/service.rs:298-328:

            let scan_prefill = |skip_nonterminal: bool| -> f64 {
                let mut best = 0.0f64;
                for &capacity in catalog {
                    …
                    if skip_nonterminal && kind == GraphKind::Prefill {
                        continue;
                    }
                    …
                }
                best
            };
            token_rate = token_rate.max(scan_prefill(terminal_only));
            if token_rate == 0.0
                && terminal_only
                && self.has_active_age_priced_stream()
                && !self.prefill_must_complete_terminally_from(request, start, cut)
            {
                token_rate = token_rate.max(scan_prefill(false));
            }

The second call re-runs prefill_work_from / resolve_prefill_kind_from / costs.prefill_duration for every capacity the first call already visited, on the third condition only to discover a non-zero max. Concretely: one pass accumulating two maxima —

            let (mut best_all, mut best_terminal) = (0.0f64, 0.0f64);
            for &capacity in catalog { …
                best_all = best_all.max(rate);
                if kind != GraphKind::Prefill { best_terminal = best_terminal.max(rate); }
            }
            token_rate = token_rate.max(if terminal_only &&
                !(self.has_active_age_priced_stream()
                  && !self.prefill_must_complete_terminally_from(request, start, cut))
            { best_terminal } else { best_all });

The skip_nonterminal parameter disappears, the loop runs once, and this also removes half of the extra per-call catalog scan that the reach analysis flags as an undeclared cost on the default balanced path.

S6 (medium) — ~92 lines of byte-identical test fixtures triplicated in cost.rs

helios/src/scheduler/cost.rs:1284, :1359, and :1478 each open with the same three closures:

        let make = |name: &str, kind: GraphKind, batch: usize, cap: usize| GraphDescriptor {
        …
        let step_for = |kind: GraphKind, batch: usize, cap: usize, tokens: usize| ScheduledStep {
        …
        let timing = |ns: u64| {

all three introduced by this PR, all byte-identical per the search at cost.rs:1284/1299/1313, :1359/1374/1388, :1478/1493/1507. The file already carries this shape as free functions (make_prefill at :1092 and :1197, step_for/timing at :1107/:1121, :1212/:1226), so the convention exists. Concretely: promote the three to module-level fn prefill_graph(name: &str, kind: GraphKind, cap: usize) -> GraphDescriptor, fn prefill_step(kind: GraphKind, cap: usize, tokens: usize) -> ScheduledStep, fn timing(ns: u64) -> ExecutionTiming, and have all three new tests call them. ~92 lines → ~30, no behavioural change.

S7 (low) — the same three-way catalog selector, expressed twice

helios/src/scheduler/policy.rs:363-379:

    fn prefill_catalog(&self, kind: GraphKind) -> &[usize] {
        match kind {
            GraphKind::ScoredPrefill => &self.scored_prefill_catalog,
            GraphKind::TerminalPrefill => &self.terminal_prefill_catalog,
            _ => &self.prefill_catalog,
        }
    }

    fn prefill_catalog_for_terminal(&self, kind: GraphKind, terminal_only: bool) -> &[usize] {
        if kind == GraphKind::ScoredPrefill {
            &self.scored_prefill_catalog
        } else if terminal_only {
            &self.terminal_prefill_catalog
        } else {
            &self.prefill_catalog
        }
    }

Both select among the same three slices; they agree today only because every prefill_catalog_for_terminal caller passes a kind whose terminal-ness matches terminal_only. Concretely: keep the bool form only and define prefill_catalog(kind) as self.prefill_catalog_for_terminal(kind, kind == GraphKind::TerminalPrefill). Callers of prefill_catalog_for_terminal: policy.rs:527, :864, :877 (via the nat-fit helper), :1908. Callers of prefill_catalog: :449, :1632, :2054.

S8 (low, follow-up rather than a demand) — PrefillSlotPlan memoises a value that is already cached

helios/src/scheduler/policy.rs:89-96:

#[derive(Clone, Copy, Default)]
struct PrefillSlotPlan {
    ready: bool,
    cut: Option<usize>,
    terminal_only: bool,
    nat_fit_ready: bool,
    nat_fit: Option<usize>,
}

filled by prefill_slot_state (policy.rs:501-516) and prefill_slot_nat_fit (:518-537). The cut half is redundant: estimated_checkpoint_cut (policy.rs:382) routes through checkpoint_selections (checkpoints.rs:410-428, called at checkpoints.rs:745-753), a per-planning-scope RefCell<Option<HashMap<..>>> cache. Only nat_fit genuinely needs memoising. If prefill_slot_state goes, the struct collapses to the single field (nat_fit: Option<Option<usize>>, or [Option<Option<usize>>; REQUEST_LANES]) and ready/cut/terminal_only/nat_fit_ready disappear. Worth noting the plumbing cost this parameter carries, because it argues for doing it soon rather than later: &mut [PrefillSlotPlan; REQUEST_LANES] is on two signatures (continuation_candidate policy.rs:1048, add_candidate :1436) and is passed at :1571, :1633, :1637, :1643, :1649, :2055, :2059, with fresh arrays allocated at :1599 and :2052.

S9 (low) — the runtime-design doc states the exploration rule twice

docs/scheduling-runtime-design.md:486-498 (exploration section) already carries the full rule:

"When active age-priced streams (decoding, resume, or terminal cleanup) exist and a measured sibling (PREFILL or TERMINAL_PREFILL) or strictly larger measured peer plus a positive lower floor (a smaller measured prefill peer or the fastest measured decode step) is available, unmeasured pure-prefill capacities up to the natural fit compete by ValueRate using that positive interpolated GPU estimate…"

and docs/scheduling-runtime-design.md:665-668 (dispatch pricing) restates it in compressed form: "Pure prefill dispatch explores only capacities up to the natural-fit capacity (the natural fit alone when no active age-priced streams exist)…". Since the two copies must stay in sync with policy.rs:1115-1139 and :1467-1491 (see S1), that is three places encoding one rule. Concretely: keep :486-505 as the normative statement and cut :665-668 to a cross-reference ("(exploration limits: see Pure prefill exploration above)"), or vice versa.


Checked and found already lean (stated plainly, so this reads as a verdict)

Suggested order of work

Land S1+S2+S3 as one mechanical "extract the shared exploration/discovery rules" commit — it removes ~80 lines, deletes a speculative memo, and eliminates the class of two-copies-drifting bug this PR most needs to avoid. S5 is a cheap, self-contained follow-up that also reduces the reach cost. S4, S6, S7, S9 are tidy-ups. S8 is a follow-up PR, not a #661 blocker.

Open questions / what I could not verify