PR #729: helios: preserve KV across grammar transitions, fix KV codec batching/locking, and stratify Mixed graph costs

Raw Markdown for agents: https://autobot.eidonix.com/api/v1/cases/139ca301-0d03-4767-8eea-037621985791

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:

Full report · Notes

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

Priority

Type

Area

Model

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:

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-100 still 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:

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


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:

  1. 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-246 is explicit that the existing run does not satisfy this.
  2. Model the (fill, kv_context) NNLS strata including the zero_fill bucket and mixed_context_slopes in scripts/scheduling_sim/, update their comments, and run the screening plus 64-seed catalog in learning.py (docs/design-review.md:195-206).
  3. Run verification/helios-lifecycle/check.py (not opened) --mutations against the new park and grammar-toggle guards (docs/design-review.md:226-228); disclosure does not excuse it (:247-251).
  4. Add a served-workload A/B against main using an exported core through flare run for the grammar-transition bucket, and a measurement for the older-speculative-core Snapshot+Restore cost; cite a source for the "2K-32K" figure (docs/design-review.md:109-115, charter #210).
  5. Load and serve a previously exported core to substantiate the compatibility claim, particularly the non-speculative GrammarEnabled 0→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.

Full report · Notes

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:

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)


E. Ranked ask

  1. C1 — merge the three mixed scoring loops (~80–100 lines).
  2. A1/A2/A3 — one can_toggle_live helper, one shared toggle/park/rollback helper, one park struct (~60–80 lines, and removes the already-diverged predicate).
  3. A5 + A4 — delete waiting_for_drain/remaining/exact_len mirrors; read scheduler state.
  4. A7 — replace grammar_enabled + grammar_mask with one three-state enum.
  5. B1 + B2 + B3 — delete the duplicate routes vec, one transform_ns rule, one GPU-else-CPU restore helper (~40 lines).
  6. 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.

Full report

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):

2-point exact fit: theta_0 = 15 ms, theta_1 = 16 ms, u_min = 0, u_max = 0.0625 (spread 0.0625 < 0.15).

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


Explicitly checked and found CORRECT (no defect)

Not verified / limits

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

Walkthrough

Pre-merge Checks

