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

Raw Markdown for agents: https://autobot.eidonix.com/p/c1cde688-85d0-467a-942e-765e73ba4f57.md

Subtraction, Simplicity & Conventions review — PR #693 (helios/scheduler: cache per-lane powered survival curves), head 000a6ac8

Key findings

The diff is materially leaner than the version the posted review saw (a9f7dd7), and I verified that in code, not from the author's claims: the Option<&mut CurveCache> wrapper layer, the duplicated mixed_catalog loop, the stack fallback cache, and the mislabelled CurveCache::new(false) are all genuinely gone. What remains is duplication, not bloat — the PR adds one abstraction (CurveCache) and then writes the same two identities around it three and four times. Five consolidations below, in value order; none is a rescue, and none requires new behavior.

  1. F1 (high) — the adaptive_verification_alpha == 1.0 identity is now written four times in rounds.rs, three of them new in this PR.
  2. F2 (high) — the PR ships a per-lane curve cache but leaves three hand-rolled get_or_insert_with / uncached rebuild sites (service.rs:322/337, service.rs:352/386-387, policy.rs:1999-2007) that the new cached_expected_tokens / cached_lane_value replace line-for-line — and replacing them would close three of the four "outside the cache" gaps the description discloses, with less code than exists today.
  3. F3 (med) — the width <= 1 ⇒ f64::from(width != 0) identity is encoded in three places, one of which (rounds.rs:1028-1030) already produces it by construction.
  4. F4 (med) — test-only CURVE_EVALUATIONS thread-local plus three of the four new tests exist only to assert the counter's own value; the load-bearing parity test needs none of it. AGENTS.md:194-199.
  5. F6 (low) — cached_lane_value is a one-line forwarder with one production caller.
  6. F5 (low, informational) — optimistic is stored in CurveCache solely for a debug_assert_eq! and re-passed at every call site. Keep it: it caught a real construction bug at a9f7dd7.

Also stated plainly below: what the PR correctly deleted (so a maintainer can see the subtraction lens is not asking it to undo good work), plus open questions and citations I could not verify.


F1 (high) — alpha == 1.0 fast path duplicated four times in rounds.rs

Three of these four copies are introduced by this PR (the diff at helios/src/scheduler/rounds.rs shows all three as + lines).

helios/src/scheduler/rounds.rs:571-577 (prefix_lengths_with_values, inside std::array::from_fn):

                let alpha = self.policy.adaptive_verification_alpha;
                request.acceptance.curve(request.generated_tokens, optimistic)
                    .into_iter().map(|probability| {
                        let powered = if alpha == 1.0 { probability } else { probability.powf(alpha) };
                        powered * values[slot].output_token
                    }).collect()

helios/src/scheduler/rounds.rs:599-605 (host_prefix_ranking):

            let alpha = self.policy.adaptive_verification_alpha;
            let curve = request.acceptance.curve(request.generated_tokens, optimistic);
            probabilities[slot] = if alpha == 1.0 {
                curve
            } else {
                curve.into_iter().map(|probability| probability.powf(alpha)).collect()
            };

helios/src/scheduler/rounds.rs:645-656 (powered_curve):

    pub(super) fn powered_curve(&self, request: &LiveRequest, optimistic: bool) -> Vec<f64> {
        #[cfg(test)]
        CURVE_EVALUATIONS.set(CURVE_EVALUATIONS.get() + 1);
        let curve = self.speculative_curve(request, optimistic);
        if self.policy.adaptive_verification_alpha == 1.0 {
            return curve;
        }
        curve
            .into_iter()
            .map(|p| p.powf(self.policy.adaptive_verification_alpha))
            .collect()
    }

And the pre-existing fourth copy, helios/src/scheduler/rounds.rs:882-885 (fixed-prefix path, untouched by this PR, same predicate written a third way):

                            .iter().map(|&probability| {
                                if self.policy.adaptive_verification_alpha == 1.0 { probability }
                                else { probability.powf(self.policy.adaptive_verification_alpha) }
                            }).sum::<f64>();

Concrete simplification. Add one helper on RequestScheduler (next to powered_curve, rounds.rs:644) and delete all four inline predicates:

/// Prefix survival raised to the adaptive verification exponent (`powf(p, 1.0) == p`).
fn powered(&self, probability: f64) -> f64 {
    match self.policy.adaptive_verification_alpha {
        1.0 => probability,
        alpha => probability.powf(alpha),
    }
}

Then rounds.rs:571-577 becomes curve.into_iter().map(|p| self.powered(p) * values[slot].output_token).collect(); rounds.rs:599-605 becomes probabilities[slot] = request.acceptance.curve(..).into_iter().map(|p| self.powered(p)).collect();; rounds.rs:645-656 becomes self.speculative_curve(request, optimistic).into_iter().map(|p| self.powered(p)).collect() (losing the return curve early-return and the separate alpha binding); rounds.rs:882-885 collapses to .map(|&p| self.powered(p)).sum::<f64>(). Net: roughly −15 lines, one statement of each fact, and the fast path applies uniformly to the fourth site that this PR left inconsistent.

Caveat worth flagging to the correctness lens rather than duplicating: match self.policy.adaptive_verification_alpha { 1.0 => .. } and == 1.0 are the same predicate, so this is a pure refactor.

F2 (high) — the new cache is not used at the three remaining rebuild sites; using it is shorter than what is there

This is the biggest subtraction available, because the PR's own description lists these sites as a limitation ("Scope note: outside candidates(), select_plan() still evaluates per-lane curves in lane_values() ... and on resize_prefill"). The code needed to close them already exists in this diff.

Site A — helios/src/scheduler/service.rs:322 + :337 (service_rates):

            let mut curve = None;
...
                                let curve = curve.get_or_insert_with(|| self.powered_curve(request, false));
                                consider(
                                    GraphKind::Speculative,
                                    batch,
                                    width,
                                    super::rounds::forecast_tokens(curve, tokens),
                                    true,
                                );

Site B — helios/src/scheduler/service.rs:352 + :386-387 (same function, mixed_catalog loop):

            let mut mixed_curve = None;
...
                            let curve = mixed_curve
                                .get_or_insert_with(|| self.powered_curve(request, false));
                            super::rounds::forecast_tokens(curve, tokens)

Both are hand-rolled single-mode instances of exactly what CurveCache now provides, including the false (non-optimistic) tag. Replace with let mut curves = CurveCache::new(false); before the loop and self.cached_expected_tokens(request, tokens, false, &mut curves) at the use sites — i.e. delete the let mut curve = None; / let mut mixed_curve = None; declarations, the if tokens > 0 + get_or_insert_with two-step, and the forecast_tokens(curve, tokens) call, which cached_expected_tokens already performs (policy.rs:1404). Note that this also removes the tokens > 0 guard at service.rs:336/:382, since cached_expected_tokens short-circuits tokens <= 1 itself (policy.rs:1396-1398) — but check that equivalence with the correctness lens before deleting the guard, because consider(...) also consumed the tokens > 0 decision.

