Subtraction, Simplicity & Conventions review — PR #663 (helios/scheduler: price first-output waiting age on incumbent decode rounds)
Key findings
- The production surface is honest and close to minimal, but not as lean as it could be. 11 files,
+511/−40, ≈105 net production Rust lines; no new CLI flag, no newPolicyConfigfield, no new graph kind, no Protobuf/ABI change, no new crate or module. The snakeLaneValue.first_output_value→prefill_within→lane_value_for_tokens_within/next_progressis about the minimum needed to thread one new priced term through the existing selector. No speculative generality, no dead field, no unused flag, no duplicated abstraction that should be deleted outright. - Six concrete simplifications exist. Three of them (S1, S2, S3) are worth asking for before merge; the other three (S4, S5, S6) are cheap cleanups.
- S1
helios/src/scheduler.rs:2677-2702— thepreserve_first_output_waitpredicate re-derivesfinished/prefill/outputthat the same loop body computes again 60 lines later, contains a dead conjunct, and uses asaturating_subthe completion validator already makes unnecessary. Biggest readability win, zero behaviour change. - S2
helios/src/scheduler/service.rs:150-181—b_served * T_decis tracked per slot and then un-derived by squaring (served * served * per_delivery_ms), althoughconsideralready hasnanos/servedonce per candidate. Move the comparison intoconsider: fewer lines, once per candidate instead of once per (candidate × slot). - S3
helios/src/scheduler/policy.rs:442-464—fits_single_prefill_fromre-implements the three-way catalog choice thatprefill_catalog(kind)(policy.rs:357-363) already encodes and duplicatesnatural_fit_prefill_capacity(policy.rs:413-438) body-for-body. This is the drift risk that matters: two copies of "does one eligible graph cover this remaining work", in the exact area #660 also edits.
- S1
- One meaningful convention hit: the new contract is written out twice in two docs and has already drifted (S6), which is the "unsolicited prose expansion / duplicate framing" item in
AGENTS.md:188-193. - Two things in the diff are net simplifications and should be said so plainly: extracting
LiveRequest::initial_prefill_tokens()replaced an inlinesaturating_sub(..).max(1)at three call sites with one definition (policy.rs:523-525in the diff), and keepingdelivery_referencesas a thin.0wrapper (service.rs:59-64) is cheaper than updating its second caller (service.rs:376) and the tests to destructure a tuple. - The Python mirror (
scripts/scheduling_sim/utility.py) needs no simplification: its_first_output_valuecache +_initial_prefillreuse follows the file's existing_coalesce_tokenidiom exactly (init, clear inprepare,unit *scaling at the end, per-lane application inlane_value). Its real problem is fidelity to the Rust formula, which belongs to the correctness/evidence lens, not this one.
S1 (high) — preserve_first_output_wait duplicates locals computed 60 lines later, and contains a dead conjunct
helios/src/scheduler.rs:2677-2702:
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
and the same predicate written a second time at helios/src/scheduler.rs:2742-2745:
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);
Three problems, all removable:
record.status != 3 && !finished(:2691-2692) is dead:finished's first disjunct isrecord.status == 3, so!finishedalready implies it. Delete the conjunct..saturating_sub(request.consumed_tokens)(:2688-2689) is an unnecessary fallback: the completion path already validatesrecord.consumed_tokens >= request.consumed_tokens(scheduler.rs:2624), and the sibling code later in the same loop body uses plain subtraction.- The identical 3-disjunct
finisheddefinition, plusprefill/output, appears again at:2742-2745and again in the credit block further down (~:2784-2789).record.status == 3is tested three times in this region (:2684,:2691, and again below).
Concrete change: hoist let record = &records[lane.request.slot as usize]; 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 :2742 and the credit block; drop the dead conjunct and the saturating_sub. Alternatively extract a named helper next to fits_single_prefill_from, e.g. fn forced_anchor_cut(&self, request: &LiveRequest, record: &CompletionRecord) -> bool, which also makes the 4-line comment at :2677-2680 unnecessary (a well-named predicate is the comment). Removes ~10 lines and one duplicated predicate definition.
S2 (high) — b_served * T_dec is computed per slot, then un-derived by squaring
helios/src/scheduler/service.rs:161-181:
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() {
*reference = Some(DeliveryReference {
excluded_wait_ms: (count - served).max(0.0) * per_delivery_ms,
served_share: (served / count).min(1.0),
});
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);
}
}
}
}
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 — the wanted round work-time, recovered through a multiply that only works because per_delivery_ms was divided by served earlier. And the value is already available once per candidate in the existing closure at helios/src/scheduler/service.rs:111-122:
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;
for slot in policy::bits(eligible) {
if cost < best[slot].0 || (cost == best[slot].0 && served > best[slot].1) {
best[slot] = (cost, served);
}
}
};
Concrete change: record the decode figure inside consider (add, after the best[slot] update, if matches!(kind, Decode | Speculative) && (cost < best_decode.0 || (cost == best_decode.0 && served > best_decode.1)) { best_decode = (cost, served); }), delete the if matches!(kind, …) block from the per-slot loop, and return the honest quantity — either best_decode.1 * best_decode.0 * 1e6 or, preferably, track best_decode = (nanos, served) and return served * nanos as f64 / 1e6 so nothing is divided out and multiplied back. Removes ~8 lines, evaluates the comparison once per candidate instead of once per (candidate × slot), and stops reverse-engineering a value from a normalized one. Behaviour is unchanged: the per-slot loop is fed only by consider (including the Mixed rounds at :150-160), so the winner is the same.
S3 (high) — fits_single_prefill_from duplicates prefill_catalog and natural_fit_prefill_capacity; the repo already has the _from convention to collapse it
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
};
The three-way catalog choice is already encoded — twice — by pre-existing helpers:
helios/src/scheduler/policy.rs:357-363:
fn prefill_catalog(&self, kind: GraphKind) -> &[usize] {
match kind {
GraphKind::ScoredPrefill => &self.scored_prefill_catalog,
GraphKind::TerminalPrefill => &self.terminal_prefill_catalog,
_ => &self.prefill_catalog,
}
}
and helios/src/scheduler/policy.rs:365-378 (effective_prefill_catalog). This PR adds a third inline copy of the same selection rule.
The scan loop then duplicates natural_fit_prefill_capacity (helios/src/scheduler/policy.rs:413-438) body-for-body: iterate the catalog, compute per-capacity work, skip terminal_only && resolved == GraphKind::Prefill, require a measured cost, and (in the new helper) test work == remaining instead of keeping the max.
Concrete change: because prefill_work_from is bounded by prompt_tokens - start, "some capacity's work equals remaining" holds exactly when "the maximum work equals remaining". So thread the already-existing _from style through the fit search — the repo already has prefill_work_from, resolve_prefill_kind_from and prefill_requires_terminal_completion_from precisely because the cursor became a parameter — i.e. add a natural_fit_prefill_capacity_from(request, start, catalog, cut) and express fits_single_prefill_from as "the natural-fit work for that capacity equals the remaining work", selecting the catalog with prefill_catalog(kind):
let kind = if request.prompt_logprobs { GraphKind::ScoredPrefill }
else if terminal_only { GraphKind::TerminalPrefill }
else { GraphKind::Prefill };
let catalog = self.prefill_catalog(kind);
That deletes ~20 lines of parallel logic and makes the two "does one graph cover this" rules impossible to drift — which matters because #660 edits interior-split budgeting in exactly this area. Honest caveat for the reviewer: the new code uses costs.prefill_entry(resolved, capacity).is_some() where the existing helper uses costs.duration(resolved, 1, capacity).is_none(); these are equivalent today (prefill_entry returns Some(None) only when nanos == 0, where duration returns Some(0)), so the collapse preserves behaviour — and if the intent is "measured, not merely registered", that should become the single rule used by both, not a third predicate.
S4 (medium) — set_first_output_wait duplicates set_arrival's validation for one caller pair
helios/src/scheduler/policy.rs:259-281:
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(())
}
The new setter has one production caller (helios/src/server/runtime.rs:1574-1577), which always calls it immediately after set_arrival(handle, incoming.arrival_ns)?, and one test caller. Both calls repeat the same "before admission, before dispatch" validation and do a second slot lookup.
Concrete change: one setter, e.g.
pub fn set_arrival_and_wait(&mut self, handle: RequestHandle, arrival_ns: u64, first_output_wait_ns: Option<u64>) -> Result<()>
validating once and writing arrival_ns, last_progress_ns, and first_output_wait_ns.unwrap_or(arrival_ns).max(arrival_ns); runtime becomes 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 an ordering requirement between two public calls that the max(arrival_ns) clamp at :279 currently papers over.
S5 (medium) — the #[cfg(test)]-only prefill() shim weakens the test it exists for; prefill_within has unreachable clamps
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)
};
- The
#[cfg(test)]prefillis a leftover adapter whose only caller ishelios/src/scheduler/utility.rs:410-412(prefill_tail_counts_consumed_tokens_and_one_first_output). It passesconsumed.max(1)asinitial_prefill, sofractionis always1.0on partial chunks — meaning the surviving test no longer exercises the production partial-chunk path at all. Change the three call sites tovalue.prefill_within(64, 64, true)and delete the shim (~5 lines). - Given
initial_prefill_tokens()is always>= 1and the documented invariantconsumed <= initial_prefillon a first prefill, bothinitial_prefill.max(consumed).max(1)and the outer.min(1.0)are defensive clamps that cannot fire;consumed as f64 / initial_prefill as f64suffices at all three production callers (policy.rs:806,:859,:1298).
S6 (medium) — the same new contract is written twice in two docs, already out of step
The PR adds docs/scheduling-utility.md:287-318 (33 lines: heading "First-output waiting age against active decoders", the formula, then A_first, frac, the penalty-sum exclusion, the three inert conditions and the anchor-preservation rule), and docs/scheduling-runtime-design.md:266-284 (the selection formula gains one line plus a 13-line paragraph restating 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` ...
The neighbouring paragraphs in scheduling-runtime-design.md deliberately defer mechanism to the utility doc ("Normalized service prices follow the entropy-dual update in scheduling-utility.md"), so the second copy breaks the doc's own division of labour. They have already drifted: runtime-design drops the prompt_logprobs inert case that utility.md (not opened) states, and puts the readmission last_output_ns clamp in a different sentence from utility.md (not opened)'s anchor rule. AGENTS.md:188-193 (reject unsolicited prose expansion and duplicate framing) is the relevant convention.
Concrete change: keep the added formula line, cut the 13-line paragraph to one sentence pointing at the utility doc for A_first, frac, the T/2 * sum c_i exclusion and the inert conditions. Removes ~10 duplicated lines and one drift site. One-clause companion fix in the same file: docs/scheduling-runtime-design.md:234 still says "Only decoding requests have a delivery coordinate or output-age cost", which the new term no longer leaves true as written.
Conventions checked (no action)
AGENTS.md:452-460(no env-var behaviour switches; no new config home) — compliant by construction: no new knob, no new config.AGENTS.md:152-160(disclosed qualifications) — satisfied; the PR has a "Disclosed limitations" paragraph.- Completion-record status literals (
status == 3,status >= 2) are pre-existing repo idiom, not introduced here; I did not ask for a named enum as part of this lens. - Test additions (
policy_tests.rs+214,tests/test_scheduling_utility.py+52/−15) are coverage-dense and well-shaped; I did not nitpick them. The loosened coalescing assertions (tests/test_scheduling_utility.py:363-395: relative guarantees replaced by absolute ceilings) are a genuine reduction in assertion strength but belong to the evidence/validation lens, not this one.
Deliberately not flagged
- The four-condition gate at
helios/src/scheduler/policy.rs:729-733is not redundant: one clause is the prompt-unfinished rule, the other three are the documented inertness conditions. values[slot].first_output_value *= unit(policy.rs:768) and its exclusion from theage_pricesum (:769, onlyvalue.age_priceis summed) is minimal correct wiring, not duplication.delivery_references(.0wrapper,service.rs:59-64) is justified by its second caller (service.rs:376) and tests — do not ask for it to be deleted.LiveRequest::initial_prefill_tokens()is a net simplification (one definition replacing three inlinesaturating_sub(..).max(1)sites); say so in review so it is not mistaken for added surface.scripts/scheduling_sim/utility.py's cache shape matches the file's existing idiom; no simplification warranted.
Open questions for the author
- Is
costs.prefill_entry(..).is_some()vscosts.duration(..).is_none()a deliberate distinction (measured vs registered) infits_single_prefill_from? If not, S3's collapse is free; if yes, the two rules should converge on the stricter reading rather than coexist. - Does
first_output_wait_nsneed to be public API at all, or can S4's combined setter keep it private (it is not published in metrics orRequestDetail, so nothing external reads it)? - Should the doc duplication in S6 be cut in this PR or after #654/#660/#661 settle, given
docs/scheduling-runtime-design.mdis open in four PRs at once?