Opened by a workflow run, Dec 4, 2026 12:52 PM EST. decide malicious: all_clear (100%): No malicious content found
explore
Author: lukealonso (COLLABORATOR; charter-listed priority contributor; Discord: lukealonso)
Motivation: Two recently merged Helios PRs left loose ends: closing or reopening </think> for a grammar-constrained request threw away all accumulated KV and recurrent state and re-prefilled the whole prompt, KV-offload restore lost GPU batching after the first non-GPU page while background captures held the codec mutex, and MIXED graphs were still priced from one flat median across very different fills and context depths. This PR adds an in-place grammar toggle and a terminal-checkpoint restore path, re-partitions restore pages into maximal batching runs with a gate-before-mutex lock order, and puts MIXED on the same (fill, kv_context) NNLS model pure prefill already uses.
Scale: +2219 / −370 in 14 files
Proposal:
- New
Admission::grammar_enabledplusGrammarEnabledpacking asenabled || mask.is_some();RequestScheduler::{set_grammar_constrained, pause_for_park, finish_for_park}andLiveRequest::paused_for_parkto drain a request out of scheduling without retiring it. - Three-way grammar transition in
Worker::complete: toggle in place for non-speculative models and for speculative cores that bindValueSource::GrammarEnabledper step; terminal-checkpoint park (Snapshot→finish→Restore) for other speculative cores;cancelonly on overshoot or device error. partition_restore_pages/restore_single_unitin the KV codec keep GPU-batched runs afterLiteral/CPU/singleton pages; all five GPU codec lock sites go throughwith_gpu_codec_locked/try_with_gpu_codec_locked, which takeCopyEngineGatebeforegpu.codec.PrefillCostModelextended toGraphKind::Mixedwith azero_fillbucket,t_at_uminfallback,u_min > 0floor gating, and same-(batch, width)peer context-slope borrowing;next_progress,continuation_candidate,mixed_candidates,resize_prefillandservice_ratesquery Mixed at live(work, start_position)and(0,0).- 10 named new tests, one updated doc, no new flags, no ABI or core-format change. Touches:
helios/src/server/runtime.rs(+270) andhelios/src/offload/transfer/codec.rs(+487/−250): grammar-transition state machine and codec batching/locking.helios/src/scheduler/{cost,policy,service}.rs(+598/−56):MIXEDcost stratification and every caller of it.helios/src/scheduler.rsandhelios/src/model/{admission,packing}.rs: park guards,paused_for_parkexclusions, grammar packing. Related items:- #626 Allow speculative reasoning for grammar-constrained requests (merged): same author, 4 days earlier; created the
cancel-based transition this PR replaces. - #628 helios: gate offload Copy Engine batches during peer-copy graphs (merged): explicitly required
gpu.codecbeforeCopyEngineGate; this PR reverses that order. - #645 Overhaul Helios prefill scheduling, cost modeling, and two-frame pipelining (merged): built
PrefillCostModelfor pure prefill only, which this PR extends toMixed. - #715 additive packed multi-request prefill (open): edits the same
cost.rsgating lines; direct textual conflict. - #530 Structured output decodes ~2-3× slower (open): the user-visible ancestor that #619/#626 cite and this PR does not.
Link: https://github.com/NVIDIA/hyperflare-inference/pull/729
Autobot comments: The description omits two things a reader will trip over. Its diff against the local
main(which is stale) shows hunks from already-merged #655, #659, #674, #697 and #709 — includingcheckpoints.rsandserver/request.rs, which are not in the PR's 14 files at all; the real change is smaller than a raw diff suggests. It also reverses a lock-order invariant #628 deliberately established and reviewed, not an accidental violation, and that reversal moves where a foreground restore can block becauseenter_offload_batchwaits untimed on the gate rather than on the codectry_lock. All three defects are self-introduced by PRs merged 1–9 days earlier (#525, #626, #628, #645), no issue tracks any of them and the PR links no issue orFixes/Closestrailer. Every performance claim, including the "2K-32K KV wipe" figure, is unmeasured and the PR says so — a divergence from the charter's #210 requirement, where peers #645/#659/#674 all shipped live A/B. Docs are updated in one file only, so present-state docs on the codec fallback (docs/prefix-cache-offload.md:96-100) and grammar transitions still describe the old behavior.
Value Proposition
Value Proposition — PR #729 (helios: grammar-transition KV preservation, KV codec batching/locking, Mixed graph cost stratification)
1. Charter alignment. Architecturally aligned: the change stays inside Helios and branches on runtime-derived properties (speculative_widths.is_empty(), contract-derived sampling_graphs_bind_grammar_enabled), not model names — consistent with "keep the runtime small and model-agnostic." It adds no ValueSource, no captured-graph op, no flags/defaults/dependencies, and no ABI or core-format change, so the op-contract approval rule is not triggered. The divergence is evidentiary and procedural: all three buckets are performance-motivated, yet the PR itself states "not benchmarked end-to-end here," has no Fixes/Closes trailer, and links no issue. That is exactly the #210 bar; the same author's #645 cleared it with live SM120 A/B tables. Bundling three unrelated subsystems also cuts against "stay focused."
2. Novelty & status. Genuinely additive — neither obsolete nor superseded. All three defects are live on main, self-inflicted by merged PRs from 1–9 days earlier (#525's single leading GPU batch loop, #626's cancel-based transition, #628's lock order, #645's deliberate exclusion of Mixed from PrefillCostModel); no other open PR addresses grammar transitions or the codec lock order. Bucket 3 is not superseded by #715, but conflicts textually at the same cost.rs gating sites, and its new zero_fill/mixed_context_slopes strata exist in no on-disk schema (#301).
3. Value vs maintenance cost. Bucket 1 is the strongest: it serves still-open user issue #530 ("structured output decodes ~2-3x slower than unconstrained"), confirmed across three merged PRs, with a mechanism the dossier independently inspected. Bucket 2 benefits TP2+ PCIe/SM120 prefix-cache-offload users, but deliberately reverses #628's reviewed lock invariant and may push foreground restores behind the untimed gate wait (finding 3) — that needs yatesdr, not just passing tests. Bucket 3 benefits only cores exporting Mixed graphs and ships without simulator validation (scripts/scheduling_sim/ unmodeled) or --mutations, while also altering pure-prefill pricing as a side effect (finding 9). Test evidence is broad but author-reported; CI is pending; and prefix-cache-offload.md plus the grammar-transition docs still describe pre-#729 behavior.
Verdict: Worth it with changes. Split into the three separable PRs; add a served-workload A/B against main for bucket 1 and a measurement for the older-core Snapshot+Restore cost; cite #530 and #628/#627; obtain yatesdr's sign-off on the inverted lock order with the gate-wait question answered; reconcile with #715 and run --mutations/simulator checks for the Mixed strata; update the remaining dependent docs.
Full report Decide Value: yes (100%): This change is worth reviewing: it provides value to the project in line with its charter.
Classify intake
Selected: triage:review, bug, performance, area:scheduling
Threshold: 65%
Triage
- [✓]
triage:review: 99.4% -
triage:validation: 0.4% -
triage:design-review: 0.1% -
none: 0.0% -
triage:integration: 0.0% -
triage:investigate: 0.0% -
triage:partial: 0.0% -
triage:verify-for-closure: 0.0% -
triage:superseded: 0.0%
Priority
-
none: 69.9% -
priority:P2: 22.7% -
priority:P1: 7.4%
Type
- [✓]
performance: 97.7% - [✓]
bug: 83.5% -
community: 53.1% -
enhancement: 11.9% -
duplicate: 8.5% -
documentation: 0.2%
Area
- [✓]
area:scheduling: 97.4% -
area:caching: 37.8% -
area:memory: 37.8% -
area:preparation: 7.6% -
area:kernels: 6.0% -
area:rocenante: 5.3% -
area:selene: 3.7% -
area:api: 1.8% -
area:orbit: 0.5% -
area:packaging: 0.4% -
area:engram: 0.3%
Model
-
model:deepseek-v4.1: 11.9% -
model:deepseek-v4: 2.6% -
model:glm-5.3: 0.9% -
model:qwen3.8-flash-next: 0.6% -
model:mimo-v2.6: 0.4% -
model:nemotron-3.5-bolt: 0.4% -
model:gemma4: 0.4% -
model:muse-glimmer: 0.3% -
model:inkling-small: 0.3% -
model:kimi-k3.1: 0.2% -
model:qwen3.8-27b: 0.2%
Apply Labels (Intake)
Applied: +triage:review, +bug, +performance, +area:scheduling
Gates and contracts
Contracts, Charter & Verification Gates Audit — PR #729
Scope: only the 14 files in pr_files (the local base is stale, so a raw pr_diff over-reports; hunks for checkpoints.rs (not opened), server/request.rs (not opened), RowRestoreLatency, attach_async_transfers, preserve_message_anchor, snapshot_discovery belong to already-merged #655/#659/#674/#697/#709 and are excluded from this audit).
Gate 1 — Signed core-format / wire / captured-graph / public contract boundaries: CLEAR
No new operation contract, enum value, wire kind, or Protobuf field:
helios/src/model/admission.rs(+15/−2) addsAdmission::grammar_enabled, a plain Rust struct field — not a Protobuf field, not aValueSourcevariant, not aGraphOperationvariant. It also splitsvalidateintovalidate_continuation(config, initial_prompt_tokens), an internal signature change.helios/src/model/packing.rs:800-806only widens the packed value for the pre-existingValueSource::GrammarEnabledinput:i64::from(admission.grammar_enabled || admission.grammar_mask.is_some()). Existing cores that bindGrammarEnabledkeep the same binding; cores that do not bind it are unaffected by this line.- No
GraphOperation,ValueSource,BoundaryKind,Kind, orCacheContractenum gains a member.helios/src/scheduler/cost.rs(not opened) adds internal cost strata (zero_fill,t_at_umin,mixed_context_slopes) that are in-memory only — nothing is persisted, so no on-disk schema changes (relevant to open #301 but not a violation here).
The docs/design-review.md:22-25 owner-approval rule for "introducing a captured-graph operation family" / "a new operation contract" is therefore not triggered, and docs/design-review.md:34-35 (no hardcoded batch-capacity or graph-shape enumeration) is respected — the branch condition is config.speculative_widths.is_empty() and a contract-derived scan (sampling_graphs_bind_grammar_enabled, runtime.rs:~509), not a hardcoded list or model name.
Normative-doc consistency (part of Gate 1): docs/scheduling-runtime-design.md is updated in the same PR for the Mixed stratification change (lines 460-490 region), so no docs/scheduling-theory.md or docs/scheduling-runtime-design.md invariant is contradicted silently. docs/core-design.md:1726-1735 and docs/api.md:781-789 (native replay loop, "two-frame pipelining … transitions to device-masked decoding at MTP width one with one step in flight") remain consistent with the new Worker behavior. docs/scheduling-runtime-design.md:252,278 still say parity service rates "exclud[e] MIXED durations", which the PR does not change.
Informational only, not a gate finding:
docs/prefix-cache-offload.md:96-100still describes the GPU-codec CPU fallback without the new gate-before-mutex ordering. That is a present-state doc omission, not a contradicted normative invariant — but it should be reconciled before merge.
Gate 2 — Vendored upstream dependencies & cross-PR conflicts: CLEAR
All 14 changed paths are helios/src/** plus docs/scheduling-runtime-design.md. No helios/native/*.c (e.g. roce_proxy.c (not opened)), no Cargo.toml (not opened)/Cargo.lock, no .cu/PTX, no Protobuf, no external recipe or unmerged-PR dependency, no new dependency to pin. original-el8's #715 and #710 touch the same cost.rs (not opened) gating sites, but that is a textual merge conflict risk, not a vendored-fork or unpinned-dependency gate violation — the PR's own branch is self-contained.
Gate 3 — Mandatory verification evidence & failing tests
3a/3b. Layer 2 and Layer 3 gates: THREE BLOCKING OMISSIONS
(1) BLOCKER — new lifecycle state added without extending the TLA+ models or conformance fixtures. This PR adds a genuinely new request-lifecycle state and three new transition entry points:
helios/src/scheduler.rs:267—paused_for_park: boolonLiveRequest.helios/src/scheduler.rs:1433, 1449, 1531—&& !request.paused_for_parkexclusions from starvation detection, page-growth/preemption candidate selection, and the reserve-ahead filter;helios/src/scheduler/policy.rs:335— the same ineligible().helios/src/scheduler.rs:3234 set_grammar_constrained,:3254 pause_for_park,:3267 finish_for_park.
A search over verification/ for paused_for_park|pause_for_park|finish_for_park|set_grammar_constrained|grammar_enabled returns no matches — the models and the Rust observed-edge fixtures were not updated. docs/design-review.md:211-220 requires the TLA+ models and trace-conformance suite for changes to "cancellation, speculation accounting, cache compaction, snapshot aliases, response buffering or ownership"; :234-240 makes it decisive: "Never touch covered code without running and updating its simulator and formal checks. Modifying the Helios scheduler, admission, speculation, cancellation, cache ownership … without running — and updating when behavior, transitions, or supported bounds change — the applicable TLA+ models, Rust conformance fixtures … is a blocking design failure, regardless of whether CPU unit tests pass." :241-246 is exactly on point: "When a change adds protocol states … update the model, conformance fixture, or Kani harness to cover the added domain rather than leaving it unverified."
The PR does run check.py (not opened) (10 models, 9 suites, 621,749 observed transitions) — so this is not a "check not run" finding. The finding is narrower and harder: the run exercised the pre-existing models only, so the newly added domain (paused_for_park draining, grammar toggle with pending == 0, terminal-checkpoint park) is conformance-unverified. This matters because the park path deliberately keeps a request visible-but-unschedulable across an in-flight frame, which is precisely the ownership/ordering property TLA+ is there to model.
(2) BLOCKER — Layer 2 scheduling-simulator evaluation not performed or updated.
Bucket 3 changes graph selection, service pricing, and timing estimation: cost.rs (not opened) (+309/−38, PrefillCostModel extended to GraphKind::Mixed, new zero_fill bucket, t_at_umin, mixed_context_slopes, mixed_entry/mixed_duration), plus every caller — policy.rs mixed_candidates, next_progress, resize_prefill, continuation_candidate; service.rs shape_duration→mixed_entry. docs/design-review.md:195-206 requires such changes be "evaluated against the Python simulator and reference solvers in scripts/scheduling_sim/", and timing-estimation changes require "running the screening and 64-seed validation catalog in scripts/scheduling_sim/learning.py". The PR itself discloses: "scripts/scheduling_sim/ models scalar per-graph durations without per-fill/per-context NNLS strata" — i.e. the new strata are neither modelled nor validated, and the simulator was not updated. :147-149 additionally requires updating simulator comments when the cost terms change.
(3) BLOCKER — mutation testing not run on newly added safety guards.
Three new guards were added with typed rejection strings ("grammar constraint mode requires a live request with no pending GPU work", "pausing for park requires an active request with pending GPU work", "finishing for park requires a live request with no pending GPU work", plus the BoundaryKind::ConditionedWindow park rejection and the consumed_tokens <= exact_len check in runtime.rs). docs/design-review.md:226-228 requires check.py (not opened) --mutations or cargo-mutants "when adding or changing safety guards"; the PR lists --mutations under unrun checks. :247-251 forecloses the disclosure defense directly: "Disclosure does not excuse skipping runnable CPU checks … Leaving an applicable crate test, simulator sweep, TLA+ conformance run, or Kani proof unrun blocks commit and PR acceptance; noting it as a limitation does not make the omission acceptable." This one matters more than usual because the guards are atomic pre-check-then-mutate predicates whose correctness the new unit tests assert only for the cases the author chose.
By contrast, the Kani omission is genuinely N/A and I do not flag it: no completion-vector validation, prepared completion contract, state-view extent arithmetic, or sequential validator was modified (docs/design-review.md:221-225).
3c. Failing CI / failing tests on 150f705: NOT A FINDING
The PR reports zero failures across eos, selene, selene-manager, helios (--lib and --test '*'), flare, flare-cli, the Python suites, and live SM120 GPU codec tests. CI is pending, which is not a failure and is not observable to me. Not flagged.
3d. Performance claim without an attributable served-workload A/B: MAJOR
All three buckets are performance-motivated, and the PR states outright: "Expected serving impact (not benchmarked end-to-end here)" and "No end-to-end exported-core flare run latency or throughput benchmark was run on this branch." docs/design-review.md:109-115 (principle 12) requires "actual Helios service measurements" for performance claims, with comparisons against exported cores through flare run; :15 of docs/verification.md makes the live benchmark the primary check for "latency, throughput, or memory cost". The charter's #210 bar says the same. The headline "eliminates 2K-32K KV and recurrent state wipes" figure has no measurement, citation, or reproducer anywhere. The same author's #645 shipped live SM120 A/B tables, so the bar is demonstrably reachable in this area. This is a Major (not Blocker) because the correctness work is real and independently motivated by open issue #530.
3e. Legacy core loading-and-serving (principle 13): MAJOR
The PR claims "existing exported cores load and run without re-export or ABI changes", but the only reported evidence is a packing unit test. docs/design-review.md:116-123 requires "Test previous core layouts through loading and serving alongside newly exported cores", and the charter's review standards say "verify that existing data, artifacts, and exported cores still load". The claim is not merely structural here — it changes packed behavior: runtime.rs:1700-1706 sets device_grammar_enabled = prompt.grammar.is_some() && (!unmasked_reasoning || !speculative), so a non-speculative core's existing GrammarEnabled binding now receives 1 during open reasoning where it previously received 0. That is very likely fine (speculative verification kernels force width = 1 only on speculative cores, and the PR supplies a cached all-ones mask), but it is exactly the kind of change principle 13 asks to be proven by loading and serving a previous core, not asserted.
I do not render this a Blocker because the format is unchanged (no new Proto field, no new enum value, GrammarEnabled binding unchanged) and the existing reader path is untouched; the gap is evidentiary.
Gate 4 — Material scope / claim contradictions
- Nit (informational). The description lists
delivery_referencesamong updated functions. Theservice.rsdiff contains two hunks —mixed_duration(batch, width, prefill, 0, 0)inservice_rates(~line 232) and themixed_entry/predictor.predictrewrite in the continuation path (~line 351) — neither insidedelivery_referencesordelivery_references_and_decode_batch. Minor description imprecision;mixed_candidates,next_progress,service_rates,continuation_candidate, andresize_prefillare all confirmed updated. - Nit (informational). The second
docs/scheduling-runtime-design.mdhunk (anchor budgeting,preserve_message_anchor, snapshot-copy discovery) is already-merged #697/#655 work surfaced by the stale local base. It should not read as this PR's change; the description's doc bullet conflates the two. - No unrelated standalone tooling. The 14-file, +2219/−370 change is three subsystems in shared Helios code, all in-repo, no new frameworks, no vendored files, no scaffolding. Bundling three independent subsystems is a focus concern the value lens owns, not a scope-vs-claims contradiction.
Verdict
Gate 1 (contract boundaries): CLEAR. Gate 2 (vendored deps): CLEAR. Gate 3: THREE BLOCKING OMISSIONS + TWO MAJORS. Gate 4: two informational nits only.
Required before this can pass the mandatory verification gates:
- Extend and re-run the formal checks to cover
paused_for_park/pause_for_park/finish_for_park/set_grammar_constrained— update the applicable TLA+ model (Lifecycle/Speculation/CheckpointReservation) and the Rust observed-edge suite to model the draining-but-unschedulable state, and report the run.docs/design-review.md:234-246is explicit that the existing run does not satisfy this. - Model the
(fill, kv_context)NNLS strata including thezero_fillbucket andmixed_context_slopesinscripts/scheduling_sim/, update their comments, and run the screening plus 64-seed catalog inlearning.py(docs/design-review.md:195-206). - Run
verification/helios-lifecycle/check.py (not opened) --mutationsagainst the new park and grammar-toggle guards (docs/design-review.md:226-228); disclosure does not excuse it (:247-251). - Add a served-workload A/B against
mainusing an exported core throughflare runfor the grammar-transition bucket, and a measurement for the older-speculative-coreSnapshot+Restorecost; cite a source for the "2K-32K" figure (docs/design-review.md:109-115, charter #210). - Load and serve a previously exported core to substantiate the compatibility claim, particularly the non-speculative
GrammarEnabled0→1 packing change (docs/design-review.md:116-123).
Optional but advisable: reconcile docs/prefix-cache-offload.md:96-100 with the new gate-before-mutex order, and correct the delivery_references claim plus the #697/#655 doc-hunk attribution in the description.
Subtraction and simplicity
Subtraction & Simplicity Lens — PR #729 (helios: grammar-transition KV, KV codec, Mixed graph costs)
Scope audited: the grammar-transition bucket (helios/src/server/runtime.rs, helios/src/scheduler.rs, helios/src/scheduler/policy.rs, helios/src/model/{admission,packing}.rs), the codec bucket (helios/src/offload/transfer/codec.rs), and the Mixed-cost bucket (helios/src/scheduler/{cost,policy,service}.rs). Line numbers are the PR head (150f705).
Verdict: not lean. Buckets 2 and 3 are mostly justified rewrites, but each contains one clearly redundant data structure or rule duplication. Bucket 1 (the grammar toggle) is the problem child: the same three-way decision, the same guard predicate, and the same field bundle are written out 2–3 times, and a new parallel state machine (PendingGrammarPark + waiting_for_drain + scheduler paused_for_park) duplicates state that already exists in LiveRequest.
Attribution caveat: the discovery dossier records that the local base is stale, so some hunks in these files belong to already-merged PRs (#674/#709/#655/#659/#697). Everything I cite below I verified sits inside the described #729 buckets; I flag the two items (
Admission::from_prompt/validate,refresh_admission_plan_in_place) whose attribution the dossier lists as unresolved.
A. High-value simplifications (grammar transitions)
A1. The identical can_toggle_live predicate is written out three times
helios/src/server/runtime.rs:2352-2362
let can_toggle_live = skipped == 0
&& live.pending() == 0
&& extra == 0
&& live.error_code.is_none()
&& can_toggle_in_place
&& !matches!(
live.phase,
RequestPhase::Inbound | RequestPhase::Finishing
)
&& !(live.phase == RequestPhase::Snapshot
&& live.terminal_snapshot.is_some());
helios/src/server/runtime.rs:2431-2440 — byte-identical except the extra == 0 conjunct, which is absent because extra is not in scope in the re-entry arm.
helios/src/server/runtime.rs:2337-2349 (earlier hunks of the same function) repeat the same shape.
Extract one fn grammar_toggle_allowed(live: &LiveRequest, skipped: u32, extra: u32, can_toggle_in_place: bool) -> bool and pass extra: 0 in the re-entry arm. This deletes ~20 duplicated lines and removes the exact hazard the third copy already demonstrates — a conjunct silently dropped in one copy.
A2. The toggle / checkpoint-park / rollback three-way branch is duplicated verbatim for both directions
helios/src/server/runtime.rs:2363-2407 (reasoning close) and helios/src/server/runtime.rs:2441-2481 (reasoning re-entry) are the same if can_toggle_live { …set_grammar_mask… } else if skipped == 0 && live.error_code.is_none() && !live.deferred_prefill() { checkpoint_parks.push(…) } else { transitions.push(…) } skeleton, differing only in speculative_reasoning: false vs true, drop_reasoning, and the mask/enable values. One closure taking (speculative_reasoning, drop_reasoning, mask_action) collapses both to ~15 lines each and guarantees the three paths stay mutually consistent.
A3. GrammarTransition and PendingGrammarPark carry the same five fields, and the drain loop copies field-by-field
helios/src/server/runtime.rs:2106-2114
struct GrammarTransition {
slot: usize,
handle: RequestHandle,
exact_len: usize,
emitted: u32,
remaining: u32,
speculative_reasoning: bool,
drop_reasoning: bool,
}
helios/src/server/runtime.rs:509-517
struct PendingGrammarPark {
exact_len: usize,
emitted: u32,
remaining: u32,
speculative_reasoning: bool,
drop_reasoning: bool,
/// True while waiting for an already-queued second frame to drain before snapshotting.
waiting_for_drain: bool,
}
The conversion back is manual at helios/src/server/runtime.rs:2523-2537:
let park = self.active[slot]
.as_mut()
.unwrap()
.pending_grammar_park
.take()
.unwrap();
transitions.push(GrammarTransition {
slot,
handle: lane.request,
exact_len: park.exact_len,
emitted: park.emitted,
remaining: park.remaining,
speculative_reasoning: park.speculative_reasoning,
drop_reasoning: park.drop_reasoning,
});
This is precisely the "pair optional fields into one Option<(A, B)>" case. One struct with waiting: bool (or Active.checkpoint_park: Option<PendingGrammarPark> whose enum variant carries the half that still needs a rollback) removes the second type, the second Vec, the manual field copy, and the checkpoint_parks.iter().any(|(_, h, _)| *h == token.request) duplicate-suppression at :2128.
A4. exact_len, emitted, remaining are derived quantities that LiveRequest already holds
helios/src/server/runtime.rs:2182-2185, :2309-2311, :2422-2425 — the same three lines, three times:
let skipped = burst_counts[slot].saturating_sub(position as u32);
let emitted = live.generated_tokens.saturating_sub(skipped);
let remaining = request.incoming.prompt.max_new_tokens.saturating_sub(emitted);
let exact_len = live.prompt_tokens + emitted as usize;
Three of these four values are functions of live + skipped alone (exact_len = live.prompt_tokens + emitted, remaining = max_new_tokens - emitted). Carrying emitted (plus skipped) is enough; exact_len/remaining in PendingGrammarPark are a snapshot of derived state that then has to be kept coherent across the drain at :2503-2521. Store one computed struct (ParkTarget { skipped, emitted }) and derive; the park.emitted override of live.generated_tokens at :1603-1610 also disappears.
A5. Two independent sources of truth for "waiting to drain"
helios/src/scheduler.rs:3254-3262
pub fn pause_for_park(&mut self, handle: RequestHandle) -> Result<()> {
let request = self.request(handle)?;
if request.pending == 0
|| matches!(request.phase, RequestPhase::Inbound | RequestPhase::Finishing)
{
return Err("pausing for park requires an active request with pending GPU work".into());
}
self.request_mut(handle)?.paused_for_park = true;
versus helios/src/server/runtime.rs:516 waiting_for_drain: bool and the paired writes at :2514-2521 (park.waiting_for_drain = false; immediately followed by finish_for_park, which itself does self.request_mut(handle)?.paused_for_park = false; at helios/src/scheduler.rs:3283). The runtime's bool is a mirror of the scheduler's paused_for_park and both must be flipped in lockstep at four sites (:2394, :2468, :2494, :2514). Read live.paused_for_park() instead of storing waiting_for_drain — the scheduler is already the owner of that state and already excludes paused requests from eligible/starvation/preemption (helios/src/scheduler/policy.rs:335, helios/src/scheduler.rs:1433,1449,1531).
A6. Three near-identical "settled request" guards, each with its own error string
helios/src/scheduler.rs:3239-3246
if request.pending != 0
|| matches!(request.phase, RequestPhase::Inbound | RequestPhase::Finishing)
|| (request.phase == RequestPhase::Snapshot && request.boundary_capture.is_none())
{
return Err(
"grammar constraint mode requires a live request with no pending GPU work".into(),
);
}
helios/src/scheduler.rs:3256-3261 (pause_for_park) and helios/src/scheduler.rs:3268-3271 (finish_for_park) repeat the same pre-check-then-mutate shape. Collapse into one private fn require_live_unsettled(&self, handle) -> Result<&LiveRequest> (or a single park_guard taking the mode) so the three differing predicates live in one place; today a change to RequestPhase handling must be found in three spots.
A7. grammar_enabled doubles the grammar state — a single enum makes the impossible state unrepresentable
helios/src/model/admission.rs:66-69
pub grammar_mask: Option<Vec<i32>>,
/// Enables device-side grammar masking at admission even while `grammar_mask` is `None`
/// (all-ones), so non-speculative requests can toggle masks in place without `Restore`.
pub grammar_enabled: bool,
plus the packing OR at helios/src/model/packing.rs:803-805
GrammarEnabled => values.push(i64::from(
admission.grammar_enabled || admission.grammar_mask.is_some(),
)),
The || is the giveaway: grammar_mask.is_some() already implies enabled, so the two fields encode three states (off, all-ones, masked) that must be kept consistent by hand across set_grammar_mask(mask, enabled) (helios/src/model/admission.rs:125-128) and its four call sites (helios/src/server/runtime.rs:2376-2379, :2444-2447, :2450-2453, plus grammar_updated at :2238-2241). A enum GrammarBinding { Off, AllOnes, Mask(Vec<i32>) } field replaces both fields, set_grammar_mask, and the packing OR, and removes the "mask Some but enabled false" state that the OR exists to paper over.
A8. Test-only shims in the admission API
helios/src/model/admission.rs:75-77 and :130-147: validate() is now a one-line delegate to validate_continuation(config, self.prompt.len()), and from_prompt is a wrapper that passes grammar_constrained for both grammar_mask_active and grammar_enabled. Grep shows the only remaining callers are tests: Admission::from_prompt → helios/src/server/runtime/phase_tests.rs:6707 (not opened); admission.validate(config) → helios/src/server/runtime/phase_tests.rs:6719 (not opened). Making from_prompt/validate #[cfg(test)] (or deleting them and calling from_continuation in the tests) removes two API entry points that encode a grammar_constrained == grammar_enabled assumption the production path deliberately broke.
(Attribution note: the dossier lists validate_continuation/from_continuation(initial_prompt_tokens) among hunks it could not attribute; verify against the true base before acting.)
B. High-value simplifications (KV codec)
B1. The routes vector is a duplicate of what pages already stores
helios/src/offload/transfer/codec.rs:685-695
let mut pages = Vec::with_capacity(job.pages.len());
let mut routes = Vec::with_capacity(job.pages.len());
for (i, (page, _)) in job.pages.iter().enumerate() {
...
let route = self.decode_route(u, representation)?;
routes.push(route);
pages.push((u, route, chunks, spans));
}
Every tuple in pages already carries route at index 1; partition_restore_pages(&routes, …) at :699 could take pages.iter().map(|p| p.1). Delete routes (one allocation + one push per page) or, better, make partition_restore_pages take a slice of pages and yield index ranges only.
B2. The "skip transform_ns on pure-Literal batches" rule is implemented twice with different shapes
helios/src/offload/transfer/codec.rs:569-574
if items
.iter()
.any(|(_, route, _)| *route != DecodeRoute::Literal)
{
stats.transform_ns += start.elapsed().as_nanos() as u64;
}
and helios/src/offload/transfer/codec.rs:643-645
if route != DecodeRoute::Literal {
stats.transform_ns += start.elapsed().as_nanos() as u64;
}
Two spellings of one accounting rule, in two functions that will drift. A single fn add_transform(stats: &mut DecodeStats, start: Instant, routes: impl Iterator<Item = DecodeRoute>) (skipping when all are Literal) keeps the invariant stated once — important because the whole point of the change is that transform_ns no longer charges pure-copy work.
B3. restore_single_unit and the GpuBatch fallback encode the same two-step "GPU else CPU" restore
helios/src/offload/transfer/codec.rs:599-654 (restore_single_unit) and :704-755 (the GpuBatch arm) both implement: try try_with_gpu_codec_locked → on None (or non-GPU route) decode via decode_pages_cpu_batch/decode_unit_cpu and copy_spans_batch. The dedicated restore_single_unit function plus the bespoke fallback loop inside the batch arm is the same logic at two granularities. Folding the fallback into a restore_cpu_runs(slice) helper lets restore_single_unit become a one-element call and removes ~30 lines of duplicated staging/plan selection (let plan = if row { &self.cpu.gpu_row } else { &self.cpu.gpu_page } appears at :600-604, :631-636, and again inside the fallback).
B4. with_gpu_codec_locked / try_with_gpu_codec_locked differ by one line
helios/src/offload/transfer/codec.rs:878-899: the two wrappers are identical except codec.lock().unwrap() vs codec.try_lock().ok()?. They are a reasonable abstraction, but the pair can be one function parameterised by a try: bool (or keep both and accept the 8-line duplication). Lower priority than B1–B3; listing it because the diff pays two doc comments (16 lines) for what is a single policy.
B5. gpu_batch_cap guards with map_or(1, …) then callers re-unwrap
helios/src/offload/transfer/codec.rs:677-683 computes
let gpu_batch_cap = if self.cpu.gpu_page.num_mats() == 0
&& self.cpu.gpu_page.num_chunks() > 0
{
self.gpu.as_ref().map_or(1, |gpu| gpu.page_batch_cap)
} else {
1
};
and then :704-707 and :605-607 immediately do &self.gpu.as_ref().unwrap().codec. Because PageRunKind::GpuBatch implies at least two GpuOnDevice routes, decode_route guarantees self.gpu.is_some() (:520-523), so the unwrap is safe — but the map_or(1, …)/unwrap pair hides that argument. Returning Option<&GpuCodec> (or binding let Some(gpu) = self.gpu.as_ref()) removes the double representation of "GPU present".
C. High-value simplifications (Mixed cost model)
C1. Three copies of the mixed scoring loop — the new one is ~90% of the old one
helios/src/scheduler/policy.rs:
:1755-1868— new non-constant-predictor branch inmixed_candidates(buildsdecoder_slots/prefill_slots, scores decoders, picks best prompt).:1869-1947— the retained flat branch, same slot scan, samebest_cohort+ prompt merge.:1166-1303—continuation_candidate's inlineeval_mixedclosure, again the same slot scan,best_two_stage_cohort, prompt merge.
The two mixed_candidates branches share the frame let mut decoders = [(0usize, 0.0); REQUEST_LANES]; … best_cohort::<REQUEST_LANES>(&decoders[..count], batch - usize::from(prompt.is_some())) and differ only in whether duration_ns is a single pred.predict(0,0) or is recomputed per prompt candidate as pred.predict(work, start_pos). A single loop with let slot_ns = predictor.map_or(0, |p| if work > 0 { p.predict(work, start_pos) } else { p.predict(0, 0) }) serves both, deleting ~80 lines. This is the single largest subtraction available in the PR.
C2. PrefillPredictor::predict's clamp is duplicated inside the new work == 0 early return
helios/src/scheduler/cost.rs:176-188
if work == 0 {
let base = if self.theta[0] > 0.0 && self.theta[0].is_finite() {
self.theta[0]
} else {
self.t_at_umin
};
return if !base.is_finite() || base <= 1.0 {
1
} else if base >= u64::MAX as f64 {
u64::MAX
} else {
base.round() as u64
};
}
and helios/src/scheduler/cost.rs:198-204
if !pred.is_finite() || pred <= 1.0 {
1
} else if pred >= u64::MAX as f64 {
u64::MAX
} else {
pred.round() as u64
}
Identical clamp written twice. fn clamp_nanos(value: f64) -> u64 used at both, plus let base = if work == 0 { … } else { … } to share the tail, removes 8 lines and the risk of the two clamps diverging.
C3. zero_fill is reset in three places alongside strata
helios/src/scheduler/cost.rs:302-303 (in reset_with_full) and helios/src/scheduler/cost.rs:322-324 (in observe):
self.zero_fill = PrefillBucket::default();
self.strata = [PrefillBucket::default(); PREFILL_STRATA];
The zero_fill bucket exists only to hold work == 0 medians; it is reset, observed (:326-329), and fitted (:349-354) in lockstep with strata at every site. Either add it as an extra element of the array ([PrefillBucket; PREFILL_STRATA + 1]) so reset/observe/fit walk one collection, or add fn reset_samples(&mut self). Today reset_with_full and observe are two places that must both learn about any future bucket.
C4. borrowed_mixed_context_slope is borrowed_prefill_context_slope with a different predicate
helios/src/scheduler/cost.rs:871-881
fn borrowed_prefill_context_slope(&self, kind: GraphKind, capacity: usize) -> Option<f64> {
let slot = prefill_kind_slot(kind)?;
self.prefill_context_slopes[slot]
.iter()
.find(|&&(peer_cap, slope, observed_at_ns)| {
peer_cap > capacity
&& slope > 0.0
&& self.now_ns.saturating_sub(observed_at_ns) < self.ttl_ns
})
.map(|&(_, slope, _)| slope * capacity.max(1) as f64)
}
helios/src/scheduler/cost.rs:883-899 is the same function with peer_batch == batch && peer_width == width && peer_prefill > prefill. Also mixed_context_slopes: Vec<(usize, usize, usize, f64, u64)> (helios/src/scheduler/cost.rs:596-598) is a five-tuple that mirrors prefill_context_slopes: [Vec<(usize, f64, u64)>; 3] — an unnamed struct that the closure at :891-897 destructures positionally and the sort at :935 indexes by .2. A struct ContextSlope { batch, width, capacity, slope, observed_at_ns } plus one generic borrowed_context_slope(peers, capacity, batch, width) (or a Key-keyed map) removes the parallel mechanism, the magic indices, and the two nearly identical borrow policies. Note the two policies deliberately differ (the PR body says so), so keep the predicate as a parameter rather than duplicating the walk.
C5. mixed_entry's Option<Option<PrefillPredictor>> tri-state collapses to one Option
helios/src/scheduler/cost.rs:741-770 returns None (shape absent), Some(None) (estimate.nanos == 0), or Some(Some(predictor)) — and the Some(Some(..)) arm already falls back to PrefillPredictor::constant(prefill.max(1), estimate.nanos) at :759-763, which yields 0 for the Some(None) case anyway. Every caller then writes the same unwrap: predictor.map_or(0, |p| p.predict(0, 0)) at helios/src/scheduler/policy.rs:948, :959, :1308, :1869, and .flatten() at helios/src/scheduler/service.rs:356-359. Returning Option<PrefillPredictor> (constant fallback covering the nanos == 0 case) deletes the inner Option, four map_or sites, and one .flatten(). mixed_duration (:772-782) then becomes a two-line wrapper or disappears.
C6. mixed_duration is used three ways but only wraps mixed_entry + predict
helios/src/scheduler/cost.rs:772-782, called at :1050, helios/src/scheduler/policy.rs:2113, helios/src/scheduler/service.rs:235. It is fine as a helper, but combined with C5 it is self.mixed_entry(b,w,p).map(|p| p.predict(work, start)) — i.e. after C5 it can be deleted and callers written directly, removing a public surface on ActionCosts.
C7. duration and shape_duration remain as two names for the same call
helios/src/scheduler/cost.rs:692-694
pub fn duration(&self, kind: GraphKind, batch: usize, tokens: usize) -> Option<u64> {
self.shape_duration(kind, batch, tokens, 0)
}
shape_duration (:963-971) is now used only with prefill = 0 (its sole non-zero caller, helios/src/scheduler/policy.rs:1310, passes prefill for non-Mixed kinds, which is 0 for every non-Mixed graph since prefill_capacity() is 0 there — helios/src/scheduler.rs:479). The PR deletes fresh_duration (:993-1002 diff) but leaves this second alias. Folding duration into shape_duration (or inlining shape_duration's body into exact_duration(kind, batch, tokens, 0, 0)) is a small, safe deletion.
C8. measured_duration re-implements a filter that entry() + observation() already express
helios/src/scheduler/cost.rs:995-1002 loops self.batches(kind) with .filter(|&nanos| nanos != 0). observation() (:1020-1024) already returns (nanos, observed, fresh); the same result is self.observation(key).map(|(n,_,_)| n).filter(|&n| n != 0). Low priority, but it is a third spelling of the same lookup.
D. Confirmed lean (no action)
helios/src/model/packing.rs:803-805— the packing change is three lines and is the minimum possible given A7.partition_restore_pages(helios/src/offload/transfer/codec.rs:837-873) — a clean, small state machine; the oldall_pages_cpu_path+else { break; }it replaces was the convolution, and this is a genuine simplification, not an addition.HostAdmissionProbe(helios/src/server/runtime.rs, replacing 9 positional arguments ofadmit_with_host_store) andconditioned_inputs_from_images/clear_pool_lookup/issue_pool_lookupextractions are net simplifications and should not be reverted. (Theplan_refreshedflag and(Some(plan), true) => plan.clone()in the same hunk are a wash: the PR removes the clone inrefresh_admission_planonly to reintroduceplan.clone()on the refreshed path — worth a question to the author, but attribution to #729 is unresolved per the dossier.)close_store(helios/src/server/runtime.rs:1330-1355) — extracting the shared store-close body out ofWorker::close_storeis a correct de-duplication.docs/scheduling-runtime-design.md(not opened) — the Mixed stratification paragraph is a real spec update, appropriately sized (+23/−18).
E. Ranked ask
- C1 — merge the three mixed scoring loops (~80–100 lines).
- A1/A2/A3 — one
can_toggle_livehelper, one shared toggle/park/rollback helper, one park struct (~60–80 lines, and removes the already-diverged predicate). - A5 + A4 — delete
waiting_for_drain/remaining/exact_lenmirrors; read scheduler state. - A7 — replace
grammar_enabled+grammar_maskwith one three-state enum. - B1 + B2 + B3 — delete the duplicate
routesvec, onetransform_nsrule, one GPU-else-CPU restore helper (~40 lines). - C2 + C3 + C4 + C5 — one clamp helper, one bucket-reset path, one context-slope mechanism, drop the
Option<Option<_>>tri-state (~40 lines).
Nothing here is a correctness defect; all findings are duplicated structure in the PR's own new code.
Code correctness
Deep Code Correctness / Invariants / Hot-Path Audit — PR #729 @ 150f705
14 files, 3 distinct Helios subsystems → audited via 3 concurrent sub-agents (offload codec, scheduler Mixed cost-model, runtime grammar/park), then key findings independently re-verified by me against the files at 150f705.
Verdict: 2 Major defects (both unconditional, code-level), 4 Minor. No Blocker found. The rest of the slice — including the claims most at risk (partition_restore_pages batching correctness, paused_for_park never stuck, pending domain exhaustiveness, no semantic outlier in the Mixed cost model, no per-step NNLS re-solve) — I checked and found correct.
FINDING 1 — MAJOR: try_with_gpu_codec_locked blocks on CopyEngineGate before try_lock, so the foreground-restore CPU fallback is unreachable (and it burns a wave token)
Diff site — helios/src/offload/transfer/codec.rs:888-899 (re-verified by me):
/// Acquires `CopyEngineGate::enter_offload_batch` before `try_lock` on the GPU codec mutex.
/// Returns `None` when another thread currently holds the codec mutex, releasing the gate
/// immediately so foreground restores can fall back to CPU decoding without blocking.
fn try_with_gpu_codec_locked<T, R>(
copy_gate: Option<&super::super::CopyEngineGate>,
codec: &Mutex<T>,
f: impl FnOnce(&mut T) -> Result<R>,
) -> Option<Result<R>> {
let _ce = copy_gate.map(super::super::CopyEngineGate::enter_offload_batch);
let mut guard = codec.try_lock().ok()?;
Some(f(&mut guard))
}
Callee definition — helios/src/offload/copy_gate.rs:173-195: enter_offload_batch is an unbounded blocking condvar wait, not a try:
fn must_wait(&self, state: &GateState) -> bool {
state.peer_graphs_active > 0
|| (state.peer_graphs_waiting > 0
&& !(state.turn == Turn::Offload && state.offload_wave_remaining > 0))
}
// ...
while self.must_wait(&state) {
state = self.changed.wait(state).unwrap_or_else(|e| e.into_inner());
}
Defect. Line 896 is the blocking step and it runs before line 897's non-blocking try_lock. The doc comment at :888-890 — which states the helper releases the gate immediately so restores can fall back to CPU "without blocking" — is false: by the time try_lock is evaluated the thread has already parked on the gate. The whole purpose of the PR's fix (docs/PR body: "preventing background captures blocked on CopyEngineGate from forcing foreground restores onto CPU decoding") is defeated for the try variant: the restore stalls for the full peer-graph drain (bounded only by the 120 s PEER_GRAPH_GATE_TIMEOUT) instead of taking the CPU path.
Concrete counterexample. Background capture thread holds gpu.codec (via with_gpu_codec_locked, codec.rs:883-885) and a gate ticket; a pipelined peer-copy graph calls enter_peer_graph → peer_graphs_waiting = 1 (copy_gate.rs:127). A foreground restore reaches try_with_gpu_codec_locked (call sites codec.rs:605, :704) and blocks at :896 for the entire peer drain. The CPU-fallback branch it was supposed to reach (codec.rs:729-755, the None arm that decodes on CPU) is never taken.
The new test cannot catch it — helios/src/offload/transfer/codec.rs:1737-1748 (copy_engine_gate_before_codec_mutex_leaves_mutex_unheld_while_waiting_on_peer_graph) drops peer_guard before exercising the helper, so it only proves the mutex is unheld during f(), never that the try path is non-blocking.
Fix. Reverse the order, or add a genuinely non-blocking gate entry:
let mut guard = codec.try_lock().ok()?; // cheap, non-blocking first
let _ce = copy_gate.map(CopyEngineGate::enter_offload_batch);
f(&mut guard)
or add CopyEngineGate::try_enter_offload_batch() -> Option<Guard> that returns None instead of waiting, and use it here.
FINDING 2 — MAJOR: a single decode-only Mixed sample permanently disables the upward extrapolation floor, letting partial fills discount full-chunk cost ~2x
Diff site — helios/src/scheduler/cost.rs:132-142 (re-verified by me):
fn upward_extrapolation_floor(&self, u: f64) -> f64 {
if self.u_min > 0.0
&& (self.u_max - self.u_min) < 0.15
&& u > self.u_max
&& self.u_max > 0.0
{
self.t_at_umax * (u / self.u_max).min(PREFILL_MAX_UPWARD_EXTRAPOLATION)
} else { 0.0 }
}
Callee / invariant — helios/src/scheduler/cost.rs:368-373 + :354-361 (re-verified by me). The new zero_fill bucket is recorded into the same u_min/u_max extent as the positive-fill strata, with u = 0.0:
if let Some((t, u, h)) = self.zero_fill.median()
&& t > 0.0 && t.is_finite()
{
record_point(t, u, h); // u == 0.0
}
...
if u < u_min - 1e-12 || ((u - u_min).abs() <= 1e-12 && h < h_at_umin) {
u_min = u; // u_min becomes 0.0
Spec violated. docs/scheduling-runtime-design.md (cost-model section) requires the floor "when only a narrow positive fill regime (u_min > 0, spread < 0.15) has been observed, queries above u_max apply a bounded constant-throughput upward floor … so partial fills cannot discount full-chunk cost estimates or lock out a large capacity after TTL reset". The u_min > 0 wording is meant to exclude the decode-only point, but the zero-fill bucket is folded into the same u_min, so the guard is dead as soon as one decode-only Mixed step is observed. Note the gate is not needed for work == 0 anyway — predict returns before the floor at cost.rs:176-189, so u_min > 0.0 protects nothing there. This also creates a prefill/Mixed parity break: pure-prefill graphs never push a u=0 point, Mixed graphs always do.
Concrete counterexample. Mixed(4,1,2048) just after a TTL reset (buckets cleared, cost.rs:317-320):
- sample A: decode-only, 15 ms →
zero_fill = (15 ms, u=0, h=0) - sample B: partial fill
work=128,start_position=0, 16 ms → stratum 0 =(16 ms, u=0.0625, h=0)
2-point exact fit: theta_0 = 15 ms, theta_1 = 16 ms, u_min = 0, u_max = 0.0625 (spread 0.0625 < 0.15).
predict(2048, 0)=15 + 16·1.0= 31 ms (floor skipped, sinceu_min == 0.0)- Correct (floor over positive fills only:
u_min = 0.0625):t_at_umax · min(1/0.0625, 4)=16 ms · 4= 64 ms
A 2.06x under-prediction of full-chunk cost, caused solely by the presence of an observation that carries no information about fill cost. Downstream this makes a full-chunk Mixed plan look cheap and win select_plan/service_rates comparisons against correctly-priced candidates.
Existing coverage misses it: cost.rs:1830-1840 (asserts guarded == 80_000_000) exercises only the no-zero_fill path, so the regression test passes while the guard is disabled in the Mixed case.
Fix. Track u_min_positive/u_max_positive/t_at_umax_positive over the self.strata loop only (cost.rs:374-385) and gate upward_extrapolation_floor on that extent; keep zero_fill in the NNLS pts vector (:372) so the intercept is still fitted. Update the doc sentence accordingly.
FINDING 3 — MINOR: degenerate fit clamped to 1 ns, which is the best possible score rather than "unknown"
helios/src/scheduler/cost.rs:182-188 and :198-200 (re-verified by me):
return if !base.is_finite() || base <= 1.0 {
1
} else if base >= u64::MAX as f64 { u64::MAX } else { base.round() as u64 };
...
if !pred.is_finite() || pred <= 1.0 { 1 }
Callee — helios/src/scheduler/utility.rs:154-171: a duration_ns of 1 is not treated as the optimistic-exploration sentinel (that is duration_ns == 0); it gets score = expected_value / 1e-6 (1e6x), and is_unmeasured_candidate (policy.rs:546-549) returns false because duration_ns != 0, so it is dispatched as PlanOrigin::Ordinary with estimated_duration_ns = 1.
Counterexample. NNLS with a clamped small intercept — points (100 ns, u=0.25, h=0) and (395 ns, u=1.0, h=0) — can leave the enumerated active-set solution at theta_0 = 0.4, theta_1 = 0 (cost.rs:407-440 clamps theta[idx[pos]] = sol[pos].max(0.0)). predict(2048, 0) → 0.4 → 1 ns → that candidate wins max_by against every measured graph and is treated as a free execution window.
Fix. Clamp to t_at_umin (or the smallest observed stratum median); reserve the literal 1 for the no-sample case only.
FINDING 4 — MINOR: grammar toggle is non-atomic; caller and callee phase guards are different predicates, so a rejected toggle leaves host and device grammar state disagreeing
Diff site — helios/src/server/runtime.rs:2363-2380 (mirror at :2441-2454): mutates incoming.grammar_reasoning_mode, request.reasoning, admissions[slot].set_grammar_mask(...) and then calls self.scheduler.set_grammar_constrained(...)?.
Callee — helios/src/scheduler.rs:3240-3247 (re-verified by me):
if request.pending != 0
|| matches!(request.phase, RequestPhase::Inbound | RequestPhase::Finishing)
|| (request.phase == RequestPhase::Snapshot && request.boundary_capture.is_none())
{
return Err("grammar constraint mode requires a live request with no pending GPU work".into());
}
The caller gate (runtime.rs:2357-2362, :2435-2440) accepts Snapshot && boundary_capture.is_some(), which the callee rejects; conversely the caller rejects Snapshot && terminal_snapshot.is_some(), which the callee accepts. Neither predicate implies the other. On the rejected path the ? aborts complete() after the admission mask and request.reasoning were already mutated while grammar_constrained stays true — device keeps Width = 1 while the host believes reasoning is unmasked. Not proven reachable across a completion boundary (phase Snapshot with neither capture is transient inside complete_inner, scheduler.rs:3106-3113), hence Minor.
Fix. Call set_grammar_constrained first (it is a pure check + flag write, idempotent), then mutate incoming/admissions; or have the caller reuse the callee's predicate.
FINDING 5 — MINOR (fairness/hot path): the try-wrapper consumes two gate wave tokens per restore unit
codec.rs:896 enters the gate, then GatedCopies::batch (helios/src/offload/transfer.rs:335-336) enters it again. enter_offload_batch decrements offload_wave_remaining and flips the turn back to Peer at zero (copy_gate.rs:187-192), while the wave is armed to exactly offload_batches_waiting (copy_gate.rs:62) with MAX_PEER_STREAK_WHILE_OFFLOAD_WAITING = 4 (copy_gate.rs:34). A restore that later fails try_lock thus burned 2 tokens for one page run, shortening offload's turn against peer graphs. Same fix as Finding 1.
FINDING 6 — MINOR (hot path): per-frame invariant recomputation and per-page allocation on the foreground path
helios/src/server/runtime.rs:2118-2120:sampling_graphs_bind_grammar_enabled(self.config)(walks every graph × every input binding,runtime.rs:526-543) runs on everyWorker::complete. It is invariant for the immutable model config (the phase tests have to mutateconfig.contract.graphsbefore constructing the worker,phase_tests.rs:8695-8716). Fix: compute once inWorker::newand storecan_toggle_grammar_in_place: bool.helios/src/offload/transfer/codec.rs:685-695,:713-714,:738,:764,:766-770:restore_windowmaterialisespages+routesfor the whole window, then clones spans and chunks again per run — ~2-3 allocations per page per 64-pageWINDOW_PAGESwindow on the foreground restore path, and eager work for pages a later error never touches. Fix: pass&[Vec<DeviceSpan>]/&Vec<&[u8]>instead ofch.clone().
Explicitly checked and found CORRECT (no defect)
partition_restore_pages/restore_single_unit(codec.rs:837-873): handles empty window, all-Literal, leading+trailingLiteral,[Gpu,Cpu,Gpu],[Gpu,Gpu,Literal,Gpu](the post-LiteralGPU run is genuinely oneGpuBatch, not split or dropped — the originalelse { break; }bug is really fixed), all-singleton, andcap == 1.GpuBatchis only produced forlen > 1, so theself.gpu.as_ref().unwrap()at:706cannot panic. Pure-Literalbatches contribute exactly 0transform_ns(:569-574,:643-645) — no divide-by-zero, stale accumulator or mis-attribution.stored/transferredadvance exactly once per page on every branch (:756-757,:779-780,:784-785, row at:805).try_lockfallback cannot drop or double-consume a page (None → CPU path for the same slice,Some(Err)propagates aftersync_on_err)._ceand theMutexGuardare RAII, so no ticket leaks on?, panic, or the try-Nonepath.- Lock order: only the two wrappers plus
RankCodec::new:125(before any gate) touchgpu.codec; no path takes the mutex before the gate on the capture side. The PR's lock-order inversion is fixed; Finding 1 is the remaining consequence of gating too early inside the try variant. - Runtime state machine (
scheduler.rs/runtime.rs):paused_for_parkis cleared on every drain-loop exit (scheduler.rs:3265-3295), including the overshoot case, which routes topark_with_tokens→cancel(handle)→retire(request removed entirely, not left excluded fromeligible()/has_starved_request()/refill_reservations()/preempt_newest()). No early-?between pause and resume leaves a per-request hang. Reservation cleanup on bothfinish_earlyexits is intact. pendingdomain exhaustiveness: at most 2 outstanding submissions globally (scheduler.rs:2530-2535), and apending > 0request is scheduler-eligible only ifpending < 2 && !grammar_constrained(policy.rs:342-353), sopending ∈ {0,1}at the transition block — the in-place (pending == 0) / checkpoint (pending > 0) arms partition the domain. No dead or always-true guard.- Partial
ValueSource::GrammarEnabledbinding is handled conservatively —runtime.rs:526-543is anall()with early return plus asaw_samplingguard, so a partially-bound contract yieldsfalse→ safe checkpoint path. - Device/host grammar disagreement is unreachable:
Admission::from_continuation(admission.rs:160-173) yieldsgrammar_mask = Someonly whengrammar_mask_active, andruntime.rs:1712-1715guaranteesmask_active ⇒ device_grammar_enabled, so the||inpacking.rs:803-805is purely defensive; the.expect("grammar admission has a mask")inadmission.rs:117-122is likewise unreachable. - Mixed cost model enum hygiene:
cost.rs:653-659attaches the stratified model only foris_prefill()kinds and forMixedwithprefill > 0;Init/Restore/Snapshot/Decode/Speculative/Resume/Visionstill use the flatReplayTimesmedian (cost.rs:1097-1099), so no semantic outlier (sampling/resume/projection step) can poisonu_min/u_max/the floor. The Mixed sample really is recorded at(work, start_position)(cost.rs:1081-1090;policy.rs:2202-2206;validate_mixedatscheduler.rs:451-476). - No half-updated model / no stale coefficients:
fit()is pure;observedoeslet predictor = self.fit(); self.predictor = Some(predictor)(cost.rs:339-341);n == 0→constant(capacity, 1)(:386-388);mixed_entryreturnsSome(None)whenestimate.nanos == 0(:756-758), so the pre-first-sample path can never produce a free Mixed step. - Peer slope borrowing is bounded and cannot cross-borrow:
borrowed_mixed_context_slope(cost.rs:883-899) requirespeer_batch == batch && peer_width == width && peer_prefill > prefill && slope > 0.0 && fresh; no peer → no borrow → slope 0.context_slope_per_tokenalready requirestheta[2] > 0andhas_deep_context(cost.rs:119-122). - Boundaries:
work == 0short-circuits before the floor;u = work.clamp(1, cap)/cap.max(1)has no divide-by-zero;mixed_candidates'score_decoders(slot_ns, batch - 1)(policy.rs:1836) andcontinuation_candidate'scapacity - preparing_prompt/batch - usize::from(...)(policy.rs:1272-1274) cannot underflow becausemixed_graphsrequiresbatch >= 2(scheduler.rs:1056) andREQUEST_LANES = 64(manifest.rs:18). - Polarity: lower duration → higher score →
max_byeverywhere (policy.rs:867,:949,:1840-1845,:1979) and1e6/nsinservice_rates(service.rs:375,:387). - No per-step NNLS re-solve:
fit()runs only insideobserve(cost.rs:339), never in a pricing path;mixed_candidatesisO(mixed_catalog × 64)with fixed stack arrays and zero heap allocation. - New tests are non-vacuous and would fail on the pre-change code:
phase_tests.rs:8592-8687assertsparked.is_empty()+ sameRequestHandle(the oldpark_with_tokens(..., publish_terminal: false)→cancelpath clears the active slot and pushes toparked);:8802-8996assertsconsumed_tokens == 5ofprompt_tokens == 6(partial KV reuse) andconsumed_tokens == prompt_tokens == 5after the drain (zero re-prefill), both impossible undercancel.
Not verified / limits
- No tests were executed (no build/GPU access); all findings are from reading files at
150f705. - Finding 3 requires NNLS to leave
theta_0 ∈ (0, 1]; I traced the enumerated active-set clamping (cost.rs:407-440) but no existing test produces that exact state, so it is proven reachable-by-construction rather than observed in practice. - Finding 1's production impact depends on how often
peer_graphs_waiting > 0overlaps a restore; the code-level defect (the documented non-blocking path is unreachable) is unconditional. - Not audited: non-grammar hunks in the same
runtime.rsdiff (RowRestoreLatency,close_store, pool-lookup-reissue,observe_prefill_rate), and the chat-template tests the PR lists as unrun.
Full report Merge Risk: medium_high (100%): Medium or high merge risk (core runtime/scheduler/GPU/CUDA/VMM/RoCE/multi-rank/contracts/ABI, large multi-crate changes, or Blocker/Major findings) — route to Super Agent.
Final review
Recommendation: Changes Requested
This PR tackles three real, well-motivated Helios issues cleanly within the model-agnostic runtime layer with zero core-format/ABI/Protobuf changes, and its core partition_restore_pages batching and ValueSource::GrammarEnabled packing mechanics are sound. However, direct verification at 150f705 confirms three concrete runtime/locking/cost-model bugs (including a preemption-coincident PendingGrammarPark state-corruption bug, a blocking CopyEngineGate wait inside try_with_gpu_codec_locked that defeats CPU restore fallback, and zero_fill permanently disabling upward_extrapolation_floor for GraphKind::Mixed), plus two unmet mandatory verification gates (uncovered new scheduler lifecycle state / unrun check.py --mutations, and unbenchmarked performance / legacy-core serving claims).
Merge Risk
Level: High
- Request-lifecycle state corruption under KV pressure: Deferring grammar-transition parking from
Worker::completetoWorker::publishviaPendingGrammarParkinteracts withpreempt_newest()incomplete_inner;publish()executespark_if_preemptedfirst, silently discardinggrammar_reasoning_mode,drop_reasoning, andthinking_token_budget'scut.afterbudget. - Foreground KV-offload restore stall & lock-order reversal: Reversing
#628's reviewedgpu.codec→CopyEngineGatelock order puts an unboundedCopyEngineGate::enter_offload_batchwait ahead ofcodec.try_lock()intry_with_gpu_codec_locked, blocking foreground restores behind peer-copy graphs instead of falling back to CPU decoding, while burning two offload wave tokens on contention. - Unbenchmarked behavior shifts across three unrelated hot-path subsystems: Non-speculative grammar requests lose two-frame pipelining during reasoning and pack
GrammarEnabled = 1during open reasoning; existing speculative cores without per-stepGrammarEnabledbindings paySnapshot+Restoreper transition; andGraphKind::MixedNNLS stratification alters mixed scheduling and collides textually incost.rswith open#715.
Walkthrough
- Grammar-transition KV preservation (
helios/src/model/{admission,packing}.rs,helios/src/scheduler.rs,helios/src/scheduler/policy.rs,helios/src/server/runtime.rs, tests): AddsAdmission::grammar_enabledand widensValueSource::GrammarEnabledpacking togrammar_enabled || grammar_mask.is_some()(packing.rs:803-805). AddsLiveRequest::paused_for_parkandRequestScheduler::{set_grammar_constrained, pause_for_park, finish_for_park}(scheduler.rs:267, 1433, 1449, 1531, 3234-3295;policy.rs:335). Replaces unconditionalcancel()transitions inWorker::completewith in-place toggling for non-speculative models and per-step-GrammarEnabledspeculative cores, or terminal-checkpoint parking viaPendingGrammarPark(runtime.rs:509-545, 1698-1706, 2118-2120, 2350-2614). - KV offload restore batching & lock ordering (
helios/src/offload/transfer/codec.rs): Replaces the single leading GPU loop inrestore_windowwithpartition_restore_pages(GpuBatch,CpuBatch,Single) andrestore_single_unit(codec.rs:586-873), skippingtransform_nson pure-Literalbatches (:569-574, 643-645). Routes all five GPU codec lock sites (:288, 317, 352, 605, 704) throughwith_gpu_codec_locked/try_with_gpu_codec_locked(:878-899), acquiringCopyEngineGatebeforegpu.codec. - Stratified
GraphKind::Mixedcost modeling (helios/src/scheduler/{cost,policy,service}.rs,docs/scheduling-runtime-design.md, tests): AttachesPrefillCostModeltoGraphKind::Mixed(cost.rs:655-656) with azero_fillbucket (:286, 321-323, 368-373),t_at_uminfallback forwork == 0(:176-189),u_min > 0.0gating onupward_extrapolation_floor(:132-142), and same-(batch, width)peer KV-context slope borrowing (:600, 883-936). Wiresmixed_entry/mixed_durationthroughnext_progress,continuation_candidate,mixed_candidates,resize_prefill,delivery_references_and_decode_batch, andservice_rates(policy.rs:934-969, 1166-1308, 1751-1947, 2112-2120;service.rs:232-240, 353-395) and updatesdocs/scheduling-runtime-design.md:466-490.
Pre-merge Checks
- [PASS] Security / malicious screen: Pure host-side scheduling, runtime state, and codec synchronization; no new dependencies, external I/O, wire/Protobuf/kernel changes, or prompt-injection attempts.
- [WARN] Charter & value fit: Model-agnostic Helios placement with no new op contracts, flags, or ABI changes (
#267,#334), and valid Discord contact; however, all three buckets are performance-motivated with zero served-workloadflare runA/B benchmarks (#210,docs/design-review.md:109-115), bundle three unrelated subsystems, and omit issue/PR links (#530,#626,#628,#645). - [WARN] Related / duplicate / conflict check: Genuinely additive over
#525/#626/#628/#645(not a duplicate), but reverses#628's reviewed lock-order invariant (needs@yatesdrsign-off once fixed) and conflicts textually incost.rswith open#715. - [WARN] Tests & verification evidence: Strong targeted CPU and SM120 GPU codec unit tests are reported passing, but
paused_for_park/pause_for_park/finish_for_park/set_grammar_constrainedlack TLA+ conformance coverage,check.py --mutationswas skipped (docs/design-review.md:226-251), and neither legacy-core loading/serving norscripts/scheduling_simvalidation was run.
Blockers
-
Preemption in
complete_innerclobbersPendingGrammarParkinWorker::publish(), corrupting grammar mode and losingthinking_token_budget(helios/src/server/runtime.rs:2580-2614,:2350-2407,helios/src/scheduler.rs:1515, 1523-1542, 3121, 3267-3295)- Verified defect: When a growable request emits
</think>(or re-enters reasoning) on a frame withskipped == 0andpending == 0,RequestScheduler::complete_innerrunsself.refill_reservations()?(scheduler.rs:3121) before returninggeneratedtoWorker::complete. Under page pressure,preempt_newest()(scheduler.rs:1523-1542) can pick that request (pending == 0 && !paused_for_park && phase == Decode) and callfinish_early(handle, /*preempted=*/ true), settingpreempted = trueandphase = RequestPhase::Snapshot(withterminal_snapshot = Some(_)) orRequestPhase::Finishing. Worker::completethen clearsrequest.incoming.prompt.reasoning_cut = None(runtime.rs:2350), evaluatescan_toggle_live == false(because ofFinishing/terminal_snapshot), enterscheckpoint_parks, callsfinish_for_park(handle)?(scheduler.rs:3285, 3292returnsOk(())without clearingpreempted), and storesPendingGrammarPark { remaining (including cut.after), speculative_reasoning, drop_reasoning, waiting_for_drain: false }.- When
Worker::publish()runs (runtime.rs:2580-2583),self.park_if_preempted(slot)?executes before thepending_grammar_parkhandler at:2589-2614. Becauselive.preempted()istrue,park_if_preempted(runtime.rs:2801-2834) parks withgrammar_reasoning_mode: None,drop_reasoning: false, andremaining = max_new_tokens - live.generated_tokens, discardingPendingGrammarPark. On readmission, the request resumes in the wrong grammar/reasoning mode (e.g., still unmasked after</think>or still constrained after re-entry), retains dropped reasoning state, and permanently losescut.afterfromthinking_token_budget. - Fix: In
Worker::publish()(runtime.rs:2580-2614), check and handlepending_grammar_park.take_if(|park| !park.waiting_for_drain)(whenlive.phase == RequestPhase::Finishing && live.last_use() <= self.scheduler.completed()) beforeself.park_if_preempted(slot)?(or gatepark_if_preemptedonactive.pending_grammar_park.is_none()), and add a phase test exercising preemption during the samecomplete_innerstep as a grammar transition (withreasoning_cut.after > 0).
- Verified defect: When a growable request emits
-
try_with_gpu_codec_lockedblocks onCopyEngineGate::enter_offload_batchbeforetry_lock(), defeating non-blocking CPU restore fallback and burning two wave tokens (helios/src/offload/transfer/codec.rs:888-899,:605-629,:704-755;helios/src/offload/copy_gate.rs:173-195;helios/src/offload/transfer.rs:335-336)- Verified defect:
try_with_gpu_codec_locked(codec.rs:896-898) callsCopyEngineGate::enter_offload_batch—an unbounded blocking condvar wait (copy_gate.rs:175-194)—before callingcodec.try_lock(). Whenever a peer-copy graph is active (peer_graphs_active > 0) or queued behind an active background capture (peer_graphs_waiting > 0), a foreground restore blocks at:896for the full capture + peer-graph drain instead of returningNoneand decoding on the CPU pool in parallel. This directly contradicts the helper's doc comment (codec.rs:888-890) and breaks the critical-path CPU fallback; the new unit test (codec.rs:1719-1736) dropspeer_guardbefore callingtry_with_gpu_codec_locked, so it misses this case. - In addition, during
Turn::Offload, a contendedtry_with_gpu_codec_lockeddecrementsoffload_wave_remainingon entry (copy_gate.rs:187-191), failstry_lock(), drops_ce, and then the CPU fallback callscopy_spans_batch→GatedCopies::batch→enter_offload_batch()(transfer.rs:336) a second time, consuming two wave tokens for one run (or flippingTurn::Peerand blocking again). - Fix (deadlock-free): Do not simply swap
try_lock()ahead of blockingenter_offload_batch()—that would introduce a 3-way deadlock againstwith_gpu_codec_locked(captureholdsOffloadBatchGuardwaiting ongpu.codec;restoreholdsgpu.codecwaiting inenter_offload_batchonpeer_graphs_waiting;peer_graphsetspeer_graphs_waiting = 1waiting oncapture'sOffloadBatchGuardup to the 120 sPEER_GRAPH_GATE_TIMEOUT). Instead, add a non-blockingCopyEngineGate::try_enter_offload_batch(&self) -> Option<OffloadBatchGuard<'_>>that returnsNoneimmediately whenmust_wait(&state)is true (and avoids consuming anoffload_wave_remainingtoken if the caller bails ontry_lock), use it intry_with_gpu_codec_lockedbeforecodec.try_lock(), and add a test provingtry_with_gpu_codec_lockedreturnsNoneimmediately while aPeerGraphGuardis held.
- Verified defect:
-
zero_fill(u = 0.0) setsu_min = 0.0, permanently disablingupward_extrapolation_floorforGraphKind::Mixed(helios/src/scheduler/cost.rs:132-142, 347-385;docs/scheduling-runtime-design.md:475-479)- Verified defect:
upward_extrapolation_floor(cost.rs:132-142) requiresself.u_min > 0.0 && (self.u_max - self.u_min) < 0.15. However,PrefillCostModel::fit(cost.rs:368-373, 354-361) routesself.zero_fill.median()(u == 0.0) throughrecord_point, settingu_min = 0.0. Once any single decode-onlyMixedstep is observed,self.u_minstays0.0until TTL reset andupward_extrapolation_flooris permanently disabled—contradictingdocs/scheduling-runtime-design.md:475-479("when only a narrow positive fill regime (u_min > 0, spread< 0.15) has been observed"). - Concrete counterexample: On
Mixed(4, 1, 2048)post-TTL with decode-only15 ms(u = 0) and partial fillwork = 128(u = 0.0625,16 ms), NNLS fitstheta_0 = 15 ms, theta_1 = 16 ms;predict(2048, 0)returns31 msinstead of the4×floor64 ms(2.06× under-prediction of full-chunk cost). The new test atcost.rs:1854-1858only checks the post-TTL path without azero_fillsample. - Fix: Track positive-fill bounds (
pos_u_min,pos_u_max,pos_t_at_umax) overself.strataonly (cost.rs:374-385) and use them forupward_extrapolation_floor(and the narrow-regime check inconstant_nanosat:441-444), while keepingzero_fillinptsfor NNLS fitting andt_at_umin. Add a regression test asserting the4×floor still fires after observing bothzero_filland a narrow partial-fill sample.
- Verified defect:
-
Mandatory Layer 3 formal verification & mutation gates unmet for new scheduler lifecycle states and safety guards (
helios/src/scheduler.rs:267, 1433, 1449, 1531, 3234-3295;helios/src/scheduler/policy.rs:335;docs/design-review.md:226-251)- Verified gate violation: This PR adds a new live-request lifecycle state (
paused_for_park, excluding requests fromeligible, starvation detection, reservation refill, and preemption) and three guarded scheduler transitions (set_grammar_constrained,pause_for_park,finish_for_park, plusBoundaryKind::ConditionedWindowrejection andconsumed_tokens <= exact_lendrain checks).verification/has zero references to any of these states/transitions, and the PR explicitly listsverification/helios-lifecycle/check.py --mutationsas unrun. docs/design-review.md:226-251is explicit: modifying Helios scheduler lifecycle transitions without updating and running the applicable TLA+ models / Rust observed-edge conformance fixtures is a blocking design failure, new safety guards require--mutations(orcargo-mutants), and disclosing runnable CPU checks as unrun does not waive them. (Blocker 1 is a concrete example of the exact preemption × park lifecycle gap left uncovered.)- Fix: Extend the applicable TLA+ lifecycle/conformance suite (
verification/helios-lifecycle/) to coverpaused_for_park/pause_for_park/finish_for_park/set_grammar_constrained(including interaction with preemption/terminal snapshots), and runverification/helios-lifecycle/check.py --mutationscleanly.
- Verified gate violation: This PR adds a new live-request lifecycle state (
-
Performance-motivated changes and legacy-core behavior changes lack live served-workload A/B and previous-core serving verification (Charter
#210;docs/design-review.md:109-123)- Verified gate violation: All three buckets are performance-motivated ("eliminates 2K-32K KV and recurrent state wipes", GPU restore batching,
Mixedpricing), yet the PR explicitly reports "not benchmarked end-to-end here" and "No end-to-end exported-coreflare runlatency or throughput benchmark was run on this branch." Moreover, non-speculative models now packGrammarEnabled = 1during open reasoning and disable two-frame pipelining during reasoning, and existing speculative cores without per-stepGrammarEnabledbindings now runSnapshot+Restoreper transition—making live loading/serving on previously exported cores (docs/design-review.md:116-123) andflare runA/B measurements againstmain(docs/design-review.md:109-115, Charter#210) essential rather than optional. - Fix: Run and report a
flare runA/B benchmark overmainon an exported core exercising structured-output reasoning transitions (covering both in-place andSnapshot+Restorepaths on an existing core to substantiate both performance and Principle 13 compatibility).
- Verified gate violation: All three buckets are performance-motivated ("eliminates 2K-32K KV and recurrent state wipes", GPU restore batching,
Should Fix
-
Discontinuous
predict(0, 0)cliff down to1 ns/ microseconds whenu_min > 0and NNLS produces a tiny positivetheta[0](helios/src/scheduler/cost.rs:176-189,helios/src/scheduler/utility.rs:154-171,helios/src/scheduler/policy.rs:546-549)- When no
zero_fillsample has been observed (u_min > 0),predict(0, 0)checksif self.theta[0] > 0.0 && self.theta[0].is_finite() { self.theta[0] } else { self.t_at_umin }. If two positive-fill observations are barely sub-linear—e.g.,(u = 0.25, 20_000_000 ns)and(u = 1.0, 79_999_000 ns)(or79_999_999 ns)—exact NNLS solvestheta[0] = 333.33 ns(or0.33 ns, clamped to1 ns) with SSE0.0. Becausetheta[0] > 0.0,predict(0, 0)skipst_at_uminand returns333 ns(or1 ns), inflatingValueRate::new(utility.rs:155-165) by 60,000×–20,000,000× whileis_unmeasured_candidate(policy.rs:546-549) remainsfalse. - Fix: When no
zero_fillsample has been observed (has_zero_fill == false), either returnt_at_uminforwork == 0directly or clamptheta[0]against a lower bound derived fromt_at_uminrather than lettingtheta[0] > 0.0collapse toward1 ns.
- When no
-
Cache
sampling_graphs_bind_grammar_enabledonWorkerand enforce atomic scheduler-first ordering on in-place toggle (helios/src/server/runtime.rs:519-545, 2118-2120, 2364-2380, 2441-2454)sampling_graphs_bind_grammar_enabled(self.config)walks every prepared graph and every input binding on everyWorker::completecall even thoughself.configis immutable; compute and cachecan_toggle_grammar_in_place: boolonce inWorker::new.- In both in-place toggle arms (
runtime.rs:2372-2380and:2442-2448),incoming.grammar_reasoning_mode,request.reasoning, andadmissions[slot]are mutated beforeself.scheduler.set_grammar_constrained(...)?. Callself.scheduler.set_grammar_constrained(...)?first so an unexpected error cannot leave host and scheduler grammar state diverged.
-
Update stale present-state docs and confirm Layer 2 simulator validation for
Mixed(docs/prefix-cache-offload.md:96-100,docs/core-design.md(not opened),docs/mtp-design.md(not opened),docs/design-review.md:195-206)docs/prefix-cache-offload.md:96-100still describes GPU-codec CPU fallback without the newCopyEngineGateordering, anddocs/core-design.md(not opened) /docs/mtp-design.md(not opened) still describe#626's unconditionalcanceltransition; update them alongside the code and obtain@yatesdr's sign-off on reversing#628's lock-order invariant once Blocker 2 is fixed.- For Bucket 3 (
cost.rstiming estimation), runscripts/scheduling_sim/learning.py --preset validate(matching#645's precedent underdocs/design-review.md:195-206) or modelMixedstrata inscripts/scheduling_sim/.
Subtract / Simplify
- Unify the duplicated
mixed_candidatesscoring loops (helios/src/scheduler/policy.rs:1755-1868vs:1869-1947): Both branches perform the same slot scan, decoder cohort scoring, and decode-only + prompt-paired candidate emission; merging the constant and non-constant predictor branches deletes ~75 lines. - Deduplicate grammar-transition helpers and park state (
helios/src/server/runtime.rs:509-517, 2106-2114, 2352-2407, 2431-2481, 2523-2537):can_toggle_liveand the three-way toggle/park/rollback branch are duplicated across reasoning close and re-entry;GrammarTransitionandPendingGrammarParkduplicate the same five fields (exact_len, emitted, remaining, speculative_reasoning, drop_reasoning); andPendingGrammarPark.waiting_for_drainmirrorsLiveRequest.paused_for_park(scheduler.rs:267). Extracting one helper and one unified park struct removes ~60–80 lines and prevents branch drift. - Replace
Admission::{grammar_mask, grammar_enabled}with a 3-state enum (helios/src/model/admission.rs:66-69, 125-128,helios/src/model/packing.rs:803-805): Eliminates the unrepresentable(Some(mask), false)state thatgrammar_enabled || grammar_mask.is_some()currently papers over. - Drop redundant
routesVecand per-page clones inrestore_window(helios/src/offload/transfer/codec.rs:685-699, 713-714, 735-744, 762-770):pagesalready carriesrouteat index 1, and passing borrowed slices avoids 2–3 extra heap allocations per page on the foreground restore path. - Deduplicate
PrefillPredictor::predictclamping and unnamed 5-tuplemixed_context_slopes(helios/src/scheduler/cost.rs:176-205, 597-600, 871-936): Extract a sharedclamp_nanos(f64) -> u64helper and a namedContextSlopestruct to replace positional.2tuple indexing.
Nits
- Consider splitting these three disjoint Helios subsystems (grammar transitions, KV codec batching/locking,
Mixedcost stratification) into separate PRs so each can be benchmarked, reviewed by its area owner (@yatesdrfor codec/gate), and merged cleanly around open#715(cost.rsconflict). - Link
#530and predecessor PRs#626,#628, and#645in the PR description, and clarify that the seconddocs/scheduling-runtime-design.mdhunk reflects already-merged#697/#655work from the base rather than new#729behavior. - Extract a single
transform_nsnon-Literalaccounting helper acrossdecode_pages_cpu_batch(codec.rs:569-574) andrestore_single_unit(codec.rs:643-645).
Dropped on verification
- Upstream Code Audit Finding 4 ("caller and callee
Snapshotpredicates disagree atruntime.rs:2357-2362vsscheduler.rs:3240-3247"): False—the upstream audit invertedscheduler.rs:3242's rejection predicate (if ... || (phase == Snapshot && boundary_capture.is_none()) { return Err(...); }). Both caller and callee acceptSnapshot && boundary_capture.is_some()and rejectSnapshot && terminal_snapshot.is_some(), andscheduler.rs:3089-3114ensuresSnapshotalways holds one of the two. Only the defensive call-ordering cleanup was retained in Should Fix 2. - Upstream Code Audit Finding 1's naive fix ("call
codec.try_lock()beforeCopyEngineGate::enter_offload_batch()"): Unsafe—would create a 3-way deadlock withwith_gpu_codec_locked+enter_peer_graph(). Replaced with the deadlock-freeCopyEngineGate::try_enter_offload_batch()fix in Blocker 2. - Upstream Code Audit Finding 3's counterexample detail ("
predict(2048, 0)returns1 ns"): Inaccurate—for(100, u=0.25)and(399, u=1.0),predict(2048, 0)returns399; it ispredict(0, 0)(work == 0,cost.rs:176-189) that collapses to1 ns/ µs. Reframed accurately in Should Fix 1. - Upstream Contracts Audit Gate 4 nit ("
delivery_referencesnot updated as claimed"): False—delivery_references(service.rs:59-64) delegates directly todelivery_references_and_decode_batch, which was updated atservice.rs:235to callmixed_duration(batch, width, prefill, 0, 0). - Upstream Subtraction Audit A8 (
Admission::from_prompt/validatetest-only shims) & C5 (mixed_entryOption<Option<_>>): Dropped—from_prompt/validateare pre-existing compatibility wrappers, andOption<Option<PrefillPredictor>>intentionally mirrorsprefill_entry(cost.rs:707-735) to distinguish absent vs unmeasured shapes. - Stale-base diff hunks (
checkpoints.rs(not opened),server/request.rs(not opened),RowRestoreLatency,preserve_message_anchor,snapshot_discovery,device_spansnull-row guard) & Kani / pending CI: Confirmed excluded—the hunks belong to already-merged#655/#659/#660/#674/#697/#709, Kani-covered validators were not modified, and pending CI is not a failure.
Full report Decision to Test: no (100%): Testing will not add significant value as the code stands today. The code is either not yet ready to merge, or adequate testing has already been done to validate the contents of the code, or the available hardware is not suitable to test with.
Classify triage
Selected: triage:review
Threshold: 65%
Triage
- [✓]
triage:review: 95.5% -
triage:validation: 3.3% -
triage:design-review: 0.9% -
triage:investigate: 0.1% -
triage:partial: 0.1% -
none: 0.0% -
triage:integration: 0.0% -
triage:verify-for-closure: 0.0% -
triage:superseded: 0.0%
Apply labels
No label changes decide malicious: all_clear (100%): No malicious content found
explore
Author: lukealonso (COLLABORATOR; charter-listed priority contributor; Discord: lukealonso) Motivation: Restricted/structured-output requests that enter or leave reasoning currently throw away the live KV and recurrent state and re-prefill the whole reasoning trace, and the KV-offload codec loses its GPU batching whenever a window mixes page kinds while a background capture can hold the codec lock. Separately, mixed prefill-plus-decode graphs are priced from one flat median, so the scheduler cannot tell a decode-only step from a deep-context chunk. Scale: +2954 / −591 lines in 24 files Proposal:
- Replace the cancel-and-readmit grammar transition with an in-place mask toggle (
ToggleInPlace) or a terminal-checkpoint park (CheckpointPark) plusRollback, driven bydecide_grammar_transitionand a newPausedscheduler lifecycle state. - Replace
Admission::{grammar_mask, grammar_enabled}with the three-stateAdmissionGrammarenum and packGrammarEnabledfrom it. - Partition restore windows into maximal GPU/CPU/single-page runs and route all GPU codec sites through gate-before-codec helpers, adding non-blocking
CopyEngineGate::try_enter_offload_batchso foreground restores fall back to CPU instead of stalling. - Attach a 6-stratum
(fill, kv_context)NNLSPrefillCostModeltoGraphKind::Mixedwith azero_fillstratum, an anchoredtheta_0intercept, and peer KV-context slope borrowing. - Extend
Lifecycle.tlawithPauseForPark/FinishForPark/ToggleGrammarand add six Rust mutation guards tocheck.py(not opened). Touches: helios/src/offload/transfer/codec.rs(+518/−255) — reverses #628's reviewed lock order.helios/src/server/runtime.rs(+294/−71) — request lifecycle and preemption/park ordering.helios/src/scheduler/cost.rs(+376/−64) — Mixed pricing; textual conflict with open #715. Related items:- #626 Allow speculative reasoning for grammar-constrained requests (merged): the transition mechanism #729 replaces.
- #628 helios: gate offload Copy Engine batches during peer-copy graphs (merged): its lock-order invariant is reversed here.
- #645 Overhaul Helios prefill scheduling, cost modeling, and two-frame pipelining (merged):
PrefillCostModel, extended here to Mixed. - #530 Structured output decodes ~2-3x slower than unconstrained (open): user-facing problem, now cited in the body.
- #715 helios,ignition: implement additive packed multi-request prefill (open): edits the same
cost.rsgates and doc paragraph. Link: https://github.com/NVIDIA/hyperflare-inference/pull/729 Autobot comments: The PR was force-revised at68fe22fdafter the first head: scope grew from 14 to 24 files / +2954 lines, labels and aPausedTLA+ model were added, the two runtime blockers from the earlier review were fixed, and a real served A/B now backs bucket 1 only. Two things the description understates: default MTP 5 at 20,648 prompt tokens is 30% slower (40.9→54.1 ms) and is disclosed but not gated, and #628's lock order is still reversed for the capture path with no prose statement of the invariant anywhere indocs/. Buckets 2 (codec) and 3 (Mixed NNLS) have no whole-model benchmark, and the Layer-2 simulator gate is explicitly not runnable for bucket 3. Still zero human comments or reviews; the only automated review was verified against the superseded150f705.
Classify intake
Selected: triage:review, bug, performance, area:scheduling
Threshold: 65%
Triage
- [✓]
triage:review: 99.7% -
triage:validation: 0.1% -
triage:design-review: 0.1% -
none: 0.0% -
triage:partial: 0.0% -
triage:investigate: 0.0% -
triage:integration: 0.0% -
triage:verify-for-closure: 0.0% -
triage:superseded: 0.0%
Priority
-
none: 91.2% -
priority:P2: 6.6% -
priority:P1: 2.1%
Type
- [✓]
performance: 99.1% - [✓]
bug: 75.5% -
community: 40.7% -
enhancement: 32.1% -
duplicate: 14.8% -
documentation: 0.0%
Area
- [✓]
area:scheduling: 99.2% -
area:caching: 40.7% -
area:memory: 13.3% -
area:preparation: 2.6% -
area:api: 0.9% -
area:selene: 0.5% -
area:engram: 0.5% -
area:kernels: 0.2% -
area:orbit: 0.1% -
area:rocenante: 0.1% -
area:packaging: 0.0%
Model
-
model:muse-glimmer: 2.6% -
model:qwen3.8-flash-next: 2.3% -
model:gemma4: 1.4% -
model:qwen3.8-27b: 1.1% -
model:deepseek-v4: 0.2% -
model:glm-5.3: 0.2% -
model:inkling-small: 0.2% -
model:mimo-v2.6: 0.1% -
model:nemotron-3.5-bolt: 0.1% -
model:kimi-k3.1: 0.1% -
model:deepseek-v4.1: 0.0%
Apply Labels (Intake)
No label changes
Subtraction and simplicity
Subtraction & Simplicity audit — PR #729 (68fe22fd), 24 files / +2954 −591
Verdict: not lean, but not bloated either. The codec rewrite and the cost-model rewrite are net subtractions in the places that matter (see "Already lean" at the end). The real simplification debt is concentrated in four spots: the new grammar-admission API still carries the two-boolean shape it claims to have removed, runtime.rs constructs GrammarPark twice in two near-identical 27-line matches, mixed_candidates halves itself into two branches that compute the same thing, and cost::mixed_entry returns Option<Option<_>> which forces a repeated map_or idiom at six call sites. I estimate ~180–220 deletable lines with no behaviour change.
S1 (high) — Admission::from_continuation still takes two grammar booleans, exactly the anti-pattern the PR says it removed
helios/src/model/admission.rs:186-193:
grammar_mask_active: bool,
grammar_enabled: bool,
) -> Result<Self> {
let grammar = match prompt.grammar.as_ref() {
Some(grammar) if grammar_mask_active => AdmissionGrammar::Masked(grammar.mask().to_vec()),
Some(_) if grammar_enabled => AdmissionGrammar::UnmaskedEnabled,
_ => AdmissionGrammar::Disabled,
};
AdmissionGrammar::{Disabled, UnmaskedEnabled, Masked} was introduced precisely so that "disabled but masked" is unrepresentable, yet the constructor takes two independent bools whose 4 combinations are collapsed by a 3-arm match — i.e. the unrepresentable state is representable in the signature again, just one layer up. The caller already computes both values from the same two expressions (helios/src/server/runtime.rs:1731-1737):
let unmasked_reasoning = incoming.speculative_grammar_reasoning();
let grammar_mask_active = incoming.prompt.grammar.is_some() && !unmasked_reasoning;
// Non-speculative cores do not gate verification width on `grammar_enabled`, so
// initializing `grammar_enabled = 1` with a cached all-ones mask allows in-place
// mask toggling at `</think>` and reasoning re-entry without re-running `Restore`.
let device_grammar_enabled =
incoming.prompt.grammar.is_some() && (!unmasked_reasoning || !speculative);
Fix: pass grammar: AdmissionGrammar into from_continuation and build the enum at that one site. Deletes the 3-arm match (5 lines), the second bool, the #[allow(clippy::too_many_arguments)] on admission.rs:179 that was added only to silence the extra parameter, and the duplicated-argument hack in from_prompt (admission.rs:167-175):
grammar_constrained,
grammar_constrained,
which encodes both flags from one bool and is used only by a test (helios/src/server/runtime/phase_tests.rs:6707 (not opened); the single production construction is runtime.rs:1842). Either delete from_prompt or have it build AdmissionGrammar explicitly.
Savings: ~15 lines plus one public parameter and one allow.
S2 (high) — grammar_updated keeps a mask_mut() accessor whose expect is now a live panic
helios/src/model/admission.rs:146-152:
pub(crate) fn grammar_updated(&mut self, mask: &[i32]) {
self.grammar
.mask_mut()
.expect("grammar admission has a mask")
.copy_from_slice(mask);
}
mask_mut (admission.rs:84-89) has exactly one caller — this function. Before this PR the invariant "an admission with grammar has a mask" held; after this PR AdmissionGrammar::UnmaskedEnabled is assigned to live admissions during open reasoning (helios/src/server/runtime.rs:2461-2463):
} else {
self.admissions[slot].as_mut().unwrap().set_grammar(
crate::model::AdmissionGrammar::UnmaskedEnabled,
);
}
so any host mask push routed through grammar_updated on such a slot panics. Both the panic and the accessor disappear if grammar_updated simply becomes:
pub(crate) fn grammar_updated(&mut self, mask: &[i32]) {
self.grammar = AdmissionGrammar::Masked(mask.to_vec());
}
(reuse set_grammar, or assign directly since the field is pub). Deletes mask_mut (7 lines), a panic path, and a redundant copy_from_slice.
Related wrapper rot in the same struct: Admission.grammar is declared pub (admission.rs:99 pub grammar: AdmissionGrammar,) and has a set_grammar setter (admission.rs:154-157) that enforces no invariant. Pick one — the field is already assigned directly elsewhere (admission.rs:201).
S3 (high) — the same GrammarPark literal is built twice inside two near-identical 27-line matches
helios/src/server/runtime.rs:2401-2427 and runtime.rs:2467-2493 are the same three-arm dispatch, with the same field-by-field GrammarPark construction repeated in the CheckpointPark and Rollback arms of each:
GrammarTransitionAction::CheckpointPark { pause_for_drain } => {
checkpoint_parks.push((
slot,
token.request,
GrammarPark {
exact_len,
emitted,
remaining,
speculative_reasoning: false,
drop_reasoning,
},
pause_for_drain,
));
}
GrammarTransitionAction::Rollback => {
transitions.push((
slot,
token.request,
GrammarPark {
exact_len,
emitted,
remaining,
speculative_reasoning: false,
drop_reasoning,
},
));
}
exact_len, emitted, remaining and drop_reasoning are all in scope and already fixed before the match; only speculative_reasoning differs per site (false here, true at runtime.rs:2475/2489). Construct once above the match:
let park = GrammarPark { exact_len, emitted, remaining, speculative_reasoning: false, drop_reasoning };
match decide_grammar_transition(...) {
GrammarTransitionAction::ToggleInPlace => { ... }
GrammarTransitionAction::CheckpointPark { pause_for_drain } => checkpoint_parks.push((slot, token.request, park, pause_for_drain)),
GrammarTransitionAction::Rollback => transitions.push((slot, token.request, park)),
}
Two arms execute at most once, so the move is fine. Savings: ~26 lines (13 per site) with zero change to behaviour; also removes the risk of the two copies drifting.
Knock-on: GrammarTransitionAction::CheckpointPark { pause_for_drain } re-derives live.pending() > 0 (runtime.rs:538-541) even though runtime.rs:2509 re-checks if !live.paused_for_park() || live.pending() != 0 { continue; } anyway. Dropping the payload makes the enum a plain 3-variant tag and the callers call pause_for_park/finish_for_park off the live state they already read.
S4 (high) — mixed_candidates splits into two branches that differ by one expression
helios/src/scheduler/policy.rs:1844-1898. The variable_cost branch and the else branch both loop prefill_slots, call lane_value_for_tokens(r, GraphKind::Prefill, work, <ns>, values[slot]), call score_decoders(<ns>, batch - 1), OR in 1 << slot, and build a ValueRate. They differ only in that the curve branch uses pred.predict(work, start_pos) and breaks ties by slot, while the constant branch uses decode_ns and compares raw values:
let best_prompt = if variable_cost {
let pred = predictor.unwrap();
let mut best: Option<(usize, u64, u64, ValueRate)> = None;
for &(slot, work, start_pos) in &prefill_slots[..prefill_count] {
let slot_ns = pred.predict(work, start_pos);
...
} else {
let mut best_value: Option<(usize, f64)> = None;
for &(slot, work, _) in &prefill_slots[..prefill_count] {
...
With a constant predictor, rate ordering and value ordering select the same slot (both are value / ns with a shared ns), so the whole else arm is redundant:
let slot_ns = predictor.map_or(decode_ns, |p| if variable_cost { p.predict(work, start_pos) } else { decode_ns });
one loop, ties broken by slot as in the curve branch. Deletes variable_cost (policy.rs:1756) and ~50 lines.
S5 (high) — ActionCosts::mixed_entry returns Option<Option<_>>, forcing a repeated map_or idiom at every call site
helios/src/scheduler/cost.rs:762-767:
pub fn mixed_entry(
&self,
batch: usize,
width: usize,
prefill: usize,
) -> Option<Option<PrefillPredictor>> {
Three states ("no entry", "entry with nanos == 0", "measured") are packed into nested Option, and every consumer immediately unpacks them with the same expression predictor.map_or(0, |p| p.predict(...)):
policy.rs:948let ns = predictor.map_or(0, |p| p.predict(work, r.scheduled_consumed));policy.rs:959let ns = predictor.map_or(0, |p| p.predict(0, 0));policy.rs:1308Some(mixed_predictor.map_or(0, |p| p.predict(0, 0)))cost.rs:801.map(|predictor| predictor.map_or(0, |p| p.predict(work, start_position)))service.rs(both sites) andpolicy.rs:1755replicate it asmap_or(0, |p| p.predict(0, 0))- plus
.flatten()workarounds:service.rs.mixed_entry(batch, width, capacity).flatten(), and the double-guard atpolicy.rs:1158-1168:
let mixed_predictor = if following == GraphKind::Mixed {
let Some(predictor) = self.costs.mixed_entry(batch, width, prefill) else {
return;
};
predictor
} else {
None
};
if following == GraphKind::Mixed
&& let Some(pred) = mixed_predictor
&& !pred.is_constant()
Fix: one enum
enum MixedCost { Unmeasured, Fixed(u64), Curve(PrefillPredictor) }
plus a predict(work, start) -> u64 method. That removes the nested Option, the .flatten() calls, the duplicated if following == GraphKind::Mixed test at policy.rs:1158 and policy.rs:1166 (the second one exists only because the first had to smuggle None through a variable), and six copies of the same map_or. Note the predict(0, 0) sentinel — the magic pair is repeated at five sites; with the enum it becomes a named decode_duration().
S6 (medium) — dead conditional in PrefillCostModel::fit
helios/src/scheduler/cost.rs:461:
pos_u_min: if pos_u_max > 0.0 { pos_u_min } else { 0.0 },
The sole consumer already short-circuits on pos_u_max > 0.0 (cost.rs:141-151):
if self.pos_u_max > 0.0
&& (self.pos_u_max - self.pos_u_min) < 0.15
&& u > self.pos_u_max
so when pos_u_max == 0.0 the field is never read. The branch is unobservable — assign pos_u_min directly (one fewer sentinel-normalization to reason about).
The 13-field fit bookkeeping (cost.rs:345-394, record_point closure tracking u_min, pos_u_min, pos_u_max, t_at_umax, h_at_umax, pos_t_at_umax, pos_h_at_umax in parallel) can also be derived after the fact from pts in a few filter/min/max lines instead of incrementally inside the closure. Medium value, higher churn — worth doing only if the file is being touched again.
S7 (medium) — restore_single_unit's CPU half duplicates decode_pages_cpu_batch's single-item path
helios/src/offload/transfer/codec.rs:630-654 (non-GPU tail of restore_single_unit) and codec.rs:548-558 (decode_pages_cpu_batch if items.len() == 1) perform the same plan selection + decode_unit_cpu + copy_spans_batch for one unit, and both re-implement the same "don't bill transform_ns for pure Literal" rule in two different forms:
codec.rs:569-574:if items.iter().any(|(_, route, _)| *route != DecodeRoute::Literal) { stats.transform_ns += ... }codec.rs:643-645:if route != DecodeRoute::Literal { stats.transform_ns += ... }
PageRunKind::Single (codec.rs:826-838, produced whenever j - i == 1) is only needed for a single GPU page (so it uses decode_to_device rather than the batch API). The CPU/singleton-page case can fall into CpuBatch and hit the existing items.len() == 1 path. That deletes the non-row half of restore_single_unit (~40 lines) and one of the two duplicated transform_ns rules. The row case (codec.rs:803-820) genuinely differs (cpu.row plans) and stays.
S8 (medium) — copy_spans_batch grew a generic parameter it no longer needs
helios/src/offload/transfer/codec.rs:~1062:
fn copy_spans_batch<S: AsRef<[DeviceSpan]>>(
...
batch: &[(usize, S)],
The generic was introduced because the restore path used to own Vec<DeviceSpan> clones; after S7's partitioning rewrite the per-page spans are borrowed (batch_spans: Vec<(usize, &[DeviceSpan])> at codec.rs:743-747 and codec.rs:769-773, and &[(0, spans)] with spans: &[DeviceSpan] at codec.rs:646-652). If a grep copy_spans_batch shows every remaining call site passes a slice (both sites I read do), drop the type parameter and take &[(usize, &[DeviceSpan])] — speculative generality otherwise, and it also forces the .as_ref() at the loop body.
S9 (medium) — duplicated slope store for Mixed
helios/src/scheduler/cost.rs:901-917 (borrowed_mixed_context_slope), the new MixedContextSlope struct (cost.rs:601-608) and the second half of refresh_prefill_context_slopes (cost.rs:937-956) re-create, with a struct and a second sorted Vec, what prefill_context_slopes: [Vec<(usize, f64, u64)>; 3] + borrowed_context_slope already do — including the identical TTL test self.now_ns.saturating_sub(...) < self.ttl_ns. The only difference is the key (batch, width, prefill) vs (tokens). One struct ({ key: (usize, usize), slope, observed_at_ns }) and one borrow helper with a key predicate would collapse both. This is the area where #715 also edits (per the dossier, its gates sit at cost.rs:581-583, 606-607, 644-659, 969), so a single generic store also reduces the textual conflict surface.
S10 (low) — sampling_graphs_bind_grammar_enabled re-lists GraphKind::samples() verbatim
helios/src/server/runtime.rs:552-561:
if matches!(
graph.kind,
GraphOperation::Prefill
| GraphOperation::TerminalPrefill
| GraphOperation::ScoredPrefill
| GraphOperation::Decode
| GraphOperation::Speculative
| GraphOperation::Mixed
| GraphOperation::Resume
) {
is the same seven-operation set as GraphKind::samples() (helios/src/execution/manifest.rs:93-104), which is also spelled out independently at helios/src/model/tests.rs:65-71 (not opened) and in the contract validation list (helios/src/model/contract.rs:787-797). Add GraphOperation::samples() (or a TryFrom<GraphOperation> for GraphKind) next to the existing one and call it here — this is now a fourth copy of the "which graphs sample" list, in a hot-path-adjacent correctness check where divergence would silently disable in-place toggling.
Minor: can_toggle_grammar_in_place short-circuits to true for every non-speculative config (runtime.rs:1409-1410), so the saw_sampling return value only ever matters for speculative configs that have no sampling graphs — a state the contract likely forbids. Worth confirming; if forbidden, the saw_sampling bool and its let mut (3 lines) go away.
S11 (low) — repeated speculative derivation and shadowed Worker field
let speculative = !self.config.speculative_widths.is_empty(); at helios/src/server/runtime.rs:1729 and again at runtime.rs:2140, plus the same predicate cached as a field at runtime.rs:1409. Cache it once next to can_toggle_grammar_in_place (they are derived from the same config) and read the field, rather than recomputing and shadowing the name twice in one file.
Already lean — no action
partition_restore_pages_by(codec.rs:840-877, 38 lines) genuinely replaces a ~90-line triple-nestedwhile/breakloop with attachedVec<Vec<DeviceSpan>>run builders. Net deletion, good factoring.take_offload_lease(copy_gate.rs:180-190) and theoffload_must_waitpredicate hoist duplicate wave-token accounting out ofenter_offload_batchand lettry_enter_offload_batchshare it verbatim — the right kind of extraction (the predicate was previously an inlinemust_waitclosure; it is now shared by both paths).try_with_gpu_codec_locked(codec.rs:895-906, 11 lines) replaced five hand-rolledtry_lock()+ gate blocks with one helper;clamp_nanos(cost.rs:79-87) deletes three copies of the NaN/overflow clamp.decide_grammar_transition(runtime.rs:523-545) collapses what the Autobot review at150f705described as six inline conditions at two sites into one predicate plus a 3-variant enum. That is the right shape; the problem is only that the callers then re-expand it (S3).- No new CLI flags, env vars, config knobs or feature gates anywhere in the 24 files — the PR adds no user-facing surface. That check is clean.
Suggested order
- S1 + S2 (one coherent edit to
model/admission.rs, removes a public bool, a panic, and two accessors). - S3 (delete 26 lines of duplicated struct literal in
runtime.rs). - S4 + S5 (one edit to the Mixed cost surface: enum replaces
Option<Option<_>>, then the twomixed_candidatesbranches collapse). - S7 + S8 (codec single-unit/CPU-batch consolidation) — do this before the
#715rebase, since it touches the samecost.rs/codec.rsregions. - S6, S9, S10, S11 as follow-ups.
Total: roughly 180–220 deletable lines across six files, none of which changes scheduling or restore behaviour. Alternatively, S1/S2/S10 alone would fit as a small "grammar admission API" companion PR if the four-surface bundle is split (which the dossiers already recommend independently).
Gates and contracts
Contracts, Charter & Verification Gates Audit — PR #729 @ 68fe22f
Verdict: ONE mandatory verification gate blocker (Layer 2 scheduling simulator, bucket 3), plus two Majors (unbenchmarked buckets 2–3 and an ungated 30% MTP-5 regression). Gates 1 and 2 are CLEAR. Two of the three blocking omissions from the 150f705 round are resolved at this head and must not be re-cited.
Scope caveat: the local base is stale, so I audited only the 24 paths in pr_files at 68fe22f. pr_diff for scripts/scheduling_sim and helios/src/model/contract.rs correctly reports no change (results 39, 40), so the stale-base hunks do not affect these findings.
Gate 1 — Signed core-format / wire / captured-graph / public contract boundaries: CLEAR
- No new enum member or wire identifier.
helios/src/model/contract.rsis untouched by this PR;ValueSource::GrammarEnabled = 30pre-exists onmain(result 33,contract.rs:60). NoGraphOperation,BoundaryKind,CacheContract, or Protobuf field is added, and no core-format/ABI change is present. The captured-graph-op approval rule (docs/design-review.md:22-25,AGENTS.md:376-379) is therefore not triggered. - The new grammar representation is host-local.
AdmissionGrammar::{Disabled, UnmaskedEnabled, Masked(Vec<i32>)}is a plain Rust enum (helios/src/model/admission.rs:59-90) replacing the two formerAdmissionfields;Admission::validate/validate_continuation(admission.rs:105-113) are internal reshapes. It is not aValueSourcevariant and is not persisted. - Packed value change is within the existing contract.
helios/src/model/packing.rs:803:GrammarEnabled => values.push(i64::from(admission.grammar.is_enabled()))— same binding, same Int32 dtype (helios/src/model/testing.rs:287(not opened)), still constrained to{0,1}by the consuming kernel's admission validator (ignition/components/sampling.py:735-736). No signature, resource, or capacity change. - Normative docs updated in the same PR, no silent contradiction.
docs/scheduling-runtime-design.md:463-496now specifies the six positive-fill strata, thezero_fillbucket, NNLS fit,pos_u_max - pos_u_min < 0.15upward floor,theta_0-vs-t_at_umindecode-only rule and per-(batch,width)slope borrowing;docs/core-design.md:1729-1736(not opened) anddocs/mtp-design.md:426-440(not opened) describe the toggle/checkpoint-park split;docs/prefix-cache-offload.md:96-107describes gate-before-codec for captures, run partitioning, and the non-blockingtry_enter_offload_batchfallback that "without blocking or consuming a gate wave token". Code matches:helios/src/offload/transfer/codec.rs:879-906andhelios/src/offload/copy_gate.rs:171-210. Parity service rates still excludeMIXED(scheduling-runtime-design.md:252,278) and the PR does not change that. - Branching is structural, not per-model.
can_toggle_grammar_in_placederives fromconfig.speculative_widths.is_empty() || sampling_graphs_bind_grammar_enabled(config)(helios/src/server/runtime.rs:1409-1410, 547), i.e. from core contract bindings, not model identity — consistent with principles 1/3 and the no-hardcoded-enumeration rule.
Info / Nit (not a gate): #628's invariant was "preserve strict lock ordering (
gpu.codecbeforeCopyEngineGate)" (PR #628 body, result 26). This PR keeps that order for the blocking capture path and adds a codec-first, gate-second try path. The new order is stated in the code comment atcodec.rs:879-880, 891-894and behaviourally indocs/prefix-cache-offload.md:96-106; nodocs/sentence names "gate before codec" as an invariant (grep 'lock order' docs/→ no hits). Worth an@yatesdrack, but the deadlock question is answered in code (both try acquisitions are non-blocking, so no inversion against the blocking capture path).
Gate 2 — Vendored upstream dependencies & cross-PR conflicts: CLEAR
No helios/native/* (e.g. roce_proxy.c (not opened)), no Cargo.toml (not opened)/Cargo.lock, no .cu/PTX, no Protobuf, no recipe or unmerged-PR dependency, no new dependency to pin. Open #715 touches the same cost.rs gating lines and the same docs/scheduling-runtime-design.md paragraph — that is a textual merge-conflict risk, not a gate violation, noted as Info (see the dossier's merge-order analysis; unchanged).
Gate 3 — Mandatory verification evidence: ONE BLOCKER, no failing tests
Fixed since the previous round (do not re-flag)
- TLA+ lifecycle coverage for the new park state now exists.
verification/helios-lifecycle/Lifecycle.tlaaddsPaused == 3(:11),PauseForPark(:65-68),FinishForPark(:70-73),ToggleGrammar(:75-78), wires them intoNext(:90-92) andAllowedEdgeactions 7/8/9 (:174-176), and widensWellTyped/Cancelto the paused domain (:60, :99). The Rust↔model map is documented atverification/helios-lifecycle/README.md:52-54, 63-65. The PR reports 10 models passing and 623,904 observed Rust transitions checked. check.py --mutationswas run and now covers the new guards: six Rust mutations includingset_grammar_constrainedpending-work rejection,pause_for_park/finish_for_parkpredicates, thepaused_for_parkscheduling exclusion inpolicy.rs(not opened), thepublish()preemption ordering, andCopyEngineGate::try_enter_offload_batch(verification/helios-lifecycle/check.py:458-508).docs/design-review.md:226-228is satisfied.docs/design-review.md:234-246("keep formal bounds aligned with runtime capabilities") is satisfied for the added lifecycle domain.
BLOCKER — Layer 2 scheduling-simulator gate unmet for the GraphKind::Mixed timing-estimation change
docs/design-review.md:195-206 is explicit and directly on point: "Changes to graph selection, service pricing, timing estimation, refresh or exploration budgets … must be evaluated against the Python simulator and reference solvers in scripts/scheduling_sim/… Changes to timing estimation … require running the screening and 64-seed validation catalog in scripts/scheduling_sim/learning.py." And :234-240 makes it blocking: modifying Helios scheduling "without running—and updating when behavior, transitions, or supported bounds change—the applicable TLA+ models, Rust conformance fixtures, Kani harnesses, and scheduling simulator is a blocking design failure, regardless of whether CPU unit tests pass." :247-251 forecloses the disclosure defense.
Concrete state at 68fe22f:
- The PR changes timing estimation and graph selection for
MIXED: a six-stratum NNLS model pluszero_fill(helios/src/scheduler/cost.rs:288, 346, 68-70), pos-fill floor (cost.rs:145-149), anchored decode-only intercept (cost.rs:191), and rewiresmixed_entry/mixed_durationthroughmixed_candidates,next_progress,continuation_candidate,resize_prefill, andservice_rates. scripts/scheduling_sim/is not touched:pr_diffover that path returns "the pull request changes no file matching" (result 39), andsearch_history --path scripts/scheduling_simshows the newest commit is merged #645 (result 37).- The simulator's cost model is scalar, not stratified:
scripts/scheduling_sim/model.py:23-39(Graph= oneduration_ms+ capacities), andscripts/scheduling_sim/timing.py:301+(TimingEstimate) has no fill/context strata, no NNLS, nozero_fill, not_at_umin(result 11: no matches forentry|observation|batches|context_slope|strata). So the PR's new pricing rule is unmodelled in the reference implementation. - The PR body states the limitation explicitly ("the Python scheduling simulator models scalar per-graph costs rather than
(fill, kv_context)NNLS curves, so theGraphKind::MixedNNLS fit is verified throughhelioscost and policy unit tests"), i.e. it describes skipping the gate. - No
learning.py --preset screen|validaterun is reported anywhere in the description or dossier (the dossier records "no simulator curve sweep for bucket 3 — the PR says so explicitly").
This is a runnable CPU check (no GPU, no checkpoint: docs/design-review.md:247), the same check the author's own #645 cleared when it introduced the prefill NNLS model — so it is reachable, not hypothetical.
Required: either model the (fill, kv_context) strata incl. zero_fill in scripts/scheduling_sim/model.py/timing.py and run learning.py --preset validate (64-seed catalog), or run the screening + validation catalog against the unchanged scalar model and state which conclusion it supports. Update the simulator comments for the new cost terms (:147-149 of the old numbering — "update simulator comments when the cost terms change") and docs/scheduling-runtime-design.md's assurance statement accordingly.
Not a finding: CI / failing tests
No CI failure is reported for 68fe22f, and no test failure is reported for any crate. cargo kani is declared unrun, but no Kani-governed surface is modified (completion-vector validation, prepared completion contracts, state-view extent arithmetic, sequential validators are all untouched — helios/src/model/contract.rs unchanged), so docs/design-review.md:221-225 does not apply. Layer 1 is claimed green across eos, selene, selene-manager, helios (--lib 1,919 + --test '*' 59), flare, flare-cli and the named pytest suites.
MAJOR — buckets 2 and 3 carry no served-workload A/B
Principle 12 (docs/design-review.md:106-115) and docs/verification.md:15 require "actual Helios service measurements" on exported cores for a performance claim; charter #210 says the same.
- Bucket 1 is now properly evidenced (this retracts the prior round's finding):
flare runA/B on a signedQwen4-35B-A3BSM120 core,main f705086bvs68fe22fd,</think>→first-content median 41.2→12.4 ms (6,382 tokens) and 58.5→12.9 ms (20,648 tokens), countess prefill-token and snapshot-page reductions, 6/6 schema-valid JSON — including on a core lackingValueSource::GrammarEnabled, which doubles as partial principle-13 evidence. - Bucket 2 (KV codec batching/locking) has only four ignored
offload::transfer::codec::tests::GPU tests plustests/test_kv_codec.py(not opened).docs/design-review.md:263-269allows documentation-only changes to skip GPU tests but this is a hot-path restore change; it has no end-to-end measurement. The PR explains the SM120 core withcodec_layoutwas unavailable — a material limitation, honestly disclosed, so Major rather than Blocker, but it must be resolved before aperformancelabel is justified. - Bucket 3 (Mixed NNLS) has unit-test-only coverage plus the unmet Layer 2 gate above.
MAJOR — measured default-configuration regression is disclosed but ungated
Same A/B, default MTP 5 at 20,648 prompt tokens: main 40.9 ms median vs PR 54.1 ms (~30% slower); the 6,382-token cell is flat (39.1 vs 39.0). The mechanism is stated (pause_for_park waits one speculative frame that then overshoots and rolls back), and the claim/result section distinguishes it from the measured win — so principle 12's "report evidence honestly" is met at the description level. But every default-MTP-5 structured-output deployment pays it, and there is no stated guard (e.g. skip parking when the frontier is within a speculative burst of the transition). This is a claim-vs-benefit contradiction of the "claimed result" section's framing as an overall win; it needs either a heuristic + re-measure, or an explicit statement that the default path is expected to regress.
Gate 4 — Material scope / claim contradictions: CLEAR of hard contradictions
Every artifact the description claims exists and is where it says:
helios/src/scheduler/cost.rs:1764mixed_cost_model_tracks_zero_fill_partial_fill_deep_context_and_peer_slope;helios/src/offload/transfer/codec.rs:1618partition_restore_pages_continues_gpu_batching_after_literal_and_cpu_pagesand:1694copy_engine_gate_before_codec_mutex_leaves_mutex_unheld_while_waiting_on_peer_graph;helios/src/offload/copy_gate.rs:662try_enter_offload_batch_returns_none_without_blocking_or_burning_wave_tokens;helios/src/server/runtime/phase_tests.rs:9074preemption_coincident_with_grammar_transition_preserves_grammar_mode_and_reasoning_budget(the exact guard thecheck.pymutation at:483-492targets);helios/src/scheduler.rs:3238, 3258, 3271for the three new scheduler operations.
No unrelated standalone tooling is bundled: all 24 files are Helios runtime/scheduler/offload code, its tests, the TLA+/mutation fixtures, and five normative docs. The bundle is large (+2954/−591 across four review surfaces), which is a focus concern for the value lens, not a scope contradiction.
Info / Nits: (a) the description lists
delivery_referencesamong updated functions while theservice.rs(not opened) hunks are inservice_rates/the continuation path — the auditor note thatdelivery_referencesdelegates todelivery_references_and_decode_batchmakes this a wash, not a contradiction. (b) Thedocs/scheduling-runtime-design.mdanchor-budgeting hunk belongs to already-merged #697/#655 and should not read as #729 work. (c)ToggleGrammaris modelled as an identity transition overphase = Live ∧ not-queued(Lifecycle.tla:75-78), weaker than the Rust guard which also excludespending != 0and a terminalSnapshot(scheduler.rs:3244-3251); conformance is one-directional there — a model-fidelity nit, since the Rust-side rejection guards are separately mutation-tested.
Required before this can pass the mandatory gates
- Run the Layer 2 simulator gate for bucket 3 (
docs/design-review.md:195-206, 234-251): model the(fill, kv_context)strata incl.zero_fillinscripts/scheduling_sim/and runlearning.py --preset validate(64 seeds), or run screening+validation against the existing scalar model and report what it establishes. Disclosure is not a waiver. - Add a served-workload measurement for bucket 2 on a core exporting
codec_layout(restore latency / first-token after restore), or drop theperformancejustification for that bucket. - Resolve or gate the MTP-5 30% regression at ≥20K prompt tokens so the default configuration does not silently regress.
No contract or vendored-dependency gate blockers. The single mandatory-verification blocker is the unrun Layer 2 scheduling-simulator / 64-seed validation for the GraphKind::Mixed timing-estimation change.
Code correctness
Deep Code Correctness, Invariants & Hot-Path Performance Audit — PR #729 @ 68fe22f
Scope note (partitioning): the PR is >1,900 changed lines across three distinct subsystems (scheduler/lifecycle/runtime state machine, GPU KV offload, and the cost model), so I partitioned into 3 disjoint slices and audited them concurrently, then re-verified every reported finding myself against the real files at pr/729 (I re-read cost.rs:340-470, copy_gate.rs:165-215, codec.rs:700-740 directly and confirmed each quote below).
Result: 1 Major finding (a real numeric/algorithmic regression in the new GraphKind::Mixed cost model), 2 Minor findings (hot-path allocation regression in the restore path, bounded wave-token barging in CopyEngineGate). No Blocker. Slice A (grammar-transition state machine) is clean.
FINDING 1 — Major: a single decode-only Mixed sample turns the (fill, kv_context) model into a constant predictor, so later full-chunk prefills are priced at decode-only latency and the 4x upward floor is disabled
Diff site 1 — the offending disjunct (helios/src/scheduler/cost.rs:451-456):
let wide_or_full_positive =
pos_u_max == 0.0 || pos_u_max >= 1.0 - 1e-9 || (pos_u_max - pos_u_min) >= 0.15;
let constant_nanos = (best_theta[1] == 0.0
&& best_theta[2] == 0.0
&& wide_or_full_positive)
.then_some(clamp_nanos(best_theta[0]));
Callee/enum resolution that makes this a bug:
helios/src/scheduler/cost.rs:365-374—pos_u_maxis raised only underif u > 0.0:if u > 0.0 { if u < pos_u_min - 1e-12 { pos_u_min = u; } if u > pos_u_max + 1e-12 || ((u - pos_u_max).abs() <= 1e-12 && h < pos_h_at_umax) { pos_u_max = u; pos_t_at_umax = t; pos_h_at_umax = h; } }helios/src/scheduler/cost.rs:321-324— awork == 0(decode-only) Mixed sample is recorded only inzero_fill, withu = 0.0, h = 0.0:if work == 0 { self.zero_fill .observe(PrefillSample { nanos, u: 0.0, h: 0.0 }); } else {work == 0is a legal, routine Mixed step:validate_mixedacceptsprefill_row == None(helios/src/scheduler.rs:455-479), andservice.rs:232-239already prices a decode-only Mixed probe viamixed_duration(batch, width, prefill, 0, 0).helios/src/scheduler/cost.rs:413-414— with no positive-fill sample,pos_u_max == 0.0, sofallback_t = t_at_umin= the zero-fill median (decode latency), andbest_theta = [decode_ns, 0, 0].helios/src/scheduler/cost.rs:183-186—predictshort-circuits on the constant, so the fill/context terms are never evaluated:pub fn predict(&self, work: usize, start_position: u64) -> u64 { if let Some(nanos) = self.constant_nanos { return nanos; }helios/src/scheduler/cost.rs:144-153— the 4x upward floor cannot rescue it, because it requirespos_u_max > 0.0:fn upward_extrapolation_floor(&self, u: f64) -> f64 { if self.pos_u_max > 0.0 && (self.pos_u_max - self.pos_u_min) < 0.15 && u > self.pos_u_max { self.pos_t_at_umax * (u / self.pos_u_max).min(PREFILL_MAX_UPWARD_EXTRAPOLATION)- Downstream,
helios/src/scheduler/policy.rs:1872usesvariable_cost = predictor.is_some_and(|p| !p.is_constant()), so the predictor being constant also disables per-candidate fill/KV-context scoring for that graph, andis_unmeasured_candidate(policy.rs:546-549, viacosts.observation()→nanos != 0) no longer classifies the graph as discovery, so exploration never learns the true prefill cost.
This is a regression vs. pre-PR behaviour, not intended design. Pre-PR, the same decode-only sample produced u = work.clamp(1,cap)/cap = 1/2048, hence u_max - u_min = 0 < 0.15 → narrow → constant_nanos = None, and a later u = 1 query was caught by upward_extrapolation_floor at 4x. The new pos_u_max == 0.0 || disjunct converts "no positive-fill evidence" into "confidently constant".
Concrete counterexample. Mixed graph (batch=4, width=1, prefill=2048); true costs: decode-only 2,000,000 ns, full shallow prefill 95,000,000 ns.
- First submitted step for this catalog entry is decode-only →
observe(nanos=2_000_000, work=0, …, fresh=true)→zero_fill = {2_000_000},strataall empty →fit():n == 1,pos_u_max == 0.0,pos_u_min == INFINITY,fallback_t = t_at_umin = 2_000_000,best_theta = [2e6, 0, 0],wide_or_full_positive == true→constant_nanos = Some(2_000_000). - A prefillable request arrives;
mixed_entryreturns the constant predictor →mixed_duration(4, 1, 2048, work=2048, start=0) = 2_000_000instead of ~95,000,000 (≈47x under-priced), andpredict(2048,0)never sees thetheta[1]*uortheta[2]*hterms.mixed_candidatesalso branches to thevariable_cost == falsepath. - The graph stays mispriced for the whole TTL (30 s of
now_ns - observed_at_ns < ttl_ns), i.e. across many scheduling decisions.
Fix (three parts, all local):
- Drop the vacuous disjunct so "no positive-fill evidence" is never declared constant:
let wide_or_full_positive = pos_u_max >= 1.0 - 1e-9 || (pos_u_max - pos_u_min) >= 0.15; - Add
pub fn has_positive_fill(&self) -> bool { self.pos_u_max > 0.0 }and, inmixed_entry(cost.rs:762-790), returnSome(None)whenprefill > 0and the predictor has no positive-fill evidence, so a Mixed prefill candidate is treated as a discovery candidate instead of being priced at decode latency. - Leave the
work == 0branch ofpredictunchanged — that path is correctly anchored byhas_zero_fill(cost.rs:187-197).
(The two new tests — cost.rs:1762-1898 and policy_tests.rs:9510-9576 — both train a positive-fill sample before asserting anything about fill pricing, which is exactly why neither catches this.)
FINDING 2 — Minor (hot-path allocation): the GpuBatch restore arm still clones every per-page DeviceSpan vector, one allocation per page per restore
Diff site (helios/src/offload/transfer/codec.rs:716-717):
let run_spans: Vec<Vec<DeviceSpan>> =
slice.iter().map(|(_, _, _, sp)| sp.clone()).collect();
let res = guard.decode_pages_batch_to_device(
&self.cpu.gpu_page,
&packets,
&run_spans,
Callee resolution: slice is a sub-range of the pages vector built at codec.rs:685-693, which already owns exactly those Vec<DeviceSpan> values — the clone is pure overhead introduced to satisfy the &[Vec<DeviceSpan>] signature of decode_pages_batch_to_device (helios/src/offload/transfer/gpu_codec.rs:1693-1698). The PR already made the sibling helper generic for exactly this reason: copy_spans_batch takes impl AsRef<[DeviceSpan]> (codec.rs:1062). This partially contradicts the PR's own claim that the partitioning avoids "cloning per-page DeviceSpan vectors".
Concrete case: a 32-page GKV1 restore window with gpu_batch_cap = 8 and 4 planes per page ⇒ 32 extra Vec heap allocations and 128 DeviceSpan copies per foreground prefix-cache restore. restore_window is on the per-restore foreground hot path.
Fix: mirror the copy_spans_batch change — spans_per_page: &[impl AsRef<[DeviceSpan]>] (or &[&[DeviceSpan]]) in decode_pages_batch_to_device, and pass slice.iter().map(|(_,_,_,sp)| sp.as_slice()).collect::<Vec<_>>() (one outer allocation, zero per page). transfer_spans_batch (gpu_codec.rs:1175-1250) already only iterates the inner slice, so the change is local.
FINDING 3 — Minor (bounded fairness): try_enter_offload_batch can spend a wave token that was armed for blocked offload batches
Diff site (helios/src/offload/copy_gate.rs:177-186, :204-210):
fn take_offload_lease(&self, state: &mut State) -> OffloadBatchGuard<'_> {
if state.turn == Turn::Offload && state.offload_wave_remaining > 0 {
state.offload_wave_remaining -= 1;
if state.offload_wave_remaining == 0 {
state.turn = Turn::Peer;
}
}
state.offload_batches_active += 1;
OffloadBatchGuard { gate: self }
}
pub fn try_enter_offload_batch(&self) -> Option<OffloadBatchGuard<'_>> {
let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
if Self::offload_must_wait(&state) {
return None;
}
Some(self.take_offload_lease(&mut state))
}
Invariant resolution: maybe_arm_offload_wave (copy_gate.rs:54-68) sizes the wave as offload_wave_remaining = offload_batches_waiting, i.e. one token per thread already parked in Condvar::wait. Because offload_must_wait (:171-175) returns false for turn == Offload && offload_wave_remaining > 0, an unrelated foreground restore can satisfy the guard and consume a token reserved for a parked batch.
Concrete counterexample: 4 offload batches are blocked (offload_batches_waiting = 4, peer streak at MAX_PEER_STREAK_WHILE_OFFLOAD_WAITING = 4, :34) ⇒ maybe_arm_offload_wave sets turn = Offload, wave_remaining = 4. Four foreground GPU restores call try_enter_offload_batch() back-to-back ⇒ wave_remaining reaches 0 and turn flips to Peer before any woken batch re-evaluates; the woken threads see turn == Peer and wait again.
Severity is Minor because starvation is bounded, not unbounded: the re-arm is unconditional — every peer-graph entry increments peer_entries_while_offload_waiting while offload_batches_waiting > 0 (:159-164) and PeerGraphGuard::drop retries maybe_arm_offload_wave (:225), so at most 4 peer admissions can be inserted between waves. I found no invariant break in should_yield_to_offload (:94-100), which keys off offload_batches_waiting/peer_entries_while_offload_waiting — counters the try path correctly leaves untouched.
Fix: don't spend waiter-reserved tokens from the try path —
if Self::offload_must_wait(&state)
|| (state.turn == Turn::Offload && state.offload_batches_waiting > 0) {
return None;
}
which keeps the foreground fast path whenever nobody is queued.
Slice A (grammar transitions) — audited clean, with the proofs that mattered
No defect found in scheduler.rs {set_grammar_constrained, pause_for_park, finish_for_park, pause/eligible/refill_reservations gating}, model/admission.rs AdmissionGrammar, model/packing.rs, server/runtime.rs {complete, publish, park_*, decide_grammar_transition}, or the Lifecycle.tla/check.py additions. The non-obvious claims I verified rather than assumed:
set_grammar_constrainedcannot fail on aToggleInPlacepath. Its rejection predicate (scheduler.rs:3238-3253:pending != 0 || phase ∈ {Inbound, Finishing} || (Snapshot && boundary_capture.is_none())) is dominated by thedecide_grammar_transitiongate (runtime.rs:529-538:skipped == 0 && pending == 0 && extra == 0 && error_code.is_none() && can_toggle_in_place && !phase ∈ {Inbound,Finishing} && !(Snapshot && terminal_snapshot.is_some())).?on the scheduler call precedes the request/admission mutation (runtime.rs:2390-2399), so the two sides cannot diverge on a partial failure.pending_grammar_parkcannot leak / wedge a slot. Written atruntime.rs:2534(and kept at:2517), cleared at:2514(drained-frame error),:2519-2524(rollback),:2566(publishtake), plusclear_active_sloton failure (:2574). I enumerated all fivepublishexits for a slot holding a park (finish+last_use <= completed, finish+fence pending, still paused,Snapshotterminal-capture arm, drained error) and each either finalizes or re-parks; thecontinueat:2588cannot strand a terminal slot because the grammar branch always ends inpark_with_tokens(which pushes toself.parked) orfail+finish+clear_active_slot.ToggleInPlacecannot run with a frame in flight:pendingis decremented insidecomplete_with_survival(scheduler.rs:~2875) before the token loop readslive.pending()atruntime.rs:2376.consumed_tokens > exact_lenis handled on everyCheckpointParkbranch::2516requires<=for keep-park; otherwise:2518-2525truncates viapark_grammar_transition→live.tokens()[..exact_len](:2828), covered byphase_tests.rs:9050-9070(consumed 6 > exact 5).paused_for_parkgenuinely blocks further frames on all three gates:policy.rs:334-341(eligible),scheduler.rs:1430-1440(has_starved_request),scheduler.rs:1448-1459(refill_reservations, so it is neither grown nor chosen aspreempt_newestvictim).AdmissionGrammarsemantics are consistent in packing:UnmaskedEnabled→GrammarEnabled = 1(packing.rs:802) and all-ones mask (packing.rs:797-801,0xffon the int32 fast path at:603-637), withunconstrained_masks.retain(...)(:616-618) correctly invalidating the cached all-ones row when aMaskedupload follows — verified againstmodel/tests.rs:1886-1968.- Hot path: the only per-transition heap cost added is the mask clone
grammar.mask().to_vec()(~vocab/32i32) atruntime.rs:2382-2389, once per</think>/re-entry rather than per step; the new drain scan is O(REQUEST_LANES= 4) with an earlycontinue. No per-step O(N) or O(vocab) regression.
One non-defect robustness note (not counted as a finding): Admission::grammar_updated's .expect("grammar admission has a mask") (admission.rs:147-152) is safe only because Disabled/UnmaskedEnabled never co-occur with grammar_reasoning_mode == Some(false) — a cross-file invariant now load-bearing across admission.rs, packing.rs and runtime.rs, unenforced by types. A debug_assert! there would make it non-fragile.
Slice B (offload, apart from Findings 2–3) — audited clean
try_enter_offload_batchreturnsNoneunder exactly the blocking conditions:offload_must_wait(copy_gate.rs:171-175) is a verbatim lift of the old inline closure, andenter_offload_batch(:190-200) was refactored to call the same two helpers, so its behaviour is unchanged.- Skipping
offload_batches_waiting += 1on the try path is correct: every reader of that counter (should_yield_to_offload:97,maybe_arm_offload_wave:58,:62,PeerGraphGuard::drop:225,enter_peer_graph_timeout:160-164) only adds obligations for waiters; a caller that never waited must not arm a wave or notify. - Lock order is acyclic: only two functions take both locks —
with_gpu_codec_locked(codec.rs:881-889, gate-blocking → codec-blocking) andtry_with_gpu_codec_locked(:895-906, codec-try_lock→ gate-try_enter, neither blocking). The old capture path's codec-then-blocking-gate sites are gone, so no cycle exists. - No silent KV drop on failure: a GPU batch decode error propagates via
.transpose()?(codec.rs:729) and aborts the window; per-page CRC verification happens before the scatter (gpu_codec.rs:1729-1732,:1971-1981, scatter at:1984). Atry_locksuccess followed by gate contention drops theMutexGuardvia?(codec.rs:902) and falls back to CPU decode with the route rewritten toGpuOnCpu(codec.rs:624-628,:730-758) — no lease leak, no stream desync. - Boundary cases walked correct: 0/1-page windows, all-CPU, all-
GKV1, alternatingLiteral/GKV1(the regression this PR fixes), trailing singleGKV1, matrix pages (correctly forced toSinglebecausegpu_batch_capcollapses to 1 whennum_mats() != 0,codec.rs:677-683, since the batch kernel rejects mats atgpu_codec.rs:1707), codectry_lockcontended, gate contended by an active peer graph.
Coverage summary
- Slice A:
decide_grammar_transition,Worker::{complete, publish, park, park_if_preempted, park_grammar_transition, park_with_tokens, admit},RequestScheduler::{set_grammar_constrained, pause_for_park, finish_for_park, finish_early, retire, finish, cancel, eligible, refill_reservations, preempt_newest},AdmissionGrammar/Admission::*,packing.rsgrammar binding paths,Lifecycle.tla,check.py(all 6 new mutation strings diffed char-by-char against head sources), and the new tests. ✔ - Slice B: all of
copy_gate.rs;codec.rsRankCodec::new/run/capture_window/decode_route/decode_pages_cpu_batch/restore_single_unit/restore_window/partition_restore_pages_by/with_gpu_codec_locked/try_with_gpu_codec_locked/copy_spans_batch; cross-checkedtransfer.rsGatedCopies/RankWorker. ✔ - Slice C:
PrefillPredictor::{predict, upward_extrapolation_floor, is_constant, has_deep_context, with_borrowed_context_slope},clamp_nanos,PrefillCostModel::{observe, fit, reset_with_full},ActionCosts::{get, observe/record, prefill_entry, mixed_entry, mixed_duration, borrowed_mixed_context_slope, refresh_prefill_context_slopes},mixed_candidates/continuation_candidate/resize_prefillscoring, and both new tests. ✔
Caveats: no code was executed (read-only audit); the 9 HF chat-template and 39 checkpoint-gated tests the PR marks unrun were not assessed; the Python simulator does not model (fill, kv_context) curves so Finding 1's numeric impact is hand-computed from the code, not observed — but the defect requires only one decode-only Mixed sample, and service.rs:232-239 already issues exactly such a probe.
Full report Merge Risk: medium_high (100%): Medium or high merge risk (core runtime/scheduler/GPU/CUDA/VMM/RoCE/multi-rank/contracts/ABI, large multi-crate changes, or Blocker/Major findings) — route to Super Agent.
Re-review
Recommendation: Changes Requested
All five Round-1 blockers from 150f705 have been cleanly resolved at 68fe22f—Worker::publish() now applies pending_grammar_park before park_if_preempted, try_with_gpu_codec_locked uses non-blocking CopyEngineGate::try_enter_offload_batch, upward_extrapolation_floor and predict(0, 0) separate positive-fill bounds from zero_fill, Lifecycle.tla and check.py --mutations now cover all new park/toggle transitions and guards, and live SM120 flare run A/B benchmarks substantiate Bucket 1 and legacy-core compatibility. However, direct source verification at 68fe22f caught one new numeric/logic bug introduced in the PrefillCostModel::fit rework (pos_u_max == 0.0 in wide_or_full_positive at helios/src/scheduler/cost.rs:451-456), which causes a zero_fill-only GraphKind::Mixed model to emit constant_nanos = Some(decode_ns), under-pricing full-chunk prefills by ~47× and inflating service_rates across competing requests until a positive-fill step runs. Fix that defect (plus the remaining minor run_spans clone and wave-token barging items below) and this will be ready to merge.
Merge Risk
Level: Medium
GraphKind::Mixedzero-fill-only constant-predictor defect: Observing a single decode-only (work == 0)Mixedstep after startup or TTL expiry marks the graphconstant_nanos = Some(decode_ns), pricingwork > 0prefills at1×decode latency inmixed_candidates,next_progress,continuation_candidate, andservice_rates(where inflatedtoken_ratedistorts utility normalization across all competing requests).- Default MTP-5 latency trade-off & lock-order reversal: The disclosed live SM120 A/B shows a +32% median
</think>→content delta under default MTP 5 at 20,648 prompt tokens (40.9 → 54.1 ms) whenpause_for_drainwaits for a second speculative frame that overshoots and rolls back; separately, the capture path reverses#628'sgpu.codec→CopyEngineGateorder (deadlock-free with the non-blocking try path, pending@yatesdrsign-off). - Large four-surface diff &
#715conflict: 24 files (+2,954/−591) spanning runtime lifecycle, KV offload codec/gate, Mixed cost modeling, and TLA+/mutation verification, with direct textual and documentation overlap incost.rsanddocs/scheduling-runtime-design.mdagainst open#715.
Walkthrough
- Grammar-transition KV preservation & lifecycle verification (
helios/src/model/{mod,admission,packing}.rs,helios/src/scheduler.rs(not opened),helios/src/scheduler/policy.rs,helios/src/server/runtime.rs,verification/helios-lifecycle/{Lifecycle.tla,README.md (not opened),check.py},phase_tests.rs): Replaces(grammar_mask, grammar_enabled)withAdmissionGrammar::{Disabled, UnmaskedEnabled, Masked(Vec<i32>)}(admission.rs:61-90,packing.rs:803(not opened)); cachescan_toggle_grammar_in_placeonWorker(runtime.rs:1409-1410); routes transitions throughdecide_grammar_transition(runtime.rs:523-545) with scheduler-firstset_grammar_constrained(runtime.rs:2390-2399, 2455-2465); orderspending_grammar_parkahead ofpark_if_preemptedinWorker::publish()(runtime.rs:2561-2594, 2790-2792); and modelsPaused/PauseForPark/FinishForPark/ToggleGrammarinLifecycle.tla:11, 60-78with 6 new mutation guards incheck.py:458-508. - KV offload restore partitioning & non-blocking
CopyEngineGate(helios/src/offload/{copy_gate.rs,transfer/codec.rs}): AddsCopyEngineGate::try_enter_offload_batchsharingoffload_must_wait/take_offload_lease(copy_gate.rs:171-210), routes capture through blocking gate-then-codec (codec.rs:881-889) and foreground restores through non-blockingcodec.try_lock()thengate.try_enter_offload_batch()(codec.rs:895-906), and partitions restore windows viapartition_restore_pages_by(codec.rs:697-702, 840-877) without allocating a duplicateroutesVec. - Stratified
GraphKind::Mixedcost model (helios/src/scheduler/{cost,policy,service}.rs): Trackspos_u_min/pos_u_max/pos_t_at_umaxover positive-fill strata (cost.rs:144-153, 351-375), anchorspredict(0, 0)onhas_zero_fill(cost.rs:187-196), sharesclamp_nanos(cost.rs:79-87), namesMixedContextSlope(cost.rs:601-608), and updatesdocs/{api,core-design,mtp-design,prefix-cache-offload,scheduling-runtime-design}.md.
Pre-merge Checks
- [PASS] Security / malicious screen: Pure host-side scheduling, runtime lifecycle, and codec synchronization; no new dependencies, ABI/Protobuf/kernel changes, or prompt-injection attempts.
- [WARN] Charter & value fit: Model-agnostic Helios placement with live SM120 A/B and legacy-core verification for Bucket 1 (
3.32×–4.53×faster under--mtp-draft-tokens 0), but bundles four subsystems, discloses an ungated +32% MTP-5 regression at 20.6K tokens, and lacks whole-model A/B for Buckets 2–3. - [WARN] Related / duplicate / conflict check: Genuinely additive over
#525/#626/#628/#645and cites#530, but reverses#628's capture-path lock order (needs@yatesdrack) and conflicts with open#715incost.rsanddocs/scheduling-runtime-design.md. - [PASS] Tests & verification evidence: All reported Rust crate suites, 4 live SM120 GPU codec tests, 1,115 pytest tests, 10/10 TLA+ models (623,904 observed transitions), and 56/56
--mutationspass; remaining gap is the Layer-2scripts/scheduling_simrun noted under Should Fix.
Blockers
PrefillCostModel::fitmarks azero_fill-onlyGraphKind::Mixedmodel as a constant predictor (pos_u_max == 0.0inwide_or_full_positive), pricing full-chunk prefills at1×decode-only latency and inflatingservice_rates(helios/src/scheduler/cost.rs:451-456, 144-153, 183-206, 322-343, 762-803;helios/src/scheduler/policy.rs:546-549, 948, 1752-1898;helios/src/scheduler/service.rs:353-379)- Verified defect: When a
GraphKind::Mixedentry observes a decode-only step (work == 0, routinely emitted bymixed_candidatesatpolicy.rs:1821-1839) before any positive-fill step—either at startup or after a 30 s TTL expiry—PrefillCostModel::observe(cost.rs:322-324) populates onlyself.zero_fill(u = 0.0, h = 0.0), leavingpos_u_max == 0.0(cost.rs:365-374). Infit()(cost.rs:451-456):
Thelet wide_or_full_positive = pos_u_max == 0.0 || pos_u_max >= 1.0 - 1e-9 || (pos_u_max - pos_u_min) >= 0.15; let constant_nanos = (best_theta[1] == 0.0 && best_theta[2] == 0.0 && wide_or_full_positive) .then_some(clamp_nanos(best_theta[0]));pos_u_max == 0.0disjunct treats "zero positive-fill evidence" as "wide or full positive-fill coverage," emittingconstant_nanos = Some(decode_ns)and storingdecode_nsinestimate.nanos(cost.rs:342, 1118). - Concrete counterexample & downstream impact: On
Mixed(4, 1, 2048)with 2 ms decode-only latency and ~95 ms true full-chunk prefill, observing one decode-only step setsconstant_nanos = Some(2_000_000)andestimate.nanos = 2_000_000. Until a positive-fill step executes on that shape:predict(2048, 0)short-circuits onconstant_nanos(cost.rs:184-186)—and note that simply removingpos_u_max == 0.0 ||is not sufficient on its own becauseupward_extrapolation_floor(cost.rs:145) also requiresself.pos_u_max > 0.0, sopredict(2048, 0)would still returntheta[0] = 2_000_000(~47× under-priced).mixed_candidates(policy.rs:1756, 1872-1898) seesvariable_cost = false, prices every prompt candidate atdecode_ns, andis_unmeasured_candidate(policy.rs:546-549) returnsfalsebecauseestimate.nanos != 0, letting the mispriced candidate compete asPlanOrigin::Ordinary.service_rates(service.rs:354-379) computestoken_rate = 2048 * 1e6 / 2e6 = 1,024 tok/ms(~47× inflated), distorting service-rate normalization across all competing prefill requests even when thatMixedgraph is not selected.- Both new tests (
cost.rs:1764-1900,policy_tests.rs:9510-9576(not opened)) observe a positive-fill sample before querying positive-fill predictions and therefore miss this state.
- Fix:
- Drop
pos_u_max == 0.0 ||fromwide_or_full_positive(cost.rs:451-452) so a zero-fill-only model is never markedconstant_nanos = Some(...). - Expose
pub fn has_positive_fill(&self) -> bool { self.pos_u_max > 0.0 }onPrefillPredictor. Keeppredict(0, 0)returning the valid measured decode-only cost (do not collapsemixed_entrytoSome(None)globally), while on positive-fill queries (work > 0) when!predictor.has_positive_fill(), return0inmixed_candidates/next_progress/continuation_candidate(sois_unmeasured_candidateatpolicy.rs:547properly treats positive-fill on that shape as discovery viaduration_ns == 0) and skip it inservice_ratesprefill normalization (service.rs:373). - Add a unit test in
cost.rsobserving onlymixed_step(4, 1, 2048, None)(at init and post-TTL) and assertingpredict(0, 0) == decode_ns,!predictor.is_constant(),!predictor.has_positive_fill(), and that positive-fill queries do not price full-chunk prefill at decode-only latency.
- Drop
- Verified defect: When a
Should Fix
-
Eliminate the remaining per-page
Vec<DeviceSpan>clone inrestore_window'sGpuBatcharm (helios/src/offload/transfer/codec.rs:716-724;helios/src/offload/transfer/gpu_codec.rs:1693-1700)pages(codec.rs:685-693) already owns each page'sVec<DeviceSpan>, yetcodec.rs:716-717still allocates and clones every per-page vector (let run_spans: Vec<Vec<DeviceSpan>> = slice.iter().map(|(_, _, _, sp)| sp.clone()).collect();) solely becausedecode_pages_batch_to_devicetakes&[Vec<DeviceSpan>]—partially contradicting the PR description's claim that partitioning avoids cloning per-pageDeviceSpanvectors.- Fix: Mirror
copy_spans_batch(codec.rs:1062) by changingspans_per_pageindecode_pages_batch_to_device(gpu_codec.rs:1697) to&[impl AsRef<[DeviceSpan]>](or&[&[DeviceSpan]]) and passing borrowed slicesslice.iter().map(|(_, _, _, sp)| sp.as_slice()).collect::<Vec<_>>().
-
Prevent
CopyEngineGate::try_enter_offload_batchfrom consuming wave tokens armed for blocked offload waiters (helios/src/offload/copy_gate.rs:55-68, 171-210;docs/prefix-cache-offload.md:102-106)maybe_arm_offload_wave(copy_gate.rs:61-62) sizesoffload_wave_remaining = offload_batches_waitingspecifically for threads parked inenter_offload_batch. Becauseoffload_must_wait(:171-175) allows entry whenturn == Turn::Offload && offload_wave_remaining > 0,try_enter_offload_batch(:204-210) callstake_offload_leaseand decrementsoffload_wave_remaining, potentially flippingturn = Turn::Peerbefore woken waiters run and contradictingdocs/prefix-cache-offload.md:104-105("without blocking or consuming a gate wave token").- Fix: Return
Noneintry_enter_offload_batchwhenSelf::offload_must_wait(&state) || (state.turn == Turn::Offload && state.offload_batches_waiting > 0)so non-waiting foreground tries fall back to CPU during a waiter-reserved offload wave without stealing waiter tokens.
-
Address the disclosed default-MTP-5 latency delta, Layer-2 simulator check, and
@yatesdrlock-order ack (helios/src/server/runtime.rs:538-541;helios/src/offload/transfer/codec.rs:879-889;docs/design-review.md:109-115, 195-206)- Under default MTP 5 at 20,648 prompt tokens on the tested
Qwen4-35B-A3Bcore,pause_for_drainregresses median</think>→content latency by +32% (40.9 → 54.1 ms) because waiting for Frame 2 before rolling back on</think>\n\n{overshoot delays slot readmission compared tomain's immediatecancel(). Confirm whether this trade-off is acceptable for default MTP-5 deployments on cores lackingValueSource::GrammarEnabledor gatepause_for_drainwhen speculative overshoot is expected. - Obtain
@yatesdr's sign-off on reversing#628's capture-path lock order (codec.rs:879-889), and runscripts/scheduling_sim/learning.py --preset validate(matching#645's precedent;scripts/scheduling_sim/learning_scenarios.py:63(not opened) already includes mixed scenarios) or split Bucket 3 if whole-modelMixedvalidation is deferred.
- Under default MTP 5 at 20,648 prompt tokens on the tested
Subtract / Simplify
- Pass
AdmissionGrammardirectly toAdmission::from_continuation(helios/src/model/admission.rs:160-193;helios/src/server/runtime.rs:1731-1737): Replaces the two independentgrammar_mask_active/grammar_enabledbooleans, the 3-arm match,#[allow(clippy::too_many_arguments)], and the duplicate-bool pass-through infrom_prompt. - Construct
GrammarParkonce per transition match (helios/src/server/runtime.rs:2401-2427, 2467-2493): Buildinglet park = GrammarPark { ... };before eachmatch decide_grammar_transition(...)deletes ~26 lines of duplicated struct literals acrossCheckpointParkandRollback. - Fold non-row CPU/singleton restore into
CpuBatch(helios/src/offload/transfer/codec.rs:548-583, 630-655):decode_pages_cpu_batchalready special-casesitems.len() == 1; routing non-row CPU/singleton pages through it removes the duplicated CPU tail ofrestore_single_unitand one of the two pure-Literaltransform_nschecks. - Unify
prefill_context_slopes/mixed_context_slopesand deduplicate sampling-graph matching (helios/src/scheduler/cost.rs:601-621, 892-958;helios/src/server/runtime.rs:552-561): Sharing one context-slope helper trimscost.rsand shrinks the conflict surface with#715; sharing aGraphOperation::samples()helper avoids a fourth manual enumeration of the seven sampling graph operations.
Nits
- State the capture-path lock-ordering invariant (
CopyEngineGatebeforegpu.codec, with non-blocking try-both on foreground restores) explicitly indocs/prefix-cache-offload.md:96-107. - Cache
speculativealongsidecan_toggle_grammar_in_placeonWorkerinstead of recomputing!self.config.speculative_widths.is_empty()atruntime.rs:1409, 1729, 2140. - Coordinate merge order / rebase on
cost.rsanddocs/scheduling-runtime-design.mdwith open#715.
Dropped on verification
- Round-1 Blockers 1–4 and Round-1 Should Fix 1–3 (all resolved at
68fe22f): Verified fixed inruntime.rs:2561-2594, 2790-2792(publish/preemption order),codec.rs:895-906+copy_gate.rs:204-210(non-blockingtry_enter_offload_batch),cost.rs:144-153, 187-196(pos_u_min/pos_u_maxfloor andhas_zero_fillguard),Lifecycle.tla+check.py:458-508(TLA+ & 6 new mutations),runtime.rs:1409-1410, 2390-2399, 2455-2465(cachedcan_toggle_grammar_in_place+ scheduler-first toggle), and all 5 docs. - Upstream Gates Audit escalating
scripts/scheduling_simto a Round-2 Blocker: Kept in Should Fix 3 rather than Blocker to avoid moving goalposts—Round 1 placed this in Should Fix 3, andscripts/scheduling_sim/uses scalar per-graph costs without(fill, kv_context)NNLS strata (same as merged#645). - Upstream Code Audit inaccuracies on Blocker 1: Dropped the false claim that pre-PR
mainproducedu = 1/2048on decode-onlyMixedsteps (maincost.rs:606did not attachPrefillCostModeltoMixed), dropped the unsafe suggestion to havemixed_entryreturnSome(None)globally when!has_positive_fill()(which would discard validpredict(0, 0)decode-only costs), and scoped the persistence claim accurately (self-corrects once a positive-fill step executes on that shape, while distortingservice_ratesandPlanOrigin::Ordinarybefore then). - Upstream Subtraction S2 (
grammar_updated"live panic" and replacingcopy_from_slicewithmask.to_vec()): Dropped—verified atruntime.rs:1731-1737, 2160, 2247-2264, 2392-2399, 2454-2465that!speculative_grammarwithprompt.grammar.is_some()guaranteesAdmissionGrammar::Masked, and replacingcopy_from_slicewithAdmissionGrammar::Masked(mask.to_vec())would introduce a per-decode-token heap allocation on the hot path. - Upstream Subtraction S4 (merging
mixed_candidatesloops atpolicy.rs:1844-1898), S5 (mixed_entryOption<Option<_>>), and S8 (copy_spans_batchgeneric<S: AsRef<[DeviceSpan]>>): Dropped—S4's constant-costelsearm deliberately hoistsscore_decodersout of theprefill_slotsloop; S5 intentionally mirrorsprefill_entry(cost.rs:728-756); and S8's generic is required because capture (codec.rs:395, 466) passes ownedVec<DeviceSpan>while restore (codec.rs:575, 646) passes&[DeviceSpan]. - Unobservable CI status and stale-base diff hunks: Excluded per review standards.
Classify triage
Selected: triage:review
Threshold: 65%
Triage
- [✓]
triage:review: 99.8% -
triage:design-review: 0.1% -
triage:validation: 0.0% -
none: 0.0% -
triage:investigate: 0.0% -
triage:partial: 0.0% -
triage:integration: 0.0% -
triage:verify-for-closure: 0.0% -
triage:superseded: 0.0% Decision to Test: no (99%): Testing will not add significant value as the code stands today. The code is either not yet ready to merge, or adequate testing has already been done to validate the contents of the code, or the available hardware is not suitable to test with.
Apply labels
No label changes