Correctness and contracts scratchpad · NVIDIA/hyperflare-inference #615

Raw Markdown for agents: https://autobot.eidonix.com/p/8e894de0-3ea8-4ebf-802f-5495c3c68078.md

#1 [high] Streamed-vs-prompt divergence on UTF-8 trim (verified)

helios/src/server/runtime.rs:2156-2163 park() trims AFTER the tokens were already published:

fn park(&mut self, slot: usize, appended: &[u32], remaining: u32) -> Result<()> {
    let handle = self.active[slot].as_ref().unwrap().request;
    let live = self.scheduler.request(handle)?;
    let mut tokens = live.tokens().to_vec();
    if !appended.is_empty() {
        trim_incomplete_utf8_tail(&self.frontend, &mut tokens, live.prompt_tokens);
    }
    tokens.extend_from_slice(appended);

park() is only reached from publish() (runtime.rs:2042-2047), i.e. after complete() already ran request.emit_output(...) (runtime.rs:1902) for every generated token, and after request.reasoning.push(...) (1858-1865) advanced the worker-side parser. So the client has already received the partial-byte tokens (decoded to U+FFFD by the incremental decoder) plus the frame-close sequence; the trimmed tokens are dropped only from the continuation prompt. Effect: the client-visible text can end a reasoning block with a stray U+FFFD / half character that the model never saw, and the parser state is not rolled back. docs/api.md:817-820 documents only the prompt side ("trimmed from the re-prefilled continuation context"). Severity: Major. Fix: either document the client-visible consequence explicitly, or hold back the last few generated tokens from emission until the cut decision is known.

#6 [high] Research summary

I reviewed PR #615 at head 7dde009 against the diff, the changed files in full context, and their direct callers (Active::close_reasoning/emit_output, Scheduler::record_decoded_token, Frontend::token_bytes/prepare_token_bytes, VocabularyBytes::new, TmlOutput::prompt_start/drain, ServerConfig::validate_thinking_budget, Decoder::attribute, Metrics::progress), plus the new tests in decode.rs, phase_tests.rs and tml_tests.rs.

Four findings, one Major: (1) trim_incomplete_utf8_tail is called from park() after the generated tokens were already emitted to the client and already pushed through the worker-side parser, so it repairs only the re-prefilled prompt — the client keeps the dangling partial character (documented as prompt-side only in docs/api.md:817-820). (2) The trim is gated on !appended.is_empty(), so it silently changes the continuation prompt for every reasoning format's forced cut, while the identical hazard on preemption (park_if_preempted passes &[]) is left untrimmed. (3) A three-token forced close now runs emit_output/stop-matching per token (a user token stop can truncate the frame mid-header) and adds up to 3 to generated_tokens_total against one reasoning_budget_cuts increment, neither of which is stated in the description or docs. (4) Bootstrap::load() now calls prepare_token_bytes()? unconditionally, building one decoded Vec<u8> per vocabulary entry for every core at startup — a boot latency/memory change absent from the PR description's change list.

I found the core of the change sound: tml::text_frame_opener() resolves ids only from already-validated single-token control markers, the format branch no longer lives in the request layer, the tools/grammar guards are duplicated correctly at request and runtime level, and thinking_budget_close() still raises the 400 for required budgets on unsupported starts (no silent API-drop). The tests genuinely cover the new paths, including a worker-loop test that decodes the resulting reasoning_content/content split; only the real-checkpoint test is #[ignore]d and no CI ran on this head. Full citations, verbatim quotes and fixes are in the scratchpad notes.

#7 [high] Finding list with severity, quotes, impact, fix

F1 (Major) — the UTF-8 trim repairs the prompt but not what the client already received. helios/src/server/runtime.rs:2156-2163

fn park(&mut self, slot: usize, appended: &[u32], remaining: u32) -> Result<()> {
    let handle = self.active[slot].as_ref().unwrap().request;
    let live = self.scheduler.request(handle)?;
    let mut tokens = live.tokens().to_vec();
    if !appended.is_empty() {
        trim_incomplete_utf8_tail(&self.frontend, &mut tokens, live.prompt_tokens);
    }
    tokens.extend_from_slice(appended);

park() is reached only from publish() (runtime.rs:2044-2047), i.e. after complete() already ran request.emit_output(...) for every generated token (runtime.rs:1902) and request.reasoning.push(...) (runtime.rs:1858-1865). The partial-byte tokens therefore already reached the client (decoded to U+FFFD by the incremental decoder) and already advanced the worker's parser; the trim drops them from the continuation prompt only, and does not roll the parser back. Docs state the prompt side only: docs/api.md:817-820 "any incomplete multi-byte UTF-8 tail tokens at a forced cut boundary are trimmed from the re-prefilled continuation context before the close token is appended." Impact: client text can end reasoning with a stray U+FFFD/half character the model never saw; reasoning_tokens/content attribution and the streamed message disagree with the continuation. Fix: either state the client-visible consequence in docs/api.md and the PR description, or hold back the last ≤8 generated tokens from emission until the cut decision is made (they are already in held_logprobs-style buffers for logprobs).

F2 (Minor) — trim scope is every format's forced cut, and preemption with the same hazard is untouched. a) Scope: runtime.rs:2160 gate is !appended.is_empty(), not "ContentHeaders"; appended is non-empty for any forced reasoning cut (runtime.rs:2044). So all pre-existing formats' cut prompts now shrink by up to 3 tokens — a behaviour change outside the PR's subject, disclosed in docs/api.md:817-818 ("For all reasoning formats") but not flagged as a cross-format change in the description. b) Preemption: runtime.rs:2133-2154, self.park(slot, &[], remaining)?; (line 2152) — a preemption cut lands on an arbitrary token boundary and can leave the same dangling multi-byte suffix, but is never trimmed. Fix: move the trim into park() unconditionally (guarded by tokens.len() > prompt_tokens) or file an explicit follow-up; either way say why the scope is what it is.

F3 (Minor) — a three-token forced close breaks two invariants that were per-one-token before. runtime.rs:1995-2031

let close_allowed = !cut.close.is_empty()
    && request.incoming.prompt.grammar.as_ref().is_none_or(
        |grammar| cut.close.len() == 1 && grammar.allows(cut.close[0]),
    );

and runtime.rs:2004-2020 loop → Active::close_reasoning (runtime.rs:475-488) which does self.carried.generated_tokens += 1; and self.emit_output(close, eos, None) per token; then runtime.rs:2027-2030

self.metrics.reasoning_budget_cuts.fetch_add(1, Ordering::Relaxed);
self.metrics.progress(0, injected.len(), 0, 0, 0, 0);

Impact (i): a user token stop matching an injected <|message_model|>/<|content_text|> sets budget_stop and breaks the loop (runtime.rs:2009-2012), parking a prompt that ends in an unterminated frame header. Impact (ii): up to 3 extra generated_tokens_total per cut with one reasoning_budget_cuts increment, with no per-cut token counter — a metrics consumer cannot recover the injected count. Fix: don't stop-match injected control tokens (they are framework tokens, not model output), or document the truncation; and add/label a counter for injected tokens, or note the 1→3 accounting change in docs/api.md.

F4 (Minor) — undeclared boot-time cost: VocabularyBytes for every core. helios/src/server/config.rs:279-281

let declared = crate::model::declared_control_tokens(&frontend, &model.contract.frontend)?;
let frontend = frontend.with_controls(declared);
frontend.prepare_token_bytes()?;

(the model.max_top_logprobs != 0 gate was removed). VocabularyBytes::new (helios/src/frontend/vocabulary.rs:31-39) allocates one Vec<u8> per vocabulary id (for id in 0..tokenizer.get_vocab_size(true) as u32 { let token = tokenizer.id_to_token(id).unwrap_or_default().into_bytes(); … }). Impact: startup latency + resident memory for every deployment, including cores that will never call token_bytes() outside park(), with no measurement. The PR description's "What changed" does not list it (only the author's reply does). Fix: keep the logprob gate and gate instead on "a reasoning budget can be configured", or measure and report the delta (this is one of the clearest places the charter's evidence rule applies).

#2 [medium] Trim gated only on !appended.is_empty(); preemption untrimmed

helios/src/server/runtime.rs:2160 if !appended.is_empty() { trim_incomplete_utf8_tail(...) } — appended is non-empty only for a forced reasoning cut, so this is not scoped to ContentHeaders/TMLv0 even though that is the only format this PR adds. Every other reasoning format's forced cut now also mutates the re-prefilled prompt (behaviour change for pre-existing formats, documented at docs/api.md:817-818).

Meanwhile fn park_if_preempted (runtime.rs:2133-2154) calls self.park(slot, &[], remaining)?; at line 2152 — preemption produces exactly the same dangling multi-byte suffix (it cuts at an arbitrary token boundary) and gets no trim, so the continuation prompt after preemption still starts mid-character. Severity: Minor/Major (inconsistent; asks for a follow-up or a shared helper call in both paths).

#3 [medium] Unconditional prepare_token_bytes() boot cost, undeclared in description

helios/src/server/config.rs:281 (was if model.max_top_logprobs != 0 { frontend.prepare_token_bytes()?; }):

let declared = crate::model::declared_control_tokens(&frontend, &model.contract.frontend)?;
let frontend = frontend.with_controls(declared);
frontend.prepare_token_bytes()?;

VocabularyBytes::new (helios/src/frontend/vocabulary.rs:14-39) builds one decoded Vec<u8> per vocabulary entry, cloning the tokenizer string for every id and running the decoder wrapper; for a ~250k-entry byte-level vocab that is ~250k heap allocations that now happen for every core at startup, including deployments with max_top_logprobs == 0 that will never use token_bytes() outside park(). This is a boot-time latency + resident-memory increase for all deployments, and it is not listed in the PR description's "What changed" (only in the author's comment reply, item 1). Severity: Minor (perf/scope), but should be disclosed in the description. Fix: keep the max_top_logprobs != 0 fast path and initialize eagerly only when a reasoning budget is configured, or measure and report the delta (charter requires evidence for perf-affecting changes).

#4 [medium] Multi-token forced close: stop-matching and metric accounting

helios/src/server/runtime.rs:1995-2031:

let close_allowed = !cut.close.is_empty()
    && request.incoming.prompt.grammar.as_ref().is_none_or(
        |grammar| cut.close.len() == 1 && grammar.allows(cut.close[0]),
    );
...
for token in cut.close {
    match request.close_reasoning(token, &self.config.eos_token_ids) {
        Ok(stopped) => { injected.push(token); if stopped { budget_stop = true; break; } }
...
if forced && !abandon {
    for &token in &injected { self.scheduler.record_decoded_token(request.request, token)?; }
    self.metrics.reasoning_budget_cuts.fetch_add(1, Ordering::Relaxed);
    self.metrics.progress(0, injected.len(), 0, 0, 0, 0);
}
let remaining = cut.after.saturating_sub(injected.len() as u32);

Consequences now that cut.close can be 3 tokens instead of 1:

#5 [medium] Verified-sound areas and residual doc drift

Verified-sound points (say so in the report, do not invent issues):

#8 [medium] Claim accuracy and evidence state for the report

Accurate in the description vs the diff:

Inaccurate or incomplete:

Evidence state: no CI checks on head 7dde009; the only real-tokenizer test thinking_budget_prepares_content_headers_cut (helios/src/server/request/tml_tests.rs:355-417) is #[ignore]d behind FLARE_INKLING2_TEST_SNAPSHOT; the seven live flare run scenarios on GB10/SM121 are author-reported and not reproducible from the repo. Automatable coverage is the synthetic path in decode.rs:2033-2222 and the worker-loop path in phase_tests.rs:679-870, which are good.

Process: labels area:api/enhancement/triage:review; one bot review (Changes Requested, 2026-11-29 19:28) and one author reply 19:53 ending "@flare-autobot please re-review"; zero human review or comment at any point. I found no prompt-injection attempt in the PR text or comments.