Blockers

  1. Preemption in complete_inner clobbers PendingGrammarPark in Worker::publish(), corrupting grammar mode and losing thinking_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 with skipped == 0 and pending == 0, RequestScheduler::complete_inner runs self.refill_reservations()? (scheduler.rs:3121) before returning generated to Worker::complete. Under page pressure, preempt_newest() (scheduler.rs:1523-1542) can pick that request (pending == 0 && !paused_for_park && phase == Decode) and call finish_early(handle, /*preempted=*/ true), setting preempted = true and phase = RequestPhase::Snapshot (with terminal_snapshot = Some(_)) or RequestPhase::Finishing.
    • Worker::complete then clears request.incoming.prompt.reasoning_cut = None (runtime.rs:2350), evaluates can_toggle_live == false (because of Finishing / terminal_snapshot), enters checkpoint_parks, calls finish_for_park(handle)? (scheduler.rs:3285, 3292 returns Ok(()) without clearing preempted), and stores PendingGrammarPark { 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 the pending_grammar_park handler at :2589-2614. Because live.preempted() is true, park_if_preempted (runtime.rs:2801-2834) parks with grammar_reasoning_mode: None, drop_reasoning: false, and remaining = max_new_tokens - live.generated_tokens, discarding PendingGrammarPark. 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 loses cut.after from thinking_token_budget.
    • Fix: In Worker::publish() (runtime.rs:2580-2614), check and handle pending_grammar_park.take_if(|park| !park.waiting_for_drain) (when live.phase == RequestPhase::Finishing && live.last_use() <= self.scheduler.completed()) before self.park_if_preempted(slot)? (or gate park_if_preempted on active.pending_grammar_park.is_none()), and add a phase test exercising preemption during the same complete_inner step as a grammar transition (with reasoning_cut.after > 0).
  2. try_with_gpu_codec_locked blocks on CopyEngineGate::enter_offload_batch before try_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) calls CopyEngineGate::enter_offload_batch—an unbounded blocking condvar wait (copy_gate.rs:175-194)—before calling codec.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 :896 for the full capture + peer-graph drain instead of returning None and 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) drops peer_guard before calling try_with_gpu_codec_locked, so it misses this case.
    • In addition, during Turn::Offload, a contended try_with_gpu_codec_locked decrements offload_wave_remaining on entry (copy_gate.rs:187-191), fails try_lock(), drops _ce, and then the CPU fallback calls copy_spans_batch → GatedCopies::batch → enter_offload_batch() (transfer.rs:336) a second time, consuming two wave tokens for one run (or flipping Turn::Peer and blocking again).
    • Fix (deadlock-free): Do not simply swap try_lock() ahead of blocking enter_offload_batch()—that would introduce a 3-way deadlock against with_gpu_codec_locked (capture holds OffloadBatchGuard waiting on gpu.codec; restore holds gpu.codec waiting in enter_offload_batch on peer_graphs_waiting; peer_graph sets peer_graphs_waiting = 1 waiting on capture's OffloadBatchGuard up to the 120 s PEER_GRAPH_GATE_TIMEOUT). Instead, add a non-blocking CopyEngineGate::try_enter_offload_batch(&self) -> Option<OffloadBatchGuard<'_>> that returns None immediately when must_wait(&state) is true (and avoids consuming an offload_wave_remaining token if the caller bails on try_lock), use it in try_with_gpu_codec_locked before codec.try_lock(), and add a test proving try_with_gpu_codec_locked returns None immediately while a PeerGraphGuard is held.
  3. zero_fill (u = 0.0) sets u_min = 0.0, permanently disabling upward_extrapolation_floor for GraphKind::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) requires self.u_min > 0.0 && (self.u_max - self.u_min) < 0.15. However, PrefillCostModel::fit (cost.rs:368-373, 354-361) routes self.zero_fill.median() (u == 0.0) through record_point, setting u_min = 0.0. Once any single decode-only Mixed step is observed, self.u_min stays 0.0 until TTL reset and upward_extrapolation_floor is permanently disabled—contradicting docs/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-only 15 ms (u = 0) and partial fill work = 128 (u = 0.0625, 16 ms), NNLS fits theta_0 = 15 ms, theta_1 = 16 ms; predict(2048, 0) returns 31 ms instead of the 4× floor 64 ms (2.06× under-prediction of full-chunk cost). The new test at cost.rs:1854-1858 only checks the post-TTL path without a zero_fill sample.
    • Fix: Track positive-fill bounds (pos_u_min, pos_u_max, pos_t_at_umax) over self.strata only (cost.rs:374-385) and use them for upward_extrapolation_floor (and the narrow-regime check in constant_nanos at :441-444), while keeping zero_fill in pts for NNLS fitting and t_at_umin. Add a regression test asserting the 4× floor still fires after observing both zero_fill and a narrow partial-fill sample.
  4. 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 from eligible, starvation detection, reservation refill, and preemption) and three guarded scheduler transitions (set_grammar_constrained, pause_for_park, finish_for_park, plus BoundaryKind::ConditionedWindow rejection and consumed_tokens <= exact_len drain checks). verification/ has zero references to any of these states/transitions, and the PR explicitly lists verification/helios-lifecycle/check.py --mutations as unrun.
    • docs/design-review.md:226-251 is 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 (or cargo-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 cover paused_for_park / pause_for_park / finish_for_park / set_grammar_constrained (including interaction with preemption/terminal snapshots), and run verification/helios-lifecycle/check.py --mutations cleanly.
  5. 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, Mixed pricing), yet the PR explicitly reports "not benchmarked end-to-end here" and "No end-to-end exported-core flare run latency or throughput benchmark was run on this branch." Moreover, non-speculative models now pack GrammarEnabled = 1 during open reasoning and disable two-frame pipelining during reasoning, and existing speculative cores without per-step GrammarEnabled bindings now run Snapshot + Restore per transition—making live loading/serving on previously exported cores (docs/design-review.md:116-123) and flare run A/B measurements against main (docs/design-review.md:109-115, Charter #210) essential rather than optional.
    • Fix: Run and report a flare run A/B benchmark over main on an exported core exercising structured-output reasoning transitions (covering both in-place and Snapshot+Restore paths on an existing core to substantiate both performance and Principle 13 compatibility).

Should Fix

  1. Discontinuous predict(0, 0) cliff down to 1 ns / microseconds when u_min > 0 and NNLS produces a tiny positive theta[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_fill sample has been observed (u_min > 0), predict(0, 0) checks if 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) (or 79_999_999 ns)—exact NNLS solves theta[0] = 333.33 ns (or 0.33 ns, clamped to 1 ns) with SSE 0.0. Because theta[0] > 0.0, predict(0, 0) skips t_at_umin and returns 333 ns (or 1 ns), inflating ValueRate::new (utility.rs:155-165) by 60,000×–20,000,000× while is_unmeasured_candidate (policy.rs:546-549) remains false.
    • Fix: When no zero_fill sample has been observed (has_zero_fill == false), either return t_at_umin for work == 0 directly or clamp theta[0] against a lower bound derived from t_at_umin rather than letting theta[0] > 0.0 collapse toward 1 ns.
  2. Cache sampling_graphs_bind_grammar_enabled on Worker and 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 every Worker::complete call even though self.config is immutable; compute and cache can_toggle_grammar_in_place: bool once in Worker::new.
    • In both in-place toggle arms (runtime.rs:2372-2380 and :2442-2448), incoming.grammar_reasoning_mode, request.reasoning, and admissions[slot] are mutated before self.scheduler.set_grammar_constrained(...)?. Call self.scheduler.set_grammar_constrained(...)? first so an unexpected error cannot leave host and scheduler grammar state diverged.
  3. 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-100 still describes GPU-codec CPU fallback without the new CopyEngineGate ordering, and docs/core-design.md (not opened) / docs/mtp-design.md (not opened) still describe #626's unconditional cancel transition; 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.rs timing estimation), run scripts/scheduling_sim/learning.py --preset validate (matching #645's precedent under docs/design-review.md:195-206) or model Mixed strata in scripts/scheduling_sim/.

Subtract / Simplify

Nits

Dropped on verification

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

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:

Full report · Notes

Classify intake

Selected: triage:review, bug, performance, area:scheduling

Threshold: 65%

Triage

Priority

Type

Area

Model

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(...)):

            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:

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


