Correctness, Contracts & System-Level Consequences review — PR #626 (head f7907a2)
Key findings
The core mechanism is sound and internally coherent: Incoming::spec() sets grammar_constrained = false for eligible reasoning requests, which correctly lifts both the width clamp and the step-level feedback barrier; Admission::from_prompt gates grammar_mask on the new flag and packing emits GrammarEnabled = 0; advance() syncs a dirty mask first; preemption preserves the mode; no protobuf / kernel ABI / CUDA-graph / core-format change. I found no defect that makes the speculative reasoning phase itself incorrect.
The problems are all on the boundary path — leaving speculative reasoning — and in what the change does to a live server and to documented guarantees:
- Major — the unmasked path escalates a draft mismatch into a terminal 500.
try_advance_unmaskedonly returns the documented non-destructiveOk(false)when llguidance yieldsOk(0); anyErrpoisons the parser viafail()(helios/src/grammar.rs:744-755), andWorker::complete()turns that intoExecutionError::Completionfor the whole request (helios/src/server/runtime.rs:1909-1919). Device masking onmaincould never sample such a token. Neither cited test exercises an in-vocabulary, non-EOS forbidden token — the overshoot tokens in the pipelining test are never validated at all. - Major — every reasoning→answer transition re-prefills the entire reasoning trace and drains the frame window.
park_grammar_transitionusesscheduler.canceland readmits the full prefix from the prompt-end checkpoint only (runtime.rs:2407-2428,:2445-2449), so R reasoning tokens are recomputed withRestore+ chunkedPrefill. The tests only ever re-prefill one token (phase_tests.rs:7388-7390). Prefill is single-frame, so for its duration co-batched unconstrained requests lose exactly the pipelining the PR sells. Disclosed qualitatively, but neither side is measured (charter #210). - Major —
drop_reasoningdiscards the budget decoder for every parser except Atem/TmlJson, after which thethinking_token_budgetforce-close block can never fire (runtime.rs:2109,:2451-2453,:2239-2240). Untested. Eligibility and re-entry are also broader than described: any reasoning re-open in an Atem/TmlJson envelope re-enters speculative mode, each paying finding 2. - Minor/Major — the new path is silent:
flare_constrained_max_inflight/flare_mixed_grammar_decode_steps_totalno longer cover grammar-attached reasoning lanes, making themodel-contract.md:436-441invariant ("must remain one") vacuous for the requests it exists to watch, and three sibling doc statements (core-design.md:1242-1248,scheduling-runtime-design.md:548-552,model-contract.md:236-238) still contradict the rewritten text. - Minor — undisclosed behavioural change and untested guard. Every transition reseeds via
continuation_seed, so identical request+seed now yields a different, burst-boundary-dependent token stream thanmain; a new undocumented terminal error ("grammar rejected token with no remaining output capacity") appears; the newdebug_assert!(!mask_dirty)guards are compiled out of every cited--releaserun;?on the transition loop aborts the frame for all lanes. - Process. No live-GPU measurement (the PR says so itself) against a charter that requires it; #530 is never cited and its measured workload (
enable_thinking:false,OutputStart::Content) is entirely inside the unchanged device-constrained phase; CI failed on head, unexplained.
1. Correctness, safety & error handling
F1 (Major) — Err from try_consume_tokens poisons the parser and 500s a request that device masking would have kept healthy
helios/src/grammar.rs:715-722 documents the contract:
/// Validates and consumes a token generated without device mask enforcement.
/// Returns `Ok(false)` without modifying parser state when the token is
/// forbidden; defers full vocabulary mask computation until `sync_mask`.
pub fn try_advance_unmasked(&mut self, token: u32) -> Result<bool> {
if let Some(error) = &self.error {
return Err(error.clone());
}
but the implementation (helios/src/grammar.rs:744-755) only reaches the rollback branch on Ok(0):
let consumed = match self.matcher.try_consume_tokens(&[token]) {
Ok(consumed) => consumed,
Err(error) => {
return self.fail(Error::Admission(AdmissionError::Grammar(Failure::boxed(
format!("grammar advancement failed: {error:#}"),
error.into_boxed_dyn_error(),
))));
}
};
if consumed == 0 {
return Ok(false);
}
fail() sets self.error irrecoverably, and the caller (helios/src/server/runtime.rs:1900-1919) converts it into a terminal failure:
let allowed = match request
.incoming
.prompt
.grammar
.as_mut()
.unwrap()
.try_advance_unmasked(token.token)
{
Ok(allowed) => allowed,
Err(error) => {
request.incoming.fail(
ExecutionError::Completion(Failure::caused_by(
format!("grammar advancement failed: {error}"),
error,
)).into(),
);
Impact: a speculative draft that is in-vocabulary and grammar-forbidden but that llguidance reports as an error (rather than Ok(0)) terminates the client's request with a 500 / terminal SSE error event. On main the device mask made such a sample unreachable. This is the sole recovery mechanism the design relies on, and its failure mode is a client-visible failure, not a rollback.
Test gap (verified): the grammar-level test unmasked_advancement_matches_masked_decisions_and_defers_mask_sync only feeds EOS ids, tokenizer_vocab, model_vocab-1 and a post-stop b'a'; the runtime test speculative_grammar_reasoning_rolls_back_forbidden_token_including_premature_eos (phase_tests.rs:7458) uses premature EOS only. In speculative_grammar_reasoning_runs_pipelined_and_transitions_on_close_with_overshoot the forbidden overshoot token 4 is never validated because the burst is skipped once a transition is queued (runtime.rs:1889-1892):
if stopped.contains(&token.request)
|| transitions.iter().any(|t| t.handle == token.request)
{
continue;
}
Fix: treat Err as a rollback — clone the matcher before the attempt (or validate against the freshly synced mask) so a rejected token leaves parser state at the last accepted prefix and can transition to device-constrained decoding, rather than failing the request. Add a test with an in-vocabulary, non-EOS, grammar-forbidden token mid-burst.
F5a (Minor) — new terminal error path, and ? on the transition loop aborts the whole frame
helios/src/server/runtime.rs:1955-1961:
} else {
request.incoming.fail(Error::execution(
ExecutionError::Completion,
"grammar rejected token with no remaining output capacity",
));
stopped.push(token.request);
}
Reachable when remaining == 0 or exact_len >= limits.max_sequence_tokens at the moment of rejection. On main the device mask prevented the sample entirely, so this is a new 500 path (helios/model-contract.md:425-431 only describes generic 500s) with no documented client-facing behaviour and no test.
Then helios/src/server/runtime.rs:2156-2165:
self.retire(&stopped)?;
for transition in transitions {
self.park_grammar_transition(
transition.slot,
transition.exact_len,
transition.emitted,
transition.remaining,
transition.speculative_reasoning,
transition.drop_reasoning,
)?;
}
park_grammar_transition calls self.scheduler.request(handle)?, clear_active_slot(slot).unwrap() and park_with_tokens(..)? (runtime.rs:2416-2450). A failure in the n-th transition aborts complete() for all lanes in the frame after some transitions were already cancelled and parked, leaving the remaining active slots with stale state for a frame the scheduler has already accounted for. The surrounding code is otherwise careful to collect stopped and keep going; the transition loop should contain errors per transition the same way.
F5b (Minor) — mid-generation reseed changes the token stream for a fixed seed
helios/src/server/runtime.rs:2469-2471, reached by every transition (close, rejection, preemption):
let seed = active.carried.seed.unwrap_or(incoming.prompt.sampling.seed);
let generated_tokens = active.carried.generated_tokens + generated;
incoming.prompt.sampling.seed = continuation_seed(seed, generated_tokens);
On main a grammar-constrained request ran to completion in one admission, so sampling.seed stayed the client's seed for the whole generation. Now the same request+seed produces a different stream than main, and that stream depends on burst boundaries (how much overshoot was discarded). This is a behaviour/compat change for seeded workloads and the description does not mention it. Fix: either state it explicitly in the description/docs or make the reasoning-budget continuation deterministic in the number of consumed tokens (it already is in generated_tokens, so the issue is only that main had no continuation at all — document it).
Verified sound in this area (stated plainly)
Admission::from_promptgatesgrammar_maskon the new flag andAdmission::validateacceptsNone; packing emitsGrammarEnabled = 0.advance()(grammar.rs:785-787) syncs a dirty mask before reading it, andfail()/refresh_mask_availableclearmask_dirty, so the deferred-mask invariant holds on the masked path.- Preemption park (
runtime.rs:2395-2405) leavesgrammar_reasoning_modealone; covered atphase_tests.rs:7763-7809. - The readmission arithmetic is invariant-preserving (
exact_len + remaining = prompt_end + budget + after), so the new park paths do not create context-headroom rejections. - No protobuf, kernel-ABI, CUDA-graph or core-format change; existing exported cores load unchanged; only
Admission::from_promptgained an in-crate parameter andPrompta field.
2. Unintended system-level consequences
F2 (Major) — the transition re-prefills the whole reasoning trace, and that prefill drains the two-frame window for everyone in the batch
helios/src/server/runtime.rs:2407-2428:
fn park_grammar_transition(
&mut self,
slot: usize,
exact_len: usize,
emitted: u32,
remaining: u32,
speculative_reasoning: bool,
drop_reasoning: bool,
) -> Result<()> {
let handle = self.active[slot].as_ref().unwrap().request;
let live = self.scheduler.request(handle)?;
let tokens = live.tokens()[..exact_len].to_vec();
and runtime.rs:2445-2449:
if publish_terminal {
self.scheduler.finish(handle)?;
} else {
self.scheduler.cancel(handle)?;
}
exact_len = live.prompt_tokens + emitted (runtime.rs:2070), so the readmitted prompt ends at the last accepted token — after the whole reasoning trace. cancel publishes no terminal snapshot, and checkpoint_accounting is only carried over (runtime.rs:2473), so the only checkpoint that can serve that prefix is the prompt-end one. Every transition therefore recomputes R = exact_len - prompt_end tokens of KV (and non-invertible recurrent state) via Restore + chunked Prefill.
The tests confirm the shape and its scale: phase_tests.rs:7388-7390 exercises exactly Restore followed by a one-token Prefill — R is never more than 1.
System-level impact:
- O(R) extra prefill work and KV/page traffic injected precisely when the answer phase starts, on every grammar-constrained thinking request. For a long reasoning trace this is a large absolute cost.
- Prefill is single-frame by contract:
docs/scheduling-runtime-design.md:548-552— "Prefill, scored prefill, mixed execution, resume, vision, and state operations drain the window" — andhelios/src/scheduler.rs:1085-1094. So for the duration of the re-prefill, every co-batched unconstrained request loses the two-frame pipelining this PR exists to provide, and pays added queue latency. The PR's headline benefit is revoked for the transition interval for bystanders, not just for the transitioning request. - If the prompt-end checkpoint was evicted (the PR's own caveat), the whole prompt is re-prefilled.
- Re-entry is repeated:
allow_reasoning_reentryfires on every reasoning re-open, so a model with several reasoning blocks pays this cost several times per request.
Framing (important for adjudication): the description does disclose the mechanism ("one slot transition (cancel + Restore from the pinned prompt/prefix checkpoint + chunked Prefill over the reasoning tokens since that checkpoint)"). The finding is therefore not a description inaccuracy but (a) an unquantified cost whose bystander/window-drain consequence is not mentioned, and (b) the absence of the served-workload A/B the charter requires (#210). The codebase already knows how to do this better: the let_publish_cut special case (runtime.rs:2071-2076) deliberately lets publish() emit a terminal checkpoint and transition with KV reuse:
// If reasoning closed on the final token of a thinking-budget pass
// with no overshoot, let `publish()` publish the terminal checkpoint
// and transition with KV reuse.
let let_publish_cut = skipped == 0
&& emitted == request.incoming.prompt.max_new_tokens
&& request.incoming.prompt.reasoning_cut.is_some();
Fix/ask: apply the same KV-reusing publish path to the ordinary reasoning-close transition (publish the boundary checkpoint instead of cancel), or at minimum give a measured cost model for R and a statement about window occupancy during the re-prefill.
F3 (Major) — drop_reasoning silently disables thinking_token_budget enforcement for every parser except Atem/TmlJson
helios/src/server/runtime.rs:2109 derives the flag from the parser kind alone:
let drop_reasoning = !request.incoming.allow_reasoning_reentry();
and runtime.rs:2451-2453 acts on it:
let mut active = self.clear_active_slot(slot).unwrap();
if drop_reasoning {
active.reasoning = None;
}
The budget block then unconditionally unwraps that decoder (runtime.rs:2239-2240) behind a guard that drop_reasoning does not consider:
let forced =
request.reasoning.take().unwrap().reasoning_open() && close_allowed;
After a mid-generation close with a QwenCoder/Dsml/Glm/Xtml/MiniMaxXml/GemmaCall tool parser, the forced-close decision can never be true, so thinking_token_budget silently stops being enforced for the remainder of that request (whether the unwrap is reachable at all depends on reasoning_cut still being Some, which is why I rank this Major-but-conditional rather than a panic). There is no test for a mid-generation close on a non-Atem/TmlJson parser. Fix: do not drop the decoder when prompt.reasoning_cut.is_some(), or make the budget block tolerate reasoning == None, and add the missing test.
Two related scope observations on the same predicates:
runtime.rs:262-273allow_reasoning_reentrykeys only onToolParserKind, and the re-entry branch (runtime.rs:2121-2152) fires on any false→truereasoning_open()edge — broader than the description's "starting in a constrained header". Each re-entry pays F2.- Eligibility at
request.rs:408-426is automatic: no setting, CLI option, metric or config field is added anywhere in the diff (Prompt/Incomingare internal;prepare_inferenceis the sole producer), so operators cannot keep the previous whole-generation width-1 behaviour.
F4 (Minor/Major) — the constrained-inflight metric and its documented invariant silently lose coverage; three doc statements contradict the new text
helios/src/server/runtime.rs:3266-3273 classifies lanes purely by the scheduler field:
let (mut constrained, mut unconstrained) = (false, false);
for lane in &step.lanes {
if scheduler.request(lane.request)?.grammar_constrained {
constrained = true;
} else {
unconstrained = true;
}
}
combined with runtime.rs:281-282:
grammar_constrained: self.prompt.grammar.is_some()
&& !self.speculative_grammar_reasoning(),
a grammar-attached request running at width 8 with two frames in flight is now counted as unconstrained. Consequences:
flare_constrained_max_inflightandflare_mixed_grammar_decode_steps_totalunder-report; nothing new reports grammar-attached frames, so the operator loses the signal during exactly the phase this PR creates.helios/model-contract.md:436-441— "flare_constrained_max_inflightrecords the maximum outstanding executor frames immediately after a successful constrained submission. It is zero before any constrained submission and must remain one afterward." — is now vacuous for those requests.helios/model-contract.md:236-238still says "Host-fed pending tokens, grammar, host stops, history inputs, unknown or stale costs, and operations that change phase require completion feedback."docs/scheduling-runtime-design.md:548-552still lists "grammar" among things that "require completion feedback".docs/core-design.md:1242-1248still asserts "While any constrained request is in the decode batch, the loop runs one step in flight".
The PR updates only docs/api.md:645-658, docs/core-design.md:1694-1707 and docs/mtp-design.md:410-432. Fix: update the three stale statements in this PR and either count grammar-attached speculative-reasoning lanes in a (new or renamed) metric or document the metric's narrowed scope.
Metric span check: scrape/flare_constrained_max_inflight was previously a lifetime maximum over all grammar-constrained submissions. After this PR it samples only the device-masked subset, i.e. the measured span shrank while the contract sentence still asserts a lifetime guarantee — a textbook metric-scope regression, with no threshold or alerting change to compensate.
3. Architecture, contracts & charter compliance
- Correct layer. Host-side validation instead of per-model rollback kernels matches "Keep the runtime small and model-agnostic"; there is no model-name branch.
grammar.rs:677-692adds only generic matcher state. This is the right place for the change. - Contracts. No wire/proto/captured-graph change;
Admission::from_promptgained a fourth in-crate parameter andPrompta public fieldgrammar_reasoning, and no other crate constructs either.AGENTS.md(not opened)-level owner sign-off is not triggered. - F5c (Minor) — the new invariant is unexercised.
helios/src/grammar.rs:677-692addeddebug_assert!(!self.mask_dirty, "sync_mask must run before reading a deferred grammar mask")tomask()andallows(). Every test cited in the description runs--release(cargo test --locked --release …), where debug assertions are compiled out, and all three CI workflows for this PR use release builds. In release the guard degrades to returning a stale mask silently. Add a debug-mode test or convert the invariant into a runtime-checked assertion on the transition path. - F6 (Major, process) — charter evidence gap. The description states its own gap: "Expected performance improvement (not yet measured on a live GPU)" and "not run in this environment; performance claims above are expectations, not measured GPU numbers." The charter requires "Performance PRs need benchmarks showing an actual speedup over
mainon a served workload (#210)". The neighbouring #615 was reviewed to "Ready To Merge" with live GB10/SM121 evidence in these same files, so the bar exists in practice. - F6b — scope gap against the motivating report. The PR never cites #530, and #530's measurement used
enable_thinking: falsewithjson_schema, i.e. a request that starts inOutputStart::Contentand therefore stays device-constrained from token 0 under this eligibility rule. This is asserted in the PR's own test (phase_tests.rs:8037-8053). The answer-JSON phase — where #530's 55 tok/s vs 176 tok/s was measured — and the batch-wide feedback barrier it imposes (helios/src/scheduler.rs:1085-1094) are unchanged. If the intent is to move #530, the PR's own numbers will not show it. - F6c — CI failed on
f7907a2and the description does not explain it. None of the three workflows would catch the new debug-only assertion, which makes the failure a separate unexplained signal rather than a test of this change.
4. Tests & claim accuracy
Verified present at the cited locations and asserting what is claimed: unmasked_advancement_matches_masked_decisions_and_defers_mask_sync (grammar.rs ~1851-1920), and phase_tests.rs 7300-7455 / 7457-7595 / 7598-7735 / 7736-7815 / 7820-8012 / 8015-8071. I found no false claim about what any individual test does.
Gaps in the coverage relative to the risk, all verified:
- No in-vocabulary, non-EOS forbidden token in the unmasked path (F1) — the overshoot tokens are never validated (
runtime.rs:1889-1892). - R > 1 reasoning tokens never rolled back (F2) — every test re-prefills exactly one token.
- No mid-generation close with a non-Atem/TmlJson tool parser while
reasoning_cutis pending (F3). - No test in debug mode, so
mask_dirtyis never checked (F5c). - No test for
park_grammar_transitionfailing mid-frame (F5a). - No metric assertion that grammar-attached lanes remain visible (F4).
Open questions
- Does llguidance's
try_consume_tokensever returnErrfor an in-vocabulary but grammar-forbidden token? If it is provablyOk(0)-only, F1 degrades to a documentation/defensive concern; otherwise it is a live 500 path. The PR does not say, and no test pins it. - Did the transition cost get measured out-of-band (Discord)? Nothing is recorded on GitHub, and without it the PR cannot clear the charter's #210 bar either way.
- Is a mid-generation reasoning close reachable with a non-Atem/TmlJson tool parser plus a live
reasoning_cut? If yes, F3 is a budget-enforcement regression; the #615 author is the right reviewer. - Should the boundary transition use a published checkpoint (as
let_publish_cutalready does) instead ofcancel+ full re-prefill? - Should the three stale doc statements and the narrowed metric scope be fixed here or in a follow-up?