Recommendation: Changes Requested
The core mechanism is well-architected and cleanly placed in Helios: running host-validated unmasked reasoning with deferred bitmask sync and reusing the existing cancel → Restore → Prefill transition path lifts width-1 and feedback-barrier bottlenecks during open reasoning without ABI, protobuf, CUDA-graph, or per-model changes. However, head f7907a2 currently has an unexplained CI failure and lacks the live served-workload GPU benchmark evidence required by the charter (#210) and docs/design-review.md (Principle 12) to verify both real cache-scheme reconstruction and that speculative reasoning gains outweigh the O(R) boundary re-prefill and window-drain overhead. Before merge, CI should be green, served-workload numbers vs main should be added, the deferred-mask guard should be enforced in release builds, the untested try_consume_tokens == 0 rollback path should be covered by tests, and the three contradicting doc statements should be reconciled.
Merge Risk
Level: Medium
- Hot-path request lifecycle change: Every grammar-constrained request starting in open reasoning (
OutputStart::Reasoning) or recipient/content headers (Atem,TmlJson) now automatically executes speculative decode with two frames in flight and transitions viacancel+Restore+Prefillat the reasoning boundary (helios/src/server/runtime.rs:253-286, 1898-2165). There is no opt-out flag if a workload regresses. - Unmeasured transition & bystander cost: Every boundary transition re-prefills
Rreasoning tokens since the prompt-end checkpoint (runtime.rs:2407-2449), andGraphKind::Prefilldrains the two-frame executor window (helios/src/scheduler.rs:1085-1094), momentarily revoking pipelining for co-batched unconstrained requests. Multi-block reasoning inAtem/TmlJsonpays this transition on each block. - Unverified GPU / cache-scheme coverage: All new tests exercise CPU fixture graphs in
--release; 83 checkpoint/GPU-gated tests and live serving on real recurrent/hybrid/KV cache schemes have not been run yet.
Walkthrough
helios/src/grammar.rs(+156/−0): Addsmask_dirty,RequestGrammar::try_advance_unmasked(token)(host-side validation viallguidance::Matcher::try_consume_tokenswithout runningcompute_mask_or_eos()), andRequestGrammar::sync_mask()to recompute the bitmask lazily at transition/budget boundaries, plusunmasked_advancement_matches_masked_decisions_and_defers_mask_sync.helios/src/server/request.rs(+20/−0) &helios/src/model/admission.rs(+4/−4): PopulatesPrompt::grammar_reasoninginprepare_inferencefor eligibleOutputStart::Reasoningand recipient-envelope (RecipientHeader/RecipientFrame) grammar requests, and gatesAdmission::grammar_maskon an explicitgrammar_constrained: boolso speculative-reasoning admissions emitGrammarEnabled = 0.helios/src/server/runtime.rs(+327/−19): SetsRequestSpec::grammar_constrained = falsewhileIncoming::speculative_grammar_reasoning()is active, buildsActive.reasoningfor eligible grammar requests, validates burst tokens in order inWorker::complete(), suppresses trailing overshoot on reasoning close or forbidden token, syncs the deferred mask, and cancels/parks the truncated prefix viapark_grammar_transition/park_with_tokens. AddsAtem/TmlJsonre-entry (allow_reasoning_reentry),thinking_token_budgetintegration (let_publish_cut,cut.aftermerge, pre-checksync_mask()), and preemption mode preservation.helios/src/server/runtime/phase_tests.rs(+863/−4) &prompt_tests.rs(+1/−1): Adds 6 isolated worker-phase unit tests covering pipelined reasoning + overshoot truncation, premature-EOS rollback (mid-burst and token 0), thinking-budget + logprobs, preemption &OutputStart::Content,TmlJsonheader re-entry, andprepare_inferenceeligibility; updatesreasoning_budget_does_not_inject_a_close_inside_a_tool_callfortool_ends_reasoning.docs/api.md,docs/core-design.md,docs/mtp-design.md: Updates grammar-constrained decoding and speculative-execution sections for host-validated speculative reasoning and boundary transition behavior.
Pre-merge Checks
- [PASS] Security / malicious screen: No unsafe code, no dependency or ABI/wire changes, no prompt-injection or unexpected network/exfiltration paths.
- [WARN] Charter & value fit: Clean model-agnostic Helios placement and complete 4-part PR description, but missing live served-workload GPU benchmarks vs
mainrequired by the charter (#210) anddocs/design-review.mdPrinciple 12 (and note that #530'senable_thinking: falseOutputStart::Contentworkload remains on the unchanged device-constrained path). - [PASS] Related / duplicate / conflict check: Builds cleanly on #615, #619, and #620 (
c146d7b); no conflictingmaincommits or competing PRs. - [WARN] Tests & verification evidence: CI on head
f7907a2is currently failing (unexplained), 83 checkpoint/GPU tests were ignored,try_consume_tokens == 0rollback is not exercised by any test, anddebug_assert!(!self.mask_dirty)is compiled out of all--releasetest runs.
Blockers
- Unreconciled CI failure on head
f7907a2and missing live GPU serving benchmarks (Charter #210,docs/design-review.mdPrinciple 12):- Verified behavior/impact: CI failed on
f7907a2with no explanation in the PR description. In addition, this is a performance PR whose net speedup depends on speculative decode gains during reasoning outstrippingO(R)re-prefill at the boundary (helios/src/server/runtime.rs:2407-2449) plus the single-frame window drain during that re-prefill (helios/src/scheduler.rs:1085-1094). All cited tests ran on CPU fixture graphs withR <= 3, and 83 checkpoint/GPU-gated tests were skipped. - Concrete fix: Resolve or explain the failing CI check(s) on
f7907a2so required workflows (includinghelios-lifecycle/kaniandnative-serving) are green, and add served-workload GPU A/B measurements againstmain(covering short and long reasoning traces, mixed constrained/unconstrained batches, and real cache-scheme state reconstruction across the boundary).
- Verified behavior/impact: CI failed on
Should Fix
- Enforce the deferred-mask invariant in release builds (
helios/src/grammar.rs:677-692):RequestGrammar::mask()andallows()only guardself.mask_dirtywithdebug_assert!(!self.mask_dirty, ...). All CI workflows (.github/workflows/native-serving.yml(not opened)) and all locally reported suites run--release, wheredebug_assert!is compiled out—so any future path reading a deferred mask silently returns a stale pre-reasoning bitmask and bypasses grammar enforcement.- Fix: Replace
debug_assert!with a runtimeassert!(!self.mask_dirty, ...)(the cost is one predicted boolean check on an already-infrequent path), or makesync_mask(&mut self) -> Result<&[i32]>the sole way to obtain a synced mask after unmasked advancement.
- Cover the
try_consume_tokensrejection (consumed == 0) path with tests (helios/src/grammar.rs:753-755, 1894-1919,helios/src/server/runtime/phase_tests.rs:7350, 7458-7595):- Every rejected-token test currently exits via the early returns at
grammar.rs:722-737(premature EOS, OOV ID>= tokenizer_vocab, orself.stopped). Inspeculative_grammar_reasoning_runs_pipelined_and_transitions_on_close_with_overshoot, invalid overshoot token4("x") is skipped atruntime.rs:1889-1892beforetry_advance_unmaskedis called. Thusconsumed == 0—including the PR description's claimed "invalid merged boundary tokens" rollback—is never executed by any test. - Fix: Add a grammar unit test and a runtime rollback test feeding an in-vocabulary, non-EOS forbidden token (e.g., a merged boundary token like
"</think>x"or an illegal post-close/grammar-forbidden token) totry_advance_unmasked, verifyingOk(false), unchanged parser state, cleansync_mask(), and legal device-constrained continuation.
- Every rejected-token test currently exits via the early returns at
- Reconcile contradicting docs and clarify constrained-metric scope (
docs/core-design.md:1242-1248,docs/scheduling-runtime-design.md:548-552,helios/model-contract.md:236-238, 436-441):docs/core-design.md:1242-1248still states that "While any constrained request is in the decode batch, the loop runs one step in flight", directly contradicting the updated paragraph atdocs/core-design.md:1697-1707in the same file.docs/scheduling-runtime-design.md:550andhelios/model-contract.md:236-238likewise still listgrammarunconditionally as requiring completion feedback.helios/src/server/runtime.rs:3266-3279counts onlyscheduler.request(lane.request)?.grammar_constrainedlanes towardflare_constrained_max_inflightandflare_mixed_grammar_decode_steps_total(which is required soflare_constrained_max_inflight <= 1remains valid), sohelios/model-contract.md:436-441should specify that both metrics track device-masked grammar submissions rather than host-validated speculative reasoning.
Subtract / Simplify
- Deduplicate the five grammar-failure error blocks (
helios/src/server/runtime.rs:1909-1919, 1930-1939, 1986-1996, 2098-2108, 2220-2233): Four sites repeat the exact same 10-lineExecutionError::Completion(Failure::caused_by(...))+stopped.pushblock, and the fifth (2220-2233) repeats the same error constructor (as doesclose_reasoningat:501-506). Extract a small helper to build the error and remove ~40 lines of boilerplate. - Collapse duplicated
Decoder::newconstruction (helios/src/server/runtime.rs:1639-1660): Both branches construct the identicalsuper::output::Decoder::new(self.frontend, &self.config.eos_token_ids, Some(...)); compute theOption<OutputConfig>once viacut.output.take().or_else(|| incoming.prompt.grammar_reasoning.clone())and map once. - Simplify combinator chains (
helios/src/server/request.rs:408-426,helios/src/model/admission.rs:113-125): Replacebool.then(|| opt.filter(...)).flatten()with plainif grammar.is_some()/opt.filter(|_| grammar_constrained). Consider a small typed enum or struct field instead of two adjacentboolparameters (ignore_eos, grammar_constrained) onAdmission::from_prompt. - Remove 7-argument
park_with_tokens+ forwarding wrapper (helios/src/server/runtime.rs:2407-2440): Passing a small transition/park options struct intopark_with_tokenseliminates both#[allow(clippy::too_many_arguments)]and the 6-parameterpark_grammar_transitionforwarding wrapper.
Nits
- Consider noting in the PR description that: (a) boundary parking reseeds via
continuation_seed(seed, generated_tokens)(helios/src/server/runtime.rs:2469-2471), so seeded grammar-constrained thinking requests will produce different token streams than onmain(while remaining deterministic for a given boundary token count); and (b) worker-sideActive.reasoningdecoding now runs per accepted token for all eligible grammar requests (and stays active past reasoning close forAtem/TmlJsonre-entry).
Dropped on verification
- Correctness F1 ("escalates draft mismatch to 500" / "clone matcher per token"): Dropped.
llguidance::Matcher::try_consume_tokensreturnsOk(0)on grammar-rejected tokens andErronly on internal engine errors (matching existingTextGrammar::validateathelios/src/grammar.rs:648-655); cloningMatcherper token would be an unnecessary regression. Kept only the verified test-coverage gap onconsumed == 0. - Correctness F2 sub-suggestion ("publish boundary checkpoint via
finish()instead ofcancel()on ordinary reasoning close"): Dropped. On speculative overshoot (skipped > 0) or with a second pipelined frame already in flight on the GPU, the live slot's KV and non-invertible recurrent state have already advanced pastexact_len, so snapshotting that slot would corrupt prefix state. - Correctness F3 ("
drop_reasoningsilently disablesthinking_token_budgetfor non-Atem/TmlJson parsers"): Dropped as false.helios/src/server/runtime.rs:2078-2083callsrequest.incoming.prompt.reasoning_cut.take()and mergescut.afterintoremainingbefore settingdrop_reasoningat:2109, soreasoning_cutis alreadyNonewheneverdrop_reasoning == true(anddrop_reasoningisfalseon forbidden-token rollback at:1953). - Correctness F5a ("new reachable terminal 500 path at
runtime.rs:1955-1961" and "?in transition loop aborts frame"): Dropped.helios/src/scheduler.rs:2571, 2579enforcesgenerated_tokens <= max_new_tokensandconsumed_tokens <= max_sequence_tokens; sinceskipped = burst_counts[slot] - position >= 1on any rejected token,remaining >= 1andexact_len < max_sequence_tokensalways hold under scheduler invariants, making:1955-1961an unreachable defensive fallback. Likewise,?atruntime.rs:2156-2165matches the fatal worker-invariant convention ofself.retire(&stopped)?right above it (runtime.rs:1198, 2155). - Correctness F5b sub-claim ("reseed depends on how much overshoot was discarded"): Dropped as false.
generated_tokenspassed tocontinuation_seed(runtime.rs:2470-2471) usesemitted(exact accepted tokens), independent of discarded overshoot. - Dossier stale-doc claim on
docs/mtp-design.md:597-599: Dropped. Line 598 says "Unsupported speculative grammar or custom-stop cases exercise the declared one-token path", which does not contradict the PR. - Subtraction #2 ("burst arithmetic
positionvspositions[slot]already diverged"): Dropped as false. Atruntime.rs:1941(rejection), the current token atpositionwas not emitted, soburst_counts[slot] - positiontokens are skipped; at:2038, :2068, :2133(stop/close/re-entry), the current token was emitted, soburst_counts[slot] - positions[slot](position + 1) tokens are skipped. Both are exact. - Subtraction #4 ("tri-state
grammar_reasoning_mode: Option<bool>is unnecessary"): Dropped.Incoming::spec()runs beforeActiveexists (runtime.rs:1514), and test fixtures mutateincoming.prompt.grammar_reasoningafter constructingIncoming(phase_tests.rs:7310-7312), makingNone-derives-from-prompt practical and intentional. - Subtraction #5 ("dead conjunct
self.prompt.grammar.is_some()inallow_reasoning_reentry"): Dropped as low-signal defensive guard. - Subtraction #6 sub-suggestion ("derive
grammar_constrainedinsideAdmission::from_prompt"): Dropped as infeasible—grammar_reasoning_mode: Option<bool>lives onIncoming, notPrompt. - Subtraction #7 sub-suggestions ("move
sync_mask()intopark_with_tokens" and "gateActive.reasoningonreasoning_cut.is_some() || grammar_reasoning.is_some()"): Dropped. Movingsync_mask()intopark_with_tokenswould turn a per-request grammar failure into a worker-fatal?error (runtime.rs:1198), andActive.reasoningis already gated onreasoning_cutorgrammar_reasoning(runtime.rs:1639-1660).