Skip to content

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

Merged
lukealonso merged 3 commits into
mainfrom
helios-inplace-grammar-toggle-kv-cod
Dec 5, 2026
Merged

lukealonso merged 3 commits into
mainfrom
helios-inplace-grammar-toggle-kv-cod

Conversation

@lukealonso

@lukealonso lukealonso commented Dec 4, 2026 •

Copy link
Copy Markdown
Collaborator

Why

Three Helios runtime mechanisms leave performance or concurrency on the table across structured-output reasoning, GPU KV prefix-cache offload, and mixed prefill-plus-decode scheduling (building on #530, #626, #628, and #645):

  1. Structured-output reasoning transitions discard live reasoning KV and recurrent state. When a grammar-constrained request exits an open reasoning block (</think>) or re-enters reasoning, Worker::complete in helios/src/server/runtime.rs always cancels the live slot via RequestScheduler::cancel(handle) (publish_terminal = false), parks the request, and readmits it. Cancelling discards every generated reasoning token's KV and recurrent state—forcing re-prefill of the entire reasoning trace (or the full prompt plus reasoning if the prompt checkpoint was evicted)—even when there is no burst overshoot (skipped == 0) and no second frame in flight (live.pending() == 0). For non-speculative models, running open reasoning with two-frame pipelining also guarantees an in-flight second frame at the reasoning boundary for zero speculative gain.
  2. GPU KV codec restore batching breaks on mixed windows, and background capture inverts lock order with CopyEngineGate. In helios/src/offload/transfer/codec.rs, restore_window terminates GPU batching (else { break; }) upon encountering a Literal or CPU-routed page, forcing every subsequent GKV1 page in the window onto singleton decode. On the capture path, capture_with_codec locks gpu.codec before blocking on CopyEngineGate::enter_offload_batch(), so a background capture parked behind an active peer-copy graph holds the codec mutex and stalls or forces foreground restores onto CPU decode.
  3. GraphKind::Mixed uses flat median cost pricing. ActionCosts in helios/src/scheduler/cost.rs fits a 6-stratum (fill, kv_context) nonnegative least-squares (NNLS) curve only for GraphKind::Prefill, leaving GraphKind::Mixed on a flat 9-sample median that cannot distinguish decode-only steps (work == 0), partial fills, full chunks, or deep-context attention cost.

What changed

1. In-place and checkpoint-preserving grammar transitions (helios/src/scheduler.rs, helios/src/scheduler/policy.rs, helios/src/model/{mod,admission,packing}.rs, helios/src/server/runtime.rs, verification/helios-lifecycle/)

  • Before: Every reasoning close or re-entry cancelled the live slot without publishing a terminal checkpoint and forced re-admission and re-prefill. Admission represented grammar state with two independent fields (grammar_mask: Option<Vec<i32>> and grammar_enabled: bool).
  • After:
    • Replaced Admission::{grammar_mask, grammar_enabled} with a three-state enum AdmissionGrammar::{Disabled, UnmaskedEnabled, Masked(Vec<i32>)} so disabled-but-masked states are unrepresentable.
    • Added three lifecycle operations to RequestScheduler: set_grammar_constrained(handle, constrained) (requires a live non-finishing slot with pending == 0), pause_for_park(handle) (requires an active slot with pending > 0 and blocks policy.rs from scheduling additional frames), and finish_for_park(handle) (requires pending == 0 and transitions to terminal checkpoint publication).
    • Cached can_toggle_grammar_in_place on Worker from whether every sampling graph in PreparedContract binds ValueSource::GrammarEnabled (structural contract check, preserving Principle 13 compatibility with cores lacking that binding).
    • Non-speculative requests keep a step-level feedback barrier (pending == 0 on completion) with AdmissionGrammar::UnmaskedEnabled (GrammarEnabled = 1, cached all-ones mask) during open reasoning, then switch to AdmissionGrammar::Masked(mask) in place on the live slot when reasoning closes or re-opens without thinking-budget expansion (no cancel, no Snapshot, no Restore, no re-prefill).
    • Speculative requests keep multi-token verification and two-frame pipelining during open reasoning and dispatch through decide_grammar_transition:
      • ToggleInPlace when skipped == 0, live.pending() == 0, extra == 0, and can_toggle_grammar_in_place holds (set_grammar_constrained runs before mutating request/admission state).
      • CheckpointPark when skipped == 0 and live.error_code.is_none() and !live.deferred_prefill() (either can_toggle_grammar_in_place is false, extra > 0, or live.pending() == 1): drains any single in-flight frame under pause_for_park; if consumed_tokens <= exact_len, calls finish_for_park so Worker::publish publishes a terminal checkpoint and readmits via Restore with the updated grammar mode and preserved reasoning_cut.after.
      • Rollback on burst overshoot (skipped > 0), draining-frame overshoot (consumed_tokens > exact_len), or grammar rejection.
    • In Worker::publish, applied pending_grammar_park before park_if_preempted (and guarded park_if_preempted when pending_grammar_park.is_some()), preventing coincident page-pressure preemption from discarding the grammar-mode transition or reasoning_cut.after expansion.
    • Extended verification/helios-lifecycle/Lifecycle.tla with Paused, PauseForPark, FinishForPark, and ToggleGrammar, extended helios/src/scheduler/lifecycle_tests.rs to explore and check rejections for all three operations, and added six Rust mutation guards in verification/helios-lifecycle/check.py.

2. Restore window partitioning and non-blocking CopyEngineGate acquisition (helios/src/offload/{copy_gate.rs,transfer/codec.rs})

  • Before: restore_window aborted GPU batching on the first Literal or CPU page and cloned per-page DeviceSpan vectors; capture_with_codec locked gpu.codec before CopyEngineGate::enter_offload_batch(); foreground restores had no non-blocking CopyEngineGate try-entry.
  • After:
    • Added CopyEngineGate::try_enter_offload_batch(&self) -> Option<OffloadBatchGuard<'_>>, which returns None immediately without blocking or mutating waiting/wave-token state when peer-copy graphs block offload entry.
    • Background capture paths use with_gpu_codec_locked, acquiring CopyEngineGate::enter_offload_batch before gpu.codec.lock(). Foreground GPU restore paths use try_with_gpu_codec_locked, acquiring gpu.codec.try_lock() and CopyEngineGate::try_enter_offload_batch() non-blockingly and falling back immediately to CPU decode when either is contended (deadlock-free with with_gpu_codec_locked because both acquisitions are non-blocking).
    • Replaced the early-break loop with partition_restore_pages_by, partitioning restore windows into maximal GpuBatch, CpuBatch, and Single runs without allocating a route Vec or cloning per-page DeviceSpan vectors.

3. (fill, kv_context) NNLS pricing for GraphKind::Mixed (helios/src/scheduler/{cost.rs,policy.rs})

  • Before: ActionCosts priced GraphKind::Mixed with a flat 9-sample median and duplicated scoring loops in mixed_candidates.
  • After:
    • Extended ActionCosts with per-GraphKind::Mixed (fill, kv_context) 6-stratum NNLS models plus a zero_fill stratum for decode-only mixed steps (work == 0), sharing predict_prefill_with_peer_slope across Prefill and Mixed.
    • Tracked pos_u_min, pos_u_max, pos_t_at_umax, and has_zero_fill over positive-fill strata: observing a zero_fill sample keeps the 4x upward extrapolation floor intact on narrow positive fills, predict(0, 0) uses theta[0] only when anchored by a zero_fill observation (t_at_umin fallback otherwise), and a zero_fill-only model (pos_u_max == 0, !has_positive_fill()) never emits constant_nanos, leaving positive-fill queries (work > 0) unmeasured (0) until a positive-fill step executes so decode-only observations cannot under-price full-chunk prefills or inflate service_rates.
    • Unified the mixed_candidates_with_curves scoring loops in helios/src/scheduler/policy.rs while preserving helios/scheduler: cache per-lane powered survival curves across candidate pricing #693's per-lane CurveCache reuse, and updated present-state design specifications in docs/{api,core-design,mtp-design,prefix-cache-offload,scheduling-runtime-design}.md.

Claimed benefit and result

  • Measured (live flare run A/B on SM120 RTX PRO 6000 serving signed Qwen4-35B-A3B-FLARE-gb202-tp1-202612032159-signed, --mtp-draft-tokens 0):
    • Eliminated 100% of reasoning transition parks and reasoning re-prefill tokens across 7 requests (1 warmup + 6 measured): flare_cache_lookups_total 14 -> 7, flare_prefill_tokens_total 84,638 -> 81,832 (-2,806 wasted prefill tokens), flare_sampling_graph_launches_total{kind="prefill"} 62 -> 54 (-8 launches), flare_snapshot_publications_total 30 -> 22, and flare_snapshot_backing_pages 2,880 -> 2,112 (-26.7%).
    • Cut median </think>-to-first-content latency gap by 3.32x at 6,382 prompt tokens (41.2 ms -> 12.4 ms) and 4.53x at 20,648 prompt tokens (58.5 ms -> 12.9 ms, flat at two 6.1–6.2 ms decode steps), with 6/6 schema-valid JSON responses on an existing core lacking ValueSource::GrammarEnabled.
  • Measured (same signed Qwen4-35B-A3B core under default MTP 5, no ValueSource::GrammarEnabled binding):
    • 6/6 schema-valid JSON responses on both builds. Because MTP 5 runs widths 3–6 with two-frame pipelining on this core and Qwen4 emits </think>\n\n{, speculative bursts overshoot </think> in Frame 1 or Frame 2 and fall back to rollback on both builds (6,382 prompt tokens: median gap 39.1 ms vs 39.0 ms; 20,648 prompt tokens: 40.9 ms vs 54.1 ms, where the ~13 ms delta reflects waiting one speculative frame under pause_for_park before Frame 2 overshoots and rolls back). Cores exporting ValueSource::GrammarEnabled toggle in place when skipped == 0 && pending == 0.
  • Expected / verified by unit, GPU codec, and formal checks:
    • Coincident page-pressure preemption preserves grammar transitions and reasoning_cut.after.
    • GPU KV restore windows batch all GKV1 runs past leading or interleaved Literal/CPU pages without per-page span clones, and foreground GPU restores fall back to CPU immediately under peer-copy gate or codec contention.
    • GraphKind::Mixed cost estimation differentiates zero-fill, partial-fill, full-chunk, and deep-context steps while retaining the 4x narrow-fill upward floor, anchored decode-only intercept, and unmeasured positive-fill protection on zero_fill-only models.

Supporting evidence

  • Live flare run A/B benchmark (origin/main f705086b vs commit 68fe22fd, RTX PRO 6000 Blackwell SM120 GPU 2, /data/flare-runtime/Qwen4-35B-A3B-FLARE-gb202-tp1-202612032159-signed, temperature=0.7, top_p=0.8, max_tokens=2048, identical seeds and unique-prefix prompts per trial, 3 trials x 2 prompt lengths, strict JSON schema response_format):
    • --mtp-draft-tokens 0, 6,382 prompt tokens: main median think->content 41.2 ms (35.2 / 41.2 / 43.5 ms) vs PR 12.4 ms (12.4 / 12.4 / 12.8 ms); valid JSON 3/3 vs 3/3.
    • --mtp-draft-tokens 0, 20,648 prompt tokens: main median think->content 58.5 ms (58.2 / 58.5 / 61.6 ms) vs PR 12.9 ms (12.6 / 12.9 / 22.1 ms); valid JSON 3/3 vs 3/3.
    • Default MTP 5, 6,382 prompt tokens: main 39.1 ms (37.7 / 39.1 / 39.6 ms) vs PR 39.0 ms (37.6 / 39.0 / 46.6 ms); valid JSON 3/3 vs 3/3.
    • Default MTP 5, 20,648 prompt tokens: main 40.9 ms (40.6 / 40.9 / 63.9 ms) vs PR 54.1 ms (50.0 / 54.1 / 56.7 ms); valid JSON 3/3 vs 3/3.
  • TLA+ lifecycle verification and mutation suite on merged HEAD 2fa4e83e (prlimit --memlock=unlimited python3 verification/helios-lifecycle/check.py --tlc-jar ... --target-dir flare-cli/target --mutations):
    • All 10 TLA+ models passed (Lifecycle.tla: 18,790 states generated, 2,896 distinct states, depth 14, 0 errors).
    • 623,976 observed Rust transitions verified against the TLA+ models (3,865 transitions and 2,979 states against Lifecycle.tla, confirming paused_for_park, finished_for_park, cancelled_while_paused, toggled_grammar, rejected_pause_idle, rejected_toggle_pending, and rejected_finish_pending; 431 against AsyncTransfer.tla).
    • 60 of 60 mutations detected (19 TLA+ mutations + 41 Rust mutations, including all 6 new Rust mutations covering set_grammar_constrained, pause_for_park, finish_for_park, paused_for_park scheduling, publish preemption ordering, and CopyEngineGate::try_enter_offload_batch).
  • Rust crate test suites on merged HEAD 2fa4e83e (cargo test --locked --release):
    • helios (--features runtime-core,server): --lib 1,966 passed, 0 failed (49 ignored; 6 HF chat-template tests require tests/frontend/prepare_templates.py downloads); --test '*' 59 passed, 0 failed (39 checkpoint-gated ignored; 3 Gemma template tests require prepare_templates.py downloads).
    • helios live SM120 GPU KV codec tests (CUDA_VISIBLE_DEVICES=5 FLARE_TEST_KV_CODEC_CUBIN=... --ignored offload::transfer::codec::tests:: --test-threads=1): 4 passed, 0 failed.
    • flare: 255 passed, 0 failed, 4 ignored.
    • flare-cli: 254 passed, 0 failed, 3 ignored.
    • Pre-merge untouched crates on 68fe22fd: eos 12 passed, selene 586 passed, selene-manager 443 passed (1 ignored).
  • Python pytest on merged HEAD 2fa4e83e (CUDA_VISIBLE_DEVICES=3 FLARE_RUN_CUDA_TESTS=1):
    • tests/test_scheduling_*.py, tests/test_design_review_hook.py, tests/cli, tests/direct/test_scheduler.py, tests/test_kv_codec.py: 1,120 passed, 0 failed.
  • Unrun checks and material limitations:
    • cargo-kani is not installed locally (covered by the repository's kani CI job).
    • The 9 Hugging Face chat-template tests require templates fetched by tests/frontend/prepare_templates.py, and 39 checkpoint-gated helios integration tests require external model snapshots.
    • The Python scheduling simulator (scripts/scheduling_sim/) models scalar per-graph costs rather than (fill, kv_context) NNLS curves, so the GraphKind::Mixed NNLS fit is verified through helios cost and policy unit tests rather than a simulator curve sweep.
    • No exported SM120 core with GraphKind::Mixed graphs or codec_layout was available locally for whole-model flare run throughput benchmarks of items 2 and 3; item 2 was validated on live SM120 GPU hardware via the 4 ignored offload::transfer::codec::tests:: GPU tests and tests/test_kv_codec.py.

Discord: lukealonso

…/locking, and stratify Mixed graph costs

Three Helios runtime paths discard live GPU state, disable batched GPU
offload restores, or misprice mixed prefill-and-decode graphs:

1. Structured-output reasoning transitions (`</think>` close and
   `allow_reasoning_reentry`) previously routed every transition through
   `park_with_tokens(..., publish_terminal: false)` -> `scheduler.cancel(handle)`,
   which invokes `retire(handle, false)` without publishing a terminal
   checkpoint. Every transition therefore discarded all live KV and recurrent
   state and forced full prompt-plus-reasoning re-prefill, even when zero
   speculative overshoot occurred (`skipped == 0`). Non-speculative models also
   set `grammar_constrained = false` during reasoning, enabling two-frame
   pipelining for zero speculative width gain while guaranteeing an in-flight
   second frame at `</think>`. Existing prepared cores bind
   `ValueSource::GrammarEnabled` only on `Init` and `Restore` graphs, and
   speculative verification kernels gate width > 1 on `!grammar_enabled`, so
   non-speculative cores can keep device `grammar_enabled = 1` with a cached
   all-ones mask and toggle masks in place, speculative cores whose sampling
   graphs bind `ValueSource::GrammarEnabled` can toggle both in place when
   `pending == 0 && extra == 0`, and speculative cores without per-step
   `GrammarEnabled` bindings (or with `pending == 1` or `extra > 0`) can retain
   live state by publishing a terminal checkpoint and restoring it.
2. In `helios/src/offload/transfer/codec.rs`, `restore_window` previously
   stopped GPU batching on the first `Literal` or CPU-routed page (`else { break; }`),
   disabling GPU batching for all subsequent `GpuOnDevice` pages in the window.
   In `capture_window`, background capture threads previously locked `gpu.codec`
   before waiting on `CopyEngineGate::enter_offload_batch()`, holding the codec
   mutex while blocked on active peer-copy graphs and forcing foreground
   restores calling `try_lock()` onto CPU decoding (and creating a lock-order
   inversion if capture and restore acquired the gate and mutex in opposite
   orders).
3. In `helios/src/scheduler/cost.rs`, stratified `(fill, kv_context)` NNLS
   pricing applied only to pure prefill graphs while `GraphKind::Mixed` stayed
   on a single nine-sample median, allowing decode-only or short-tail mixed
   steps to distort full-chunk and deep-context mixed pricing.

Changes:
- Grammar transitions (`helios/src/model/{admission,packing}.rs`,
  `helios/src/scheduler.rs`, `helios/src/scheduler/policy.rs`,
  `helios/src/server/runtime.rs`):
  - Add `Admission::grammar_enabled` and update `ValueSource::GrammarEnabled`
    packing to emit `grammar_enabled || grammar_mask.is_some()`.
  - Add `RequestScheduler::{set_grammar_constrained, pause_for_park,
    finish_for_park}` and `LiveRequest::{pending, deferred_prefill,
    paused_for_park}`. `paused_for_park` excludes a draining request from
    scheduling, starvation, reservation refill, and preemption until its
    in-flight frame completes.
  - Keep `grammar_constrained = true` and initialize `grammar_enabled = true`
    with `grammar_mask = None` (cached all-ones) on non-speculative models so
    two-frame pipelining is disabled and reasoning transitions toggle
    `grammar_mask` in place with zero cancel or re-prefill.
  - On speculative models, inspect `PreparedContract` (`ValueSource::GrammarEnabled`
    on sampling graphs) to toggle in place when `skipped == 0 && pending == 0
    && extra == 0`. Otherwise, when `skipped == 0`, publish a terminal
    checkpoint (`finish_for_park` -> `Snapshot` -> `finish` -> `Restore`, or
    `pause_for_park` while a single in-flight frame drains and `consumed_tokens
    <= exact_len`) so KV and recurrent state are reused via `Restore` ->
    `Prefill(1)` or `Resume`, propagating device errors and falling back to
    cancel-and-rollback only on overshoot (`skipped > 0` or `consumed_tokens >
    exact_len`). Existing prepared cores remain compatible without re-export.
- KV offload codec (`helios/src/offload/transfer/codec.rs`):
  - Replace the single-prefix loop in `restore_window` with
    `partition_restore_pages` (`GpuBatch`, `CpuBatch`, `Single`) and
    `restore_single_unit` so leading or interleaved `Literal`/CPU/singleton
    pages never abort GPU batching for later `GpuOnDevice` runs; avoid
    recording CPU transform time on pure-`Literal` batches.
  - Route all five GPU codec lock sites (three in `capture_window`, two in
    `restore_window`/`restore_single_unit`) through `with_gpu_codec_locked` and
    `try_with_gpu_codec_locked`, which always acquire
    `CopyEngineGate::enter_offload_batch` before `gpu.codec.lock()`/`try_lock()`.
- Mixed graph cost model (`helios/src/scheduler/{cost,policy,service}.rs`,
  `docs/scheduling-runtime-design.md`):
  - Enable `PrefillCostModel` for `GraphKind::Mixed` with an additional
    `zero_fill` bucket for decode-only steps (`work == 0`), safe fallback to
    `t_at_umin` when NNLS clamps `theta_0` to zero, `u_min > 0` gating on
    `upward_extrapolation_floor`, and same-`(batch, width)` peer KV-context
    slope borrowing.
  - Price `GraphKind::Mixed` with live `(work, start_position)` and `(0, 0)`
    decode-only durations across `next_progress`, `continuation_candidate`,
    `mixed_candidates`, `resize_prefill`, `delivery_references`, and
    `service_rates`, and update the cost-model specification in
    `docs/scheduling-runtime-design.md`.

Result:
- Expected runtime impact: eliminates 2K-32K KV/recurrent cache wipes across
  structured-output reasoning transitions on both non-speculative (in-place
  toggle) and speculative (in-place toggle or terminal-checkpoint restore)
  models, preserves GPU batching across heterogeneous restore windows without
  codec-mutex lock inversion under `CopyEngineGate`, and keeps `MIXED`
  scheduler pricing responsive to prompt fill ratio and KV-context depth.
  No end-to-end exported-core `flare run` latency benchmark was measured here.
- Verified behavioral results: all new unit and runtime phase tests pass, live
  SM120 GPU codec capture/restore and `CopyEngineGate` tests pass, and all TLA+
  lifecycle conformance checks pass without invariant violations.

Evidence and limitations:
- Rust crate suites (`--locked --release --target-dir flare-cli/target`, 0
  rustc warnings, 0 clippy warnings on modified lines):
  - `eos` (12 passed), `selene --features test-support` (585 passed),
    `selene-manager --features test-support` (passed), `flare` (255 passed,
    4 ignored), `flare-cli` (250 passed, 3 ignored), `helios --features
    runtime-core,server --lib` excluding the 6 HF-template tests (1917 passed,
    0 failed, 49 ignored), and `helios --features runtime-core,server --test '*'`
    with `FLARE_TEST_TEMPLATE_DIR=/tmp/flare-test-templates` (62 passed,
    0 failed, 37 ignored).
  - Live SM120 GPU codec tests (`CUDA_VISIBLE_DEVICES=2`, compiled
    `kv_codec_gpu-sm_120a.cubin`): all 4 `#[ignore]` tests in
    `offload::transfer::codec::tests` passed (`cpu_vram_capture_and_restore`,
    `gpu_vram_capture_and_restore`, `gated_cpu_and_gpu_codec_capture_and_restore`,
    `mixed_cpu_and_gpu_modes`).
- Python suites (`.venv/bin/python -m pytest`):
  - `tests/test_scheduling_*.py` and `tests/test_design_review_hook.py`: 855 passed.
  - `tests/cli`, `tests/test_kv_codec.py` (with `FLARE_RUN_CUDA_TESTS=1`), and
    `tests/direct/test_scheduler.py`: 260 passed.
- Formal lifecycle conformance (`python3 verification/helios-lifecycle/check.py`
  with `tla2tools-1.7.4.jar`): all 10 TLA+ models and 9 Rust observed-edge
  suites passed (621,749 observed transitions across `Lifecycle`,
  `RankProtocol`, `DispatchRing`, `OffloadTransfer`, `CacheOwnership`,
  `Speculation`, `ResponseLifecycle`, `CheckpointReservation`, and
  `AsyncTransfer`).
- Limitations and unrun checks:
  - Six `helios --lib` chat-template tests require templates fetched by
    `tests/frontend/prepare_templates.py` (local `/tmp/flare-test-templates`
    lacks several entries) and were not run.
  - `cargo-kani` is not installed locally; Kani-covered `StateView` and
    completion-vector validators were not modified.
  - `scripts/scheduling_sim/` models scalar per-graph durations and does not
    represent per-fill/per-context NNLS strata; whole-model `flare run` serving
    benchmarks with exported cores were not run.

Design-Signed-Off-By: Antigravity (Gemini 3.1 Pro); design-review=2e5b
Signed-off-by: Luke Alonso <lalonso@gmail.com>
@flare-autobot

Copy link
Copy Markdown
Collaborator

A case file has been opened for 729.
Case File Intake Report

Future reviews will auto-run 90 minutes after code updates are pushed.

  • Re-review sooner: Call @flare-autobot after push.
  • Opt-out: Include #autobot:ignore in the PR or any comment.

@flare-autobot flare-autobot added area:scheduling Request scheduling, fairness, batching, and speculative-width selection. bug Something isn't working performance Performance, latency, throughput, or memory-efficiency investigation or improvement. triage:review Proposed change needs code review; this does not imply merge readiness. labels Dec 4, 2026
@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review · Value Proposition · Case File

Recommendation: Changes Requested

This PR makes genuinely additive, model-agnostic changes with sound core partition_restore_pages batching and ValueSource::GrammarEnabled packing mechanics, but verification at 150f705 confirms three concrete runtime bugs and two unmet mandatory verification gates (uncovered scheduler lifecycle states plus unbenchmarked performance/legacy-core claims).

  • Blockers: 5 · Should fix: 3 · Subtract/Simplify: 6 · Nits: 3
Walkthrough
  • Grammar-transition KV preservation (helios/src/model/{admission,packing}.rs, helios/src/scheduler.rs, helios/src/scheduler/policy.rs, helios/src/server/runtime.rs, tests): Adds Admission::grammar_enabled and widens ValueSource::GrammarEnabled packing to grammar_enabled || grammar_mask.is_some() (packing.rs:803-805). Adds LiveRequest::paused_for_park and RequestScheduler::{set_grammar_constrained, pause_for_park, finish_for_park} (scheduler.rs:267, 1433, 1449, 1531, 3234-3295; policy.rs:335). Replaces unconditional cancel() transitions in Worker::complete with in-place toggling for non-speculative models and per-step-GrammarEnabled speculative cores, or terminal-checkpoint parking via PendingGrammarPark (runtime.rs:509-545, 1698-1706, 2118-2120, 2350-2614).
  • KV offload restore batching & lock ordering (helios/src/offload/transfer/codec.rs): Replaces the single leading GPU loop in restore_window with partition_restore_pages (GpuBatch, CpuBatch, Single) and restore_single_unit (codec.rs:586-873), skipping transform_ns on pure-Literal batches (:569-574, 643-645). Routes all five GPU codec lock sites (:288, 317, 352, 605, 704) through with_gpu_codec_locked / try_with_gpu_codec_locked (:878-899), acquiring CopyEngineGate before gpu.codec.
  • Stratified GraphKind::Mixed cost modeling (helios/src/scheduler/{cost,policy,service}.rs, docs/scheduling-runtime-design.md, tests): Attaches PrefillCostModel to GraphKind::Mixed (cost.rs:655-656) with a zero_fill bucket (:286, 321-323, 368-373), t_at_umin fallback for work == 0 (:176-189), u_min > 0.0 gating on upward_extrapolation_floor (:132-142), and same-(batch, width) peer KV-context slope borrowing (:600, 883-936). Wires mixed_entry / mixed_duration through next_progress, continuation_candidate, mixed_candidates, resize_prefill, delivery_references_and_decode_batch, and service_rates (policy.rs:934-969, 1166-1308, 1751-1947, 2112-2120; service.rs:232-240, 353-395) and updates docs/scheduling-runtime-design.md:466-490.
Merge Risk: High · up to 150f705
  • Request-lifecycle state corruption under KV pressure: Deferring grammar-transition parking from Worker::complete to Worker::publish via PendingGrammarPark interacts with preempt_newest() in complete_inner; publish() executes park_if_preempted first, silently discarding grammar_reasoning_mode, drop_reasoning, and thinking_token_budget's cut.after budget.
  • Foreground KV-offload restore stall & lock-order reversal: Reversing #628's reviewed gpu.codec → CopyEngineGate lock order puts an unbounded CopyEngineGate::enter_offload_batch wait ahead of codec.try_lock() in try_with_gpu_codec_locked, blocking foreground restores behind peer-copy graphs instead of falling back to CPU decoding, while burning two offload wave tokens on contention.
  • Unbenchmarked behavior shifts across three unrelated hot-path subsystems: Non-speculative grammar requests lose two-frame pipelining during reasoning and pack GrammarEnabled = 1 during open reasoning; existing speculative cores without per-step GrammarEnabled bindings pay Snapshot + Restore per transition; and GraphKind::Mixed NNLS stratification alters mixed scheduling and collides textually in cost.rs with open #715.
Pre-merge checks: ✅ 1 passed · ⚠️ 3 warnings
  • ✅ Security / malicious screen: Pure host-side scheduling, runtime state, and codec synchronization; no new dependencies, external I/O, wire/Protobuf/kernel changes, or prompt-injection attempts.
  • ⚠️ Charter & value fit: Model-agnostic Helios placement with no new op contracts, flags, or ABI changes (#267, #334), and valid Discord contact; however, all three buckets are performance-motivated with zero served-workload flare run A/B benchmarks (#210, docs/design-review.md:109-115), bundle three unrelated subsystems, and omit issue/PR links (#530, #626, #628, #645).
  • ⚠️ Related / duplicate / conflict check: Genuinely additive over #525/#626/#628/#645 (not a duplicate), but reverses #628's reviewed lock-order invariant (needs @yatesdr sign-off once fixed) and conflicts textually in cost.rs with open #715.
  • ⚠️ Tests & verification evidence: Strong targeted CPU and SM120 GPU codec unit tests are reported passing, but paused_for_park / pause_for_park / finish_for_park / set_grammar_constrained lack TLA+ conformance coverage, check.py --mutations was skipped (docs/design-review.md:226-251), and neither legacy-core loading/serving nor scripts/scheduling_sim validation was run.

Have your agent review the Full Review for complete verified findings, file:line citations, and suggested changes.

To opt out, include #autobot:ignore in your post or comment.

… cost bounds, and lifecycle verification

Why:
Under page pressure, `RequestScheduler::complete_inner` can preempt the
newest growable decoding request in the same step where that request closes
reasoning with `reasoning_cut.after > 0`. In `Worker::publish`, running
`park_if_preempted` before applying `pending_grammar_park` silently parked
the request in stale open-reasoning mode and dropped its reasoning-cut
budget expansion. In `offload/transfer/codec.rs`, acquiring the blocking
`CopyEngineGate::enter_offload_batch` inside `try_with_gpu_codec_locked`
stalled foreground restores behind active peer-copy graphs instead of
falling back immediately to CPU decode. In `scheduler/cost.rs`, recording a
zero-fill `GraphKind::Mixed` sample set `u_min = 0.0`, disabling the 4x
upward extrapolation floor for narrow positive fills, while barely
sub-linear positive-fill pairs let `predict(0, 0)` extrapolate toward 1 ns.
Finally, `Lifecycle.tla`, its Rust conformance suite, and the mutation
suite did not cover `pause_for_park`, `finish_for_park`, or
`set_grammar_constrained`, and the runtime design docs still described the
pre-change rollback-only behavior.

What changed:
- `helios/src/server/runtime.rs`, `helios/src/scheduler.rs`,
  `helios/src/model/{mod,admission,packing}.rs`: ordered `Worker::publish`
  to apply `pending_grammar_park` before `park_if_preempted` (and guarded
  `park_if_preempted` against overwriting `pending_grammar_park`); unified
  `PendingGrammarPark` and `GrammarTransition` into `GrammarPark` backed
  by `LiveRequest::paused_for_park()`; extracted `decide_grammar_transition`
  and cached `can_toggle_grammar_in_place` on `Worker`; applied
  `scheduler.set_grammar_constrained` before mutating request/admission
  state; and replaced `Admission::{grammar_mask, grammar_enabled}` with the
  three-state `AdmissionGrammar::{Disabled, UnmaskedEnabled, Masked}` enum.
- `helios/src/offload/{copy_gate.rs,transfer/codec.rs}`: added
  `CopyEngineGate::try_enter_offload_batch` returning `None` immediately
  without blocking or consuming wave tokens when peer-copy graphs block
  entry; updated `try_with_gpu_codec_locked` to acquire `codec.try_lock()`
  and `gate.try_enter_offload_batch()` non-blockingly; and removed
  per-page `Vec` clones in `restore_window` via `partition_restore_pages_by`
  and borrowed slice transfers.
- `helios/src/scheduler/{cost.rs,policy.rs}`: tracked `pos_u_min`,
  `pos_u_max`, `pos_t_at_umax`, and `has_zero_fill` strictly over
  positive-fill strata so zero-fill observations keep the 4x upward floor
  intact and `predict(0, 0)` only uses `theta[0]` when anchored by a
  `zero_fill` sample; deduplicated `mixed_candidates` scoring loops and
  extracted `clamp_nanos` / `MixedContextSlope`.
- `verification/helios-lifecycle/{Lifecycle.tla,check.py,README.md}` and
  `helios/src/scheduler/lifecycle_tests.rs`: added `Paused`, `PauseForPark`,
  `FinishForPark`, and `ToggleGrammar` to `Lifecycle.tla`, explored and
  checked rejections in Rust conformance, and added six Rust mutation
  checks under `check.py --mutations`.
- `docs/{api,core-design,mtp-design,prefix-cache-offload,scheduling-runtime-design}.md`:
  updated present-state specifications for in-place/checkpoint-preserving
  grammar transitions, non-blocking `CopyEngineGate` fallback, and
  positive-fill `GraphKind::Mixed` cost floors.

Claimed benefit and result:
Coincident preemption no longer drops grammar-mode transitions or
thinking-budget expansion; foreground GPU KV restores never block on active
peer-copy graphs and avoid per-page restore allocations; `GraphKind::Mixed`
keeps bounded upward extrapolation and positive decode-only estimates across
zero-fill and narrow positive-fill regimes; and the new scheduler lifecycle
transitions are formally checked against `Lifecycle.tla` and mutation
guards. On a live SM120 RTX PRO 6000 `flare run` A/B test serving signed
`Qwen4-35B-A3B` (`--mtp-draft-tokens 0`), in-place grammar toggling
eliminated 100% of reasoning re-prefill tokens (84,638 -> 81,832 across 7
requests; 0 transition parks vs 7) and cut median `</think>`-to-content
transition latency by 3.32x at 6,382 prompt tokens (41.2 ms -> 12.4 ms) and
4.53x at 20,648 prompt tokens (58.5 ms -> 12.9 ms) with 6/6 valid JSON
schema outputs.

Supporting evidence:
- `python3 verification/helios-lifecycle/check.py --mutations`: all 10 TLA+
  models passed (`Lifecycle.tla`: 18,790 states generated, 2,896 distinct),
  623,904 observed Rust transitions verified (3,865 against `Lifecycle.tla`
  with all 7 new coverage flags true), and 56/56 mutations detected (17
  TLA+, 39 Rust including all 6 new Rust mutations).
- Rust release test suites: `eos` (12 passed), `selene` (586 passed),
  `selene-manager` (443 passed, 1 ignored), `helios --lib` (1,919 passed;
  6 HF template tests require `prepare_templates.py` downloads; 49
  ignored), `helios --test '*'` (59 passed; 3 Gemma template tests require
  downloads; 39 checkpoint-gated ignored), `flare` (255 passed, 4 ignored),
  `flare-cli` (250 passed, 3 ignored), and 4/4 live SM120 GPU codec tests.
- Python pytest (`tests/test_scheduling_*.py`, `tests/test_design_review_hook.py`,
  `tests/cli`, `tests/direct/test_scheduler.py`, `tests/test_kv_codec.py`
  with `FLARE_RUN_CUDA_TESTS=1` on SM120): 1,115 passed.
- Unrun / limitations: `cargo-kani` is not installed locally (CI runs
  `kani`); the 9 HF chat-template tests require `prepare_templates.py`
  downloads; `scripts/scheduling_sim/` models scalar per-graph costs rather
  than `(fill, kv_context)` NNLS curves; and under default MTP 5 on this
  existing core without `ValueSource::GrammarEnabled`, speculative
  `</think>\n\n{` bursts overshoot in Frame 1 or Frame 2 and fall back to
  rollback on both builds (6/6 valid JSON; 6,382 prompt tokens 39.1 vs
  39.0 ms; 20,648 prompt tokens 40.9 vs 54.1 ms, reflecting a 1-frame wait
  when draining Frame 2 before overshoot rollback).

Design-Signed-Off-By: Antigravity (Gemini 3.1 Pro); design-review=2e5b
Signed-off-by: Luke Alonso <lalonso@gmail.com>
@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review · Value Proposition · Case File

Recommendation: Changes Requested

All five Round-1 blockers from 150f705 are cleanly resolved at 68fe22f, but direct source verification caught one new numeric/logic bug in the PrefillCostModel::fit rework (pos_u_max == 0.0 in wide_or_full_positive at helios/src/scheduler/cost.rs:451-456). A zero_fill-only GraphKind::Mixed model emits constant_nanos = Some(decode_ns), under-pricing full-chunk prefills by ~47× and inflating service_rates until a positive-fill step runs.

  • Blockers: 1 · Should fix: 3 · Subtract/Simplify: 4 · Nits: 3
Walkthrough
  • Grammar-transition KV preservation & lifecycle verification (helios/src/model/{mod,admission,packing}.rs, helios/src/scheduler.rs, helios/src/scheduler/policy.rs, helios/src/server/runtime.rs, verification/helios-lifecycle/{Lifecycle.tla,README.md,check.py}, phase_tests.rs): Replaces (grammar_mask, grammar_enabled) with AdmissionGrammar::{Disabled, UnmaskedEnabled, Masked(Vec<i32>)} (admission.rs:61-90, packing.rs:803); caches can_toggle_grammar_in_place on Worker (runtime.rs:1409-1410); routes transitions through decide_grammar_transition (runtime.rs:523-545) with scheduler-first set_grammar_constrained (runtime.rs:2390-2399, 2455-2465); orders pending_grammar_park ahead of park_if_preempted in Worker::publish() (runtime.rs:2561-2594, 2790-2792); and models Paused/PauseForPark/FinishForPark/ToggleGrammar in Lifecycle.tla:11, 60-78 with 6 new mutation guards in check.py:458-508.
  • KV offload restore partitioning & non-blocking CopyEngineGate (helios/src/offload/{copy_gate.rs,transfer/codec.rs}): Adds CopyEngineGate::try_enter_offload_batch sharing offload_must_wait/take_offload_lease (copy_gate.rs:171-210), routes capture through blocking gate-then-codec (codec.rs:881-889) and foreground restores through non-blocking codec.try_lock() then gate.try_enter_offload_batch() (codec.rs:895-906), and partitions restore windows via partition_restore_pages_by (codec.rs:697-702, 840-877) without allocating a duplicate routes Vec.
  • Stratified GraphKind::Mixed cost model (helios/src/scheduler/{cost,policy,service}.rs): Tracks pos_u_min/pos_u_max/pos_t_at_umax over positive-fill strata (cost.rs:144-153, 351-375), anchors predict(0, 0) on has_zero_fill (cost.rs:187-196), shares clamp_nanos (cost.rs:79-87), names MixedContextSlope (cost.rs:601-608), and updates docs/{api,core-design,mtp-design,prefix-cache-offload,scheduling-runtime-design}.md.
Merge Risk: Medium · up to 68fe22f
  • GraphKind::Mixed zero-fill-only constant-predictor defect: Observing a single decode-only (work == 0) Mixed step after startup or TTL expiry marks the graph constant_nanos = Some(decode_ns), pricing work > 0 prefills at 1× decode latency in mixed_candidates, next_progress, continuation_candidate, and service_rates (where inflated token_rate distorts utility normalization across all competing requests).
  • Default MTP-5 latency trade-off & lock-order reversal: The disclosed live SM120 A/B shows a +32% median </think>→content delta under default MTP 5 at 20,648 prompt tokens (40.9 → 54.1 ms) when pause_for_drain waits for a second speculative frame that overshoots and rolls back; separately, the capture path reverses #628's gpu.codec→CopyEngineGate order (deadlock-free with the non-blocking try path, pending @yatesdr sign-off).
  • Large four-surface diff & #715 conflict: 24 files (+2,954/−591) spanning runtime lifecycle, KV offload codec/gate, Mixed cost modeling, and TLA+/mutation verification, with direct textual and documentation overlap in cost.rs and docs/scheduling-runtime-design.md against open #715.
Pre-merge checks: ✅ 2 passed · ⚠️ 2 warnings
  • ✅ Security / malicious screen: Pure host-side scheduling, runtime lifecycle, and codec synchronization; no new dependencies, ABI/Protobuf/kernel changes, or prompt-injection attempts.
  • ⚠️ Charter & value fit: Model-agnostic Helios placement with live SM120 A/B and legacy-core verification for Bucket 1 (3.32×–4.53× faster under --mtp-draft-tokens 0), but bundles four subsystems, discloses an ungated +32% MTP-5 regression at 20.6K tokens, and lacks whole-model A/B for Buckets 2–3.
  • ⚠️ Related / duplicate / conflict check: Genuinely additive over #525/#626/#628/#645 and cites #530, but reverses #628's capture-path lock order (needs @yatesdr ack) and conflicts with open #715 in cost.rs and docs/scheduling-runtime-design.md.
  • ✅ Tests & verification evidence: All reported Rust crate suites, 4 live SM120 GPU codec tests, 1,115 pytest tests, 10/10 TLA+ models (623,904 observed transitions), and 56/56 --mutations pass; remaining gap is the Layer-2 scripts/scheduling_sim run noted under Should Fix.

Have your agent review the Full Review for complete verified findings, file:line citations, and suggested changes.

To opt out, include #autobot:ignore in your post or comment.

Why:
Upstream `main` (`be4092d7`) introduced per-lane survival-curve caching
(`CurveCache` and `prefill_lane_value`, #693) and core-parameter admission
validation (`plan_admission_with_core_parameters` without an explicit
definition slice, #621), conflicting with this branch in `policy.rs`,
`policy_tests.rs`, and `runtime.rs`. Separately, in `PrefillCostModel::fit`
(`helios/src/scheduler/cost.rs`), treating `pos_u_max == 0.0` as
`wide_or_full_positive` caused a `GraphKind::Mixed` model that had observed
only `zero_fill` (`work == 0`) samples to emit `constant_nanos =
Some(decode_ns)`, under-pricing full-chunk prefills and inflating
`service_rates` until a positive-fill step ran.

What changed:
- `helios/src/scheduler/cost.rs`, `docs/scheduling-runtime-design.md`:
  removed `pos_u_max == 0.0` from `wide_or_full_positive` so a
  `zero_fill`-only model never emits `constant_nanos`; added
  `PrefillPredictor::has_positive_fill()`; returned `0` (unmeasured) from
  `PrefillPredictor::predict(work > 0, _)` and `full_chunk_affine()` when
  `pos_u_max <= 0.0`; gated `with_borrowed_context_slope` on
  `pos_u_max > 0.0`; retained positive `decode_ns` in `Estimate::nanos`
  from `PrefillCostModel::observe` when only `zero_fill` samples exist; and
  added unit coverage in `cost.rs` and `policy_tests.rs`.
- `helios/src/scheduler/{policy.rs,policy_tests.rs}`: resolved conflicts
  against #693 by threading `curves: &mut CurveCache` through
  `add_candidate`'s `eval_mixed` and `mixed_candidates_with_curves`'s
  `score_decoders`, switching prefill scoring to `prefill_lane_value`,
  gating oversized unmeasured-prefill pruning on `!has_positive_fill()`,
  and retaining both test suites.
- `helios/src/server/runtime.rs`: resolved the #621 admission-plan conflict
  in `begin_pool_lookup` using `incoming.spec(false)` with the two-argument
  `plan_admission_with_core_parameters` signature.

Claimed benefit and result:
PR #729 merges cleanly onto `origin/main` (`be4092d7`) while preserving
#693's per-lane `CurveCache` reuse across `GraphKind::Mixed` candidates,
and a `zero_fill`-only `GraphKind::Mixed` entry accurately prices
decode-only steps (`work == 0`) without under-pricing positive-fill chunks
or inflating prefill `service_rates` (verified by
`zero_fill_only_mixed_model_does_not_inflate_prefill_service_rates` and
`mixed_cost_model_tracks_zero_fill_partial_fill_deep_context_and_peer_slope`).

Supporting evidence:
- `python3 verification/helios-lifecycle/check.py --mutations`: 10/10 TLA+
  models passed, 623,976 observed Rust transitions verified (3,865 against
  `Lifecycle.tla`, 431 against `AsyncTransfer.tla`), and 60/60 mutations
  detected (19 TLA+, 41 Rust).
- Rust release test suites: `helios --lib` 1,966 passed (49 ignored; 6 HF
  template tests require `prepare_templates.py` downloads), `helios --test
  '*'` 59 passed (39 checkpoint-gated ignored; 3 Gemma template tests
  require downloads), `flare` 255 passed (4 ignored), `flare-cli` 254
  passed (3 ignored), and 4/4 live SM120 GPU KV codec tests on idle GPU 5.
- Python pytest (`CUDA_VISIBLE_DEVICES=3 FLARE_RUN_CUDA_TESTS=1`): 1,120
  passed (`tests/test_scheduling_*.py`, `tests/test_design_review_hook.py`,
  `tests/cli`, `tests/direct/test_scheduler.py`, `tests/test_kv_codec.py`).
- Unrun locally: `cargo-kani` (running in CI) and the 9 HF chat-template
  tests requiring `prepare_templates.py` downloads.

Design-Signed-Off-By: Antigravity (Gemini 3.1 Pro); design-review=2e5b
Signed-off-by: Luke Alonso <lalonso@gmail.com>
@lukealonso
lukealonso merged commit 6efbd12 into main Dec 5, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:scheduling Request scheduling, fairness, batching, and speculative-width selection. bug Something isn't working performance Performance, latency, throughput, or memory-efficiency investigation or improvement. triage:review Proposed change needs code review; this does not imply merge readiness.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants