PR #626: Allow speculative reasoning for grammar-constrained requests

Raw Markdown for agents: https://autobot.eidonix.com/api/v1/cases/cd864767-6075-4f51-92dd-e87f3e0446dc

Opened by a workflow run, Nov 29, 2026 9:09 PM EST. decide malicious: all_clear (100%): No malicious content found

explore

Author: lukealonso (COLLABORATOR; named priority contributor in the charter; dominant committer in helios/src and docs; Discord: lukealonso in the PR) Motivation: Grammar-constrained requests (JSON schemas, Lark grammars, strict tools) had to decode one token at a time with a mask uploaded every step, which also stalled every other request in the same batch. This PR validates the open reasoning phase on the host instead, so thinking models can speculate at full width during their reasoning trace and only switch back to device masks at the reasoning boundary. Scale: +1405 / −39 in 9 files Proposal:

Full report · Notes

Value Proposition

Value Proposition — PR #626 "Allow speculative reasoning for grammar-constrained requests"

1. Charter alignment — mostly aligned, one clear violation

Placed correctly: the change lives in Helios (scheduling/grammar), not in recipes; no model-name branch, no user-facing flag; eligibility is derived from envelope shape and ToolParserKind (request.rs:408-426). That matches "keep the runtime small and model-agnostic" and "no per-model special cases," and it deliberately avoids per-model rollback kernels. The description carries all four required parts (why / what changed / claimed result / evidence) plus an honest "Unrun checks" list.

