Review — PR #540, lens: conventions and duplication
Key findings
The bundle is well factored in places (SPDX headers, the wide_copy_curve/powered_curve wrapper, the lane-forecast cache, and the refreshed refresh prose in docs/scheduling-runtime-design.md all follow existing patterns). Where it departs:
draft_sourceis a new graph discriminant but is missing from the two places that define a prepared shape's identity —model/catalog.rsandcost::Key— so the layers disagree and a mixed MTP + copy core fails to load. This is the one finding with a functional consequence.- Two ~100-line cohort loops now sit in one function (
rounds.rs); only the curve source differs, and the copies have already drifted. - Two near-identical SAM-vs-shared-ring selection paths in
scheduler.rs, likewise already drifted. - Four hand-written integer ladders for one enum, where the file family otherwise keeps one
TryFrom/parsenext to the type. - The documents that own the changed semantics were not updated (
helios/manifest.md,docs/mtp-design.md,docs/cli-design.md, and the module index ofdocs/scheduling-runtime-design.md).
Plus 6 nits (repeated zero-duration pricing, the pairwise/scan duplication of the new dominance rule, unconsumed pub SAM API, unexplained constants and the duplicated 6, a non-independent test oracle, and refresh_order's undocumented tuple). Nothing blocking. Everything below was verified in the code at head 14019718.
Should fix
1. draft_source is not part of prepared-shape identity
Files: helios/src/model/catalog.rs:279-293; helios/src/scheduler/cost.rs:50-58 (duplicate rejection in ActionCosts::prepared), cost.rs:151-169, cost.rs:223-244.
GraphDescriptor::draft_source (helios/src/execution/manifest.rs:191-192) is new in this PR and is used as a discriminant at the wire layer: helios/src/runtime_core/selection.rs:250-251 includes it in the serving-variant tuple and rejects only true duplicates. Neither prepared-shape identity was extended:
// model/catalog.rs:279-287
let mut matches = manifest.graphs.iter().enumerate().filter(|(_, graph)| {
graph.kind == kind
&& graph.batch_capacity == batch
&& graph.token_capacity == tokens
&& graph.prefill_capacity == prefill
&& graph.packed_token_capacity == packed
&& graph.draft_tokens == drafts
&& graph.sampling_mode == mode
});
draft_source is absent, and catalog.rs:291-293 returns Err("ambiguous prepared model graph capacity") when two graphs match. The same holds for the cost table: Key { drafts, kind, batch, tokens, prefill, packed } (cost.rs:50-58) has no source term, and ActionCosts::prepared returns Err("prepared graphs require unique shapes") on a duplicate key. The PR instead stores the source on the value side (Estimate.draft_source) and re-derives it in is_copy_only_step (cost.rs:223-232) and max_mtp_draft_tokens (cost.rs:234-244).
Why it matters: a copy-only graph at the same width/depth as the MTP graph is the natural capture for a W=16/W=24 copy graph (ignition/preparation/execution.py:32,87-92 defaults draft_source to 1 for MTP and uses draft_tokens = width - 1), so the collision is reachable as soon as the companion recipe PRs capture wide copy graphs at an MTP width. The PR's compatibility claim ("existing W=8-only cores without copy-only wide graphs load") is not contradicted — those load — but a core that mixes the two at one geometry cannot, and catalog.rs:94-131 plus manifest.rs:845-846 explicitly contemplate copy-only graphs.
Convention violated: one object, one identity. selection.rs:250-251 is the precedent already updated by this PR.
Fix: add draft_source to cost::Key (and thread it through Key::from_step) and to the select_shape_with_drafts filter. That also lets Estimate.draft_source, PackedRoundShape::draft_source and is_copy_only_step's inference be dropped instead of maintained in parallel.
2. The wide copy-only cohort loop duplicates the ordinary packed-round loop
File: helios/src/scheduler/rounds.rs:791-902 (duplicating 925-1060).
RequestScheduler::packed_round_candidates (rounds.rs:737-1062) now contains two structurally identical cohort searches. The copy block builds scores from curve[position] * values[slot].output_token, calls rank_prefixes (800), derives ranks_by_slot/slots_by_rank (801-806), computes base/full decode values (808-816), then runs the same three orderings (select_nth_unstable_by(cohort - 1, rank), truncate, sort_unstable_by), the same frontier trim against draft_budget, the same lane_terms accumulation, and the same (count_ones, Reverse(mask)) best-mask tie-break (817-877), before pushing a Candidate with expected recomputed at zero duration (878-902). The ordinary block at 929-1060 performs exactly those steps.
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. The copy block also silently omits the ordinary block's surplus_table factor (1031-1037), so cohort pricing already has two sites that differ.
Precedent inside the same function and the same PR: rank_prefixes, fixed_round_candidate (~690-735), host_prefix_ranking (rounds.rs:490-513) and wide_copy_curve/expected_copy_tokens wrapping powered_curve/expected_speculative_tokens (541-557) are all factored as "one loop plus a closure". The existing comment "Lane forecasts stay fixed while shapes compete; evaluate each at most once" (746) describes that unit.
Fix: extract the ordering/cohort search into one helper taking a per-slot marginal-probability closure (or &[f64] per slot) plus the per-slot limit, and call it from both blocks.
3. request_copy_match_stats duplicates request_history_proposal_with_match_len
File: helios/src/scheduler.rs:1163-1205 (duplicating 1112-1159).
Both perform the identical sequence: the clamp maximum.min(completion_token_capacity - 1).min(speculation::COPY_DRAFT_CAPACITY) (1117-1119 / 1168-1170); the early exit on maximum == 0 || self.decoded_history.is_none() (1120-1122 / 1171-1173); the self.request(handle) lookup with an empty fallback (1123-1125 / 1174-1176); sam.propose(maximum) followed by truncation at the first token >= vocabulary (1127-1138 / 1178-1186); the shared-ring query lookup_with_match_len(request.tokens(), maximum) (1139-1142 / 1187-1193); and the rule "shared ring wins only on a strictly longer match" (1144-1148 / 1196-1200). The second returns (valid_len, match_len) instead of (padded, count, match_len).
Convention: helios/src/scheduler/decoded_history.rs:162-183 keeps lookup as a two-line wrapper over lookup_with_match_len in this same PR — the pattern to follow.
The copies have already drifted: the proposal path takes the (None, Some(...)) shared arm unconditionally (1154-1156, a zero-count result yields (tokens, 0, 0)), while the stats path filters .filter(|&(count, _)| count > 0) first (1194) and falls through to (0, 0). The wide-copy gate at rounds.rs:774-776 reads match_len from the filtered path while the packing path reads count from the unfiltered one, so the two entry points disagree today about whether a zero-count matched span counts.
Fix: one private helper returning (match_len, valid_len, provider) (or an Option<&MatchProposal> style borrow); both public methods shape its result, so the clip, the count > 0 rule and the tie-break exist once.
4. Four hand-written draft_source ladders, one canonical parser
Files: 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") with an explicit Some(_) => Err and None => speculative.then_some(Mtp)); helios/src/runtime_core/selection.rs:144-148 (match config[...] { "mtp" => 1, "copy" => 2, _ => Err }, moved by this PR); helios/src/runtime_core/model.rs:1095-1102 (the same string ladder again).
Convention: helios/src/server/config.rs:188-194 uses speculation::ProposalSource::parse (scheduler/speculation.rs:30-38); GraphKind::try_from (execution/manifest.rs:123-145), Dtype::try_from (manifest.rs:50-68) and SamplingMode::try_from (manifest.rs:109-121) each keep one conversion next to the type, as does the declare_conversion! macro for contract enums (model/contract.rs:23 (not opened)). The wire enum is declared once (helios/proto/runtime_core.proto:854: NO_DRAFT = 0; MTP = 1; COPY_DRAFT = 2;), and the generated wire::DraftSource already provides try_from(i32)/as_str_name(), used by runtime_core/describe.rs:534 (not opened),778.
Fix: add ProposalSource::from_wire(i32) -> Result<Option<Self>> (or TryFrom<wire::DraftSource>) and as_str() beside the existing parse, and route all four sites through it. This also unifies the currently divergent "unknown source is an error" rule.
5. Documents that own the changed semantics were not updated
(a) helios/manifest.md:29-53 documents the Python graphs[] 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-319 now emits draft_source on every graph with an explicit draft_tokens, and heliopause/src/python.rs:225-233 reads it; the field is missing from the reference. AGENTS.md:52-60 requires designed behavior to be stated as a specification, and this file is that dictionary's specification.
(b) docs/mtp-design.md:22-40 still describes copy proposals as only the shared 65,536-token ring with eight- and four-token indexes ("Both settings use the same captured MTP graphs and buffers"; "each loaded model retains the most recent 65,536 committed generated tokens"). After this PR the primary path is the per-request prompt+output suffix automaton (scheduler.rs:1099-1159) with a 131,072-token trailing prompt window, a 131,072-token output cap, a 512-token prompt-tail overlap and a six-token minimum match (scheduler/sam.rs:22-32), and the ring is only the fallback when its match is strictly longer (scheduler.rs:1144-1148). --history-drafts also now changes the retained graph set (runtime_core/selection.rs:277-298,382-396), contradicting "Both settings use the same captured MTP graphs and buffers". docs/cli-design.md:741 likewise says only "Augment learned drafts with shared decoded-history continuations".
(c) docs/scheduling-runtime-design.md:6-12 enumerates the modules that implement the documented design (policy.rs, utility.rs, service.rs (not opened), cost.rs, refresh.rs (not opened), learning.rs (not opened), rounds.rs, speculation.rs) and omits the new sam.rs, although the document specifies the copy-proposal mechanism sam.rs implements (lines 39-41). A reader following the document's own pointer cannot reach the implementation.
Rule cited: .agents/skills/repo-prose/SKILL.md:26-29 (not opened) — "Documentation is a present-state specification, not a changelog. Replace stale claims instead of layering history on top." docs/scheduling-runtime-design.md:430-495 was updated correctly for the readiness-wait exclusion, retained idle credit and the two-tier refresh ordering, which makes the three omissions above stand out.
Fix: add draft_source (with its NO_DRAFT/MTP/COPY_DRAFT values and default) to helios/manifest.md; rewrite docs/mtp-design.md:22-41 to specify the per-request automaton first and the ring as fallback (caps, six-token minimum, effect of --history-drafts on retained graphs); update docs/cli-design.md:741; add sam.rs to the docs/scheduling-runtime-design.md module list.
Nits
- The new padded-batch dominance rule is written twice in one function.
helios/src/scheduler/policy.rs:143-165adds the pairwise rule insidedominates_padding_with(strictly narrower, same capacity and depth, GPU-allocated,smaller.packed_token_capacity >= long.sum().min(larger.packed_token_capacity)), andpolicy.rs:225-254re-derives it as a scan inprune_paddingwith a different expression (other.packed_token_capacity >= needed) plus another.batch >= lanesguard the pair version gets implicitly from the sharedmask/kind/prefill_slotchecks atpolicy.rs:134. The existing peer loop atpolicy.rs:215-220is the established shape ("for each peer, askdominates_padding_with"); fold the guard in and let the scan go. - Zero-duration expected value is spelled out five times in slightly different closure shapes:
policy.rs:1083-1096,policy.rs:1263-1295,rounds.rs:725-726,rounds.rs:879-885,rounds.rs:1048-1054. One helper would state "expected value is priced at zero duration for refresh ranking" once;policy.rs:1083-1096already has to special-caseduration_ns == 0 || kind.is_prefill()to avoid double counting. - Unconsumed
pubSAM API.sam.rs:1070(propose_for_context) andsam.rs:1118(propose_conditional_continuations) have no non-test caller (tests atsam.rs:1463,sam.rs:1505); the same holds forMatchSource/MatchProposal::source,PromptSAM::build,push_sliceand most accessors — production uses onlyPromptOutputSAM::new/push_token/propose. The module doc names a "2-deep pipelined execution" that exists nowhere.AGENTS.md:188-193rejects extension points added without a concrete requirement. - Unexplained constants, and one duplicated threshold.
speculation.rs:14-21addsWIDE_COPY_PRIOR_RATE = 0.88,COPY_STEP_PRIOR_WEIGHT = 4.0,COPY_DEPTH_SHRINK_WEIGHT = 2.0with no derivation;rounds.rs:766adds a barebase_mtp_drafts.saturating_add(3); andsam.rs:22DEFAULT_MIN_MATCH_LEN = 6duplicatesspeculation.rs:18WIDE_COPY_MIN_MATCH_LEN = 6, both required atrounds.rs:776. The charter asks to "be explicit and pin everything" andAGENTS.md:446-456wants one home per setting; the SAM default governs the plain--history-draftspacking path too (packing.rs:395-407→request_history_proposal→SamConfig::default(),sam.rs:53-62), so the wide-copy constant can reference it. - The test oracle is not independent of production.
sam.rs:1236-1273brute_force_oraclereturns the productionMatchProposaland re-derivesbuild_proposal(sam.rs:1191-1227) — the samecount = max_draft_len.min(n - 1 - endpos)bound and the sameendpos >= prompt_lensource selection — so the 120-trial randomized comparison only re-checks the code against a mirrored copy. Precedent: theoracleindecoded_history.rs:228-252returns the same plain(Vec<i64>, usize)the productionlookupreturns. refresh_orderlost its contract comment.cost.rs:287-296now returns(bool, u64)—(true, attempt_ns)= "attempted while stale with no valid observation" — with no doc comment; the meaning lives only indocs/scheduling-runtime-design.md:435-441. Neighbouring helpers state theirs in one line (cost.rs:40-41,110-113,282-285).
Checked and found conforming
- SPDX header and the second "Flare community contributors" copyright line in
sam.rs:1-5matchspeculation.rs:1-5. wide_copy_curve/expected_copy_tokens(rounds.rs:541-557) correctly mirrorspowered_curve/expected_speculative_tokens(rounds.rs:528-539); the defect is only the fallback arm inside it, which recomputesWIDE_COPY_PRIOR_RATE.powi(depth + 1)even thoughCopyCalibration::curveowns exactly that prior (speculation.rs:100-151,None => priorat145,optimistichandled at122-123). Theelsearm is also unreachable for current code:LiveRequest.samandLiveRequest.copy_calibrationare set together fromdecoded_history.is_some()(scheduler.rs:1849-1856),enable_history_draftsrefuses after any submission/admission (scheduler.rs:1086-1092), and every caller is gated ondecoded_historybeing present (rounds.rs:759). Worth deleting or replacing with aCopyCalibration::prior(capacity)constructor; recorded as a nit-level cleanup rather than a defect because the dead branch is harmless.- The per-shape copy-curve cache (
rounds.rs:747-748,get_or_insert_withat794-795) follows the existing "Lane forecasts stay fixed while shapes compete" cache (rounds.rs:746). docs/scheduling-runtime-design.md:425-450prose matchesrefresh.rs(not opened)/cost.rsfor readiness-wait exclusion, retained idle credit and the two-tier refresh ordering.cost.rs:31-38observed_compute_duration_ns/timing_refresh_duration_nsbuild on the existingobserved_duration_nsrather than re-deriving the max-positive-interval rule — the right direction, not a duplication defect.- The
draft_sourceProtobuf enum defaults toNO_DRAFT/MTP behavior, preserving existing cores (AGENTS.md:437-440).
Open questions / what a test would settle
- Whether
catalog::select_shape_with_draftsandActionCosts::preparedreally reject an MTP + copy pair at identical B/D/W/P. The code says yes (nodraft_sourceterm; explicit duplicate errors), but the new test athelios/src/model/tests.rs:1861-2075(not opened) uses distinct geometries and does not exercise it. One graph pair plusInputs::newwould confirm, and would show whether finding 1 is a hard load failure or merely an ambiguity risk. - Finding 2's unreachable
elsearm: a test constructing aLiveRequestwithsam: Someandcopy_calibration: Nonewould settle whether the invariant should be enforced structurally, e.g. both behind oneOption<PerRequestCopyState>, which would also collapse the two-Option construction atscheduler.rs:1849-1856. - Finding 5 needs an author statement of intended scope: if copy proposals are meant to remain documented as "shared history" for the ring path only, then the per-request SAM is an undocumented second mechanism, which
AGENTS.md:52-56does not permit. Only the author can say which document should own the new description. - The
pubSAM surface (nit 3) was checked withsearch_codeacross the repository; no caller was found outsidesam.rstests, but downstream crates (flare/,flare-cli/) were not opened. - Live GPU evidence in the PR description (throughput and latency deltas on 4x RTX PRO 6000, copy-only
W=16/W=24export/replay) was not re-verified — no hardware in this review; the description also states those two cases were not benchmarked.