Correctness, Contracts & System-Level Consequences — PR #615 (helios: support thinking_token_budget for ContentHeaders and trim incomplete UTF-8 tails on cut)
Reviewed at head 7dde009 (9 files, +614/−50). Files opened in full context: helios/src/server/runtime.rs (changed hunks + Active::close_reasoning/emit_output, park/park_if_preempted, output_event_capacity), helios/src/server/config.rs::Bootstrap::load, helios/src/server/request.rs reasoning-cut preparation and thinking_budget_close, helios/src/output/tml.rs, helios/src/output/pipeline.rs, helios/src/frontend/mod.rs (prepare_token_bytes/token_bytes), helios/src/frontend/vocabulary.rs, plus the new tests in protocol/decode.rs, runtime/phase_tests.rs, request/tml_tests.rs.
Key findings
- Major — the UTF-8 trim repairs the continuation prompt but not what the client already received.
park()is only reached after every generated token was emitted and pushed through the worker-side parser, so trimming there leaves the streamed text ending in a dangling partial character the model never saw. Not documented as a client-visible effect. - Minor — the trim is not scoped to ContentHeaders/TMLv0, and the identical hazard on preemption is left untrimmed. The gate is
!appended.is_empty(), i.e. every forced reasoning cut in every format;park_if_preemptedpasses&[]and never trims. - Minor — a three-token forced close silently breaks two per-one-token invariants. Each injected token runs
emit_output/token-stop matching (a user token stop can truncate the frame mid-header) and incrementsgenerated_tokens, whilereasoning_budget_cutsincrements once andmetrics.progressjumps by up to 3. - Minor — undeclared boot-time cost:
VocabularyBytesis now built for every core. Themax_top_logprobs != 0gate inBootstrap::loadwas removed, so every deployment pays one decodedVec<u8>per vocabulary entry at startup, with no measurement and no line in the PR description's change list.
The core of the change is otherwise sound: marker IDs come only from already-validated single-token control markers, the format branch is out of the request layer, tools/grammar are guarded twice correctly, required budgets on unsupported output starts still 400, and the synthetic + worker-loop tests genuinely exercise the new paths.
F1 (Major) — The trim repairs the prompt, not the stream 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 the cut path at runtime.rs:2042-2048 (self.park(slot, appended, remaining)?), i.e. after the generated tokens have already been published: the token loop calls request.emit_output(...) at runtime.rs:1902 for each generated token, and emit_output (runtime.rs:490-524) pushes GenerationEvent::Token/Protocol to self.incoming, while the worker-side parser state is advanced earlier at runtime.rs:1858-1865. trim_incomplete_utf8_tail mutates only tokens, the re-prefilled prompt, and performs no rollback of request.reasoning or of anything already emitted.
Impact. The client-visible reasoning block can end with a stray U+FFFD / half character produced by the incremental decoder from the dangling byte token, and then continue with text the model generated from a repaired prompt. The model's view and the client's transcript diverge at exactly the boundary this PR is about, and docs/api.md:817-820 claims only the prompt side ("trimmed from the re-prefilled continuation context"), so no contract documents the visible artifact.
Fix. Either (a) state the client-visible consequence explicitly in docs/api.md and the PR description, or (b) hold back the last ≤8 generated tokens from emission at the cut decision (the machinery already exists — held_logprobs, runtime.rs:470, 511-520, buffers tokens for logprob ordering) so the trim happens before publication rather than after.
F2 (Minor) — Trim scope is every format's forced cut; preemption, which has the identical hazard, is untrimmed
runtime.rs:2160 gates on !appended.is_empty(), and appended is non-empty for any forced reasoning cut (runtime.rs:2044: let appended: &[u32] = if forced { &injected } else { &[] };). So every pre-existing reasoning format's continuation prompt now shrinks by up to 3 tokens relative to generated — a cross-format behaviour change outside the PR's subject (disclosed only in docs/api.md:817-818, not in the description).
Meanwhile helios/src/server/runtime.rs:2133-2154 (park_if_preempted) ends in
self.park(slot, &[], remaining)?;
Ok(true)
A preemption cut lands on an arbitrary token boundary and can leave exactly the same dangling multi-byte suffix, yet it is never trimmed because appended is empty.
Impact. Inconsistent prompt hygiene on the two paths that both shrink-and-reprefill; the preemption path keeps the pre-existing corruption the PR set out to fix, and the description gives no reasoning for the asymmetric scope.
Fix. Move the trim into park() itself behind tokens.len() > live.prompt_tokens (cheap: ≤8 token_bytes lookups) so both callers get it, or state in the description why preemption is deferred to a follow-up.
F3 (Minor) — Three injected tokens now run stop-matching and change generated-token accounting
helios/src/server/runtime.rs:1995-2030:
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;
}
...
self.metrics.reasoning_budget_cuts.fetch_add(1, Ordering::Relaxed);
self.metrics.progress(0, injected.len(), 0, 0, 0, 0);
and Active::close_reasoning (runtime.rs:474-488) does self.carried.generated_tokens += 1; and self.emit_output(close, eos, None) per token.
Impact (i) — mid-frame truncation. A user token stop (or EOS ids) matching the first injected token sets budget_stop and breaks the loop, so only <|end_message|> (or worse, only part of a header sequence) is injected; remaining > 0 && !budget_stop at runtime.rs:2043 then skips park() entirely, and the turn finishes with an unterminated frame. With close.len() == 1 on main this was one benign token; now the sequence can be cut in half.
Impact (ii) — metrics shift. metrics.progress(0, injected.len(), ...) (helios/src/server/metrics.rs:333-347) adds up to 3 to generated_tokens_total per single reasoning_budget_cuts increment (still one per cut, runtime.rs:2027-2029). #167 counted 1. No counter reports injected tokens separately, so a consumer of #541's reasoning_budget_cuts_total cannot reconcile the two, and finish_reason/generated_tokens in the Finished event include framework tokens.
Fix. Do not stop-match injected framework tokens (close_reasoning is a control action, not model output), and either add an injected_tokens counter or document the 1→3 accounting change in docs/api.md and the PR description. The grammar guard itself is stronger than main and correct (cut.close.len() == 1 && grammar.allows(...), agreeing with request.rs:385-390), and output_event_capacity remains safe because remaining = cut.after.saturating_sub(injected.len() as u32) (runtime.rs:2042) — but its comment at runtime.rs:67-68 still says "forced token".
F4 (Minor) — Undeclared, unmeasured boot 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 diff removes the previous guard (- if model.max_top_logprobs != 0 { frontend.prepare_token_bytes()?; }). prepare_token_bytes (helios/src/frontend/mod.rs:1529-1532) forces VocabularyBytes::new, which (helios/src/frontend/vocabulary.rs:31-39) does
let mut result = Vec::with_capacity(tokenizer.get_vocab_size(true));
for id in 0..tokenizer.get_vocab_size(true) as u32 {
let token = tokenizer.id_to_token(id).unwrap_or_default().into_bytes();
result.push(match tokenizer.get_decoder() {
Some(decoder) => decode_piece(decoder, token, &mapping)?,
i.e. one heap Vec<u8> plus a decode pass per vocabulary entry for every core at startup, including cores with max_top_logprobs == 0 that will only ever call token_bytes() from park() after a forced cut.
Impact. Startup latency and resident memory grow for all deployments, not just budget-enabled ones; the change appears only in the author's comment reply, not in the PR description's "What changed", and comes with no measurement. That is the charter's evidence rule applied to a startup-cost change.
Fix. Keep the eager init but gate it on "a thinking budget can be configured for this core" (per-request budgets are possible whenever reasoning_cut can be built), or keep main's lazy get_or_init (frontend/mod.rs:1534-1537, already used by token_bytes) and accept the first-call initialization on the worker thread; either way report the measured boot delta.
Verified sound (stated plainly, no issue invented)
- Marker identity cannot be forged or split.
tml::text_frame_opener()(helios/src/output/tml.rs:46-57) resolves ids fromoutput.control_tokens, whichprepare_outputpopulates only after rejecting any marker whoseids.len() != 1(helios/src/model/prompt.rs:319-328). A multi-token marker cannot reach the injector, and a missing one yields an empty tail rather than a guess. - Layering is correct. The
<|message_model|>/<|content_text|>literals live with the TML dialect (helios/src/output/tml.rs:25,29), the tools check moved intoOutputConfig::reasoning_close_tail()(helios/src/output/pipeline.rs:26-41), andrequest.rs:380-397is format-agnostic. The charter's model-agnostic objection is retired. - Capacity arithmetic is right and checked once.
request.rs:387tokens.len() + tail.len() < after as usizeleaves at least one token after the frame header;runtime.rs:1995-1998never lets a multi-token sequence run under a grammar;runtime.rs:2042subtractsinjected.len()sooutput_event_capacitystays an upper bound. - No silent API drop.
thinking_budget_close()acceptsRecipientFrame/RecipientHeaderonly forReasoningParserKind::ContentHeaders;RecipientHeadersis unchanged; aRequiredbudget with no resolvable close still returns the 400 (request.rs:374-378, 398-400). This satisfies "implement it or reject it". - The UTF-8 algorithm itself is correct.
trim_incomplete_utf8_tail(runtime.rs:420-461) useserror_len().is_none()so genuinely invalid bytes and literal U+FFFD survive, the 8-token window cannot under-cover a ≤3-byte suffix,.max(prompt_tokens)keeps prompt tokens out,end > startdrops the whole offending token, and it runs beforeextend_from_slice(appended)so injected tokens are never candidates.prompt_metadata(...).extend_text(...)(runtime.rs:2174-2176) recomputes from the post-trim length. - No new concurrency surface. All of this runs on the single model-worker thread; the trim is ≤8 token lookups plus two small
Vecs;live.tokens().to_vec()was already there. No lock, queue, ABI, captured-graph or wire-contract change. - Tests are substantive.
helios/src/server/protocol/decode.rs:2033-2222covers plain, tight-capacity (29/30/31 → close only), tools,tool_choice=none, grammar, Messages and uncapped with a synthetic byte-level TML tokenizer;helios/src/server/runtime/phase_tests.rs:679-870drives the realWorker::publish/park, asserting the parked prompt,max_new_tokens,carried.generated_tokens, the cut metric and the decodedreasoning_content/contentsplit, includinggenerated_len1/2 trimming (phase_tests.rs:836-848) and literal-U+FFFD preservation.
Claim accuracy vs the diff
Accurate: ReasoningCut::close really is Vec<u32> (runtime.rs:50-59) built once at request.rs:380-397 with include_tail gone; thinking_budget_close() really narrows to ContentHeaders; text_frame_opener() really reads the literals off validated control tokens; the trim really uses token_bytes + from_utf8 + error_len() and the old "keep ≥1 generated token" floor is gone.
Incomplete: the description does not say the trim applies to every format's forced cut (F2a — only docs/api.md:817-818 does), does not say injected tokens are now up to three and individually stop-matched into generated_tokens (F3), and does not list the unconditional prepare_token_bytes() at all (F4). The Limitations section is otherwise honest (engram io_uring ENOMEM, missing java/TLC, single-GPU single-model live testing).
Residual doc drift: docs/logprobs-design.md:19 still describes "the thinking_token_budget close" in the singular; runtime.rs:67-68 says "forced token"; docs/cli-design.md (not opened) still omits the TMLv0/ContentHeaders case.
Related-work interaction a reviewer should settle
#582 (open) latches zero_budget_anchor on (raw_anchor, prompt_tokens) explicitly because park() changes the readmitted prompt length. #615 now shrinks that prompt by up to 3 tokens on the same path (F1/F2). Nothing in either PR states which is correct when the readmitted prompt is shorter than the generated token count; combine the two and the anchor arithmetic deserves a test.
Process and evidence state
Labels area:api/enhancement/triage:review; one bot review (Changes Requested, 19:28) and one author reply at 19:53 ending "@flare-autobot please re-review"; zero human review or comment. No CI checks exist on 7dde009; the only real-tokenizer test (helios/src/server/request/tml_tests.rs:355-417) is #[ignore]d behind FLARE_INKLING2_TEST_SNAPSHOT, and the seven live flare run scenarios on GB10/SM121 are author-reported and not reproducible from the repo. The central behavioural claim — a real Inkling 2 model continuing in a text frame after <|message_model|><|content_text|> — is evidenced by one author's transcript, not by CI or a second party. I found no prompt-injection attempt in the PR text or comments.
Open questions
- Is trimming a suffix the client already received (F1) acceptable, given only the prompt is repaired and the parser is not rolled back? If yes, it must be documented; if no, emission needs hold-back.
- Why is the trim scope "all forced cuts in all formats" while preemption (
runtime.rs:2152) keeps the identical hazard — deliberate follow-up or oversight? - Is the unconditional
VocabularyBytes(F4) acceptable to whoever owns startup cost/memory for multi-core deployments? No number is given. - Does #582's
zero_budget_anchorlatch tolerate a shrinking readmitted prompt? - Does the injected unnamed
<|message_model|><|content_text|>shape survive #457's EOS-on-header-without-content rule if #457 merges first? Neither PR references the other.