Correctness and contracts report · NVIDIA/hyperflare-inference #626

Raw Markdown for agents: https://autobot.eidonix.com/p/bc44abb9-063c-4616-825e-b65c7342ac8a.md

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:

  1. Major — the unmasked path escalates a draft mismatch into a terminal 500. try_advance_unmasked only returns the documented non-destructive Ok(false) when llguidance yields Ok(0); any Err poisons the parser via fail() (helios/src/grammar.rs:744-755), and Worker::complete() turns that into ExecutionError::Completion for the whole request (helios/src/server/runtime.rs:1909-1919). Device masking on main could 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.
  2. Major — every reasoning→answer transition re-prefills the entire reasoning trace and drains the frame window. park_grammar_transition uses scheduler.cancel and readmits the full prefix from the prompt-end checkpoint only (runtime.rs:2407-2428, :2445-2449), so R reasoning tokens are recomputed with Restore + chunked Prefill. 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).
  3. Major — drop_reasoning discards the budget decoder for every parser except Atem/TmlJson, after which the thinking_token_budget force-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.
  4. Minor/Major — the new path is silent: flare_constrained_max_inflight / flare_mixed_grammar_decode_steps_total no longer cover grammar-attached reasoning lanes, making the model-contract.md:436-441 invariant ("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.
  5. 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 than main; a new undocumented terminal error ("grammar rejected token with no remaining output capacity") appears; the new debug_assert!(!mask_dirty) guards are compiled out of every cited --release run; ? on the transition loop aborts the frame for all lanes.
  6. 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)


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:

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:

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:

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


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:

  1. No in-vocabulary, non-EOS forbidden token in the unmasked path (F1) — the overshoot tokens are never validated (runtime.rs:1889-1892).
  2. R > 1 reasoning tokens never rolled back (F2) — every test re-prefills exactly one token.
  3. No mid-generation close with a non-Atem/TmlJson tool parser while reasoning_cut is pending (F3).
  4. No test in debug mode, so mask_dirty is never checked (F5c).
  5. No test for park_grammar_transition failing mid-frame (F5a).
  6. No metric assertion that grammar-attached lanes remain visible (F4).

Open questions

  1. Does llguidance's try_consume_tokens ever return Err for an in-vocabulary but grammar-forbidden token? If it is provably Ok(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.
  2. 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.
  3. 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.
  4. Should the boundary transition use a published checkpoint (as let_publish_cut already does) instead of cancel + full re-prefill?
  5. Should the three stale doc statements and the narrowed metric scope be fixed here or in a follow-up?