#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:
record.status != 3 && !finishedis dead:finished's first disjunct isrecord.status == 3, so!finishedalready impliesrecord.status != 3. Delete the conjunct..saturating_sub(...)is unnecessary fallback: the completion path already validatesrecord.consumed_tokens >= request.consumed_tokens(scheduler.rs:2624) and the sibling code at scheduler.rs:2784-2785 uses plain subtraction.- The same
finishedexpression 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:
- policy.rs:357-363
fn prefill_catalog(&self, kind: GraphKind) -> &[usize]— the same three-way catalog choice, written as a match onGraphKind. Replacing the 6-line if/else withlet kind = if request.prompt_logprobs { GraphKind::ScoredPrefill } else if terminal_only { GraphKind::TerminalPrefill } else { GraphKind::Prefill }; let catalog = self.prefill_catalog(kind);uses the existing helper and keeps the two selection rules in one place. - policy.rs:413-438
natural_fit_prefill_capacityis the same loop body: iterate the catalog,prefill_work_through,resolve_prefill_kind, skipterminal_only && resolved == Prefill,continuewhencosts.duration(...)is None. The only real differences are the start cursor (prefill_cursor= max(scheduled_consumed, consumed_tokens) vsconsumed_tokens) and that it keeps the max work instead of testing equality. Because work is bounded byprompt_tokens - start,some capacity has work == remainingholds exactly whenmax work == remaining. Sofits_single_prefill_fromcan be expressed as a_fromvariant of the existing scan:natural_fit_prefill_capacity_from(request, start, catalog, None)(add astartparameter to the existing function, defaulting the current wrapper toSelf::prefill_cursor(request)) and thenself.prefill_work_from(request, start, capacity, None) == remaining. That deletes ~20 lines of parallel logic and guarantees the two "does one graph cover this" rules cannot drift. Caveat to state honestly:prefill_entry(...).is_some()vscosts.duration(...).is_none()are equivalent today (prefill_entryreturnsSome(None)only whennanos == 0, anddurationreturnsSome(0)there), so the collapse preserves behaviour; if a reviewer wants the stricter "measured, not merely registered" reading,prefill_predictor/prefill_entryshould be the single rule used by both.
#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:
- scheduler.rs:2677-2702 — the
preserve_first_output_waitpredicate re-computesfinished,prefillandoutputthat the same loop body computes again at :2743-2745 and :2784-2789, contains a dead conjunct (record.status != 3with!finished, whose first disjunct isrecord.status == 3), and usessaturating_subwhere 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. - service.rs:150-181 —
b_served * T_decis tracked per slot frombest[slot], then un-derived by squaring (best_decode.1 * best_decode.1 * best_decode.0), even thoughconsideralready hasnanos/servedonce per candidate. Moving the comparison intoconsiderand returningserved * durationis fewer lines, evaluated once per candidate instead of once per candidate × slot. - policy.rs:442-464 —
fits_single_prefill_fromre-implements the three-way catalog choice thatprefill_catalog(kind)(policy.rs:357-363) already encodes, and its scan loop duplicatesnatural_fit_prefill_capacity(policy.rs:413-438) body-for-body; because work is bounded byprompt_tokens - start, "some capacity's work equals remaining" is "max work equals remaining", so adding astartparameter to the existing helper collapses ~20 lines. - policy.rs:259-281 —
set_first_output_waitrepeatsset_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 anOption<u64>wait removes a public method and an ordering constraint. - utility.rs:94-111 —
LaneValue::prefillsurvives only as a#[cfg(test)]adapter whoseconsumed.max(1)argument makes the partial-chunk fraction 1.0, so the existing tail test no longer touches the production partial-chunk path; andinitial_prefill.max(consumed).max(1)plus.min(1.0)inprefill_withinare clamps no caller can trigger. - 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_logprobsinert case, splits thelast_output_nsclamp 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)
- Entry 1 (scheduler.rs:2677-2702) — duplicated
finished/prefill/outputlocals + dead conjunct + needlesssaturating_sub. Biggest readability win in the diff, zero behaviour change. - Entry 2 (service.rs:150-181) —
b_served * T_deccomputed per slot then un-derived by squaring; move intoconsider. Removes an O(candidates × slots) loop and a reverse-engineered multiply. - Entry 3 (policy.rs:442-464) —
fits_single_prefill_fromduplicatesprefill_catalog(kind)andnatural_fit_prefill_capacity; collapse to a_fromvariant. Most important for drift risk: two copies of "does one eligible graph cover this remaining work" is exactly the rule #660 also touches. - Entry 4 (policy.rs:259-281) —
set_first_output_waitduplicatesset_arrivalvalidation with one caller pair; merge. - Entry 5 (utility.rs:94-111) —
#[cfg(test)]-onlyprefill()shim actually weakens the pre-existing tail test (passesconsumed.max(1), so fraction is always 1.0 and the partial-chunk path is untested); plus unreachable clamps. - 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)
first_output_valuegating block policy.rs:729-733: four conditions, each functionally necessary (consumed<prompt, max_new_tokens>0, decode_age_price>0, incumbent_decode_batch_ms>0). Not redundant — the first is the prompt-unfinished rule, the rest are the documented inertness conditions.values[slot].first_output_value *= unitat policy.rs:768 and its exclusion from theage_pricesum at :769: correct minimal wiring, not duplication.- policy.rs:526 extraction of
initial_prefill_tokens()is a net simplification (it deleted an inlinesaturating_sub(..).max(1)), and all four call sites now share one definition — good, should be said plainly as a positive. delivery_referenceskept as a thin.0wrapper overdelivery_references_and_decode_batch(service.rs:59-64): justified — it has a second caller (service.rs:376) plus tests, so the wrapper is cheaper than updating it to destructure. Not removable.scripts/scheduling_sim/utility.py:_first_output_valuecache +_initial_prefillreuse follows the file's existing_coalesce_tokenpattern exactly (init, clear inprepare,unit *scaling at the end, per-lane application inlane_value). Idiomatic for this file; do not ask for a different shape. (The real Python concern is fidelity, not simplicity, and belongs to the correctness/evidence lens.)- Completion-record status literals (
status == 3,status >= 2) are pre-existing repo idiom, not introduced by this PR; I did not ask for a named enum as part of this review. - Test additions (policy_tests +214, test_scheduling_utility +52/−15): coverage-density is fine; per the brief I did not nitpick good unit tests. The loosened coalescing assertions are a real reduction in strength but belong to the evidence/validation lens, not this one — mention at most in one clause if at all.
Convention notes
- AGENTS.md:188-193 "Reject unsupported abstractions and churn ... Unsolicited ... comment expansion" is the only meaningful convention hit, and it is entry 6 (doc duplication) plus, mildly, the 8-line comment at scheduler.rs:2677-2680 explaining a predicate that could be a named helper.
- No env-var behaviour switches (AGENTS.md:452-455), no new config home needed (AGENTS.md:456-460) — compliant by construction since there is no new knob.
#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:
- docs/scheduling-utility.md:287-318 (33 new lines): heading "First-output waiting age against active decoders", the formula, then a paragraph restating
A_firstdefinition,fracrule, absence from the penalty sum, the three inert conditions, and the anchor-preservation rule. - 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).