Recommendation: Changes Requested
This PR tackles three real, well-motivated Helios issues cleanly within the model-agnostic runtime layer with zero core-format/ABI/Protobuf changes, and its core partition_restore_pages batching and ValueSource::GrammarEnabled packing mechanics are sound. However, direct verification at 150f705 confirms three concrete runtime/locking/cost-model bugs (including a preemption-coincident PendingGrammarPark state-corruption bug, a blocking CopyEngineGate wait inside try_with_gpu_codec_locked that defeats CPU restore fallback, and zero_fill permanently disabling upward_extrapolation_floor for GraphKind::Mixed), plus two unmet mandatory verification gates (uncovered new scheduler lifecycle state / unrun check.py --mutations, and unbenchmarked performance / legacy-core serving claims).
Merge Risk
Level: High
- Request-lifecycle state corruption under KV pressure: Deferring grammar-transition parking from
Worker::completetoWorker::publishviaPendingGrammarParkinteracts withpreempt_newest()incomplete_inner;publish()executespark_if_preemptedfirst, silently discardinggrammar_reasoning_mode,drop_reasoning, andthinking_token_budget'scut.afterbudget. - Foreground KV-offload restore stall & lock-order reversal: Reversing
#628's reviewedgpu.codec→CopyEngineGatelock order puts an unboundedCopyEngineGate::enter_offload_batchwait ahead ofcodec.try_lock()intry_with_gpu_codec_locked, blocking foreground restores behind peer-copy graphs instead of falling back to CPU decoding, while burning two offload wave tokens on contention. - Unbenchmarked behavior shifts across three unrelated hot-path subsystems: Non-speculative grammar requests lose two-frame pipelining during reasoning and pack
GrammarEnabled = 1during open reasoning; existing speculative cores without per-stepGrammarEnabledbindings paySnapshot+Restoreper transition; andGraphKind::MixedNNLS stratification alters mixed scheduling and collides textually incost.rswith open#715.
Walkthrough
- Grammar-transition KV preservation (
helios/src/model/{admission,packing}.rs,helios/src/scheduler.rs,helios/src/scheduler/policy.rs,helios/src/server/runtime.rs, tests): AddsAdmission::grammar_enabledand widensValueSource::GrammarEnabledpacking togrammar_enabled || grammar_mask.is_some()(packing.rs:803-805). AddsLiveRequest::paused_for_parkandRequestScheduler::{set_grammar_constrained, pause_for_park, finish_for_park}(scheduler.rs:267, 1433, 1449, 1531, 3234-3295;policy.rs:335). Replaces unconditionalcancel()transitions inWorker::completewith in-place toggling for non-speculative models and per-step-GrammarEnabledspeculative cores, or terminal-checkpoint parking viaPendingGrammarPark(runtime.rs:509-545, 1698-1706, 2118-2120, 2350-2614). - KV offload restore batching & lock ordering (
helios/src/offload/transfer/codec.rs): Replaces the single leading GPU loop inrestore_windowwithpartition_restore_pages(GpuBatch,CpuBatch,Single) andrestore_single_unit(codec.rs:586-873), skippingtransform_nson pure-Literalbatches (:569-574, 643-645). Routes all five GPU codec lock sites (:288, 317, 352, 605, 704) throughwith_gpu_codec_locked/try_with_gpu_codec_locked(:878-899), acquiringCopyEngineGatebeforegpu.codec. - Stratified
GraphKind::Mixedcost modeling (helios/src/scheduler/{cost,policy,service}.rs,docs/scheduling-runtime-design.md, tests): AttachesPrefillCostModeltoGraphKind::Mixed(cost.rs:655-656) with azero_fillbucket (:286, 321-323, 368-373),t_at_uminfallback forwork == 0(:176-189),u_min > 0.0gating onupward_extrapolation_floor(:132-142), and same-(batch, width)peer KV-context slope borrowing (:600, 883-936). Wiresmixed_entry/mixed_durationthroughnext_progress,continuation_candidate,mixed_candidates,resize_prefill,delivery_references_and_decode_batch, andservice_rates(policy.rs:934-969, 1166-1308, 1751-1947, 2112-2120;service.rs:232-240, 353-395) and updatesdocs/scheduling-runtime-design.md:466-490.
Pre-merge Checks
- [PASS] Security / malicious screen: Pure host-side scheduling, runtime state, and codec synchronization; no new dependencies, external I/O, wire/Protobuf/kernel changes, or prompt-injection attempts.
- [WARN] Charter & value fit: Model-agnostic Helios placement with no new op contracts, flags, or ABI changes (
#267,#334), and valid Discord contact; however, all three buckets are performance-motivated with zero served-workloadflare runA/B benchmarks (#210,docs/design-review.md:109-115), bundle three unrelated subsystems, and omit issue/PR links (#530,#626,#628,#645). - [WARN] Related / duplicate / conflict check: Genuinely additive over
#525/#626/#628/#645(not a duplicate), but reverses#628's reviewed lock-order invariant (needs@yatesdrsign-off once fixed) and conflicts textually incost.rswith open#715. - [WARN] Tests & verification evidence: Strong targeted CPU and SM120 GPU codec unit tests are reported passing, but
paused_for_park/pause_for_park/finish_for_park/set_grammar_constrainedlack TLA+ conformance coverage,check.py --mutationswas skipped (docs/design-review.md:226-251), and neither legacy-core loading/serving norscripts/scheduling_simvalidation was run.
Blockers
-
Preemption in
complete_innerclobbersPendingGrammarParkinWorker::publish(), corrupting grammar mode and losingthinking_token_budget(helios/src/server/runtime.rs:2580-2614,:2350-2407,helios/src/scheduler.rs:1515, 1523-1542, 3121, 3267-3295)- Verified defect: When a growable request emits
</think>(or re-enters reasoning) on a frame withskipped == 0andpending == 0,RequestScheduler::complete_innerrunsself.refill_reservations()?(scheduler.rs:3121) before returninggeneratedtoWorker::complete. Under page pressure,preempt_newest()(scheduler.rs:1523-1542) can pick that request (pending == 0 && !paused_for_park && phase == Decode) and callfinish_early(handle, /*preempted=*/ true), settingpreempted = trueandphase = RequestPhase::Snapshot(withterminal_snapshot = Some(_)) orRequestPhase::Finishing. Worker::completethen clearsrequest.incoming.prompt.reasoning_cut = None(runtime.rs:2350), evaluatescan_toggle_live == false(because ofFinishing/terminal_snapshot), enterscheckpoint_parks, callsfinish_for_park(handle)?(scheduler.rs:3285, 3292returnsOk(())without clearingpreempted), and storesPendingGrammarPark { remaining (including cut.after), speculative_reasoning, drop_reasoning, waiting_for_drain: false }.- When
Worker::publish()runs (runtime.rs:2580-2583),self.park_if_preempted(slot)?executes before thepending_grammar_parkhandler at:2589-2614. Becauselive.preempted()istrue,park_if_preempted(runtime.rs:2801-2834) parks withgrammar_reasoning_mode: None,drop_reasoning: false, andremaining = max_new_tokens - live.generated_tokens, discardingPendingGrammarPark. On readmission, the request resumes in the wrong grammar/reasoning mode (e.g., still unmasked after</think>or still constrained after re-entry), retains dropped reasoning state, and permanently losescut.afterfromthinking_token_budget. - Fix: In
Worker::publish()(runtime.rs:2580-2614), check and handlepending_grammar_park.take_if(|park| !park.waiting_for_drain)(whenlive.phase == RequestPhase::Finishing && live.last_use() <= self.scheduler.completed()) beforeself.park_if_preempted(slot)?(or gatepark_if_preemptedonactive.pending_grammar_park.is_none()), and add a phase test exercising preemption during the samecomplete_innerstep as a grammar transition (withreasoning_cut.after > 0).
- Verified defect: When a growable request emits
-
try_with_gpu_codec_lockedblocks onCopyEngineGate::enter_offload_batchbeforetry_lock(), defeating non-blocking CPU restore fallback and burning two wave tokens (helios/src/offload/transfer/codec.rs:888-899,:605-629,:704-755;helios/src/offload/copy_gate.rs:173-195;helios/src/offload/transfer.rs:335-336)- Verified defect:
try_with_gpu_codec_locked(codec.rs:896-898) callsCopyEngineGate::enter_offload_batch—an unbounded blocking condvar wait (copy_gate.rs:175-194)—before callingcodec.try_lock(). Whenever a peer-copy graph is active (peer_graphs_active > 0) or queued behind an active background capture (peer_graphs_waiting > 0), a foreground restore blocks at:896for the full capture + peer-graph drain instead of returningNoneand decoding on the CPU pool in parallel. This directly contradicts the helper's doc comment (codec.rs:888-890) and breaks the critical-path CPU fallback; the new unit test (codec.rs:1719-1736) dropspeer_guardbefore callingtry_with_gpu_codec_locked, so it misses this case. - In addition, during
Turn::Offload, a contendedtry_with_gpu_codec_lockeddecrementsoffload_wave_remainingon entry (copy_gate.rs:187-191), failstry_lock(), drops_ce, and then the CPU fallback callscopy_spans_batch→GatedCopies::batch→enter_offload_batch()(transfer.rs:336) a second time, consuming two wave tokens for one run (or flippingTurn::Peerand blocking again). - Fix (deadlock-free): Do not simply swap
try_lock()ahead of blockingenter_offload_batch()—that would introduce a 3-way deadlock againstwith_gpu_codec_locked(captureholdsOffloadBatchGuardwaiting ongpu.codec;restoreholdsgpu.codecwaiting inenter_offload_batchonpeer_graphs_waiting;peer_graphsetspeer_graphs_waiting = 1waiting oncapture'sOffloadBatchGuardup to the 120 sPEER_GRAPH_GATE_TIMEOUT). Instead, add a non-blockingCopyEngineGate::try_enter_offload_batch(&self) -> Option<OffloadBatchGuard<'_>>that returnsNoneimmediately whenmust_wait(&state)is true (and avoids consuming anoffload_wave_remainingtoken if the caller bails ontry_lock), use it intry_with_gpu_codec_lockedbeforecodec.try_lock(), and add a test provingtry_with_gpu_codec_lockedreturnsNoneimmediately while aPeerGraphGuardis held.
- Verified defect:
-
zero_fill(u = 0.0) setsu_min = 0.0, permanently disablingupward_extrapolation_floorforGraphKind::Mixed(helios/src/scheduler/cost.rs:132-142, 347-385;docs/scheduling-runtime-design.md:475-479)- Verified defect:
upward_extrapolation_floor(cost.rs:132-142) requiresself.u_min > 0.0 && (self.u_max - self.u_min) < 0.15. However,PrefillCostModel::fit(cost.rs:368-373, 354-361) routesself.zero_fill.median()(u == 0.0) throughrecord_point, settingu_min = 0.0. Once any single decode-onlyMixedstep is observed,self.u_minstays0.0until TTL reset andupward_extrapolation_flooris permanently disabled—contradictingdocs/scheduling-runtime-design.md:475-479("when only a narrow positive fill regime (u_min > 0, spread< 0.15) has been observed"). - Concrete counterexample: On
Mixed(4, 1, 2048)post-TTL with decode-only15 ms(u = 0) and partial fillwork = 128(u = 0.0625,16 ms), NNLS fitstheta_0 = 15 ms, theta_1 = 16 ms;predict(2048, 0)returns31 msinstead of the4×floor64 ms(2.06× under-prediction of full-chunk cost). The new test atcost.rs:1854-1858only checks the post-TTL path without azero_fillsample. - Fix: Track positive-fill bounds (
pos_u_min,pos_u_max,pos_t_at_umax) overself.strataonly (cost.rs:374-385) and use them forupward_extrapolation_floor(and the narrow-regime check inconstant_nanosat:441-444), while keepingzero_fillinptsfor NNLS fitting andt_at_umin. Add a regression test asserting the4×floor still fires after observing bothzero_filland a narrow partial-fill sample.
- Verified defect:
-
Mandatory Layer 3 formal verification & mutation gates unmet for new scheduler lifecycle states and safety guards (
helios/src/scheduler.rs:267, 1433, 1449, 1531, 3234-3295;helios/src/scheduler/policy.rs:335;docs/design-review.md:226-251)- Verified gate violation: This PR adds a new live-request lifecycle state (
paused_for_park, excluding requests fromeligible, starvation detection, reservation refill, and preemption) and three guarded scheduler transitions (set_grammar_constrained,pause_for_park,finish_for_park, plusBoundaryKind::ConditionedWindowrejection andconsumed_tokens <= exact_lendrain checks).verification/has zero references to any of these states/transitions, and the PR explicitly listsverification/helios-lifecycle/check.py --mutationsas unrun. docs/design-review.md:226-251is explicit: modifying Helios scheduler lifecycle transitions without updating and running the applicable TLA+ models / Rust observed-edge conformance fixtures is a blocking design failure, new safety guards require--mutations(orcargo-mutants), and disclosing runnable CPU checks as unrun does not waive them. (Blocker 1 is a concrete example of the exact preemption × park lifecycle gap left uncovered.)- Fix: Extend the applicable TLA+ lifecycle/conformance suite (
verification/helios-lifecycle/) to coverpaused_for_park/pause_for_park/finish_for_park/set_grammar_constrained(including interaction with preemption/terminal snapshots), and runverification/helios-lifecycle/check.py --mutationscleanly.
- Verified gate violation: This PR adds a new live-request lifecycle state (
-
Performance-motivated changes and legacy-core behavior changes lack live served-workload A/B and previous-core serving verification (Charter
#210;docs/design-review.md:109-123)- Verified gate violation: All three buckets are performance-motivated ("eliminates 2K-32K KV and recurrent state wipes", GPU restore batching,
Mixedpricing), yet the PR explicitly reports "not benchmarked end-to-end here" and "No end-to-end exported-coreflare runlatency or throughput benchmark was run on this branch." Moreover, non-speculative models now packGrammarEnabled = 1during open reasoning and disable two-frame pipelining during reasoning, and existing speculative cores without per-stepGrammarEnabledbindings now runSnapshot+Restoreper transition—making live loading/serving on previously exported cores (docs/design-review.md:116-123) andflare runA/B measurements againstmain(docs/design-review.md:109-115, Charter#210) essential rather than optional. - Fix: Run and report a
flare runA/B benchmark overmainon an exported core exercising structured-output reasoning transitions (covering both in-place andSnapshot+Restorepaths on an existing core to substantiate both performance and Principle 13 compatibility).
- Verified gate violation: All three buckets are performance-motivated ("eliminates 2K-32K KV and recurrent state wipes", GPU restore batching,
Should Fix
-
Discontinuous
predict(0, 0)cliff down to1 ns/ microseconds whenu_min > 0and NNLS produces a tiny positivetheta[0](helios/src/scheduler/cost.rs:176-189,helios/src/scheduler/utility.rs:154-171,helios/src/scheduler/policy.rs:546-549)- When no
zero_fillsample has been observed (u_min > 0),predict(0, 0)checksif self.theta[0] > 0.0 && self.theta[0].is_finite() { self.theta[0] } else { self.t_at_umin }. If two positive-fill observations are barely sub-linear—e.g.,(u = 0.25, 20_000_000 ns)and(u = 1.0, 79_999_000 ns)(or79_999_999 ns)—exact NNLS solvestheta[0] = 333.33 ns(or0.33 ns, clamped to1 ns) with SSE0.0. Becausetheta[0] > 0.0,predict(0, 0)skipst_at_uminand returns333 ns(or1 ns), inflatingValueRate::new(utility.rs:155-165) by 60,000×–20,000,000× whileis_unmeasured_candidate(policy.rs:546-549) remainsfalse. - Fix: When no
zero_fillsample has been observed (has_zero_fill == false), either returnt_at_uminforwork == 0directly or clamptheta[0]against a lower bound derived fromt_at_uminrather than lettingtheta[0] > 0.0collapse toward1 ns.
- When no
-
Cache
sampling_graphs_bind_grammar_enabledonWorkerand enforce atomic scheduler-first ordering on in-place toggle (helios/src/server/runtime.rs:519-545, 2118-2120, 2364-2380, 2441-2454)sampling_graphs_bind_grammar_enabled(self.config)walks every prepared graph and every input binding on everyWorker::completecall even thoughself.configis immutable; compute and cachecan_toggle_grammar_in_place: boolonce inWorker::new.- In both in-place toggle arms (
runtime.rs:2372-2380and:2442-2448),incoming.grammar_reasoning_mode,request.reasoning, andadmissions[slot]are mutated beforeself.scheduler.set_grammar_constrained(...)?. Callself.scheduler.set_grammar_constrained(...)?first so an unexpected error cannot leave host and scheduler grammar state diverged.
-
Update stale present-state docs and confirm Layer 2 simulator validation for
Mixed(docs/prefix-cache-offload.md:96-100,docs/core-design.md(not opened),docs/mtp-design.md(not opened),docs/design-review.md:195-206)docs/prefix-cache-offload.md:96-100still describes GPU-codec CPU fallback without the newCopyEngineGateordering, anddocs/core-design.md(not opened) /docs/mtp-design.md(not opened) still describe#626's unconditionalcanceltransition; update them alongside the code and obtain@yatesdr's sign-off on reversing#628's lock-order invariant once Blocker 2 is fixed.- For Bucket 3 (
cost.rstiming estimation), runscripts/scheduling_sim/learning.py --preset validate(matching#645's precedent underdocs/design-review.md:195-206) or modelMixedstrata inscripts/scheduling_sim/.
Subtract / Simplify
- Unify the duplicated
mixed_candidatesscoring loops (helios/src/scheduler/policy.rs:1755-1868vs:1869-1947): Both branches perform the same slot scan, decoder cohort scoring, and decode-only + prompt-paired candidate emission; merging the constant and non-constant predictor branches deletes ~75 lines. - Deduplicate grammar-transition helpers and park state (
helios/src/server/runtime.rs:509-517, 2106-2114, 2352-2407, 2431-2481, 2523-2537):can_toggle_liveand the three-way toggle/park/rollback branch are duplicated across reasoning close and re-entry;GrammarTransitionandPendingGrammarParkduplicate the same five fields (exact_len, emitted, remaining, speculative_reasoning, drop_reasoning); andPendingGrammarPark.waiting_for_drainmirrorsLiveRequest.paused_for_park(scheduler.rs:267). Extracting one helper and one unified park struct removes ~60–80 lines and prevents branch drift. - Replace
Admission::{grammar_mask, grammar_enabled}with a 3-state enum (helios/src/model/admission.rs:66-69, 125-128,helios/src/model/packing.rs:803-805): Eliminates the unrepresentable(Some(mask), false)state thatgrammar_enabled || grammar_mask.is_some()currently papers over. - Drop redundant
routesVecand per-page clones inrestore_window(helios/src/offload/transfer/codec.rs:685-699, 713-714, 735-744, 762-770):pagesalready carriesrouteat index 1, and passing borrowed slices avoids 2–3 extra heap allocations per page on the foreground restore path. - Deduplicate
PrefillPredictor::predictclamping and unnamed 5-tuplemixed_context_slopes(helios/src/scheduler/cost.rs:176-205, 597-600, 871-936): Extract a sharedclamp_nanos(f64) -> u64helper and a namedContextSlopestruct to replace positional.2tuple indexing.
Nits
- Consider splitting these three disjoint Helios subsystems (grammar transitions, KV codec batching/locking,
Mixedcost stratification) into separate PRs so each can be benchmarked, reviewed by its area owner (@yatesdrfor codec/gate), and merged cleanly around open#715(cost.rsconflict). - Link
#530and predecessor PRs#626,#628, and#645in the PR description, and clarify that the seconddocs/scheduling-runtime-design.mdhunk reflects already-merged#697/#655work from the base rather than new#729behavior. - Extract a single
transform_nsnon-Literalaccounting helper acrossdecode_pages_cpu_batch(codec.rs:569-574) andrestore_single_unit(codec.rs:643-645).
Dropped on verification
- Upstream Code Audit Finding 4 ("caller and callee
Snapshotpredicates disagree atruntime.rs:2357-2362vsscheduler.rs:3240-3247"): False—the upstream audit invertedscheduler.rs:3242's rejection predicate (if ... || (phase == Snapshot && boundary_capture.is_none()) { return Err(...); }). Both caller and callee acceptSnapshot && boundary_capture.is_some()and rejectSnapshot && terminal_snapshot.is_some(), andscheduler.rs:3089-3114ensuresSnapshotalways holds one of the two. Only the defensive call-ordering cleanup was retained in Should Fix 2. - Upstream Code Audit Finding 1's naive fix ("call
codec.try_lock()beforeCopyEngineGate::enter_offload_batch()"): Unsafe—would create a 3-way deadlock withwith_gpu_codec_locked+enter_peer_graph(). Replaced with the deadlock-freeCopyEngineGate::try_enter_offload_batch()fix in Blocker 2. - Upstream Code Audit Finding 3's counterexample detail ("
predict(2048, 0)returns1 ns"): Inaccurate—for(100, u=0.25)and(399, u=1.0),predict(2048, 0)returns399; it ispredict(0, 0)(work == 0,cost.rs:176-189) that collapses to1 ns/ µs. Reframed accurately in Should Fix 1. - Upstream Contracts Audit Gate 4 nit ("
delivery_referencesnot updated as claimed"): False—delivery_references(service.rs:59-64) delegates directly todelivery_references_and_decode_batch, which was updated atservice.rs:235to callmixed_duration(batch, width, prefill, 0, 0). - Upstream Subtraction Audit A8 (
Admission::from_prompt/validatetest-only shims) & C5 (mixed_entryOption<Option<_>>): Dropped—from_prompt/validateare pre-existing compatibility wrappers, andOption<Option<PrefillPredictor>>intentionally mirrorsprefill_entry(cost.rs:707-735) to distinguish absent vs unmeasured shapes. - Stale-base diff hunks (
checkpoints.rs(not opened),server/request.rs(not opened),RowRestoreLatency,preserve_message_anchor,snapshot_discovery,device_spansnull-row guard) & Kani / pending CI: Confirmed excluded—the hunks belong to already-merged#655/#659/#660/#674/#697/#709, Kani-covered validators were not modified, and pending CI is not a failure.