Subtraction, Simplicity & Conventions — PR #693
Key findings
- The same optimization is expressed twice. Six near-identical wrappers now surround one computation (
lane_value,cached_lane_value,cached_lane_value_within,lane_value_for_tokens,lane_value_for_tokens_within,cached_lane_value_for_tokens_within), and theOption<&mut CurveCache>parameter plus itsNone => self.expected_speculative_tokens(...)fallback exists to serve exactly one production site,policy.rs:1997. Delete theOption, thread one&mut CurveCachethroughresize_prefill, and roughly 40 production lines go with no behavioural change (policy.rs:1387-1524). CurveCache.optimisticis dead state and is already inconsistent at one call site. Delete the field, theoptimisticargument ofget_or_insert_with, and thedebug_assert_eq!rather than patchingpolicy.rs:1714(policy.rs:98-130vspolicy.rs:1714androunds.rs:844).- The
tokens <= 1short-circuit is written twice, in two modules, both encodingf64::from(tokens != 0), which is exactly whatforecast_tokensalready returns for width ≤ 1 (rounds.rs:626-631vspolicy.rs:1393-1395). CURVE_EVALUATIONSand three of the four new tests re-add a test-only counter that the review of #540 asked to be deleted, and after this PR's own alpha-1 shortcut the counter no longer measures thepowfcost it was introduced to bound (rounds.rs:10-14,:634-636;policy_tests.rs:9489/9517/9545).- Everything else is lean and idiomatic. The alpha-1 shortcut, the
limit <= 1 { continue; }skip, and the slot-indexed fixed array all fit existing module conventions; noAGENTS.mdstructural rule (env var, flag, per-model branch, fallback layer) is violated.
Correction to my working notes: I initially believed the None arm was production-unreachable. That is wrong — policy.rs:1997 reaches it. The finding below is restated on the verified reachability.
1. Option<&mut CurveCache>, its None fallback, and the six-wrapper family — delete the Option, thread the single remaining caller
helios/src/scheduler/policy.rs:1387-1404:
fn cached_expected_tokens(
&self,
r: &LiveRequest,
tokens: usize,
curves: Option<&mut CurveCache>,
) -> f64 {
if tokens <= 1 {
return f64::from(tokens != 0);
}
match curves {
Some(curves) => {
let curve = curves
.get_or_insert_with(r.handle.slot as usize, false, || self.powered_curve(r, false));
super::rounds::forecast_tokens(curve, tokens)
}
None => self.expected_speculative_tokens(r, tokens),
}
}
Verified reachability of the None arm (I traced every None producer):
policy.rs:1406-1423lane_value(...)→None. Its only production decode-side caller ispolicy.rs:1756, inside theSome(GraphKind::Prefill)match arm ofmixed_candidates_with_curves, so it always takes the prefill arm atpolicy.rs:1492and never reachescached_expected_tokens. Everything else is test-only (policy_tests.rs:9646, 9700).policy.rs:1469-1479lane_value_for_tokens_within(...)→None; callerspolicy.rs:1171(guarded byif following.is_prefill(), andfollowing_kindatpolicy.rs:1068-1090returns only prefill kinds orResume, which is priced atpolicy.rs:1519-1521with a literal1.0) andpolicy.rs:1545(add_prefill_candidate, prefill kinds only).policy.rs:1993→ prefill arm after theif mixed { GraphKind::Prefill }rewrite atpolicy.rs:1992.policy.rs:1994-1999is the one real user of the fallback:
if mixed {
let decode = if self.speculative_widths.is_empty() { GraphKind::Decode } else { GraphKind::Speculative };
expected += bits(candidate.mask & !(1 << slot)).map(|slot| {
self.lane_value(self.slots[slot].request.as_ref().unwrap(), decode,
candidate.capacity, duration_ns, values[slot])
}).sum::<f64>();
}
So an entire Option marshalled through cached_expected_tokens, cached_lane_value_for_tokens_within, prerequisite_value (policy.rs:1021) and next_progress (policy.rs:900) exists for one line, and next_progress pays for it with a throwaway allocation on the None path.
Concrete simplification:
- Change the parameter to
curves: &mut CurveCachein all four functions; delete theNone =>arm atpolicy.rs:1402. resize_prefill(policy.rs:1947-2007) allocates onelet mut curves = CurveCache::new();at entry and passes&mut curvesatpolicy.rs:1993andpolicy.rs:1997;add_prefill_candidate(policy.rs:1527) and the prefill arm do the same. That is 3 short-lived dedups per resized candidate in place of the current uncached re-pricing, i.e. strictly less work.- Then
lane_value,lane_value_for_tokens,lane_value_for_tokens_withinandlane_value_within-style wrappers collapse: keep one pair (cached_lane_value(r, kind, capacity, …)andcached_lane_value_for_tokens_within(r, kind, tokens, …)) and droplane_value/lane_value_for_tokens/lane_value_for_tokens_withinentirely (their prefill-only callers do not read a curve). Test callers atpolicy_tests.rs:9318, 9340, 9399, 9436, 9472, 9646, 9700just construct a local cache; the equality test already rebuilds the uncached reference by hand atpolicy_tests.rs:9623-9634. - Result:
expected_speculative_tokens(rounds.rs:622) loses its only in-scheduler caller (policy.rs:1402) — confirm with a repo-wide search before deleting, but on this reading it becomes dead code and should go with theNonearm.
2. Delete CurveCache.optimistic — it is dead state, and it is already wrong at one call site
helios/src/scheduler/policy.rs:98-130:
/// Per-slot memoization of powered speculative survival curves within one pricing pass.
/// Each cache instance is bound to one `optimistic` mode so optimistic and ordinary curves never mix.
pub(super) struct CurveCache {
optimistic: bool,
entries: [Option<Vec<f64>>; REQUEST_LANES],
}
...
pub(super) fn get_or_insert_with(
&mut self,
slot: usize,
optimistic: bool,
build: impl FnOnce() -> Vec<f64>,
) -> &[f64] {
debug_assert_eq!(
self.optimistic, optimistic,
"CurveCache cannot mix optimistic and non-optimistic survival curves"
);
self.entries[slot].get_or_insert_with(build)
}
Nothing reads an optimistic curve back out of the cache: the optimistic mixed branch bypasses it outright —
Some(kind) if kind == decode => {
decoders[count] = (
slot,
if optimistic { values[slot].decode(self.optimistic_tokens(r, self.speculative_tokens(r, width)), duration_ns as f64 / 1e6) }
else { self.cached_lane_value(r, decode, width, duration_ns, values[slot], curves) },
);
(policy.rs:1767-1774, bypass at :1770), and the ordinary scheduler path passes a literal false at policy.rs:1399. Meanwhile the two construction sites disagree:
policy.rs:1714:let mut curves = CurveCache::new(false);insidemixed_candidates(..., optimistic: bool)atpolicy.rs:1707-1716, which then forwardsoptimistictomixed_candidates_with_curves(policy.rs:1723) — so a cache created for one mode is documented to serve the other.rounds.rs:844:CurveCache::new(optimistic)(per the PR description / dossier; not re-read this turn).
Do not fix policy.rs:1714 to CurveCache::new(optimistic). That keeps a field, a parameter on two public-ish constructors, a per-call bool in every signature, a debug assertion and a latent trap, all guarding a distinction no code observes. Delete optimistic from the struct, new(), and get_or_insert_with(&mut self, slot, build), delete the doc sentence at policy.rs:99 and the debug_assert_eq! at :119-122, and change the call sites to CurveCache::new() / get_or_insert_with(slot, …). This is the "delete the workaround, don't patch it" case: pure subtraction, no behaviour touched, and it removes the only reason the tag inconsistency matters.
3. The tokens <= 1 short-circuit is duplicated across modules — keep it in one place
helios/src/scheduler/rounds.rs:626-631:
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)
}
is the same rule the PR adds at policy.rs:1393-1395:
if tokens <= 1 {
return f64::from(tokens != 0);
}
Both encode f64::from(tokens != 0), which is exactly what forecast_tokens computes on its own — f64::from(width != 0) + powered[..width.saturating_sub(1)].iter().sum() (rounds.rs:1016-1019), whose sum is empty for width <= 1. So the guard is an optimization tweak, not a distinct rule, and it now exists in two forms in two files with no shared name. After finding 1 there is one expected-tokens function anyway; fold the guard into it and have the width-form (proposal_forecast_tokens) delegate. If you want to keep the guard at both layers for the hot path, at least express it once, e.g. fn forecast_tokens_upto(powered, width) in rounds.rs and call it from policy.rs, so the identity "0/1 tokens ⇒ 0.0/1.0" is stated in one place and cannot drift.
4. CURVE_EVALUATIONS + is_cached + three of the four new tests re-add what #540's review asked to be removed
helios/src/scheduler/rounds.rs:10-14:
#[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 rounds.rs:634-636: #[cfg(test)] CURVE_EVALUATIONS.set(CURVE_EVALUATIONS.get() + 1);
Per the dossier, this counter and its two call-count tests were introduced in #540 and the review of #540 recommended deleting both ("Subtract/Simplify"); neither exists on main today, so #693 reintroduces them without saying why. It backs three tests — waiting_init_prices_each_decoding_lane_curve_once_per_candidate_pass (policy_tests.rs:9489), mixed_candidates_price_each_decoding_lane_curve_once_per_call (:9517), decode_only_candidate_pass_builds_no_forecast_curve (:9545) — plus the #[cfg(test)] accessor is_cached (policy.rs:126-129), used only at policy_tests.rs:9645-9653.
Two further reasons it is the wrong instrument here:
- It counts
powered_curveentries, notpowfcalls. After this PR's own alpha-1 shortcut (rounds.rs:638-640) a counted "evaluation" can be a barespeculative_curveclone, so the assertion no longer bounds the cost the PR set out to remove — it bounds a proxy that the PR itself weakened. - The argument that actually carries the PR is
cached_lane_pricing_matches_uncached_for_unit_and_fractional_alpha(policy_tests.rs:9567-9781), which asserts bit-equality of candidate keys, not call counts.
Recommendation: delete CURVE_EVALUATIONS, is_cached and the three counting tests (~90 test lines plus the thread-local); if a bound is genuinely wanted, assert is_cached inside the equality test, which already loops the shapes. Contrast cost.rs:15-19's ENTRY_LOOKUPS, which is load-bearing for existing checkpoint tests — this counter has no such dependency.
5. Smaller, same-direction deletions
- Comment restated twice.
policy.rs:1641adds "Request and forecast state stay fixed within a candidate pass; evaluate each lane curve at most once." which restates theCurveCachedoc comment atpolicy.rs:98-99. Keep one. - Inconsistent visibility across a wrapper pair.
packed_round_candidates_with_curvesispub(super)(rounds.rs:849) but has one caller,policy.rs:1644, inside the same module tree, while its siblingmixed_candidates_with_curvesis private (policy.rs:1718). Make them the same (private where possible). - Stale
unwrap_or(&mut local_curves)pattern.policy.rs:957-959and theprerequisite_valuesignature atpolicy.rs:1015-1022both exist only because of finding 1; deleting theOptiondeletes both lines, and with them the fresh per-call allocationnext_progressnow performs on everyNonearrival.
What is already lean — do not touch
powered_curve'sadaptive_verification_alpha == 1.0fast path (rounds.rs:638-640) is the minimum possible form of that optimization.- The
limit <= 1 { continue; }skip in packed rounds (rounds.rs:892-894) is pure dead-work removal; the following loop isfor position in 0..limit.saturating_sub(1), so nothing is dropped. CurveCache's shape — fixed[Option<Vec<f64>>; REQUEST_LANES]indexed byr.handle.slot as usize, matching the existingvalues[slot]/bits(mask)convention — is the right shape for this module. NoHashMap, noRc, no interior mutability.- Conventions: nothing in the diff violates
AGENTS.md's structural rules — no env var, no config knob or new default, no per-model branch, no new fallback layer, nounsafe, no new dependency. Item 4 is the only convention-adjacent point (a test-only counter with no consumer onmain).
Net effect of all five: roughly 40-60 lines of production plumbing (the Option threading, the None arm, three wrapper functions, the mode tag, the expected_speculative_tokens residual) and ~100 lines of test scaffolding (counter, is_cached, three tests) disappear without losing a single behavioural assertion.
Open questions / could not verify
rounds.rscitations (:10-14,:622,:626-631,:634-636,:844,:892-894,:1016-1019) are taken from the PR description and dossier, not re-read in this session; the code quoted above frompolicy.rswas read directly at head.- Does
expected_speculative_tokens(rounds.rs:622) have any caller other than theNonearm atpolicy.rs:1402? If not, finding 1 makes it dead code — worth a grep before deleting. - Is threading a cache into
resize_prefillcheap enough to accept? It runs once per resized prefill candidate (policy.rs:1924-1935), so the extra dedup is strictly less work than today's uncached re-pricing atpolicy.rs:1993-1999, but that is a measurement I did not take. - Why re-add
CURVE_EVALUATIONSafter #540's review asked for its removal? No rationale in the PR. - The
next_progressbranch restructure (policy.rs:946-1012) is described only as "reuses cached_expected_tokens"; its equivalence is a correctness question for the Correctness lens, but note that it moved decode pricing inside theelseand now early-returns atpolicy.rs:980— if that restructure is not in fact needed for the cache, reverting it is the largest available subtraction of all.