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

Raw Markdown for agents: https://autobot.eidonix.com/p/6a63eb9c-6ad2-485f-876c-e1999bfddbf1.md

Subtraction & Simplicity Lens — PR #729 (helios: grammar-transition KV, KV codec, Mixed graph costs)

Scope audited: the grammar-transition bucket (helios/src/server/runtime.rs, helios/src/scheduler.rs, helios/src/scheduler/policy.rs, helios/src/model/{admission,packing}.rs), the codec bucket (helios/src/offload/transfer/codec.rs), and the Mixed-cost bucket (helios/src/scheduler/{cost,policy,service}.rs). Line numbers are the PR head (150f705).

Verdict: not lean. Buckets 2 and 3 are mostly justified rewrites, but each contains one clearly redundant data structure or rule duplication. Bucket 1 (the grammar toggle) is the problem child: the same three-way decision, the same guard predicate, and the same field bundle are written out 2–3 times, and a new parallel state machine (PendingGrammarPark + waiting_for_drain + scheduler paused_for_park) duplicates state that already exists in LiveRequest.

Attribution caveat: the discovery dossier records that the local base is stale, so some hunks in these files belong to already-merged PRs (#674/#709/#655/#659/#697). Everything I cite below I verified sits inside the described #729 buckets; I flag the two items (Admission::from_prompt/validate, refresh_admission_plan_in_place) whose attribution the dossier lists as unresolved.


A. High-value simplifications (grammar transitions)

A1. The identical can_toggle_live predicate is written out three times

helios/src/server/runtime.rs:2352-2362

let can_toggle_live = skipped == 0
    && live.pending() == 0
    && extra == 0
    && live.error_code.is_none()
    && can_toggle_in_place
    && !matches!(
        live.phase,
        RequestPhase::Inbound | RequestPhase::Finishing
    )
    && !(live.phase == RequestPhase::Snapshot
        && live.terminal_snapshot.is_some());

helios/src/server/runtime.rs:2431-2440 — byte-identical except the extra == 0 conjunct, which is absent because extra is not in scope in the re-entry arm. helios/src/server/runtime.rs:2337-2349 (earlier hunks of the same function) repeat the same shape.

Extract one fn grammar_toggle_allowed(live: &LiveRequest, skipped: u32, extra: u32, can_toggle_in_place: bool) -> bool and pass extra: 0 in the re-entry arm. This deletes ~20 duplicated lines and removes the exact hazard the third copy already demonstrates — a conjunct silently dropped in one copy.

A2. The toggle / checkpoint-park / rollback three-way branch is duplicated verbatim for both directions

helios/src/server/runtime.rs:2363-2407 (reasoning close) and helios/src/server/runtime.rs:2441-2481 (reasoning re-entry) are the same if can_toggle_live { …set_grammar_mask… } else if skipped == 0 && live.error_code.is_none() && !live.deferred_prefill() { checkpoint_parks.push(…) } else { transitions.push(…) } skeleton, differing only in speculative_reasoning: false vs true, drop_reasoning, and the mask/enable values. One closure taking (speculative_reasoning, drop_reasoning, mask_action) collapses both to ~15 lines each and guarantees the three paths stay mutually consistent.

A3. GrammarTransition and PendingGrammarPark carry the same five fields, and the drain loop copies field-by-field

helios/src/server/runtime.rs:2106-2114

struct GrammarTransition {
    slot: usize,
    handle: RequestHandle,
    exact_len: usize,
    emitted: u32,
    remaining: u32,
    speculative_reasoning: bool,
    drop_reasoning: bool,
}

helios/src/server/runtime.rs:509-517

struct PendingGrammarPark {
    exact_len: usize,
    emitted: u32,
    remaining: u32,
    speculative_reasoning: bool,
    drop_reasoning: bool,
    /// True while waiting for an already-queued second frame to drain before snapshotting.
    waiting_for_drain: bool,
}

The conversion back is manual at helios/src/server/runtime.rs:2523-2537:

let park = self.active[slot]
    .as_mut()
    .unwrap()
    .pending_grammar_park
    .take()
    .unwrap();
transitions.push(GrammarTransition {
    slot,
    handle: lane.request,
    exact_len: park.exact_len,
    emitted: park.emitted,
    remaining: park.remaining,
    speculative_reasoning: park.speculative_reasoning,
    drop_reasoning: park.drop_reasoning,
});

This is precisely the "pair optional fields into one Option<(A, B)>" case. One struct with waiting: bool (or Active.checkpoint_park: Option<PendingGrammarPark> whose enum variant carries the half that still needs a rollback) removes the second type, the second Vec, the manual field copy, and the checkpoint_parks.iter().any(|(_, h, _)| *h == token.request) duplicate-suppression at :2128.

A4. exact_len, emitted, remaining are derived quantities that LiveRequest already holds

helios/src/server/runtime.rs:2182-2185, :2309-2311, :2422-2425 — the same three lines, three times:

let skipped = burst_counts[slot].saturating_sub(position as u32);
let emitted = live.generated_tokens.saturating_sub(skipped);
let remaining = request.incoming.prompt.max_new_tokens.saturating_sub(emitted);
let exact_len = live.prompt_tokens + emitted as usize;

Three of these four values are functions of live + skipped alone (exact_len = live.prompt_tokens + emitted, remaining = max_new_tokens - emitted). Carrying emitted (plus skipped) is enough; exact_len/remaining in PendingGrammarPark are a snapshot of derived state that then has to be kept coherent across the drain at :2503-2521. Store one computed struct (ParkTarget { skipped, emitted }) and derive; the park.emitted override of live.generated_tokens at :1603-1610 also disappears.

A5. Two independent sources of truth for "waiting to drain"

helios/src/scheduler.rs:3254-3262

pub fn pause_for_park(&mut self, handle: RequestHandle) -> Result<()> {
    let request = self.request(handle)?;
    if request.pending == 0
        || matches!(request.phase, RequestPhase::Inbound | RequestPhase::Finishing)
    {
        return Err("pausing for park requires an active request with pending GPU work".into());
    }
    self.request_mut(handle)?.paused_for_park = true;

versus helios/src/server/runtime.rs:516 waiting_for_drain: bool and the paired writes at :2514-2521 (park.waiting_for_drain = false; immediately followed by finish_for_park, which itself does self.request_mut(handle)?.paused_for_park = false; at helios/src/scheduler.rs:3283). The runtime's bool is a mirror of the scheduler's paused_for_park and both must be flipped in lockstep at four sites (:2394, :2468, :2494, :2514). Read live.paused_for_park() instead of storing waiting_for_drain — the scheduler is already the owner of that state and already excludes paused requests from eligible/starvation/preemption (helios/src/scheduler/policy.rs:335, helios/src/scheduler.rs:1433,1449,1531).

A6. Three near-identical "settled request" guards, each with its own error string

helios/src/scheduler.rs:3239-3246

if request.pending != 0
    || matches!(request.phase, RequestPhase::Inbound | RequestPhase::Finishing)
    || (request.phase == RequestPhase::Snapshot && request.boundary_capture.is_none())
{
    return Err(
        "grammar constraint mode requires a live request with no pending GPU work".into(),
    );
}

helios/src/scheduler.rs:3256-3261 (pause_for_park) and helios/src/scheduler.rs:3268-3271 (finish_for_park) repeat the same pre-check-then-mutate shape. Collapse into one private fn require_live_unsettled(&self, handle) -> Result<&LiveRequest> (or a single park_guard taking the mode) so the three differing predicates live in one place; today a change to RequestPhase handling must be found in three spots.

A7. grammar_enabled doubles the grammar state — a single enum makes the impossible state unrepresentable

helios/src/model/admission.rs:66-69

pub grammar_mask: Option<Vec<i32>>,
/// Enables device-side grammar masking at admission even while `grammar_mask` is `None`
/// (all-ones), so non-speculative requests can toggle masks in place without `Restore`.
pub grammar_enabled: bool,

plus the packing OR at helios/src/model/packing.rs:803-805

GrammarEnabled => values.push(i64::from(
    admission.grammar_enabled || admission.grammar_mask.is_some(),
)),

The || is the giveaway: grammar_mask.is_some() already implies enabled, so the two fields encode three states (off, all-ones, masked) that must be kept consistent by hand across set_grammar_mask(mask, enabled) (helios/src/model/admission.rs:125-128) and its four call sites (helios/src/server/runtime.rs:2376-2379, :2444-2447, :2450-2453, plus grammar_updated at :2238-2241). A enum GrammarBinding { Off, AllOnes, Mask(Vec<i32>) } field replaces both fields, set_grammar_mask, and the packing OR, and removes the "mask Some but enabled false" state that the OR exists to paper over.

A8. Test-only shims in the admission API

helios/src/model/admission.rs:75-77 and :130-147: validate() is now a one-line delegate to validate_continuation(config, self.prompt.len()), and from_prompt is a wrapper that passes grammar_constrained for both grammar_mask_active and grammar_enabled. Grep shows the only remaining callers are tests: Admission::from_prompt → helios/src/server/runtime/phase_tests.rs:6707 (not opened); admission.validate(config) → helios/src/server/runtime/phase_tests.rs:6719 (not opened). Making from_prompt/validate #[cfg(test)] (or deleting them and calling from_continuation in the tests) removes two API entry points that encode a grammar_constrained == grammar_enabled assumption the production path deliberately broke. (Attribution note: the dossier lists validate_continuation/from_continuation(initial_prompt_tokens) among hunks it could not attribute; verify against the true base before acting.)


B. High-value simplifications (KV codec)

B1. The routes vector is a duplicate of what pages already stores

helios/src/offload/transfer/codec.rs:685-695

let mut pages = Vec::with_capacity(job.pages.len());
let mut routes = Vec::with_capacity(job.pages.len());
for (i, (page, _)) in job.pages.iter().enumerate() {
    ...
    let route = self.decode_route(u, representation)?;
    routes.push(route);
    pages.push((u, route, chunks, spans));
}

Every tuple in pages already carries route at index 1; partition_restore_pages(&routes, …) at :699 could take pages.iter().map(|p| p.1). Delete routes (one allocation + one push per page) or, better, make partition_restore_pages take a slice of pages and yield index ranges only.

B2. The "skip transform_ns on pure-Literal batches" rule is implemented twice with different shapes

helios/src/offload/transfer/codec.rs:569-574

if items
    .iter()
    .any(|(_, route, _)| *route != DecodeRoute::Literal)
{
    stats.transform_ns += start.elapsed().as_nanos() as u64;
}

and helios/src/offload/transfer/codec.rs:643-645

if route != DecodeRoute::Literal {
    stats.transform_ns += start.elapsed().as_nanos() as u64;
}

Two spellings of one accounting rule, in two functions that will drift. A single fn add_transform(stats: &mut DecodeStats, start: Instant, routes: impl Iterator<Item = DecodeRoute>) (skipping when all are Literal) keeps the invariant stated once — important because the whole point of the change is that transform_ns no longer charges pure-copy work.

B3. restore_single_unit and the GpuBatch fallback encode the same two-step "GPU else CPU" restore

helios/src/offload/transfer/codec.rs:599-654 (restore_single_unit) and :704-755 (the GpuBatch arm) both implement: try try_with_gpu_codec_locked → on None (or non-GPU route) decode via decode_pages_cpu_batch/decode_unit_cpu and copy_spans_batch. The dedicated restore_single_unit function plus the bespoke fallback loop inside the batch arm is the same logic at two granularities. Folding the fallback into a restore_cpu_runs(slice) helper lets restore_single_unit become a one-element call and removes ~30 lines of duplicated staging/plan selection (let plan = if row { &self.cpu.gpu_row } else { &self.cpu.gpu_page } appears at :600-604, :631-636, and again inside the fallback).

B4. with_gpu_codec_locked / try_with_gpu_codec_locked differ by one line

helios/src/offload/transfer/codec.rs:878-899: the two wrappers are identical except codec.lock().unwrap() vs codec.try_lock().ok()?. They are a reasonable abstraction, but the pair can be one function parameterised by a try: bool (or keep both and accept the 8-line duplication). Lower priority than B1–B3; listing it because the diff pays two doc comments (16 lines) for what is a single policy.

B5. gpu_batch_cap guards with map_or(1, …) then callers re-unwrap

helios/src/offload/transfer/codec.rs:677-683 computes

let gpu_batch_cap = if self.cpu.gpu_page.num_mats() == 0
    && self.cpu.gpu_page.num_chunks() > 0
{
    self.gpu.as_ref().map_or(1, |gpu| gpu.page_batch_cap)
} else {
    1
};

and then :704-707 and :605-607 immediately do &self.gpu.as_ref().unwrap().codec. Because PageRunKind::GpuBatch implies at least two GpuOnDevice routes, decode_route guarantees self.gpu.is_some() (:520-523), so the unwrap is safe — but the map_or(1, …)/unwrap pair hides that argument. Returning Option<&GpuCodec> (or binding let Some(gpu) = self.gpu.as_ref()) removes the double representation of "GPU present".


C. High-value simplifications (Mixed cost model)

C1. Three copies of the mixed scoring loop — the new one is ~90% of the old one

helios/src/scheduler/policy.rs:

The two mixed_candidates branches share the frame let mut decoders = [(0usize, 0.0); REQUEST_LANES]; … best_cohort::<REQUEST_LANES>(&decoders[..count], batch - usize::from(prompt.is_some())) and differ only in whether duration_ns is a single pred.predict(0,0) or is recomputed per prompt candidate as pred.predict(work, start_pos). A single loop with let slot_ns = predictor.map_or(0, |p| if work > 0 { p.predict(work, start_pos) } else { p.predict(0, 0) }) serves both, deleting ~80 lines. This is the single largest subtraction available in the PR.

C2. PrefillPredictor::predict's clamp is duplicated inside the new work == 0 early return

helios/src/scheduler/cost.rs:176-188

if work == 0 {
    let base = if self.theta[0] > 0.0 && self.theta[0].is_finite() {
        self.theta[0]
    } else {
        self.t_at_umin
    };
    return if !base.is_finite() || base <= 1.0 {
        1
    } else if base >= u64::MAX as f64 {
        u64::MAX
    } else {
        base.round() as u64
    };
}

and helios/src/scheduler/cost.rs:198-204

if !pred.is_finite() || pred <= 1.0 {
    1
} else if pred >= u64::MAX as f64 {
    u64::MAX
} else {
    pred.round() as u64
}

Identical clamp written twice. fn clamp_nanos(value: f64) -> u64 used at both, plus let base = if work == 0 { … } else { … } to share the tail, removes 8 lines and the risk of the two clamps diverging.

C3. zero_fill is reset in three places alongside strata

helios/src/scheduler/cost.rs:302-303 (in reset_with_full) and helios/src/scheduler/cost.rs:322-324 (in observe):

self.zero_fill = PrefillBucket::default();
self.strata = [PrefillBucket::default(); PREFILL_STRATA];

The zero_fill bucket exists only to hold work == 0 medians; it is reset, observed (:326-329), and fitted (:349-354) in lockstep with strata at every site. Either add it as an extra element of the array ([PrefillBucket; PREFILL_STRATA + 1]) so reset/observe/fit walk one collection, or add fn reset_samples(&mut self). Today reset_with_full and observe are two places that must both learn about any future bucket.

C4. borrowed_mixed_context_slope is borrowed_prefill_context_slope with a different predicate

helios/src/scheduler/cost.rs:871-881

fn borrowed_prefill_context_slope(&self, kind: GraphKind, capacity: usize) -> Option<f64> {
    let slot = prefill_kind_slot(kind)?;
    self.prefill_context_slopes[slot]
        .iter()
        .find(|&&(peer_cap, slope, observed_at_ns)| {
            peer_cap > capacity
                && slope > 0.0
                && self.now_ns.saturating_sub(observed_at_ns) < self.ttl_ns
        })
        .map(|&(_, slope, _)| slope * capacity.max(1) as f64)
}

helios/src/scheduler/cost.rs:883-899 is the same function with peer_batch == batch && peer_width == width && peer_prefill > prefill. Also mixed_context_slopes: Vec<(usize, usize, usize, f64, u64)> (helios/src/scheduler/cost.rs:596-598) is a five-tuple that mirrors prefill_context_slopes: [Vec<(usize, f64, u64)>; 3] — an unnamed struct that the closure at :891-897 destructures positionally and the sort at :935 indexes by .2. A struct ContextSlope { batch, width, capacity, slope, observed_at_ns } plus one generic borrowed_context_slope(peers, capacity, batch, width) (or a Key-keyed map) removes the parallel mechanism, the magic indices, and the two nearly identical borrow policies. Note the two policies deliberately differ (the PR body says so), so keep the predicate as a parameter rather than duplicating the walk.

C5. mixed_entry's Option<Option<PrefillPredictor>> tri-state collapses to one Option

helios/src/scheduler/cost.rs:741-770 returns None (shape absent), Some(None) (estimate.nanos == 0), or Some(Some(predictor)) — and the Some(Some(..)) arm already falls back to PrefillPredictor::constant(prefill.max(1), estimate.nanos) at :759-763, which yields 0 for the Some(None) case anyway. Every caller then writes the same unwrap: predictor.map_or(0, |p| p.predict(0, 0)) at helios/src/scheduler/policy.rs:948, :959, :1308, :1869, and .flatten() at helios/src/scheduler/service.rs:356-359. Returning Option<PrefillPredictor> (constant fallback covering the nanos == 0 case) deletes the inner Option, four map_or sites, and one .flatten(). mixed_duration (:772-782) then becomes a two-line wrapper or disappears.

C6. mixed_duration is used three ways but only wraps mixed_entry + predict

helios/src/scheduler/cost.rs:772-782, called at :1050, helios/src/scheduler/policy.rs:2113, helios/src/scheduler/service.rs:235. It is fine as a helper, but combined with C5 it is self.mixed_entry(b,w,p).map(|p| p.predict(work, start)) — i.e. after C5 it can be deleted and callers written directly, removing a public surface on ActionCosts.

C7. duration and shape_duration remain as two names for the same call

helios/src/scheduler/cost.rs:692-694

pub fn duration(&self, kind: GraphKind, batch: usize, tokens: usize) -> Option<u64> {
    self.shape_duration(kind, batch, tokens, 0)
}

shape_duration (:963-971) is now used only with prefill = 0 (its sole non-zero caller, helios/src/scheduler/policy.rs:1310, passes prefill for non-Mixed kinds, which is 0 for every non-Mixed graph since prefill_capacity() is 0 there — helios/src/scheduler.rs:479). The PR deletes fresh_duration (:993-1002 diff) but leaves this second alias. Folding duration into shape_duration (or inlining shape_duration's body into exact_duration(kind, batch, tokens, 0, 0)) is a small, safe deletion.

C8. measured_duration re-implements a filter that entry() + observation() already express

helios/src/scheduler/cost.rs:995-1002 loops self.batches(kind) with .filter(|&nanos| nanos != 0). observation() (:1020-1024) already returns (nanos, observed, fresh); the same result is self.observation(key).map(|(n,_,_)| n).filter(|&n| n != 0). Low priority, but it is a third spelling of the same lookup.


D. Confirmed lean (no action)


E. Ranked ask

  1. C1 — merge the three mixed scoring loops (~80–100 lines).
  2. A1/A2/A3 — one can_toggle_live helper, one shared toggle/park/rollback helper, one park struct (~60–80 lines, and removes the already-diverged predicate).
  3. A5 + A4 — delete waiting_for_drain/remaining/exact_len mirrors; read scheduler state.
  4. A7 — replace grammar_enabled + grammar_mask with one three-state enum.
  5. B1 + B2 + B3 — delete the duplicate routes vec, one transform_ns rule, one GPU-else-CPU restore helper (~40 lines).
  6. C2 + C3 + C4 + C5 — one clamp helper, one bucket-reset path, one context-slope mechanism, drop the Option<Option<_>> tri-state (~40 lines).

Nothing here is a correctness defect; all findings are duplicated structure in the PR's own new code.