Site C — helios/src/scheduler/policy.rs:1999-2007 (resize_prefill, fully uncached; the inline expansion is this PR's own line-1997-adjacent code path, and :1997 already uses the new prefill_lane_value):

            let decode = if self.speculative_widths.is_empty() { GraphKind::Decode } else { GraphKind::Speculative };
            expected += bits(candidate.mask & !(1 << slot)).map(|slot| {
                let r = self.slots[slot].request.as_ref().unwrap();
                let tokens = self.lane_tokens(r, decode, candidate.capacity);
                values[slot].decode(
                    self.expected_speculative_tokens(r, tokens),
                    duration_ns as f64 / 1e6,
                )
            }).sum::<f64>();

Replace by hoisting let mut curves = CurveCache::new(false); above the bits(..).map and reducing the closure body to self.cached_lane_value(r, decode, candidate.capacity, duration_ns, values[slot], &mut curves) — four lines removed and the only caller that still calls expected_speculative_tokens per lane disappears. (cached_lane_value takes capacity and calls lane_tokens itself at policy.rs:1461, so the let tokens line goes too.)

Why this matters beyond aesthetics: the PR's motivating cost is powf in powered_curve, and it documents these call paths as out of reach. They are in reach for a net line reduction, because the abstraction this PR adds is precisely the one they need. If a maintainer rejects the extension as scope creep, that is a legitimate call — but the PR should then say the omission is deliberate, not merely note it.

F3 (med) — the width <= 1 identity is stated three times; one is enough

helios/src/scheduler/rounds.rs:1027-1030 already returns that exact value by construction (empty slice sums to 0.0):

/// Expected tokens from a round of `width` positions with powered prefix survival.
pub(super) fn forecast_tokens(powered: &[f64], width: usize) -> f64 {
    f64::from(width != 0) + powered[..width.saturating_sub(1)].iter().sum::<f64>()
}

helios/src/scheduler/rounds.rs:637-642 re-states it (new in this PR):

    pub(super) fn proposal_forecast_tokens(&self, request: &LiveRequest, width: usize, optimistic: bool) -> f64 {
        if width <= 1 {
            return f64::from(width != 0);
        }
        forecast_tokens(&self.powered_curve(request, optimistic), width)
    }

helios/src/scheduler/policy.rs:1389-1398 re-states it a third time (new in this PR):

    fn cached_expected_tokens(
        &self,
        r: &LiveRequest,
        tokens: usize,
        optimistic: bool,
        curves: &mut CurveCache,
    ) -> f64 {
        if tokens <= 1 {
            return f64::from(tokens != 0);
        }

Simplification: keep only the policy.rs:1396 guard (it is the load-bearing one — it avoids building the curve, which proposal_forecast_tokens's copy does not: that guard saves a powered_curve call, so it has independent value, but the value is "don't build the curve", not "compute the identity"), and delete the rounds.rs:638-640 copy only if powered_curve + forecast_tokens is acceptable to call for width 1. If both guards are kept for cost reasons, say the identity once in the forecast_tokens doc comment (currently rounds.rs:1027) and have both guards read // see forecast_tokens — three literal copies of f64::from(x != 0) invite exactly the divergence the PR spent effort avoiding elsewhere.

F4 (med) — test-only counter instrumentation inside the function under optimization

helios/src/scheduler/rounds.rs:10-14 (new in this PR):

#[cfg(test)]
thread_local! {
    /// Powered speculative curve evaluations on this thread, for tests that bound planning work.
    pub(super) static CURVE_EVALUATIONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

and helios/src/scheduler/rounds.rs:646-647 increments it as the first statement of powered_curve — the hot function the PR exists to make cheaper.

Counter readers: policy_tests.rs:9502/9504/9533/9535/9556/9562/9665/9668/9695/9698 — i.e. tests waiting_init_prices_each_decoding_lane_curve_once_per_candidate_pass (:9489), mixed_candidates_price_each_decoding_lane_curve_once_per_call (:9517), decode_only_candidate_pass_builds_no_forecast_curve (:9547), plus count assertions inside the parity test. CurveCache::is_cached (policy.rs:126-129, #[cfg(test)]) has exactly one caller, policy_tests.rs:9660-9661.

The dossier records that a #540 review asked for this same counter family to be deleted, that main carries neither this counter nor zero_duration, and that this PR re-adds it without the CPU table that used to justify it. AGENTS.md:194-199 is the convention that applies: "Require focused, meaningful validation. Tests must exercise the affected behavior or contract; source-text checks and mocks that bypass the behavior cannot establish runtime correctness." A thread-local bump counter is not quite a source-text check, but it validates an implementation detail rather than a behavior — and there is a precedent (cost.rs:15-19 ENTRY_LOOKUPS), so this is a judgment call rather than a violation.

Concrete: the behaviorally load-bearing test is cached_lane_pricing_matches_uncached_for_unit_and_fractional_alpha (policy_tests.rs:9568-9804), which asserts score.to_bits() parity against the uncached path and needs no counter. Deleting CURVE_EVALUATIONS, its increment, the three count-only tests, and CurveCache::is_cached removes ~15 production lines and ~80 test lines while leaving the bit-exactness guarantee — the one property a maintainer actually cares about here — fully tested. If the "at most once" bound must be tested, one assertion inside the parity test (as already happens at :9665-9668) covers it without a dedicated thread_local! in the optimized function.

F6 (low) — cached_lane_value is a one-line forwarder

helios/src/scheduler/policy.rs:1436-1446:

    pub(super) fn cached_lane_value(
        &self,
        r: &LiveRequest,
        kind: GraphKind,
        capacity: usize,
        duration_ns: u64,
        value: LaneValue,
        curves: &mut CurveCache,
    ) -> f64 {
        self.cached_lane_value_within(r, kind, capacity, 0, duration_ns, value, curves)
    }

with cached_lane_value_within (:1448-1467) itself a one-line forwarder to cached_lane_value_for_tokens_within (:1491). Production callers of the three-arg-shortened form: policy.rs:1578 (add_candidate) and policy.rs:1767 (mixed_candidates_with_curves); test use at policy_tests.rs:9653. So it is a 6-argument wrapper whose only job is to supply a literal 0 for preceding_ns.

Simplification: delete cached_lane_value and have both call sites pass 0 to cached_lane_value_within — or, better, make cached_lane_value_within's preceding_ns Option<u64>/defaulted at the two call sites that genuinely want zero and keep one name instead of three. That removes ~11 lines and one hop in a chain whose names (cached_lane_value / cached_lane_value_within / cached_lane_value_for_tokens_within) already differ only by preposition. Counter-argument: the naming mirrors main's existing lane_value/lane_value_within pair, so a maintainer may prefer symmetry — low priority, listed for completeness.

F5 (low, informational) — mode passed twice

CurveCache stores optimistic (policy.rs:100-103) only to debug_assert_eq! it (policy.rs:119-122), yet every call passes it again (policy.rs:1399-1403, rounds.rs:906). Recommend keeping as-is: the dossier confirms this guard caught a real mislabelled-construction bug at a9f7dd7, which is exactly the concrete justification AGENTS.md:188-193 asks for before adding a switch. Not a finding, recorded so the recommendation is not re-raised.


What the PR correctly deleted (so the above is not read as asking to restore it)

  1. main's local array cache in packed_round_candidates is gone. The rounds.rs diff removes let mut curves: [Option<Vec<f64>>; REQUEST_LANES] = std::array::from_fn(|_| None); and its comment "Lane forecasts stay fixed while shapes compete; evaluate each at most once.", replaced by the shared CurveCache at rounds.rs:855 (wrapper) and :906 (use). That is a real de-duplication of two identical caches.
  2. Ignored arguments dropped. add_prefill_candidate now calls self.prefill_lane_value(r, kind, work, values[slot]) (policy.rs:1536) and the prefill arm at policy.rs:1997 does the same, where main threaded duration_ns into lane_value_for_tokens and never used it. The prefill_lane_value extraction (policy.rs:1407-1434) is a net simplification and is correctly named.
  3. The post-review collapse is real in code, not just claimed: let mut curves = CurveCache::new(optimistic); at policy.rs:1705; a single mixed_catalog loop in next_progress (verified by reading the spec that policy.rs:990-1013 reads clean and the early-return/duplicate-loop structure described in the prior report is absent); curves: &mut CurveCache parameter threading with no stack fallback.

Net judgment: this is close to lean and idiomatic. F1 and F2 are the two worth acting on; F3 and F4 are cheap wins; F6 is optional polish.

Open questions

  1. Are service.rs:322/352 and policy.rs:1999-2007 (F2) deliberately out of scope, or simply not noticed? The description discloses them but gives no reason, and fixing them reduces line count — #547 discusses only resize_prefill, not coalescing_prefill_log_bonus or service_rates.
  2. If CURVE_EVALUATIONS (F4) is re-added after a #540 review asked for its deletion, is there a maintainer who still wants the bound asserted by counter rather than by the bit-exactness parity test?
  3. Does the performance label stay on a PR that now explicitly claims no speedup? That is a labeling question for the maintainers, not a code finding.

What I could not verify