Subtraction, Simplicity & Conventions review — PR #644
PR: NVIDIA/hyperflare-inference#644 "fix(helios): per-step speculative calibration and excluded-only waiting/delivery fairness" · base main 4ed5d875 · head 2b15114 · author lukealonso · 10 files, +649/−230.
Key findings
The diff is structurally lean: no new flags, config knobs, feature gates, fallback layers, version gate or compatibility shim, and no Protobuf/core-format/CUDA-graph file is touched — so "subtraction" in the usual sense (dead knobs, speculative generality) is largely satisfied. The weight of the review therefore falls on duplication inside the new code, which is the one place this PR spends more code than it needs:
helios/src/scheduler/rounds.rs— the "inherit the deepest observed shallower depth" walk exists twice, once in production (Forecast::prior_calibration_factor, 290-305) and once#[cfg(test)](Forecasts::calibration_factor, 364-375), differing only in whether a request-local slot is consulted. The unit tests assert against the test-only copy, so the two can silently drift.- Same file — the cumulative-product prefix loop exists twice (
speculative_curve451-455 for pricing,observe_packed_forecasts627-637 for observation). One helper removes ~12 lines and removes the possibility that the pricing path disagrees with the learning path. helios/src/scheduler/utility.rs:121-130—LaneValue::finish's first parametercompletion_msis dead after this PR (it now appears only in adebug_assert), yet three production call sites and one test still thread it, andpolicy.rs:723buildsfirst_mssolely to pass it. Pure subtraction: delete the parameter.helios/src/scheduler/service.rs— the delivery catalog scan is performed twice per plan, anddelivery_rate's magnitude has been reduced to one pre-measurement fallback while its presence is what all three consumers check (Some(_)bound then discarded at 313 and 411). Either keep one scan or collapse the tuple element to a presence flag.- The maximum delivery rate is now the literal
1.0at every observe site, with tell-tale discarded bindings;ServicePrice::observe'smaximum_ratenormalization is constant-1 for deliveries, i.e. the parameter has become vestigial on that path. - Docs left self-contradictory inside the files this PR edits (
docs/scheduling-runtime-design.mdkeeps three superseded passages;helios/README.mdkeeps the wrong clamp bound) — a conventions problem (AGENTS.md "state support as present qualification") whose root cause is that the same model is derived in two documents.
Detail, quotes and concrete replacements follow.
F1 (high) — duplicated calibration inheritance walk, production and test-only copies
helios/src/scheduler/rounds.rs:290-305 (production):
fn prior_calibration_factor(&self, depth: usize, global: &[DepthCalibration]) -> f64 {
if let Some(entry) = global.get(depth).filter(|entry| entry.observed) {
return entry.factor();
}
// Unobserved deeper prefixes inherit the deepest verified step's calibration
// rather than defaulting to unity, preventing upward drift when shallow shapes run.
for prev in (0..depth).rev() {
if let Some(factor) = self.calibration.get(prev).and_then(|entry| entry.local_factor()) {
return factor;
}
if let Some(entry) = global.get(prev).filter(|entry| entry.observed) {
return entry.factor();
}
}
global.get(depth).map_or(1.0, |entry| entry.factor())
}
helios/src/scheduler/rounds.rs:364-375 (test-only) is the same descending search with the request-local step removed:
#[cfg(test)]
pub(super) fn calibration_factor(&self, depth: usize) -> f64 {
if let Some(entry) = self.calibration.get(depth).filter(|entry| entry.observed) {
return entry.factor();
}
for prev in (0..depth).rev() {
if let Some(entry) = self.calibration.get(prev).filter(|entry| entry.observed) {
return entry.factor();
}
}
self.calibration.get(depth).map_or(1.0, |entry| entry.factor())
}
Concretely: extract one free function fn inherited_factor(local: Option<&[RequestCalibration]>, global: &[DepthCalibration], depth: usize) -> f64 holding the single loop, and have Forecast::prior_calibration_factor call it with Some(&self.calibration) while the #[cfg(test)] wrapper calls it with None. Two bodies become one; the test wrapper shrinks to one line.
Why it matters beyond tidiness: policy_tests.rs:5257-5518 asserts the inheritance behaviour through the test-only copy, not through the code that prices rounds. Any future fix to the production walk leaves the tests green — the duplication is what makes that possible.
F2 (high) — duplicated cumulative-product prefix loop (pricing vs. observation)
helios/src/scheduler/rounds.rs:451-455 (speculative_curve, the pricing path):
let mut cumulative_factor = 1.0f64;
let mut bound = 1.0f64;
forecast.prefixes.iter().enumerate().map(|(depth, estimate)| {
cumulative_factor *= forecast.calibration_factor(depth, &self.forecasts.calibration);
let calibrated = estimate.mean() * cumulative_factor;
helios/src/scheduler/rounds.rs:627-637 (observe_packed_forecasts, the learning path):
let cal_factors = if gpu_confidence && depth_limit >= 1 {
let mut cumulative_factor = 1.0f64;
(0..depth_limit)
.map(|depth| {
cumulative_factor *= forecast.calibration_factor(depth, &self.forecasts.calibration);
cumulative_factor
})
.collect::<Vec<_>>()
Concretely: one helper
fn calibrated_prefix_means(forecast: &Forecast, global: &[DepthCalibration], depth_limit: usize) -> (Vec<f64>, Vec<f64>)
returning the running calibration product and estimate.mean() * product, used by both sites. That deletes the second loop body (~12 lines) and, more importantly, guarantees the shape actually priced is the shape actually learned from. This matters here: the PR's whole defect ("calibration drift") is a disagreement between what was observed and what was priced, so keeping two copies of that multiplication is the one duplication worth eliminating first.
F3 (high, pure subtraction) — LaneValue::finish's completion_ms is dead
helios/src/scheduler/utility.rs:121-130:
pub fn finish(&self, completion_ms: f64, horizon_ms: f64) -> f64 {
debug_assert!(horizon_ms == 0.0 || completion_ms <= horizon_ms);
let mut value = self.terminal
+ self.age_price * self.reference_delivery_ms * (self.age_ms + horizon_ms);
if horizon_ms > 0.0 {
// A selected terminal row is being retired and then absent, so it is never excluded.
value += self.age_price * horizon_ms * (self.age_ms + horizon_ms / 2.0);
}
value
}
Before this PR the body used (horizon_ms - completion_ms); after it, completion_ms survives only in the debug_assert. Every caller still threads a value:
helios/src/scheduler/policy.rs:606—return value.finish(ms, ms);helios/src/scheduler/policy.rs:741—finishing[f] = (slot, values[slot].finish(first_ms, total_ms));helios/src/scheduler/policy.rs:872—terminal[count] = (slot, values[slot].finish(ms, ms));helios/src/scheduler/policy_tests.rs:3554—map(|slot| values[slot].finish(ms, ms)).sum();
Concretely: change the signature to pub fn finish(&self, horizon_ms: f64) -> f64. The three production call sites become value.finish(ms), values[slot].finish(total_ms), values[slot].finish(ms), and helios/src/scheduler/policy.rs:723 (let first_ms = duration_ns as f64 / 1e6;) becomes unused and is deleted — it has no other use in that function (verified: first_ms appears only at 723 and 741). Net: one parameter, one local, four call sites, and one misleading invariant (completion_ms <= horizon_ms) removed. Keep the assert on horizon_ms if it still guards something; there is nothing to assert about completion_ms afterwards.
Two small follow-ons in the same cheap class, worth taking while touching the signature:
helios/src/scheduler/utility.rs:95-97—decodeis a genuine two-line wrapper overdecode_withinand should stay (it is called at six sites). No action.helios/src/scheduler/policy.rs:956-963has two arms with identical shape:
They can collapse to one arm with the expected count selected first (GraphKind::Decode | GraphKind::Speculative => value.decode_within( self.expected_speculative_tokens(r, tokens), preceding_ns as f64 / 1e6, horizon_ns as f64 / 1e6, ), GraphKind::Resume => { value.decode_within(1.0, preceding_ns as f64 / 1e6, horizon_ns as f64 / 1e6) }if matches!(kind, GraphKind::Resume) { 1.0 } else { self.expected_speculative_tokens(r, tokens) }). Minor; only take it if the arm is being edited anyway.
F4 (medium) — service.rs walks the delivery catalogs twice per plan, and delivery_rate is mostly a presence marker
delivery_references (helios/src/scheduler/service.rs:100-158) does its own full catalog walk to find the feasible served batch:
let mut best = [(f64::INFINITY, 0.0f64); REQUEST_LANES];
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;
and seeds the canonical reference from it (150-157):
let (per_delivery_ms, served) = best[slot];
if mask & (1 << slot) != 0 && per_delivery_ms.is_finite() {
*reference = Some(DeliveryReference {
excluded_wait_ms: (count - served).max(0.0) * per_delivery_ms,
served_share: (served / count).min(1.0),
});
Meanwhile service_rates (helios/src/scheduler/service.rs:165-286) already walked the same catalogs per request and computed a delivery rate — delivery_rate = delivery_rate.max(per_ms) at :185 and :277 — whose magnitude now has exactly one consumer, the pre-measurement fallback at :64-69:
let count = rates.iter().flatten().count() as f64;
let mut references = rates.map(|r| {
r.map(|r| DeliveryReference {
excluded_wait_ms: (count - 1.0).max(0.0) / r,
served_share: (1.0 / count).min(1.0),
})
});
Every other consumer wants presence only, and says so by discarding the value:
helios/src/scheduler/service.rs:313—if let (Some(price), Some(_)) = (&mut service.deliveries, participant.delivery_rate)helios/src/scheduler/service.rs:411— same binding againhelios/src/scheduler/service.rs:341—.delivery_references(&participants.map(|p| p.and_then(|p| p.delivery_rate)))— passes the magnitudes only for the fallback above.
Concretely, either:
(a) keep the measured reference only and drop the fallback default — replace delivery_rate: Option<f64> with delivery: bool (or Option<()>) in ServiceParticipant (service.rs:36-40), have service_rates return (Option<f64>, bool), and seed references with None (policy.rs:467 already falls back to ServicePrice::initial(reference.served_share) via unwrap_or_else at :470, and :422-425 already uses ServicePrice::initial(1.0), so the (count-1)/r seed is the only thing that disappears); or
(b) keep the fallback and delete the second scan, feeding per_delivery_ms/served from service_rates instead of re-walking speculative_catalog / mixed_catalog in delivery_references.
(a) is the smaller change and is in the spirit of the PR (one measured reference, no un-derived default — note (count - 1.0) / r corresponds to K = count and b = 1, an undocumented assumption). (b) is better if the fallback default is deliberate. Either way the plan currently scans the same catalogs twice for the same quantity.
F5 (medium) — the maximum rate is the literal 1.0 at every delivery observe site
helios/src/scheduler/service.rs:47-52:
price.observe(
observation.duration_ms,
observation.duration_ms,
1.0,
adaptation_ms,
);
helios/src/scheduler/service.rs:313-316:
if let (Some(price), Some(_)) = (&mut service.deliveries, participant.delivery_rate)
{
price.observe(dt, delivery, 1.0, self.policy.adaptation_ms);
}
helios/src/scheduler/service.rs:420 — price.observe(duration_ms, 0.0, 1.0, adaptation_ms);, plus the test at helios/src/scheduler/policy_tests.rs:854.
ServicePrice::observe's parameter is used as delivered / maximum_rate and maximum_rate.ln() (helios/src/scheduler/utility.rs:62-68):
let normalized = delivered / maximum_rate;
let decay = normalized / adaptation_ms;
previous -= decay;
(-(-decay).exp_m1()).ln() + duration_ms.ln() - delivered.ln()
} else {
duration_ms.ln() - adaptation_ms.ln() - maximum_rate.ln()
For the delivery price the argument is now constant 1 by construction (maximum_rate = 1.0 was fixed by this PR when deliveries stopped being a rate, docs/scheduling-utility.md). The parameter is therefore vestigial on that path, and the Some(_) bindings at :313 and :411 are the compiler-visible symptom.
Concretely: add a sibling on ServicePrice — pub fn observe_delivery(&mut self, duration_ms: f64, delivered: f64, adaptation_ms: f64) that calls the same body with maximum_rate = 1.0 folded in (or split observe into a normalized core plus two thin wrappers, observe_rate(rate) for tokens and observe_delivery()), and change the three production call sites plus policy_tests.rs:854. Then if let (Some(price), Some(_)) = (&mut service.deliveries, participant.delivery_rate) becomes if let Some(price) = price.filter(|_| participant.delivery), which also makes the "delivery-bearing stream" condition read as what it is. This is a small API change confined to service.rs/utility.rs; skip it if you would rather not touch ServicePrice in a bug-fix PR — but then at minimum drop the discarded rate binding.
F6 (high, conventions) — the docs this PR edits still state the superseded model, and the model is derived twice
docs/scheduling-runtime-design.md is rewritten to the per-step conditional model at :110-152, but ~50 lines later it still carries the old age/delivery model while docs/scheduling-utility.md:251-254 states the new one:
docs/scheduling-runtime-design.md:203-210— still "output delivery:g/z" (the delivery rate variable this PR redefines as a served share).docs/scheduling-runtime-design.md:233-247— stillsigma_i = K*T/min(batch_capacity,k)and the old score… - T/2 * sum over active decoders of c_i, whereas the PR's measuredsigma_i = (K - b_f) T_f / b_fand the excluded-only sum are documented atdocs/scheduling-utility.md:230-239and:251-254.helios/README.md:446-450(not touched by this PR) — still says the per-depth ratio is "clamped to[0, 2]", buthelios/src/scheduler/rounds.rs:13now setsCALIBRATION_FACTOR_MAX = 4.0, and it still describes a cumulative per-depth ratio.
This is the AGENTS.md "state support as present qualification" rule: the docs now qualify the same quantity two ways, and a reader of the runtime design doc has no way to know which is current. It also matches the project's "bad docs" merge criterion.
Concretely: in docs/scheduling-runtime-design.md:203-247, replace the re-derivation with the statements that survive (delivery is a served-time share; sigma_i is excluded wait) and a single pointer — "see docs/scheduling-utility.md for the current value/cadence model" — instead of keeping a second full derivation. Fix helios/README.md:446-450 to say the per-step factor is clamped to [0, 4] and that unobserved depths inherit the deepest observed shallower factor. The duplication is precisely what allowed the drift; deleting the second derivation prevents the next one. Note the competing #632 already patches helios/README.md (+3/−2) for that exact sentence — whichever lands, this paragraph must match rounds.rs:13.
Minor (listed, not argued)
scripts/scheduling_sim/utility.py:136-140 encodes the reference as a (duration/capacity, -capacity) tuple only to get a min-with-tie-break, then unpacks it at :158-162 (per_delivery_ms, neg_served = reference; served = -neg_served). A small dataclass plus min(...) over it reads directly and matches the Rust best array idiom at helios/src/scheduler/service.rs:99-110. Take it only if the file is being edited anyway.
What is already lean (said plainly)
So the review does not read as an inventory of complaints — these are the things I checked for and did not find:
- No new knobs, flags, gates or compatibility layers. No CLI flag, no
PolicyConfigfield, no feature gate, no version check, no new env var;delivery_fairnessanddecode_age_pricekeep their names and defaults (policy.rs:28-43). No Protobuf, core-format or CUDA-graph file in the diff, consistent with the "no ABI change" claim. DepthCalibrationseeding got simpler, not more complex:helios/src/scheduler/rounds.rs:337let calibration = vec![DepthCalibration::new(0.5); token_capacity - 1];replaces the previous geometric per-depth seeding — a net deletion.- The
observedflag replaces a heuristic rather than adding to one (it stands in for apredicted <= 1e-6style test), and the unweightedForecasts::observe_calibrationis correctly#[cfg(test)]-gated (rounds.rs:352-356) instead of dead production API. LaneValue::decode(utility.rs:95-97) is a genuine two-line wrapper overdecode_withinwith six call sites — it earns its keep; do not inline it.DeliveryReference(service.rs:27-33) is a documented two-field struct replacing a baref64, with the units in the doc comments — that is the right direction, not over-modelling.- The arithmetic is shared, not copy-pasted, where it counts:
ValueRate::new(utility.rs:142-152) keeps the common- decode_age_price * duration_ms / 2.0subtraction in one place anddecode_withinsupplies the matching+c_i·T/2only for served lanes, so the "no duration penalty when nothing is excluded" property falls out of existing structure rather than a new branch.
Open questions / what I could not settle
- F4's direction depends on intent I cannot read from the PR: whether the pre-measurement default
excluded_wait_ms = (count - 1.0) / r(service.rs:66) is a deliberateK = count, b = 1reference or residue from when deliveries were a rate. No derivation for it appears in the PR body or docs, and it is the same class of gap the competing #632 was twice asked to close (undocumented constants). - Whether
docs/scheduling-runtime-design.mdis meant to be normative at all — the new model lives indocs/scheduling-utility.md, so F6 could be resolved either by pruning the runtime-design passages or by declaring one doc normative. The PR does neither, which is the defect. - Cross-PR collision on these exact sites: #645 (same author, opened one minute after #644) rewrites
policy.rscandidate pricing and addsLaneValue::prefill_finishto the same type, and still prices the old delivery-rate variablez_ss— so F3 (changingfinish's signature) and F5 (changingServicePrice's delivery update) will each need re-doing on whichever branch lands second. #632 editsrounds.rsanddocs/scheduling-runtime-design.mdtoo, so F1/F2/F6 conflict textually. I could not determine the intended merge order from the PR, and neither voipmonitor (author of the estimator this replaces, #515/#522) nor original-el8 (#632) has commented. - Not verified in this pass:
pytest/cargowere not run, so I cannot confirm that the three new production call sites offinishare the complete set (I verified the search overhelios/src/scheduler—boundary_tests.rs(not opened)/tests.rs(not opened) hits areScheduler::finish(handle), an unrelated method); and thescheduler::test count (400 vs #632's 399+4 ignored) could not be reconciled without running the suite.