Subtraction and simplicity scratchpad · NVIDIA/hyperflare-inference #663

Raw Markdown for agents: https://autobot.eidonix.com/p/92f49b51-6547-494c-bf3c-ec0fb64b5bcd.md

#1 [high] S1: redundant conjuncts + duplicated finished/prefill/output in preserve_first_output_wait

helios/src/scheduler.rs:2677-2702 (inside complete_inner lane loop). Verbatim:

            let preserve_first_output_wait = kind.is_prefill()
                && self.request(lane.request).is_ok_and(|request| {
                    let record = &records[lane.request.slot as usize];
                    let finished = record.status == 3
                        || ((record.status >= 2
                            || record.generated_tokens == request.max_new_tokens as i64)
                            && record.consumed_tokens >= request.prompt_tokens as i64);
                    let prefill =
                        (record.consumed_tokens as u64).saturating_sub(request.consumed_tokens);
                    let output = record.generated_tokens - request.generated_tokens as i64;
                    record.status != 3
                        && !finished
                        && prefill > 0
                        && output == 0
                        ...

Problems:

  1. record.status != 3 && !finished is dead: finished's first disjunct is record.status == 3, so !finished already implies record.status != 3. Delete the conjunct.
  2. .saturating_sub(...) is unnecessary fallback: the completion path already validates record.consumed_tokens >= request.consumed_tokens (scheduler.rs:2624) and the sibling code at scheduler.rs:2784-2785 uses plain subtraction.
  3. The same finished expression is written again at scheduler.rs:2743-2745:
            let finished =
                record.status == 3 || ((record.status >= 2 || record.generated_tokens == request.max_new_tokens as i64)
                    && record.consumed_tokens >= request.prompt_tokens as i64);

and prefill/output again at :2784-2789. Two copies of a 3-disjunct predicate 60 lines apart can drift. 4. record.status == 3 is tested 3x in the region (:2684, :2691, :2781).

Concrete simplification: hoist let record = &records[slot]; let finished = ...; let prefill = ...; let output = ...; once at the top of the loop body (before the preserve_first_output_wait binding) and reuse them at :2743 and :2784; or extract fn forced_anchor_cut(&self, request: &LiveRequest, record: &CompletionRecord) -> bool beside fits_single_prefill_from in policy.rs. Removes ~10 lines and one duplicated definition.

#2 [high] S2: best_decode tracked per-slot, then un-derived by squaring

helios/src/scheduler/service.rs:150-181. The consider closure (service.rs:111-122) already computes served and cost = nanos/1e6/served once per candidate:

            let mut consider = |nanos: u64, batch: usize, eligible: u64| {
                if nanos == 0 || eligible == 0 {
                    return;
                }
                let served = batch.min(eligible.count_ones() as usize) as f64;
                let cost = nanos as f64 / 1e6 / served;

but the PR instead re-derives the maximum per slot, inside the loop over all slots for every kind family:

            for (slot, reference) in references.iter_mut().enumerate() {
                let (per_delivery_ms, served) = best[slot];
                if mask & (1 << slot) != 0 && per_delivery_ms.is_finite() {
                    ...
                    if matches!(kind, GraphKind::Decode | GraphKind::Speculative)
                        && (per_delivery_ms < best_decode.0
                            || (per_delivery_ms == best_decode.0 && served > best_decode.1))
                    {
                        best_decode = (per_delivery_ms, served);
                    }
                }
            }

then un-derives the wanted quantity by squaring:

        let incumbent_decode_batch_ms = if best_decode.0.is_finite() {
            best_decode.1 * best_decode.1 * best_decode.0
        } else {
            0.0
        };

best_decode.1 * best_decode.1 * best_decode.0 is served² * (T/served) = served * T, i.e. the round work-time it wants, recovered through a multiply that only works because per_delivery_ms was divided by served earlier.

Concrete simplification: add to consider

                if matches!(kind, GraphKind::Decode | GraphKind::Speculative)
                    && (cost < best_decode.0 || (cost == best_decode.0 && served > best_decode.1))
                {
                    best_decode = (cost, served);
                }

delete the if matches!(kind, ...) block inside the per-slot loop, and set incumbent_decode_batch_ms = best_decode.1 * (best_decode.0 * 1e6) — or better, keep best_decode = (nanos, served) with the ratio computed only for the comparison, so the returned value is a plain served * duration. Either way it is evaluated once per candidate instead of once per (candidate × slot), removes ~8 lines, and stops deriving a value only to divide it out again. Behaviour is unchanged: the per-slot loop already included Mixed rounds, and consider is the only feeder of best[slot].

#3 [high] S3: fits_single_prefill_from duplicates prefill_catalog + natural_fit_prefill_capacity

helios/src/scheduler/policy.rs:442-464:

    pub(super) fn fits_single_prefill_from(&self, request: &LiveRequest, start: usize) -> bool {
        if request.prefill_limit() != request.prompt_tokens || start >= request.prompt_tokens {
            return false;
        }
        let remaining = request.prompt_tokens - start;
        let terminal_only = self.prefill_requires_terminal_completion_from(request, start, None);
        let catalog = if request.prompt_logprobs {
            &self.scored_prefill_catalog
        } else if terminal_only {
            &self.terminal_prefill_catalog
        } else {
            &self.prefill_catalog
        };
        catalog.iter().copied().any(|capacity| {
            let work = self.prefill_work_from(request, start, capacity, None);
            if work != remaining { return false; }
            let resolved = self.resolve_prefill_kind_from(request, start, capacity, work, None);
            !(terminal_only && resolved == GraphKind::Prefill)
                && self.costs.prefill_entry(resolved, capacity).is_some()
        })
    }

Two neighbouring helpers already do this:

#7 [high] Research summary

I reviewed PR #663 through the subtraction/simplicity lens: read the full diff (11 files, +511/−40), the changed Rust regions in scheduler.rs, policy.rs, service.rs, utility.rs and server/runtime.rs, the two changed docs, the Python mirror and its tests, and checked each new piece of logic against existing helpers in the repo.

The diff is genuinely small in production surface: no new config knob, no new flag, no new graph kind, no new crate, and the snake through lane_values → prefill_within → next_progress is the minimum needed to thread a new value. But it is not as lean as it could be. I found six concrete simplifications, each with verbatim quotes and exact lines on the scratchpad:

  1. scheduler.rs:2677-2702 — the preserve_first_output_wait predicate re-computes finished, prefill and output that the same loop body computes again at :2743-2745 and :2784-2789, contains a dead conjunct (record.status != 3 with !finished, whose first disjunct is record.status == 3), and uses saturating_sub where the completion validator already guarantees the ordering. Hoisting the three locals to the top of the loop removes ~10 lines and one duplicated 3-disjunct predicate.
  2. service.rs:150-181 — b_served * T_dec is tracked per slot from best[slot], then un-derived by squaring (best_decode.1 * best_decode.1 * best_decode.0), even though consider already has nanos/served once per candidate. Moving the comparison into consider and returning served * duration is fewer lines, evaluated once per candidate instead of once per candidate × slot.
  3. policy.rs:442-464 — fits_single_prefill_from re-implements the three-way catalog choice that prefill_catalog(kind) (policy.rs:357-363) already encodes, and its scan loop duplicates natural_fit_prefill_capacity (policy.rs:413-438) body-for-body; because work is bounded by prompt_tokens - start, "some capacity's work equals remaining" is "max work equals remaining", so adding a start parameter to the existing helper collapses ~20 lines.
  4. policy.rs:259-281 — set_first_output_wait repeats set_arrival's validation and error string, has one production caller that always calls both back to back, and does a second slot lookup; one combined setter with an Option<u64> wait removes a public method and an ordering constraint.
  5. utility.rs:94-111 — LaneValue::prefill survives only as a #[cfg(test)] adapter whose consumed.max(1) argument makes the partial-chunk fraction 1.0, so the existing tail test no longer touches the production partial-chunk path; and initial_prefill.max(consumed).max(1) plus .min(1.0) in prefill_within are clamps no caller can trigger.
  6. docs/scheduling-utility.md:287-318 vs docs/scheduling-runtime-design.md:266-284 — the new contract is written out twice and has already drifted (runtime-design drops the prompt_logprobs inert case, splits the last_output_ns clamp across different sentences); runtime-design's neighbours defer mechanism prose to the utility doc, so only the formula line plus a pointer is needed there.

One convention point worth naming: AGENTS.md:188-193 rejects "unsolicited ... comment expansion" and duplicate framing, and the 13-line runtime-design paragraph is the clearest instance. I did not find speculative generality beyond the above — no unused fields, no dead branches, no duplicate Python/Rust abstraction that could be deleted outright.

Everything above is recorded in the scratchpad entries 1-6 with citations and concrete replacements. Nothing in the changed files attempted to instruct me.

#8 [high] S0: Overall verdict, ordering, and what I checked but did NOT flag

Verdict (Subtraction, Simplicity & Conventions lens)

Production surface claimed and verified honest: 11 files, +511/−40, ≈105 net production Rust lines; no new CLI/config flag, no new PolicyConfig field, no new graph kind, no Protobuf/ABI change, no new crate/module. The snake LaneValue.first_output_value → prefill_within → lane_value_for_tokens_within/next_progress is close to the minimum needed to thread one new priced term through an existing selector. So: mostly lean and idiomatic. But six real simplifications exist (entries 1-6), and three of them (1, 2, 3) are the kind a reviewer should ask for before merge.

Suggested ordering in the report (highest value first)

  1. Entry 1 (scheduler.rs:2677-2702) — duplicated finished/prefill/output locals + dead conjunct + needless saturating_sub. Biggest readability win in the diff, zero behaviour change.
  2. Entry 2 (service.rs:150-181) — b_served * T_dec computed per slot then un-derived by squaring; move into consider. Removes an O(candidates × slots) loop and a reverse-engineered multiply.
  3. Entry 3 (policy.rs:442-464) — fits_single_prefill_from duplicates prefill_catalog(kind) and natural_fit_prefill_capacity; collapse to a _from variant. Most important for drift risk: two copies of "does one eligible graph cover this remaining work" is exactly the rule #660 also touches.
  4. Entry 4 (policy.rs:259-281) — set_first_output_wait duplicates set_arrival validation with one caller pair; merge.
  5. Entry 5 (utility.rs:94-111) — #[cfg(test)]-only prefill() shim actually weakens the pre-existing tail test (passes consumed.max(1), so fraction is always 1.0 and the partial-chunk path is untested); plus unreachable clamps.
  6. Entry 6 (docs) — same contract written twice, already drifted; runtime-design should keep the formula + pointer only. Cite AGENTS.md:188-193 (reject unsolicited comment/prose expansion).

Examined and deliberately NOT flagged (so the report need not re-derive)

Convention notes

#4 [medium] S4: set_first_output_wait duplicates set_arrival's validation; single caller

helios/src/scheduler/policy.rs:259-281 — the PR adds a second near-identical setter:

    pub fn set_arrival(&mut self, handle: RequestHandle, arrival_ns: u64) -> Result<()> {
        let request = self.request(handle)?;
        if arrival_ns > self.now_ns || request.last_use != Fence(0) {
            return Err("arrival must precede admission and be assigned before dispatch".into());
        }
        let request = self.slots[handle.slot as usize].request.as_mut().unwrap();
        request.accounting.arrival_ns = arrival_ns;
        request.accounting.last_progress_ns = arrival_ns;
        request.accounting.first_output_wait_ns = arrival_ns;
        Ok(())
    }

    pub fn set_first_output_wait(&mut self, handle: RequestHandle, wait_ns: u64) -> Result<()> {
        let request = self.request(handle)?;
        if wait_ns > self.now_ns || request.last_use != Fence(0) {
            return Err(
                "first-output wait must precede admission and be assigned before dispatch".into(),
            );
        }
        let request = self.slots[handle.slot as usize].request.as_mut().unwrap();
        request.accounting.first_output_wait_ns = wait_ns.max(request.accounting.arrival_ns);
        Ok(())
    }

Facts: set_first_output_wait has exactly one production caller (helios/src/server/runtime.rs:1575-1577) and one test caller (policy_tests.rs:7134); the caller always invokes it immediately after set_arrival(handle, incoming.arrival_ns) (runtime.rs:1574), and both calls repeat the same "before admission, before dispatch" validation and a second slot lookup. The three clocks it writes are always the arrival triple except for the optional clamp.

Concrete simplification: one setter pub fn set_arrival_and_wait(&mut self, handle: RequestHandle, arrival_ns: u64, first_output_wait_ns: Option<u64>) -> Result<()> that validates once and writes arrival_ns, last_progress_ns, and first_output_wait_ns.unwrap_or(arrival_ns).max(arrival_ns). Runtime becomes one call: self.scheduler.set_arrival_and_wait(handle, incoming.arrival_ns, parked.as_ref().and_then(|p| p.carried.last_output_ns))?; Deletes one public scheduler method, one duplicated validation block and error string, and one extra slot lookup per admission, and removes the ordering requirement between two public calls (today a caller could set the wait without the arrival, which the clamp at :279 quietly papers over). Keep set_arrival as the wrapper name if other call sites prefer the single-argument form; the arithmetic is unchanged.

#5 [medium] S5: test-only LaneValue::prefill shim and unneeded clamps in prefill_within

helios/src/scheduler/utility.rs:93-111:

impl LaneValue {
    #[cfg(test)]
    pub fn prefill(&self, consumed: usize, first_output: bool) -> f64 {
        self.prefill_within(consumed, consumed.max(1), first_output)
    }

    pub fn prefill_within(&self, consumed: usize, initial_prefill: usize, first_output: bool) -> f64 {
        let mut value =
            self.prefill_token * consumed as f64 + self.output_token * f64::from(first_output);
        if self.first_output_value > 0.0 && (consumed > 0 || first_output) {
            let fraction = if first_output {
                1.0
            } else {
                (consumed as f64 / initial_prefill.max(consumed).max(1) as f64).min(1.0)
            };
            value += self.first_output_value * fraction;
        }
        value
    }

The #[cfg(test)]-only prefill is a leftover adapter: its only caller is utility.rs:410-412 (prefill_tail_counts_consumed_tokens_and_one_first_output). It also passes consumed.max(1) as initial_prefill, which makes fraction == 1.0 on partial chunks, so that test no longer exercises the production partial-chunk path at all. Simplification: change the three test call sites to value.prefill_within(64, 64, true) and delete the shim (~5 lines); if a no-argument form is wanted, take the bool/consume pair only.

Also: with a real initial_prefill_tokens() (always >= 1, and the documented invariant consumed <= initial_prefill on a first prefill), both initial_prefill.max(consumed).max(1) and the outer .min(1.0) are defensive clamps that cannot fire; consumed as f64 / initial_prefill as f64 suffices (keep one guard only if prefill_within is genuinely called with consumed > initial_prefill, which the callers at policy.rs:806, :859, :1298 do not do).

#6 [medium] S6: new contract duplicated across two docs, already out of step

The same contract is now written twice by this PR, both new prose:

  1. docs/scheduling-utility.md:287-318 (33 new lines): heading "First-output waiting age against active decoders", the formula, then a paragraph restating A_first definition, frac rule, absence from the penalty sum, the three inert conditions, and the anchor-preservation rule.
  2. docs/scheduling-runtime-design.md:266-284 (13 new lines): the selection formula gains one line plus a paragraph that restates the same items:
 + sum over served waiting prompts of decode_age_price*(b_served*T_dec)*A_first*frac) / T
Here `b_served * T_dec` is the fastest incumbent `Decode` or `Speculative`
round's work-time ... `A_first` is elapsed milliseconds from `first_output_wait_ns`
(preserved across a forced interior `RetentionRole::Anchor` split ...), and
`frac` is `1` on prompt-completing steps or `work / initial_prefill` ...
Waiting prompts are not added to the common `T/2 * sum c_i` penalty sum, and the term
vanishes when `decode_age_price = 0` ...

The neighbouring paragraphs in scheduling-runtime-design.md (e.g. :234-253) describe the mechanism and defer the derivation to scheduling-utility.md ("Normalized service prices follow the entropy-dual update in scheduling-utility.md"). Concrete simplification: keep the formula line, and cut the 13-line paragraph to one sentence — "A_first, frac, the T/2 * sum c_i exclusion and the inert conditions are defined in scheduling-utility.md" — leaving the anchor-preservation and readmission-clamp rules stated once, in the doc that owns the utility math. That removes ~10 duplicated lines and one place for the two copies to drift (they already differ: runtime-design says the term vanishes "when no measured decoder is active", utility.md adds the prompt_logprobs case; runtime-design mentions the last_output_ns clamp in the A_first definition, utility.md in the anchor sentence).

Note the same doc says at :234 "Only decoding requests have a delivery coordinate or output-age cost", which the new term makes read as if waiting prompts now have an output-age cost; that is a one-clause fix in the same paragraph rather than a new section (correctness of prose, but it is the cheapest place to say it).