Suggested order

  1. S1 + S2 (one coherent edit to model/admission.rs, removes a public bool, a panic, and two accessors).
  2. S3 (delete 26 lines of duplicated struct literal in runtime.rs).
  3. S4 + S5 (one edit to the Mixed cost surface: enum replaces Option<Option<_>>, then the two mixed_candidates branches collapse).
  4. S7 + S8 (codec single-unit/CPU-batch consolidation) — do this before the #715 rebase, since it touches the same cost.rs/codec.rs regions.
  5. 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).

Full report

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

Info / Nit (not a gate): #628's invariant was "preserve strict lock ordering (gpu.codec before CopyEngineGate)" (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 at codec.rs:879-880, 891-894 and behaviourally in docs/prefix-cache-offload.md:96-106; no docs/ sentence names "gate before codec" as an invariant (grep 'lock order' docs/ → no hits). Worth an @yatesdr ack, 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)

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:

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.

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:

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_references among updated functions while the service.rs (not opened) hunks are in service_rates/the continuation path — the auditor note that delivery_references delegates to delivery_references_and_decode_batch makes this a wash, not a contradiction. (b) The docs/scheduling-runtime-design.md anchor-budgeting hunk belongs to already-merged #697/#655 and should not read as #729 work. (c) ToggleGrammar is modelled as an identity transition over phase = Live ∧ not-queued (Lifecycle.tla:75-78), weaker than the Rust guard which also excludes pending != 0 and a terminal Snapshot (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

  1. 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_fill in scripts/scheduling_sim/ and run learning.py --preset validate (64 seeds), or run screening+validation against the existing scalar model and report what it establishes. Disclosure is not a waiver.
  2. Add a served-workload measurement for bucket 2 on a core exporting codec_layout (restore latency / first-token after restore), or drop the performance justification for that bucket.
  3. 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.

Full report

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:

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.

  1. First submitted step for this catalog entry is decode-only → observe(nanos=2_000_000, work=0, …, fresh=true) → zero_fill = {2_000_000}, strata all 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).
  2. A prefillable request arrives; mixed_entry returns the constant predictor → mixed_duration(4, 1, 2048, work=2048, start=0) = 2_000_000 instead of ~95,000,000 (≈47x under-priced), and predict(2048,0) never sees the theta[1]*u or theta[2]*h terms. mixed_candidates also branches to the variable_cost == false path.
  3. 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):

  1. 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;
  2. Add pub fn has_positive_fill(&self) -> bool { self.pos_u_max > 0.0 } and, in mixed_entry (cost.rs:762-790), return Some(None) when prefill > 0 and 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.
  3. Leave the work == 0 branch of predict unchanged — that path is correctly anchored by has_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:

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


Coverage summary

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

Walkthrough

Pre-merge Checks

