#1 [high] Should fix: request_copy_match_stats duplicates request_history_proposal_with_match_len
File: helios/src/scheduler.rs:1099-1205.
request_history_proposal_with_match_len (1112-1159) and request_copy_match_stats (1163-1205) repeat the same chain: same clamp (maximum.min(completion_token_capacity-1).min(COPY_DRAFT_CAPACITY)), same early exit on maximum == 0 || decoded_history.is_none(), same self.request(handle) lookup, same sam.propose(maximum), same out-of-vocabulary truncation (position(|&t| (t as usize) >= vocabulary)), same shared-ring query via DecodedHistory::lookup_with_match_len(request.tokens(), maximum), and the same "shared ring wins only on strictly longer match" rule. The second function differs only in returning (valid_len, match_len) instead of a padded vector.
Precedent: the same PR follows the opposite (correct) pattern in helios/src/scheduler/decoded_history.rs:162-183, where lookup is a two-line wrapper over lookup_with_match_len, and the sole difference is the returned tuple. helios/src/scheduler/rounds.rs powered_curve/expected_speculative_tokens (537-557) also factor a cheap view out of the expensive computation rather than copying it.
Risk beyond duplication: the two copies are already not identical. In request_history_proposal_with_match_len the shared-ring result is used unconditionally in the (None, Some(..)) arm (no count > 0 filter), whereas request_copy_match_stats filters .filter(|&(count, _)| count > 0) before the match; a zero-count shared result therefore yields (tokens, 0, 0) in one path and is skipped in the other. Any future fix to the vocabulary clip, the tie-break, or the count == 0 handling has to be made twice.
Fix: express one on the other, e.g. request_copy_match_stats calls a shared private helper returning (match_len, valid_len, provider) and drops the padded build (an Option<&MatchProposal>-style return), so the clip and tie-break exist once.
#2 [high] Should fix: wide_copy_curve fallback duplicates CopyCalibration's own prior and is unreachable
File: helios/src/scheduler/rounds.rs:541-553 (wide_copy_curve).
The else arm recomputes speculation::WIDE_COPY_PRIOR_RATE.powi(depth+1) over completion_token_capacity-1 depths, which is exactly what CopyCalibration::new(capacity).curve(generated, optimistic) returns when depths are all None (speculation.rs:121-151: prior = rate.powi(depth+1) for the None entry, with rate seeded at WIDE_COPY_PRIOR_RATE). The scoring structure the fix belongs to (wide_copy_curve/expected_copy_tokens wrapping powered_curve/expected_speculative_tokens) is the right precedent, but the fallback curve should live next to its owner.
The branch is also unreachable in practice: LiveRequest.sam and LiveRequest.copy_calibration are set together from the same predicate self.decoded_history.is_some() at admission (scheduler.rs:1849-1856), enable_history_drafts must run before admission (scheduler.rs:1086-1092: rejects when self.submitted != Fence(0) || self.admissions != 0), and every caller of wide_copy_curve is already gated on self.decoded_history.is_none() == false (rounds.rs:759). So copy_calibration cannot be None where this arm runs.
Fix: delete the else arm and use request.copy_calibration.as_ref().expect(...), or make CopyCalibration::curve the only source and give it a CopyCalibration::prior(capacity) constructor so no caller re-derives the geometric prior. This also removes the second hard-coded use of WIDE_COPY_PRIOR_RATE outside speculation.rs.
#3 [high] Remaining findings: doc staleness, cost.rs repetition, unwired public SAM API
Observations verified in the diff but not fully cross-checked against every convention precedent. Order by confidence. These were collected just before the time limit.
-
Deviation from convention (should fix) —
docs/scheduling-runtime-design.md:7-12lists the scheduler modules that specify the design (policy.rs,utility.rs,service.rs,cost.rs,refresh.rs,learning.rs,rounds.rs,speculation.rs). The newhelios/src/scheduler/sam.rsimplements a mechanism the same document specifies (copy proposals, lines 39-41 and 102) but is not added to that module index, so a reader of the design document cannot find the implementation. Fix: addsam.rs(per-request prompt and output suffix automata for copy proposals) to the list. -
Deviation from convention (should fix) —
docs/mtp-design.md:31-40describes copy proposals solely as the shared 65,536-token ring with eight- and four-token indexes, and lines 22-29 say history drafting uses "shared decoded history" only. After this PR a request's proposals come first from a per-request prompt+output suffix automaton (scheduler.rs:1099-1159) with a six-token minimum match (sam.rs:22, raised from three) and a 131,072-token prompt plus 131,072-token output cap per request (sam.rs:25-28).docs/cli-design.md:742likewise says only "shared decoded-history continuations". repo-prose SKILL.md:26-29 requires replacing stale present-state claims rather than layering; this is the file that owns copy-draft semantics. -
Nit —
helios/src/scheduler/cost.rs:195, 199, 229, 239plusrounds.rs:756spell outestimate.draft_source != Some(ProposalSource::Copy)five times. A single small accessor onEstimate(the file already carriesEstimate::fresh, cost.rs:111) would match local style and keep the meaning in one place;is_copy_only_stepandmax_mtp_draft_tokensread from it. -
Nit —
cost.rs:287-296:refresh_orderchanged return type to(bool, u64)and lost the doc comment explaining the ordering, which now lives only indocs/scheduling-runtime-design.md:437-441.(true, attempt_ns)meaning "attempted while stale, no valid observation" is not self-evident; neighbouring helpers in cost.rs (lines 21-48, 210-213) carry their invariants in one-line doc comments. -
Nit —
helios/src/scheduler/sam.rs:1236-1273: the test-onlybrute_force_oraclereturns the productionMatchProposaland re-implementsbuild_proposal's source selection and token slicing (sam.rs:1191-1227), so the oracle can drift with production code. Precedent: theoraclehelper inhelios/src/scheduler/decoded_history.rs:228-252returns the same plain(Vec<i64>, usize)the productionlookupreturns. The 120-trial randomized oracle (sam.rs:1402) is only as strong as its independence. -
Not a finding —
DEFAULT_MIN_MATCH_LEN = 6(sam.rs:22) andWIDE_COPY_MIN_MATCH_LEN = 6(speculation.rs:18) are two constants for the same threshold; rounds.rs:776 requires both to pass. Since the SAM default governs the plain--history-draftspacking path too (packing.rs:395-407 →request_history_proposal→SamConfig::default(), sam.rs:53-62), the wide-copy constant could reference the SAM default rather than repeat 6. Neither is wired to a flag, so both satisfy the "no magic defaults" rule only if the value is argued in prose; docs/mtp-design.md currently justifies neither. -
Not a finding —
helios/src/scheduler/sam.rsmodule doc (lines 7-17) and public API (PromptSAM::build,PromptOutputSAM::new,SamConfig,MatchProposal,MatchSource) do not use lifecycle labels, follow the SPDX header convention used acrosshelios/src/scheduler/, and add "Flare community contributors" as a second copyright line (matching speculation.rs:3).propose_conditional_continuationsandpropose_for_context(sam.rs:1070, 1118) are public but have no caller outside the test module;propose_for_contextis exercised only by sam.rs:1463. Consuming-only-in-tests public API is the kind of speculative surface AGENTS.md rejects ("Reject unsupported abstractions... Do not add frameworks, extension points... without a concrete requirement"), so this should be raised: either the 2-deep pipelined execution path that needs them lands in this PR, or the two functions and their tests should not ship aspub.
#5 [high] Should fix: draft_source is not part of prepared-shape identity
PR #540 adds GraphDescriptor::draft_source (helios/src/execution/manifest.rs:191-192) as a new graph discriminant, but the two places that define a prepared shape's identity were not extended, and both have a hard failure path when two graphs share a shape.
helios/src/model/catalog.rs:279-293(select_shape_with_drafts) filters manifest graphs onkind && batch_capacity && token_capacity && prefill_capacity && packed_token_capacity && draft_tokens && sampling_modeand returnsErr("ambiguous prepared model graph capacity")when two match.draft_sourceis absent, so a copy-only speculative graph captured at the same B/D/W/P as an MTP graph fails catalog validation, even though the new validation at catalog.rs:94-131 specifically contemplates copy-only graphs.helios/src/scheduler/cost.rs:50-58Key {drafts, kind, batch, tokens, prefill, packed}is the cost-table identity, andActionCosts::prepared(cost.rs:151-169) returnsErr("prepared graphs require unique shapes")on a duplicate key. The PR instead storesdraft_sourceon the value side (Estimate.draft_source, cost.rs:81/169) and re-derives the source inis_copy_only_step(cost.rs:223-232) andmax_mtp_draft_tokens(cost.rs:234-244). So two graphs identical exceptdraft_sourcemake the core fail to load with "prepared graphs require unique shapes".
Precedent for the correct identity, already in the tree and already updated for this PR: helios/src/runtime_core/selection.rs:250-251 treats a serving variant as (kind, sampling_mode, batch_capacity, token_capacity, prefill_capacity, packed_token_capacity, draft_tokens, draft_source, speculation_enabled) and rejects only true duplicates. The wire layer therefore accepts an MTP + copy pair at the same geometry, and the manifest/cost layers reject it — three identities for one object.
Why it matters: a copy-only graph at the same width/depth as the MTP graph is the natural capture for W=16 when MTP also has W=16 (ignition draft_source defaults to 1 and copy graphs use draft_tokens = width - 1, ignition/preparation/execution.py:32,87-92), so this is reachable as soon as the sibling recipe PRs capture copy-only graphs at an MTP width. It also contradicts the PR's compatibility claim that "existing W=8-only cores without copy-only wide graphs load" — those load, but a core that mixes the two at one geometry cannot.
Fix: add draft_source to cost::Key (and Key::from_step, which then needs the graph's source passed in or the step to carry it) and to the select_shape_with_drafts filter, so graph identity is stated once, as selection.rs:250-251 already states it. That also lets Estimate.draft_source, PackedRoundShape::draft_source and is_copy_only_step's inference be dropped.
Verified by reading catalog.rs:279-293, cost.rs:50-58/147-179/223-244, selection.rs:250-251.
#6 [high] Should fix: wide copy-only cohort loop duplicates the ordinary packed-round loop
RequestScheduler::packed_round_candidates (helios/src/scheduler/rounds.rs:737-1062) now contains two structurally identical cohort searches.
Copy-only block, rounds.rs:791-902:
- build
scoresfromcurve[position] * values[slot].output_tokenper available slot, thenrank_prefixes(&mut scores)(800); - derive
ranks_by_slot/slots_by_rank(801-806); base[slot]/full[slot]decode values atnanos(808-816);- for three orderings (
full,base,full/limits):select_nth_unstable_by(cohort - 1, rank),truncate,sort_unstable_by, clearfrontier, trimhost_lengthsagainstdraft_budget, accumulatevaluevialane_terms, keep the best mask with the same(count_ones, Reverse(mask))tie-break (817-877); - push a
Candidatewithexpectedrecomputed at zero duration (878-902).
Ordinary block, rounds.rs:925-1047, performs exactly the same steps: scores/gains from the forecast curve (929-956), base/base_zero/full/limits (964-976), the same three orderings with select_nth_unstable_by + truncate + sort_unstable_by + frontier trim + lane_terms + the identical best-mask predicate (981-1047), and the same Candidate construction with zero-duration expected (1048-1060).
The only real differences are the curve source (copy_curves vs curves/host_ranking) and that the copy block never uses host_ranking/surplus_table. That is a per-slot curve provider, not a separate algorithm.
Precedent inside the same file/PR: the function already factors cohort-independent helpers exactly this way — rank_prefixes (rounds.rs:505 and 800), fixed_round_candidate (rounds.rs:~690-735) which builds a Candidate once for all shapes sharing a ranking, host_prefix_ranking (rounds.rs:490-513), and wide_copy_curve/expected_copy_tokens wrapping powered_curve/expected_speculative_tokens (541-557). The reviewable unit is "one loop plus a curve closure", which is also what the existing comment "Lane forecasts stay fixed while shapes compete; evaluate each at most once" (rounds.rs:746) is about.
Cost of the duplication: ~100 lines, two copies of the frontier/host_lengths budget arithmetic (851-853 vs 1026-1030) and of the best-mask tie-break (868-873 vs 1040-1043) that must be kept in step; the copy block also silently lacks the surplus_table factor the ordinary block applies (1031-1037), so a future change to cohort pricing has two sites and one of them already differs.
Fix: extract the ordering/cohort search into one helper taking &[f64] per slot (or a fn(slot, position) -> f64 marginal-probability closure) and the per-slot limit, and call it from both blocks.
Verified by reading rounds.rs:737-1062.
#8 [high] Should fix: manifest.md and copy-draft design prose not updated for draft_source and the per-request SAM
Two documents that this PR makes stale were not updated, and both are the owning reference for a field the PR adds.
-
helios/manifest.md:29-53documents the Pythongraphs[]dictionary field by field (name,kind,sampling_mode,handle,batch_capacity,token_capacity,draft_tokens,packed_token_capacity,prefill_capacity,confidence_width,estimated_duration_ns,input_bindings,tuned_bindings).ignition/preparation/execution.py:316-319now emitsdraft_sourceon every graph with an explicitdraft_tokens, andheliopause/src/python.rs:225-233reads it; the field is absent from the manifest reference.AGENTS.md:52-60requires designed behavior to be stated as a specification, and this file is the specification of that dictionary. -
docs/mtp-design.md:22-40still describes copy proposals as only the shared 65,536-token ring with eight- and four-token indexes returning up to seven continuations ("It requires speculative graphs that declare copy-token inputs ... Both settings use the same captured MTP graphs and buffers", lines 22-29; "each loaded model retains the most recent 65,536 committed generated tokens", lines 31-34). After this PR the primary path is the per-request prompt+output suffix automaton (helios/src/scheduler.rs:1099-1159), with a 131,072-token trailing prompt window, a 131,072-token output cap, a 512-token boundary overlap and a six-token minimum match (helios/src/scheduler/sam.rs:22-32), and the ring is only the fallback taken when its match is strictly longer (scheduler.rs:1144-1148).--history-draftsalso now changes the retained graph set (helios/src/runtime_core/selection.rs:277-298,382-396), contradicting "Both settings use the same captured MTP graphs and buffers".docs/cli-design.md:741says only "Augment learned drafts with shared decoded-history continuations".
Rule: .agents/skills/repo-prose/SKILL.md:26-29 — "Documentation is a present-state specification, not a changelog. Replace stale claims instead of layering history on top."
docs/scheduling-runtime-design.md:6-12enumerates the modules inhelios/src/scheduler/that implement the design (policy.rs,utility.rs,service.rs,cost.rs,refresh.rs,learning.rs,rounds.rs,speculation.rs) and omits the newsam.rs, which implements the copy-proposal mechanism the same document specifies at lines 39-41. A reader following the document's own pointer cannot reach the implementation.
Fix: add draft_source to helios/manifest.md:29-53 with its NO_DRAFT/MTP/COPY_DRAFT values and default; rewrite docs/mtp-design.md:22-41 to specify the per-request automaton first and the shared ring as the fallback (caps, six-token minimum, and that --history-drafts retains copy-only graphs); update docs/cli-design.md:741; add sam.rs to the docs/scheduling-runtime-design.md:6-12 list.
#9 [high] Remaining findings: dominance rule twice, expected-value pricing, SAM API surface, constants, oracle, refresh_order
Smaller findings, all verified in the code at head 14019718.
-
Should fix (moderate) — the new padded-batch dominance rule exists twice in one function.
helios/src/scheduler/policy.rs:143-165adds a pairwise rule insidedominates_padding_with("strictly narrower same-capacity same-depth GPU-allocated ragged batch whosepacked_token_capacity >= min(lane_ceiling_sum, larger.packed_token_capacity)dominates"), andpolicy.rs:225-254re-derives the same rule as a scan insideprune_paddingoverdominated[index]/other.batch. The two express one invariant in two code shapes with slightly different bounds: the pair version comparessmaller.packed_token_capacity >= neededwhereneeded = long.sum().min(larger.packed_token_capacity), while the scan usesother.packed_token_capacity >= length(index).sum().min(candidate.packed_token_capacity)and additionally requiresother.batch >= lanes(the active-cohort guard, which the pair version gets implicitly from the sharedmaskcheck at line 134). Fix: haveprune_paddingrely on the pairwise rule only (with theother.batch >= lanescondition folded intodominates_padding_with), which is the pattern the pre-existing loop at policy.rs:215-220 already uses ("for each peer, askdominates_padding_with"). That removes 30 lines and one place for the two thresholds to drift. -
Nit — the zero-duration expected value for a candidate is computed in four places:
policy.rs:1083-1096(ordinary candidate),policy.rs:1263-1295(refresh_expected),rounds.rs:725-726(fixed_round_candidate),rounds.rs:879-885androunds.rs:1048-1054(copy and ordinary packed cohorts). Each spells out "sumvalues[slot].decode(expected_tokens, 0.0)over the mask". A single helperfn expected_value(&self, mask, tokens_per_slot: impl Fn(usize) -> f64, values) -> f64would state the "expected value is priced at zero duration for refresh ranking" invariant once; today it is restated with a different closure shape five times, andpolicy.rs:1083-1096already has to special-caseduration_ns == 0 || kind.is_prefill()to avoid double counting. -
Nit —
helios/src/scheduler/sam.rs:1070(propose_for_context),sam.rs:1118(propose_conditional_continuations),MatchSource/MatchProposal::source,PromptSAM::build,PromptOutputSAM::push_sliceand the accessorsprompt_sam/config/prompt_len/output_len/total_len/state_count/memory_bytes/dynamic_memory_bytes/state_count/transition_counthave no caller outside the test module (production uses onlyPromptOutputSAM::new,push_token,propose, andsam()in tests; verified withsearch_codeover the whole repository).docs/mtp-design.mdand the module doc name a "2-deep pipelined execution" (sam.rs:1117) that exists nowhere.AGENTS.md:188-193rejects "speculative compatibility, fallback layers, or configuration switches without a concrete requirement" and "extension points"; that applies to an unconsumed public API surface. Either the consumer lands in this PR or the surface should be private. -
Nit —
helios/src/scheduler/speculation.rs:14-21introduces five new unexplained constants (WIDE_COPY_PRIOR_RATE = 0.88,COPY_STEP_PRIOR_WEIGHT = 4.0,COPY_DEPTH_SHRINK_WEIGHT = 2.0) androunds.rs:766adds a barebase_mtp_drafts.saturating_add(3), plussam.rs:22DEFAULT_MIN_MATCH_LEN = 6duplicatesWIDE_COPY_MIN_MATCH_LEN = 6(speculation.rs:18), both required byrounds.rs:776. The charter requires "Be explicit and pin everything. No magic defaults" andAGENTS.md:452-456requires a setting to have one home; a constant with no derivation and no doc line does not satisfy either. The two6s should be one constant (the SAM default also governs the plain--history-draftspacking path viapacking.rs:395-407→request_history_proposal→SamConfig::default()). -
Nit — the test-only
brute_force_oracle(sam.rs:1236-1273) returns the productionMatchProposaland re-derivesbuild_proposal's source selection and token slicing (sam.rs:1191-1227), so the randomized 120-trial comparison atsam.rs:1402+is not independent of the code it checks. Precedent for the opposite: theoraclehelper inhelios/src/scheduler/decoded_history.rs:228-252returns the same plain(Vec<i64>, usize)the productionlookupreturns, so the comparison is of values, not of a shared struct. -
Nit —
helios/src/scheduler/cost.rs:287-296:refresh_orderchanged to return(bool, u64)and now carries no comment. The meaning of the tuple ((true, attempt_ns)= "attempted while stale without a valid observation";(false, 0)otherwise) exists only indocs/scheduling-runtime-design.md:435-441. Its neighbours in the same file state their invariant in one line (cost.rs:40-41,110-113,282-285), andrepo-proseSKILL.md:38-39 asks comments to explain invariants. -
Conforming, checked: SPDX header and second copyright line in
sam.rs:1-5matchspeculation.rs:1-5; thewide_copy_curve/expected_copy_tokenswrapper structure mirrorspowered_curve/expected_speculative_tokens(rounds.rs:528-557); the per-shape curve cache in the wide-copy block (rounds.rs:747-748, 794-795) follows the existing "Lane forecasts stay fixed while shapes compete" cache comment (rounds.rs:746);docs/scheduling-runtime-design.md:430-495was correctly updated for the readiness-wait exclusion, retained idle credit and the two-tier refresh ordering.
#10 [high] Report of 2026-11-26, run 2 — conventions and duplication
Review — PR #540, lens: conventions and duplication
Verdict: should-fix issues; nothing blocking from this lens
Findings, in the order they should be addressed. Every one was checked in the code at head 14019718.
Should fix
-
draft_sourceis not part of prepared-shape identity (entry #5).GraphDescriptor::draft_source(execution/manifest.rs:191-192) is a new discriminant, butcatalog::select_shape_with_drafts(model/catalog.rs:279-293) andcost::Key(scheduler/cost.rs:50-58, with the duplicate rejection inActionCosts::preparedat cost.rs:159-161) both omit it, and both fail hard on a duplicate shape ("ambiguous prepared model graph capacity" / "prepared graphs require unique shapes"). So an MTP and a copy graph at the same B/D/W/P cannot coexist, even thoughruntime_core/selection.rs:250-251already treatsdraft_sourceas part of the serving-variant identity and the new checks at catalog.rs:94-131 and manifest.rs:845-846 contemplate copy-only graphs. Fix: adddraft_sourcetoKey/Key::from_stepand to theselect_shape_with_draftsfilter; thenEstimate.draft_source,PackedRoundShape::draft_sourceandis_copy_only_step's table probe (cost.rs:223-232) can go. -
The wide copy-only cohort loop duplicates the ordinary packed-round loop (entry #6). rounds.rs:791-902 repeats rounds.rs:925-1060 step for step —
scoresfromcurve * output_token,rank_prefixes,ranks_by_slot/slots_by_rank, the three orderings withselect_nth_unstable_by/truncate/sort_unstable_by, thefrontiertrim againstdraft_budget,lane_terms, and the identical best-mask tie-break. Only the curve source differs. Precedent in the same function:rank_prefixes,fixed_round_candidate,host_prefix_ranking, andwide_copy_curvewrappingpowered_curveare all factored that way. The copy branch also silently omits the ordinary branch'ssurplus_tablefactor (1031-1037), so the two copies already differ. -
Four hand-written
draft_sourcewire ladders, one canonical parser (entry #7). serving.rs:58-63, python.rs:225-233, selection.rs:144-148 and model.rs:1095-1102 each spell the integer mapping;server/config.rs:188-194usesProposalSource::parse(speculation.rs:30-38).GraphKind,Dtype,SamplingModeand the contract enums all keep oneTryFromnext to the type (manifest.rs:50-68,109-121,123-145; contract.rs:23), and the generatedwire::DraftSourcealready exists (proto/runtime_core.proto:854). AddProposalSource::from_wire/as_strand call it; the copies currently disagree on whether an unknown value is an error. -
Docs that own the changed field were not updated (entry #8).
helios/manifest.md:29-53omitsdraft_source, althoughignition/preparation/execution.py:316-319now emits it andheliopause/src/python.rs:225-233reads it.docs/mtp-design.md:22-40still describes copy proposals as only the 65,536-token shared ring ("Both settings use the same captured MTP graphs and buffers") when the primary path is the per-request SAM (scheduler.rs:1099-1159; sam.rs:22-32) and--history-draftsnow also changes the retained graph set (selection.rs:277-298,382-396);docs/cli-design.md:741likewise.docs/scheduling-runtime-design.md:6-12omitssam.rsfrom the module index of the document that specifies copy proposals. Cite repo-prose SKILL.md:26-29 and AGENTS.md:52-60. -
The new padded-batch dominance rule is written twice in one function (entry #9, item 1). policy.rs:143-165 (pairwise, in
dominates_padding_with) and policy.rs:225-254 (scan, inprune_padding) encode the same invariant with different threshold expressions and only the scan carries theother.batch >= lanesguard. Fold the guard into the pairwise rule and let the existing peer loop (policy.rs:215-220) be the only caller.
Nits
- Zero-duration expected value is spelled out five times (policy.rs:1083-1096, policy.rs:1263-1295, rounds.rs:725-726, rounds.rs:879-885, rounds.rs:1048-1054) in slightly different closure shapes; one helper would state the "refresh ranks by expected value at zero duration" invariant once.
- Unconsumed public SAM API:
propose_for_context(sam.rs:1070),propose_conditional_continuations(sam.rs:1118),MatchSource/MatchProposal::source,PromptSAM::build,push_slice, and the accessors have no caller outside tests; the doc names a "2-deep pipelined execution" that exists nowhere. AGENTS.md:188-193 rejects surface added without a concrete requirement. - Five unexplained constants:
WIDE_COPY_PRIOR_RATE = 0.88,COPY_STEP_PRIOR_WEIGHT = 4.0,COPY_DEPTH_SHRINK_WEIGHT = 2.0(speculation.rs:14-21), a bare+3(rounds.rs:766), andDEFAULT_MIN_MATCH_LEN/WIDE_COPY_MIN_MATCH_LENboth6(sam.rs:22, speculation.rs:18). Charter: "Be explicit and pin everything. No magic defaults"; AGENTS.md:452-456: one home per setting. - The test oracle (
sam.rs:1236-1273) returns the productionMatchProposaland re-derivesbuild_proposal, unlikedecoded_history.rs:228-252whose oracle returns plain tuples. refresh_order's(bool, u64)(cost.rs:287-296) lost its contract comment; neighbours carry theirs.
Checked and conforming
SPDX/second copyright line in sam.rs matches speculation.rs; the wide_copy_curve/expected_copy_tokens wrapper mirrors powered_curve/expected_speculative_tokens; the per-shape curve cache follows the existing lane-forecast cache comment; docs/scheduling-runtime-design.md:430-495 was updated correctly for readiness-wait exclusion, retained idle credit, and the two-tier refresh ordering; the draft_source Protobuf field defaults to MTP, preserving existing cores (AGENTS.md:437-440).
#11 [high] Research summary
Reviewed PR #540 through the conventions-and-duplication lens; all changed files were read in context and every finding verified at head 14019718. Full report is scratchpad entry #10, with supporting detail in entries #5–#9.
Verdict: should-fix issues, nothing blocking.
Should fix:
draft_source(newGraphDescriptorfield) is missing from both prepared-shape identities —catalog::select_shape_with_drafts(model/catalog.rs:279-293) andcost::Key(cost.rs:50-58, duplicate rejection at 159-161) — so an MTP and a copy graph at the same B/D/W/P fail to load, whileruntime_core/selection.rs:250-251already treats the field as part of the variant identity.- The new wide copy-only cohort loop (rounds.rs:791-902) duplicates the ordinary packed-round loop (rounds.rs:925-1060) step for step, differing only in the curve source, and already lacks the ordinary block's
surplus_tablefactor. - Four hand-written
draft_sourceinteger ladders (serving.rs:58-63, python.rs:225-233, selection.rs:144-148, model.rs:1095-1102) where the repository keeps oneTryFromper enum andProposalSource::parsealready exists. helios/manifest.md:29-53omitsdraft_source;docs/mtp-design.md:22-40anddocs/cli-design.md:741still describe copy drafting as only the shared ring;docs/scheduling-runtime-design.md:6-12omitssam.rs.- The new padded-batch dominance invariant is encoded twice in
policy.rs(143-165 pairwise, 225-254 as a scan), with only the scan carrying the active-cohort guard.
Nits: five-way repeated zero-duration expected-value pricing, unconsumed pub SAM API, five unexplained constants (plus the duplicated 6), a test oracle that shares production shapes, and refresh_order's undocumented (bool, u64). Conforming items (SPDX header, curve-wrapper structure, forecast caching, and the correctly updated refresh prose in docs/scheduling-runtime-design.md) are listed in the report.
#12 [high] Coverage, non-findings and open items for the #540 conventions review
Supplementary note for the final report on PR #540 (head 14019718). Complements entry #10 (the report) and #5–#9 (per-finding evidence).
Files read in context (all 25 changed files, at least around every hunk)
- helios/src/scheduler.rs (1-45, 1080-1215, 1840-1900, 2500-2520, 2790-2910), scheduler/{cost.rs 1-380, decoded_history.rs 100-200, policy.rs 100-300, rounds.rs 490-1069, refresh.rs diff, sam.rs 986-1240 + module docs + 1-60 of the file body, speculation.rs 1-300, tests.rs 1950-2130, policy_tests.rs diff}.
- helios/src/execution/{manifest.rs 40-140, 820-880, tests.rs}, model/{catalog.rs 60-296, packing.rs 370-430 and 680-730, testing.rs, tests.rs diff}, runtime_core/{selection.rs 130-400 and 1551-1625, serving.rs 30-95, describe.rs via search}, server/{runtime.rs 1718-1730 / 2128-2150, config.rs 180-200}.
- heliopause/src/python.rs 200-260; heliopause/src/export/binding.rs 136-250 (the manifest→wire conversion); ignition/preparation/execution.py 1-130, 290-340; helios/proto/runtime_core.proto 820-870.
- Rules: AGENTS.md (whole structure, 1-80, 170-210, 420-470), .agents/skills/repo-prose/SKILL.md, read_charter, docs/mtp-design.md 1-50, docs/scheduling-runtime-design.md 1-60 + diff, docs/cli-design.md 725-760, helios/manifest.md 1-90.
Deliberately not flagged (checked, conforming)
draft_sourceProtobuf field is a defaulted enum (NO_DRAFT = 0) withMTP = 1behaviour preserved, satisfying AGENTS.md:437-440.helios/src/scheduler/decoded_history.rs:162-183correctly keepslookupas a wrapper overlookup_with_match_len— the model to follow for the duplicate in scheduler.rs (entry #5, finding 1 in the earlier run).docs/scheduling-runtime-design.md:430-495prose matchesrefresh.rsandcost.rs(readiness-wait exclusion, retained idle credit, two-tier refresh ordering).helios/src/scheduler/cost.rs:31-38observed_compute_duration_ns/timing_refresh_duration_nsare built on the existingobserved_duration_nsrather than re-deriving the max-positive-interval rule (cost.rs:21-29); the same subtraction already exists at cost.rs:325 and checkpoints.rs:764, but costing it as a named helper is the right direction rather than a duplication defect.rounds.rs:541-557wide_copy_curve/expected_copy_tokensmirrorspowered_curve/expected_speculative_tokens(rounds.rs:528-539) as intended; the defect is only the unreachableelsearm re-derivingWIDE_COPY_PRIOR_RATE.powi(depth+1)instead of usingCopyCalibration's own prior (speculation.rs:121-151), recorded as finding 2 in the earlier run.
Only a test settles these two
- Whether
catalog::select_shape_with_drafts/ActionCosts::preparedreally reject an MTP + copy pair at identical B/D/W/P: reading the filters says yes (nodraft_sourceterm, explicit duplicate errors), but the new test athelios/src/model/tests.rs:1861-2075uses distinct geometries and therefore does not exercise it. One graph pair plusInputs::newwould confirm. - Whether
LiveRequest.copy_calibrationcan ever beNonewherewide_copy_curveruns: admission setssamandcopy_calibrationfrom the samedecoded_history.is_some()predicate (scheduler.rs:1849-1856) andenable_history_draftsrefuses after any admission (scheduler.rs:1086-1092), so theelsearm looks dead. A test constructingsam: Somewithcopy_calibration: Nonewould settle whether the invariant should be enforced structurally (oneOption<PerRequestCopyState>holding both).
Scope note
The PR bundles four commits (cost-refresh recovery, prompt+output SAM, calibrated wide copy-verify, padding dominance). Findings are attributed per file; entries #5/#6 cover commits 3 and the rounds cost, entries #7/#8 cover the wire/doc surface across commits 2 and 3, entry #9 covers commit 4 (policy.rs dominance) plus nits. Live GPU evidence in the description was not re-verified — no hardware in this review.
#14 [high] Report of 2026-11-26, run 3 (head e5a69669) — conventions and duplication
Review — PR #540, lens: conventions and duplication, head e5a69669
Resolved by e5a69669 (previously recorded findings, now closed)
cost::Keygaineddraft_source(cost.rs:61-84) andmodel/catalog.rs:247-307gainedselect_shape_with_sourcewith the source in the filter, so an MTP and a copy graph at identical B/D/W/P now load and pack (manifest.rs:191-192 identity is honoured in cost, catalog and packing.rs:40-53). Prior should-fix #5 no longer reproduces.scheduler.rs:1112-1194:resolve_copy_match+CopyMatchnow back bothrequest_history_proposal_with_match_lenandrequest_copy_match_stats, and the zero-count shared-ring drift is fixed (.filter(|&(_, count, _)| count > 0)at 1138). Prior should-fix #1 closed.rounds.rs:764-862select_host_allocated_candidateserves both the wide copy-only block and the ordinary host-allocated block, withbuild_host_prefix_ranking(505-527) shared; the duplicated cohort loop of prior #6 is gone.- Three of the four
draft_sourceladders now route throughProposalSource::from_wire/to_wire(speculation.rs:55-69): serving.rs:58 and python.rs:225-233 and selection.rs:144-148. Onlyruntime_core/model.rs:1095-1102(prefix-state digest string ladder) still hand-rolls "mtp"/"copy" — pre-existing, unchanged by this PR. - Docs: helios/manifest.md:38 now documents
draft_source; docs/mtp-design.md:22-73 rewritten for the per-request SAM + fallback; cli-design.md:200-207,744 updated; scheduling-runtime-design.md:12-15 addssam.rs, :71-90 adds the proposal-source section, :409-433 the per-source packed tables; scheduling-theory.md:574-582,714-747 the retained-credit/two-tier delta. Prior should-fix #8 closed.
Confirmed findings at e5a69669 (this pass)
Should fix 1 — the removed has_mtp existence scan came back inside packed_round_duration
helios/src/scheduler/cost.rs:237-252. The commit deleted has_mtp from refresh_packed_durations (cost.rs:204-221 now writes both tables unconditionally), but the combined lookup reintroduces the same whole-table existence scan:
(None, Some(0)) if !self.packed_round_durations[ProposalSource::Mtp as usize]
.iter().any(|row| row.iter().any(Option::is_some)) => Some(0),
This asks "was any MTP shape ever measured, at any batch and width", not the question the neighbouring arms ask ("do MTP covering shapes exist for this (batch, width)"). Consequences: a copy-only (batch,width) that is unmeasured returns None on a core with any other measured MTP shape and Some(0) on a core without one; both mean unmeasured, but the contract in docs/scheduling-runtime-design.md:424-433 ("return zero only when covering shapes exist without a positive measurement") is met only by the (Some(0), _) arm. Fix: give packed_round_duration_for the same presence signal refresh_packed_durations writes (a covering-shape predicate, or a third covered: [[bool; …]; 2] table), and express the combined rule as mtp.or(copy) over that, so the "covering shapes exist" test exists once instead of an existence scan over the whole catalog.
Should fix 2 — history_proposal bypasses the clamp_copy_capacity helper added directly below it
helios/src/scheduler.rs:1101-1110. history_proposal (1101-1104) inlines maximum.min(self.capabilities.completion_token_capacity - 1).min(speculation::COPY_DRAFT_CAPACITY), while clamp_copy_capacity (1106-1110) is the same expression with saturating_sub(1). The two have already diverged on the completion_token_capacity == 0 case, and every other copy path now goes through the helper (1169, 1188). Fix: let maximum = self.clamp_copy_capacity(maximum); in history_proposal and delete the inline copy.
Should fix 3 — Option<ProposalSource> canonicalization repeated where the helper cannot reach
helios/src/scheduler/cost.rs:50-59 adds canonical_draft_source(kind, Option<ProposalSource>) = "speculative graphs default to Mtp", pub(super). The same rule is then written by hand twice outside the scheduler module, where pub(super) makes the helper unusable:
helios/src/model/catalog.rs:296-299:graph.draft_source.unwrap_or(speculation::ProposalSource::Mtp) == draft_source.unwrap()helios/src/model/packing.rs:48-51: the sameunwrap_or(...Mtp)comparison againststep.draft_source. Convention: this isProposalSource's own default, not a cost-table detail, andspeculation.rsis where the enum and itsparse/from_wire/to_wirealready live (speculation.rs:46-70). Fix: addProposalSource::default_for(kind, Option<Self>) -> Option<Self>(orimpl From<(GraphKind, Option<ProposalSource>)>) next tofrom_wireand have cost, catalog and packing call it, so the "speculative graphs default to MTP, others have no source" rule is stated once.
Nits
helios/src/scheduler/policy.rs:1052-1056(and 1256-1260): the new zero-duration pricing re-implements theDecode | Speculativearm oflane_value_for_tokens(policy.rs:987-1007) inline, so the two must be kept in step; alane_values-style helper returning(at_duration, at_zero)would keep the arm in one place and still satisfy the curve-reuse tests (policy_tests.rs:6290-6330).helios/src/scheduler/cost.rs:262-272max_mtp_draft_tokensstill scansentriesfilteringdraft_source != Some(Copy)to find a maximum, althoughpacked_round_durationsis now per source; a per-source maximum written inrefresh_packed_durationswould match the new table layout.helios/src/scheduler/cost.rs:223-235packed_round_duration_foris the only method that takes aProposalSourcewhile its siblingpacked_round_duration(237) is the combined convenience; the pair reads as two different concepts with no doc comment on either, unlike neighbourscost.rs:40-41,110-113,324.helios/src/scheduler/rounds.rs:570-579wide_copy_curvenow.expectscopy_calibration, whichscheduler.rs:1843-1850only creates whendecoded_historyis set; the invariant is real but stated only in the panic message — adebug_assert-documented?/Optionsignature (asresolve_copy_matchuses) would match the module's style.
Verified conforming this pass
cost.rs:204-221per-source tables follow the[Vec<Option<u64>>; 7]precedent and usemin_measured_duration(cost.rs:42-48) rather than open-coding the minimum.heliopause/src/export/binding.rs:201-216derives the wire string and rejects unknown/COPY_DRAFT-non-speculative values, matchingbinding.rs:996-998(PromptEncoder::try_from+invalid("unsupported …")) as the local idiom.ignition/preparation/execution.py:102-108now rejectsdraft_source == 2onmixedanddecodealike, matching the Rust check atexecution/manifest.rs:845-850.scheduler.rs:1196-1199is_copy_only_stepreads the step's own source instead of doing a cost-table lookup (previouslycosts.is_copy_only_step), so the source is stated once.model/packing.rs:40-53matches_stepreplaces the two identical inline graph-matching closures, matching the "one predicate" shape ofcatalog::select_shape.
#15 [high] Research summary
Reviewed PR #540 at head e5a69669 through the conventions-and-duplication lens; full findings are in scratchpad entry #14.
The review-fix commit closed every should-fix item I recorded at 14019718: cost::Key and model::catalog::select_shape_with_source now carry draft_source (so an MTP and a copy graph at identical B/D/W/P coexist and pack); resolve_copy_match backs both SAM entry points and the zero-count ring drift is gone; select_host_allocated_candidate / build_host_prefix_ranking collapsed the duplicated cohort loop; three of the four draft_source ladders now route through ProposalSource::from_wire/to_wire; and helios/manifest.md, docs/mtp-design.md, docs/cli-design.md (not opened), docs/scheduling-runtime-design.md and docs/scheduling-theory.md (not opened) now specify the per-request SAM, the retained graph selection, the per-source packed tables and the retained idle credit.
Three new should-fix items, all small and mechanical:
helios/src/scheduler/cost.rs:237-252— thehas_mtpexistence scan that the commit deleted fromrefresh_packed_durationsreappears inside the combinedpacked_round_duration: it asks whether any MTP shape anywhere was measured, not whether MTP shapes cover this(batch, width), so an unmeasured copy-only cell returnsNoneon one catalog andSome(0)on another, and the "zero only when covering shapes exist without a measurement" contract indocs/scheduling-runtime-design.md:424-433is met by only one arm.helios/src/scheduler.rs:1101-1104—history_proposalinlines the copy-capacity clamp thatclamp_copy_capacity(1106-1110) states directly below it, and the two already diverge (min(… - 1)vssaturating_sub(1)).helios/src/model/catalog.rs:296-299andhelios/src/model/packing.rs:48-51re-state "speculative graphs default toMtp" becausecost::canonical_draft_sourceispub(super); the rule belongs next toProposalSourceinspeculation.rs, whereparse/from_wire/to_wirealready live.
Plus four nits (the zero-duration pricing re-implementing lane_value_for_tokens' Decode/Speculative arm in policy.rs:1052-1056,1256-1260; max_mtp_draft_tokens still scanning entries; undocumented packed_round_duration_for; wide_copy_curve's .expect), and a note on what I verified as conforming. No blocking issues.
#16 [high] Verdict and coverage for the e5a69669 conventions review
Verdict (head e5a69669)
Verdict: should-fix only. No blocking items found.
Per-finding ordering for the report (details, line numbers and fixes are in entry #14):
- Should fix 1 —
helios/src/scheduler/cost.rs:237-252:has_mtp-style whole-table existence scan returns inside the combinedpacked_round_duration; an unmeasured copy-only(batch, width)yieldsNonewhen any MTP shape is measured anywhere andSome(0)otherwise, contradictingdocs/scheduling-runtime-design.md:424-433("return zero only when covering shapes exist without a positive measurement"). Fix: carry a per-source "covered" flag alongsidepacked_round_durationsso the presence test is written once. - Should fix 2 —
helios/src/scheduler.rs:1101-1104:history_proposalinlines the clamp thatclamp_copy_capacity(1106-1110) states immediately below; the copies differ oncompletion_token_capacity == 0(min(… - 1)vssaturating_sub(1)). - Should fix 3 —
helios/src/model/catalog.rs:296-299+helios/src/model/packing.rs:48-51: "speculative graphs default toMtp" is restated by hand becausecost::canonical_draft_source(cost.rs:50-59) ispub(super); the rule belongs next toProposalSource(scheduler/speculation.rs:46-70). - Nits (4) —
policy.rs:1052-1056,1256-1260re-implementlane_value_for_tokens' Decode/Speculative arm inline;cost.rs:262-272max_mtp_draft_tokensstill scans entries after the per-source split;cost.rs:223-237packed_round_duration_for/packed_round_durationpair has no doc comment unlike neighbours (40-41, 110-113, 324);rounds.rs:570-579wide_copy_curve.expectscopy_calibration, whose invariant lives only in the panic string (scheduler.rs:1843-1850). Also noteruntime_core/model.rs:1095-1102keeps the one remaining hand-written"mtp"/"copy"ladder — pre-existing, not introduced here.
Coverage
Every file changed by the PR was read in context at e5a69669: the docs (cli-design.md, mtp-design.md, scheduling-runtime-design.md, scheduling-theory.md, helios/manifest.md), heliopause/src/export/binding.rs and heliopause/src/python.rs, helios/src/execution/{manifest.rs,tests.rs}, helios/src/model/{catalog.rs,packing.rs,testing.rs,tests.rs}, helios/src/runtime_core/{selection.rs,serving.rs}, helios/src/scheduler.rs, helios/src/scheduler/{checkpoints,cost,decoded_history,planning_tests,policy,policy_tests,refresh,rounds,sam,speculation,speculative_lifecycle_tests,tests}.rs, helios/src/server/{metrics/scheduler.rs,runtime.rs,runtime/phase_tests.rs}, ignition/preparation/execution.py, tests/preparation/test_execution.py. Callers followed for every behaviour change: server/runtime.rs:2238 → catalog::select_shape_with_source; scheduler.rs:1843-1850 → the SAM/CopyCalibration admission gate; rounds.rs:879-936 → request_copy_match_stats and wide_copy_curve; service.rs:109,156 and policy.rs:629,785 → speculative_duration → packed_round_duration.
Settled only by running code: the two behaviour claims the PR makes about the copy-only cohort path (that an unmeasured copy-only wide graph still competes on its prior, and that unmeasured_mtp_and_measured_copy_coexist_at_identical_shape_and_preserve_packed_duration covers the combined-lookup arm on a real catalog) — the code shows the branches exist, but only a test that exercises cost.rs:244-249 on a catalog with a measured MTP shape at a different batch would demonstrate the divergence in should-fix 1.
#18 [high] Should fix: helios/README.md still says idle discards positive credit
PR #540 head 982a9ce3. This PR deletes RefreshState::idle (helios/src/scheduler/refresh.rs:95-99 area; idle removed, abort inlined) and makes RequestScheduler::idle (helios/src/scheduler.rs:1158-1168) a pure validation that retains credit.
Updated by this PR:
- docs/scheduling-runtime-design.md:436-444 ("Idle retains bounded earned credit (
<= 5 ms) and negative debt; abort discards positive credit and preserves debt.") - docs/scheduling-runtime-design.md:489-496 (acceptance section, same change)
- docs/scheduling-theory.md:576-583, 729-738 (simulator default +
--retain-idle-credit)
NOT updated but now false:
- helios/README.md:432-437: "Ordinary valid execution earns refresh credit at
0.002 / 0.998times its measured duration, capped at 5 ms. ... Another refresh waits for full credit. Idle discards positive credit and preserves debt."
helios/README.md is the crate-level present-state spec (docs/scheduling-runtime-design.md's own sibling; it already restates the median-of-nine rule and links to #funded-timing-refresh). Precedent for keeping it in sync: it was edited by the same series of scheduling PRs and line 437 is a one-sentence restatement of exactly the paragraph this PR rewrites. Fix: replace that clause with "Idle retains bounded earned credit and preserves debt; abort discards positive credit and preserves debt," and say credit is 0.002 / 0.998 of measured compute duration (excluding readiness wait), matching the doc.
Severity: should fix (docs contradiction with new behaviour, not correctness).
#19 [high] Should fix: readiness-wait sample selection now has a fifth hand-written copy
PR #540 head 982a9ce3, conventions/duplication lens.
New helper observed_compute_duration_ns (helios/src/scheduler/cost.rs:37-45):
let wait_ns = timing.readiness.map_or(0, |intervals| intervals.wait_ns());
let gpu_ns = timing.gpu_ns.into_iter().flatten().max().filter(|&ns| ns > 0)?;
if gpu_ns <= wait_ns { return None; }
let observed = if timing.queued { gpu_ns } else { gpu_ns.max(timing.wall_ns) };
Some(observed - wait_ns)
Its own doc comment says "Mirrors ActionCosts::observe". ActionCosts::observe (cost.rs:330-337) independently writes the same two steps:
let Some(raw_sample) = timing.gpu_ns.into_iter().flatten().max().filter(|n| *n > 0) else { return; };
let sample = raw_sample.saturating_sub(timing.readiness.map_or(0, |intervals| intervals.wait_ns()));
if sample == 0 { return; }
Existing precedents for the same idiom (no shared helper today):
- helios/src/scheduler/checkpoints.rs:754-764 (
credit_checkpoint_decode):gpu_ns.into_iter().flatten().max().filter(|&n| n > 0)thengpu_ns.saturating_sub(readiness.map_or(0, |r| r.wait_ns())). - helios/src/server/metrics/scheduler.rs:201-206 and 179-180:
timing.gpu_ns.into_iter().flatten().max().filter(|ns| *ns > 0).
So this PR adds a fourth copy of a two-part predicate (max positive gpu_ns; readiness.wait_ns() as the subtraction operand) in the same module, forty lines from the first copy, and the doc comment admits they must stay in lockstep ("when gpu_ns <= wait_ns the cost sample is discarded as zero"). Any future change to the readiness-exclusion rule (e.g. per-interval exclusion, or excluding wait only on queued samples) has to be made in observe, observed_compute_duration_ns, and credit_checkpoint_decode together; they already differ subtly (observe uses saturating_sub + == 0, the new helper uses <= + -).
Fix: give ActionCosts::observe the helper, i.e. extract fn measured_gpu_sample(timing) -> Option<u64> (max positive gpu_ns) and fn readiness_wait_ns(timing) -> u64 once in cost.rs, then have observe call them and derive its 0-discard from the same predicate observed_compute_duration_ns uses (gpu_ns <= wait_ns). Note observe deliberately does not take wall_ns when unqueued (cost.rs:334 vs 343), so only the two extractors can be shared without changing behaviour — that asymmetry should then be documented on both, since it is currently silent.
Severity: should fix (duplication of a predicate the PR itself had to keep in lockstep, in the file that owns it).
#24 [high] Report of 2026-11-28, run 4 (head 982a9ce3) — conventions and duplication
Verdict: no blocking issues; 3 should-fix (all duplication/doc-sync), 4 nits.
This is a fourth-pass conventions-and-duplication review of PR #540 at head 982a9ce3, after the author narrowed it to idle-credit retention + readiness-wait exclusion. Almost all previous findings are gone with the SAM/wide-copy/padding-pruning code: entries #1, #2, #5, #6, #7, #9 are moot (their code no longer exists in the diff), and #8's SAM/copy prose items are moot. helios/README.md staleness (#3's doc-index item) survives and is now worse.
Changed files read in context: helios/src/scheduler.rs (idle 1158-1168; complete 2655-2658; release_after_shutdown 3062), helios/src/scheduler/cost.rs (21-57 new helpers; 330-353 observe; 439-504 new test), helios/src/scheduler/refresh.rs (whole file, 101 lines), helios/src/scheduler/policy_tests.rs (fixtures 91-274, 792-799, 1196-1208, existing refresh tests 2380-2616, new tests + fixture 5812-6183), scripts/scheduling_sim/learning.py (40-180, 455-500), scripts/scheduling_sim/learning_policy.py (1-140, 600-704), tests/test_scheduling_learning_experiments.py (470-540, 741-791), tests/test_scheduling_learning_policy.py (1500-1572), docs/scheduling-runtime-design.md (430-500), docs/scheduling-theory.md (540-620, 670-760), plus callers/rules: AGENTS.md, docs/design-review.md testing hierarchy, helios/README.md 415-460, helios/src/server/runtime.rs:1184, helios/src/server/metrics/scheduler.rs, helios/src/scheduler/checkpoints.rs:754-764, helios/src/execution/readiness.rs, helios/src/execution/transport.rs:1042-1063.
Should fix:
- helios/README.md:432-437 still says "Idle discards positive credit and preserves debt" and omits the readiness-wait exclusion — the crate-level present-state spec contradicts the new behaviour and its two updated siblings (docs/scheduling-runtime-design.md:436-444, 489-496). Entry #18.
- cost.rs:37-45
observed_compute_duration_nsis a fourth hand-written copy of "max positive gpu_ns, subtract readiness wait" —ActionCosts::observeforty lines below (cost.rs:330-337) computes the same two steps, and they already diverge (saturating_sub+== 0vs<=+-). Its own doc says "Mirrors ActionCosts::observe". Precedents for the idiom: cost.rs:331-334, checkpoints.rs:754-764, metrics/scheduler.rs:179-206. Entry #19. - policy_tests.rs:5812-5878
large_prefill_engineis the third copy of the terminal-prefill fixture (engine_with_terminal_prefill4364-4406,cold_deepseek_16k_engine5443-5508): sameprefill_graphs/terminal_prefill_graphs/duration_graphs/retain/descriptor-literal sequence with the samehandle: 100 + capacityconvention. Entry #20.
Nits: income-rate literal instead of refresh::INCOME_RATE (#21); four parallel PolicyConfig field lists in learning.py:105-137/478-483 instead of deriving from dataclasses.fields (#22); the exploration bound re-derived three ways with two different overrun terms — last_refresh_ns in Rust vs max(145, 30) in Python (#23).
Verified-correct non-findings (worth saying so):
abortnow inlines the two.min(0.0)lines that wereidle;RefreshState::idledeletion leaves no stale caller (scheduler.rs:1163is the onlyidle,tests/.../policy_tests.rs:3548updated toabort), andrefresh.credit_ns/acceptance_credit_nsretention is exactly what docs/scheduling-runtime-design.md:436-444 and 489-496 now state.timing_refresh_duration_ns'sor_else(observed_duration_ns).unwrap_or(wall_ns)is a strictly-positive fallback chain and is covered for<,==,wall_ns == 0and> 0(cost.rs:468-503); acceptance stays onobserved_duration_ns(refresh.rs:77-79, 83-85), matching the doc's "acceptance-learning budgets use raw physical time".- The PR no longer touches
ActionCosts::refresh_order(cost.rs:303-305 unchanged frommain) — the starvation concern raised in the review is addressed by restoration, and the regression test at policy_tests.rs:5964-6057 exercises it. RequestScheduler::idle's doc comment (scheduler.rs:1158-1162) is accurate and stays inside the crate's idiom of documenting a validation gate rather than a state transition.--retain-idle-creditfollows the established simulator idiom exactly:store_true, default=None(learning.py:439-440), boolean type check inPolicyConfig.__post_init__(learning_policy.py:83-84), id suffix viaconfiguration_id, and the same sweep/validate guards as--partial-blocks(compare learning.py:132/478-483 with tests/test_scheduling_learning_experiments.py:492-509). The new test at tests/test_scheduling_learning_experiments.py:746-791 mirrorstest_partial_block_uncertainty_is_explicit_and_keeps_default_idsclosely enough that it is borderline duplication, but the extramain()argv rejection is genuinely new coverage.
Not verified by me (only a test/run can settle): the 64-seed simulator validation and the Rust suite claims in the PR body; live GPU/HTTP readiness-stall behaviour (tests/server/test_scheduler.py, power-cap recovery) was not run here.
#25 [high] Research summary
Reviewed PR #540 at head 982a9ce3 through the conventions-and-duplication lens. The reworked PR is much narrower than the version I last saw, so most earlier findings (SAM/copy-draft entry points, wide copy-verify, padding pruning, draft_source wire ladders, refresh_order tiering) are moot — that code is gone. Every changed file was read in context, including the sibling specs and the callers of the changed behaviour.
Verdict: no blocking issues. 3 should-fix, 4 nits — all duplication or doc-sync, none behavioural.
Should fix:
helios/README.md:432-437still states "Idle discards positive credit and preserves debt" and omits the readiness-wait exclusion; this crate-level present-state spec now contradicts the behaviour and the two docs this PR did update (docs/scheduling-runtime-design.md:436-444,489-496).helios/src/scheduler/cost.rs:37-45— the newobserved_compute_duration_nsis a fourth hand-written copy of "max positivegpu_ns, subtract readiness wait".ActionCosts::observeforty lines below (cost.rs:330-337) computes the same two steps and its own doc comment says it "Mirrors" it; they already diverge (saturating_sub+== 0vs<=+-). Existing precedents:checkpoints.rs:754-764,server/metrics/scheduler.rs:179-206.helios/src/scheduler/policy_tests.rs:5812-5878—large_prefill_engineis the third copy of the terminal-prefill fixture, afterengine_with_terminal_prefill(4364-4406) andcold_deepseek_16k_engine(5443-5508), down to thehandle: 100 + capacityconvention.
Nits: 0.002 / 0.998 retyped instead of refresh::INCOME_RATE; four parallel PolicyConfig field lists in learning.py:105-137,478-483 where dataclasses.fields is the established mechanism (configuration_id already uses it) — adding retain_idle_credit needed four edits; and the exploration bound re-derived three ways with two different overrun terms (last_refresh_ns in Rust vs max(145, 30) in Python).
I also verified and cleared the things most likely to be wrong here: the RefreshState::idle deletion leaves no stale caller, abort correctly keeps only non-positive balances, timing_refresh_duration_ns is a strictly-positive fallback chain covered for <, ==, wall_ns == 0 and > 0, acceptance ledgers stay on raw physical time as documented, and refresh_order is untouched from main. --retain-idle-credit follows the --partial-blocks idiom exactly. The simulator/GPU evidence in the body was not re-run by me.
#26 [high] Superseded findings: which earlier scratchpad entries are moot at 982a9ce3
PR #540 was reworked to 982a9ce3 ("Retain bounded timing-refresh credit across idle and exclude readiness wait"). All SAM / history copy-drafting, wide copy-verify (COPY_DRAFT, W=16/24), speculative batch-padding pruning, and refresh_order tiering were REMOVED from the PR by the author in response to review. Therefore these earlier high-importance notes are MOOT and must not appear as current findings:
- #1 (request_copy_match_stats duplicates request_history_proposal_with_match_len) — SAM code removed.
- #2 (wide_copy_curve fallback duplicates CopyCalibration prior) — removed.
- #5 (draft_source not part of prepared-shape identity) — the
draft_sourcegraph field / per-source cost keys are gone from this PR. - #6 (wide copy-only cohort loop duplicates ordinary packed-round loop) — removed.
- #7 (four hand-written draft_source wire ladders) — removed.
- #9 (prune_padding dominance duplication, five-way expected-value pricing, unconsumed SAM API, refresh_order tuple docs) — removed/shifted out of scope.
- #10, #11, #13, #14, #15, #16, #17 — reports of earlier heads; superseded by #24.
Partly surviving:
- #3 / #8 doc-sync item: the SAM/copy-draft prose items are moot, but the
helios/README.mdstaleness survives and got worse — see #18. - The reviewer's
refresh_orderstarvation concern (raised ate5a69669) is resolved by restoration:ActionCosts::refresh_order(cost.rs:303-305) is byte-identical tomain, and the regression test is policy_tests.rs:5964-6057.
Current findings live in #18 (README staleness), #19 (cost.rs readiness predicate duplication), #20 (policy_tests fixture duplication), #21/#22/#23 (nits), all summarised in #24 (the report).
#7 [medium] Should fix: four hand-written draft_source wire ladders, one canonical parser
The PR adds a fourth hand-written integer ladder for ProposalSource, while the same file family already has the canonical one.
Duplicated ladders:
helios/src/runtime_core/serving.rs:58-63—match g.draft_source { 0 => None, 1 => Mtp, 2 => Copy, _ => Err }.heliopause/src/python.rs:225-233—match graph.get_item("draft_source") { Some(0), Some(1), Some(2), Some(_) => Err, None => speculative.then_some(Mtp) }.helios/src/runtime_core/selection.rs:144-148(pre-existing, moved by this PR) —match config[...] { "mtp" => 1, "copy" => 2, _ => Err }.helios/src/runtime_core/model.rs:1095-1102(pre-existing) — the same string ladder again.helios/src/server/config.rs:188-194uses the correct one:speculation::ProposalSource::parse(...)(helios/src/scheduler/speculation.rs:30-38).
Precedent: every other closed enum in this layer has one TryFrom<&str>/TryFrom<i32> impl next to the enum and callers use it — GraphKind::try_from (execution/manifest.rs:123-145), Dtype::try_from (manifest.rs:50-68), SamplingMode::try_from (manifest.rs:109-121), and the declare_conversion! macro generating TryFrom<i32> for contract enums (model/contract.rs:23). The wire enum itself is declared once, DraftSource { NO_DRAFT = 0; MTP = 1; COPY_DRAFT = 2; } (helios/proto/runtime_core.proto:854), and the generated wire::DraftSource already has try_from(i32) and as_str_name(), which runtime_core/describe.rs:534,778 use.
Fix: add impl ProposalSource { pub fn from_wire(i32) -> Result<Option<Self>> } (or TryFrom<wire::DraftSource>) plus as_str() beside the existing parse, and have serving.rs, python.rs, selection.rs and model.rs call it. That also keeps the "unknown draft source is an error" rule in one place, which matters because the four copies disagree today: python.rs and serving.rs reject unknown values, selection.rs/model.rs only know the config strings.
Severity: should fix (small, mechanical, and the divergence is already visible).
#20 [medium] Should fix: large_prefill_engine is the third copy of the same test fixture
PR #540 head 982a9ce3. large_prefill_engine at helios/src/scheduler/policy_tests.rs:5812-5878 is a near-copy of two existing fixtures in the same file:
engine_with_terminal_prefill(policy_tests.rs:4364-4406): sameprefill_graphs(...)+terminal_prefill_graphs(...)+duration_graphs(1)+retain(|g| g.kind != GraphKind::Prefill)+ hand-builtGraphDescriptorloop for Prefill and TerminalPrefill.cold_deepseek_16k_engine(policy_tests.rs:5443-5508): same shape again (retain + push Prefill/TerminalPrefill descriptors withhandle: 100 + capacity/handle: 1000 + capacity).
The only differences in the new copy are: max_sequence_tokens: 131_072, prefill_chunk_size: 8192, replacing RequestScheduler::new(...)'s limits (identical field-by-field at 5444-5465), and estimated_duration_ns: 10 * MS / 12 * MS instead of the per-capacity formula. The three copies share the handle: 100 + capacity / 1000 + capacity convention and the retained duration_graphs base.
Fix: parameterise one helper — the existing engine_with_terminal_prefill(capacities) already takes the capacity list; add the limits/chunk override and the duration closure as arguments, or hoist a prefill_descriptors(kind, capacities, handle_base, duration) builder used by all three. That removes ~55 duplicated lines and keeps the future "graph descriptor gains a field" edit to one place (it has already been touched repeatedly — cf. the estimated_duration_ns additions in this PR's own test).
Severity: should fix (test-fixture duplication; the file already has the precedent helper, and the descriptor literal is repeated verbatim in three places).
#21 [low] Nit: income rate literal re-typed in the new assertions
PR #540 head 982a9ce3. Both new Rust tests re-derive the 0.002 / 0.998 income rate as a bare literal instead of using the module constant that governs the asserts:
- policy_tests.rs:5961
assert!(refresh_ns as f64 <= ordinary_ns as f64 * 0.002 / 0.998 + last_refresh_ns as f64); - policy_tests.rs:6056 same line again
- policy_tests.rs:6075
assert!((state.credit_ns - (145 * MS) as f64 * 0.002 / 0.998).abs() < 1e-6);
Precedent: refresh::INCOME_RATE (helios/src/scheduler/refresh.rs:10) is pub(super) and already the single definition; old tests in this file also hard-code 0.002 / 0.998 (2493, 2592, 2611, 2613), so the new code follows the local precedent but inherits its drift risk. refresh::ACCEPTANCE_INCOME_RATE (refresh.rs:11) likewise exists while the tests write 0.01 / 0.99 (e.g. policy_tests.rs:6076, 6086).
Fix: use refresh::INCOME_RATE / refresh::ACCEPTANCE_INCOME_RATE in the new assertions (they are already in scope via use super::...::refresh); the rate appears in the docs three times too (docs/scheduling-runtime-design.md:436, 467).
Severity: nit.
#22 [low] Nit: four hand-written PolicyConfig field lists, one dataclass
PR #540 head 982a9ce3. build_configurations in scripts/scheduling_sim/learning.py maintains four hand-written lists of the same boolean/categorical PolicyConfig fields:
- learning.py:105-109 — the field-name tuple whose non-None CLI values become
parameters. - learning.py:132 —
("estimator", "anneal", "initial_discovery", "mean_estimator", "partial_blocks", "retain_idle_credit"): the "categorical/boolean → reject--sweep" set. - learning.py:134-137 — the numeric
--sweepallow-list (parameters.keys() | {...}). - learning.py:478-483 — the validate-preset override guard tuple, same membership as (1).
Precedent for a single source: PolicyConfig (scripts/scheduling_sim/learning_policy.py:24-88) is a @dataclass(frozen=True) that already validates each field's type in __post_init__ (e.g. if type(self.retain_idle_credit) is not bool: raise …, learning_policy.py:83-84), and configuration_id (learning.py:48-56) already derives the id from fields(config) rather than a hand-written list. So the dataclass field list is the existing mechanism this change should have used: adding retain_idle_credit required four separate edits, and the --sweep rejection at line 132 is a newly moved duplicate of the numeric allow-list at 134-137 (the PR reordered the two checks so both now test membership of the same field family).
Note also that the boolean/categorical set is incomplete-by-construction: anneal and retain_idle_credit are booleans, estimator/initial_discovery/mean_estimator are categoricals, but the sweep allow-list at 134-137 is an explicit numeric set, so any future PolicyConfig field is silently sweepable unless added to line 132. That is the failure mode this PR just walked into.
Fix: derive the three sets from dataclasses.fields(PolicyConfig) plus a small NUMERIC_SWEEP_FIELDS / CATEGORICAL_FIELDS table declared next to the dataclass (or a class-level sweepable/categorical marker), so (1), (2) and (4) fall out of the field list and only (3) needs a decision.
Severity: nit (mechanism duplicated; no behavioural defect — the new tests at tests/test_scheduling_learning_experiments.py:746-791 do cover the sweep rejection and validate rejection for the new field).
#23 [low] Nit: the same bound is re-derived three ways with two different overrun terms
PR #540 head 982a9ce3. Both new tests assert an accounting bound with the same inline expression:
- policy_tests.rs:5961 and 6056:
assert!(refresh_ns as f64 <= ordinary_ns as f64 * 0.002 / 0.998 + last_refresh_ns as f64); - tests/test_scheduling_learning_policy.py:1561-1562:
allowance = s.ordinary_ms * s.config.alpha / (1 - s.config.alpha)thenassert s.probe_ms <= allowance + max(145.0, 30.0) + 1e-8— a third inline spelling of the same bound already asserted intest_retained_refresh_allowance_covers_overdraw_invalid_timings_and_idle(tests/test_scheduling_learning_policy.py:1519-1520), which derives it fromalpha / (1 - alpha) * s.ordinary_ms.
These are genuine independent re-derivations of E <= alpha/(1-alpha) * F + D (docs/scheduling-theory.md:569-574), which is a virtue for an oracle, so I would NOT require a shared helper. But the Rust copies subtract last_refresh_ns (the most recent episode) while the Python copy uses max(145, 30) (the largest episode), which are two different overrun terms for the same theorem. Worth a comment naming which term the theorem allows (the doc says "the charge of the most recent probe"), or the Rust bound should use the running maximum so the assertion is the tighter/looser direction intentionally.
Severity: nit.