The violation is the evidence rule (#210): performance PRs need a measured speedup over main on a served workload. The PR states the gain is "expected … not measured on a live GPU." Its correctness claim — Restore + chunked Prefill reconstructing exact KV and non-invertible recurrent state "across every supported cache scheme" — rests only on CPU fixture-graph tests; 83 checkpoint/GPU-gated tests were not run, and CI on head f7907a2 failed with no explanation (the gap flagged on #619).

2. Novelty & status — genuinely additive

Nothing on main since c146d7b touches these files, so it is not obsolete. #619 (merged 2026-11-29) explicitly declined to fix this, listing grammar-constrained requests as remaining on width-1 and the single-frame barrier; #418/#417 instead ratified and measured the whole-generation rule this PR narrows. No duplicate issue or competing PR exists; #530 is open and unanswered.

3. Value vs maintenance cost

Beneficiaries are concrete: json_schema/json_object, Lark-grammar, and strict-tool clients against reasoning-first or content-header (Atem/TmlJson/DSML) models. But #530's own measurement used enable_thinking: false, which starts in OutputStart::Content and therefore stays device-constrained under this PR's eligibility rule (phase_tests.rs:8037-8068); the most-cited workload does not benefit in its constrained phase.

Undisclosed costs: an always-on Active.reasoning decoder running per accepted token; a new terminal ExecutionError::Completion failure impossible on main; same request + seed now yields different tokens; an unexercised debug_assert!(!self.mask_dirty) (all cited suites ran --release); and four doc statements left contradicting the rewritten ones.

Verdict: Worth it with changes. Merge after (a) served-workload numbers vs main plus the expected effect on #530, (b) green CI or a root cause, (c) resolution of the always-on decoder cost and the mask_dirty assertion in a debug build, (d) reconciliation of core-design.md:1242-1248, scheduling-runtime-design.md:548-552, model-contract.md:236-238, mtp-design.md:597-599, (e) a documented client-facing story for the new failure mode and seed change.

Full report Decide Value: yes (99%): This change is worth reviewing: it provides value to the project in line with its charter.

Classify intake

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

Threshold: 65%

Triage

Priority

Type

Area

Model

Apply Labels (Intake)

Applied: +triage:review, +performance, +enhancement, +area:scheduling

Subtraction and simplicity

Verdict: PR #626's mechanism is lean — no dead code, no speculative generality, no new flag (eligibility derived from envelope shape, request.rs:408-426). Nothing blocking from this lens. All findings are local, removable inline complexity.

  1. Five verbatim grammar-failure blocks (~50 lines) at runtime.rs:1909-1919, 1930-1939, 1986-1996, 2098-2108, 2220-2233 → one helper; the existing shape is Active::close_reasoning (runtime.rs:499-506).
  2. One burst expression copied 3x and already diverged: position as u32 (:1941) vs positions[slot] as u32 (:2068, :2133), where positions[slot] == position + 1 (:1888). Duplication created the divergence; extract one helper and let the correctness lens pick the value.
  3. The policy paragraph is written 3x (docs/api.md:647-655, docs/core-design.md:1697-1707, docs/mtp-design.md +15/−2) while four sibling statements keep the superseded rule (core-design.md:1242-1248, scheduling-runtime-design.md:548-552 (not opened), model-contract.md:236-238 (not opened), mtp-design.md:597-599). One canonical paragraph + links is the repo's own pattern (api.md already links to core-design.md#native-replay-loop).
  4. Tri-state grammar_reasoning_mode: Option<bool> (runtime.rs:211-218, 253-260) where None only means "derive from prompt" → initialise eagerly, field becomes bool, unwrap_or_else disappears, and park_with_tokens:2459-2461 becomes a plain assignment.
  5. Dead conjunct self.prompt.grammar.is_some() && in allow_reasoning_reentry (runtime.rs:262-263) — grammar_reasoning is only Some when a grammar exists.
  6. Combinator bloat: request.rs:408-426 (.then(…).flatten() for two conditions) and admission.rs:123-125 (bool.then(…).flatten()) → Option::filter/plain control flow; plus two adjacent unnamed bools in from_prompt (ignore_eos, grammar_constrained).
  7. Decoder::new written twice (runtime.rs:1639-1660); GrammarTransition.speculative_reasoning is false at 2 of 3 sites feeding a 6-param wrapper over a 7-param #[allow(clippy::too_many_arguments)] fn for 2 callers. Convention: debug_assert! at grammar.rs:677-692 is unreachable — every workflow and every cited suite is --release (AGENTS.md:309-320, 188-193); make mask_dirty a real invariant or delete it, and fold two of the five sync_mask() calls into the park boundary. Fairness: enable_speculative_worker (phase_tests.rs:7290-7298) and speculative_burst_frame (:7257-7288) are correct consolidations.

Open: which skipped value is intended; canonical-docs home vs follow-up; whether the always-on Active.reasoning decoder is accepted; exact mtp-design.md line range of the third copy (not re-verified — its wording differs, phrase search missed it).

Full report · Notes

Correctness and contracts

Reviewed PR #626 (allow speculative reasoning for grammar-constrained requests) at head f7907a2 for correctness, contracts and system-level consequences.

The mechanism is sound: grammar_constrained=false during speculative reasoning correctly lifts the width clamp and feedback barrier, admission gates grammar_mask on the new flag (packing emits GrammarEnabled=0), advance() syncs a dirty mask first, preemption preserves the mode, readmission arithmetic preserves budgets, and no protobuf/kernel/graph/core contract changed.

Problems are on the reasoning→answer boundary:

  1. Major — try_advance_unmasked only rolls back on Ok(0); any Err poisons the parser (grammar.rs:744-755) and Worker::complete turns it into ExecutionError::Completion (runtime.rs:1909-1919). Device masking on main made such a sample unreachable. Overshoot tokens are never validated (runtime.rs:1889-1892) and no test uses an in-vocabulary non-EOS forbidden token.
  2. Major — park_grammar_transition cancels and readmits from the prompt-end checkpoint only (runtime.rs:2407-2428, :2445-2449), so R reasoning tokens are re-prefilled; tests only ever re-prefill 1 token (phase_tests.rs:7388-7390). Prefill drains the window (scheduling-runtime-design.md:548-552), so co-batched unconstrained requests lose pipelining during the transition. Disclosed but unmeasured (charter #210).
  3. Major — drop_reasoning = !allow_reasoning_reentry() (runtime.rs:2109, :2451-2453) nulls Active.reasoning, disabling thinking_token_budget force-close (:2239-2240) for every parser except Atem/TmlJson; untested.
  4. Minor/Major — flare_constrained_max_inflight now excludes grammar-attached reasoning lanes (runtime.rs:3266-3273, :281-282), making the model-contract.md:436-441 "must remain one" invariant vacuous; core-design.md:1242-1248, scheduling-runtime-design.md:548-552, model-contract.md:236-238 still contradict the rewritten text.
  5. Minor — every transition reseeds (runtime.rs:2469-2471), so fixed-seed output differs from main; new undocumented "no remaining output capacity" error (:1955-1961); ? on the transition loop aborts the frame for all lanes (:2156-2165); new debug_assert!(!mask_dirty) never runs because all cited tests are --release.

Process: no live-GPU measurement, #530 never cited though its measured workload stays in the unchanged constrained phase, and CI failed on head unexplained.

Open: does llguidance return Err for forbidden in-vocab tokens; is a mid-generation close reachable on non-Atem/TmlJson parsers; should the transition publish a checkpoint instead of re-prefilling.

Full report · Notes

Final review

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

Walkthrough

Pre-merge Checks

Blockers

  1. Unreconciled CI failure on head f7907a2 and missing live GPU serving benchmarks (Charter #210, docs/design-review.md Principle 12):
    • Verified behavior/impact: CI failed on f7907a2 with no explanation in the PR description. In addition, this is a performance PR whose net speedup depends on speculative decode gains during reasoning outstripping O(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 with R <= 3, and 83 checkpoint/GPU-gated tests were skipped.
    • Concrete fix: Resolve or explain the failing CI check(s) on f7907a2 so required workflows (including helios-lifecycle / kani and native-serving) are green, and add served-workload GPU A/B measurements against main (covering short and long reasoning traces, mixed constrained/unconstrained batches, and real cache-scheme state reconstruction across the boundary).

Should Fix

  1. Enforce the deferred-mask invariant in release builds (helios/src/grammar.rs:677-692):
    • RequestGrammar::mask() and allows() only guard self.mask_dirty with debug_assert!(!self.mask_dirty, ...). All CI workflows (.github/workflows/native-serving.yml (not opened)) and all locally reported suites run --release, where debug_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 runtime assert!(!self.mask_dirty, ...) (the cost is one predicted boolean check on an already-infrequent path), or make sync_mask(&mut self) -> Result<&[i32]> the sole way to obtain a synced mask after unmasked advancement.
  2. Cover the try_consume_tokens rejection (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, or self.stopped). In speculative_grammar_reasoning_runs_pipelined_and_transitions_on_close_with_overshoot, invalid overshoot token 4 ("x") is skipped at runtime.rs:1889-1892 before try_advance_unmasked is called. Thus consumed == 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) to try_advance_unmasked, verifying Ok(false), unchanged parser state, clean sync_mask(), and legal device-constrained continuation.
  3. 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-1248 still states that "While any constrained request is in the decode batch, the loop runs one step in flight", directly contradicting the updated paragraph at docs/core-design.md:1697-1707 in the same file. docs/scheduling-runtime-design.md:550 and helios/model-contract.md:236-238 likewise still list grammar unconditionally as requiring completion feedback.
    • helios/src/server/runtime.rs:3266-3279 counts only scheduler.request(lane.request)?.grammar_constrained lanes toward flare_constrained_max_inflight and flare_mixed_grammar_decode_steps_total (which is required so flare_constrained_max_inflight <= 1 remains valid), so helios/model-contract.md:436-441 should specify that both metrics track device-masked grammar submissions rather than host-validated speculative reasoning.

Subtract / Simplify

  1. 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-line ExecutionError::Completion(Failure::caused_by(...)) + stopped.push block, and the fifth (2220-2233) repeats the same error constructor (as does close_reasoning at :501-506). Extract a small helper to build the error and remove ~40 lines of boilerplate.
  2. Collapse duplicated Decoder::new construction (helios/src/server/runtime.rs:1639-1660): Both branches construct the identical super::output::Decoder::new(self.frontend, &self.config.eos_token_ids, Some(...)); compute the Option<OutputConfig> once via cut.output.take().or_else(|| incoming.prompt.grammar_reasoning.clone()) and map once.
  3. Simplify combinator chains (helios/src/server/request.rs:408-426, helios/src/model/admission.rs:113-125): Replace bool.then(|| opt.filter(...)).flatten() with plain if grammar.is_some() / opt.filter(|_| grammar_constrained). Consider a small typed enum or struct field instead of two adjacent bool parameters (ignore_eos, grammar_constrained) on Admission::from_prompt.
  4. Remove 7-argument park_with_tokens + forwarding wrapper (helios/src/server/runtime.rs:2407-2440): Passing a small transition/park options struct into park_with_tokens eliminates both #[allow(clippy::too_many_arguments)] and the 6-parameter park_grammar_transition forwarding wrapper.

Nits

Dropped on verification

Full report Decision to Test: no (98%): 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: (none)

Threshold: 65%

Triage

Apply labels

No label changes