Blockers

  1. PrefillCostModel::fit marks a zero_fill-only GraphKind::Mixed model as a constant predictor (pos_u_max == 0.0 in wide_or_full_positive), pricing full-chunk prefills at 1× decode-only latency and inflating service_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::Mixed entry observes a decode-only step (work == 0, routinely emitted by mixed_candidates at policy.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 only self.zero_fill (u = 0.0, h = 0.0), leaving pos_u_max == 0.0 (cost.rs:365-374). In fit() (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]));
      
      The pos_u_max == 0.0 disjunct treats "zero positive-fill evidence" as "wide or full positive-fill coverage," emitting constant_nanos = Some(decode_ns) and storing decode_ns in estimate.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 sets constant_nanos = Some(2_000_000) and estimate.nanos = 2_000_000. Until a positive-fill step executes on that shape:
      • predict(2048, 0) short-circuits on constant_nanos (cost.rs:184-186)—and note that simply removing pos_u_max == 0.0 || is not sufficient on its own because upward_extrapolation_floor (cost.rs:145) also requires self.pos_u_max > 0.0, so predict(2048, 0) would still return theta[0] = 2_000_000 (~47× under-priced).
      • mixed_candidates (policy.rs:1756, 1872-1898) sees variable_cost = false, prices every prompt candidate at decode_ns, and is_unmeasured_candidate (policy.rs:546-549) returns false because estimate.nanos != 0, letting the mispriced candidate compete as PlanOrigin::Ordinary.
      • service_rates (service.rs:354-379) computes token_rate = 2048 * 1e6 / 2e6 = 1,024 tok/ms (~47× inflated), distorting service-rate normalization across all competing prefill requests even when that Mixed graph 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:
      1. Drop pos_u_max == 0.0 || from wide_or_full_positive (cost.rs:451-452) so a zero-fill-only model is never marked constant_nanos = Some(...).
      2. Expose pub fn has_positive_fill(&self) -> bool { self.pos_u_max > 0.0 } on PrefillPredictor. Keep predict(0, 0) returning the valid measured decode-only cost (do not collapse mixed_entry to Some(None) globally), while on positive-fill queries (work > 0) when !predictor.has_positive_fill(), return 0 in mixed_candidates/next_progress/continuation_candidate (so is_unmeasured_candidate at policy.rs:547 properly treats positive-fill on that shape as discovery via duration_ns == 0) and skip it in service_rates prefill normalization (service.rs:373).
      3. Add a unit test in cost.rs observing only mixed_step(4, 1, 2048, None) (at init and post-TTL) and asserting predict(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.

Should Fix

  1. Eliminate the remaining per-page Vec<DeviceSpan> clone in restore_window's GpuBatch arm (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's Vec<DeviceSpan>, yet codec.rs:716-717 still allocates and clones every per-page vector (let run_spans: Vec<Vec<DeviceSpan>> = slice.iter().map(|(_, _, _, sp)| sp.clone()).collect();) solely because decode_pages_batch_to_device takes &[Vec<DeviceSpan>]—partially contradicting the PR description's claim that partitioning avoids cloning per-page DeviceSpan vectors.
    • Fix: Mirror copy_spans_batch (codec.rs:1062) by changing spans_per_page in decode_pages_batch_to_device (gpu_codec.rs:1697) to &[impl AsRef<[DeviceSpan]>] (or &[&[DeviceSpan]]) and passing borrowed slices slice.iter().map(|(_, _, _, sp)| sp.as_slice()).collect::<Vec<_>>().
  2. Prevent CopyEngineGate::try_enter_offload_batch from 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) sizes offload_wave_remaining = offload_batches_waiting specifically for threads parked in enter_offload_batch. Because offload_must_wait (:171-175) allows entry when turn == Turn::Offload && offload_wave_remaining > 0, try_enter_offload_batch (:204-210) calls take_offload_lease and decrements offload_wave_remaining, potentially flipping turn = Turn::Peer before woken waiters run and contradicting docs/prefix-cache-offload.md:104-105 ("without blocking or consuming a gate wave token").
    • Fix: Return None in try_enter_offload_batch when Self::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.
  3. Address the disclosed default-MTP-5 latency delta, Layer-2 simulator check, and @yatesdr lock-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-A3B core, pause_for_drain regresses 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 to main's immediate cancel(). Confirm whether this trade-off is acceptable for default MTP-5 deployments on cores lacking ValueSource::GrammarEnabled or gate pause_for_drain when speculative overshoot is expected.
    • Obtain @yatesdr's sign-off on reversing #628's capture-path lock order (codec.rs:879-889), and run scripts/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-model Mixed validation is deferred.

Subtract / Simplify

Nits

Dropped on verification

Full report

Classify triage

Selected: triage:review

Threshold: 65%

Triage

Apply labels

No label changes