Correctness, Contracts & System-Level Consequences — PR #615
helios: support thinking_token_budget for ContentHeaders and trim incomplete UTF-8 tails on cut · head 2652c06 · base main@2147cd4 · +562/−31 over 6 files · no CI checks, no reviews.
I read all six changed files in full context plus their direct callees (TmlOutput, OutputPipeline, Active::close_reasoning/emit_output, scheduler decoded history, prompt_metadata::extend_text, TokenStops/TextStops, metrics, docs/api.md). The request-preparation and accounting core is largely sound — see "Verified sound" at the end — but the UTF-8 trim half has a scope defect that reaches every reasoning format and an actively grammar-constrained request, and the PR's "all-or-nothing" claim for the injected tail is false.
Key findings
- Blocker-adjacent (Major): the UTF-8 trim fires for every reasoning format and even when a grammar is active, while the tail injection it is meant to accompany is gated on
grammar.is_none(). Already-published, already-grammar-advanced tokens are silently deleted from the re-prefilled prompt, diverging grammar state from prompt history. Documented only under the TMLv0/ContentHeadersparagraph. - Major (claim accuracy): the injected tail is not all-or-nothing. A user token stop matching
<|message_model|>breaks the loop mid-sequence, leavingTmlOutputinState::Headerand terminating the request — the exact half-header shape the1 + close_tail.len() < afterguard exists to prevent. - Minor→Major: the
'\u{FFFD}'heuristic cannot distinguish a provisional replacement char from a legitimately generated one, which the repo itself notes is only resolvable from exact bytes (token_spans.rs:92-93); byte-fallback tokenizers really do emit U+FFFD content. - Minor: the trim silently no-ops when the partial sequence reaches the 8-token window start, contradicting
docs/api.md's unconditional "are trimmed". - Minor (metrics/observability): the hidden-token charge per cut goes 1 → up to 3 in
generated_tokens/usage.completion_tokensandflare_generated_tokens_total, whileprompt_tokensdoes not reflect the 3 tokens added to the prompt andreasoning_budget_cuts_totalsemantics are unchanged. - Minor (charter/architecture): the two content markers are hardcoded in the request layer even though
OutputPipeline::envelope_markers/declared_markersalready expose exactly those literals — a format branch inheliosagainst the model-agnostic rule (#267/#334). - Evidence gap: the central behavioural claim rests on synthetic fixtures. No live Inkling 2 / real-checkpoint run, and none of the four trim edge cases has a test.
1. Correctness, Safety & Platform Parity
F1 — Major: the UTF-8 trim is format-agnostic and not grammar-gated; it deletes already-published tokens from the re-prefilled prompt
helios/src/server/runtime.rs:2133
if !appended.is_empty() && tokens.len() > live.prompt_tokens {
let generated_len = tokens.len() - live.prompt_tokens;
let window_start = tokens.len().saturating_sub(8).max(live.prompt_tokens);
appended is &injected for any forced cut (runtime.rs:2013):
let appended: &[u32] = if forced { &injected } else { &[] };
so DeepSeek V4.1 / XTML / ThinkTags / Recipient / DSML cuts — whose close_tail is empty and whose injected is [close] — take this branch too. Contrast the tail injection, which is grammar-gated (runtime.rs:1962-1965):
let include_tail = !cut.close_tail.is_empty()
&& request.incoming.prompt.grammar.is_none()
&& u64::from(1 + cut.close_tail.len() as u32)
< u64::from(cut.after);
The trim has no such guard, so a response_format-constrained request that hits a reasoning budget at a mid-character boundary (JSON string value) truncates the token out of the parking prompt (runtime.rs:2150 tokens.truncate(end);) even though the worker already advanced the grammar over it (runtime.rs:1822-1838) and the client decoder already emitted its text. The re-admitted continuation's mask no longer composes with the JSON produced so far.
Impact: silent prompt/grammar divergence on any grammar-constrained forced cut; up to 3 tokens dropped from the continuation context. Today's docs/api.md:817-823 frames this as a TMLv0 ContentHeaders property:
close token and continues with the remaining output limit. For TMLv0 content-header
reasoning (`ContentHeaders`), when no tools or grammar are active and output capacity
remains beyond the frame opener, Flare also emits the silent `<|message_model|><|content_text|>`
control tokens after `<|end_message|>` so continuation enters a text frame directly;
when tools or a grammar are active, only `<|end_message|>` is emitted. Any incomplete
multi-byte UTF-8 tail tokens at the cut boundary are trimmed from the re-prefilled
continuation context before the close token is appended.
So the document asserts one scope and the code has another.
Fix: carry the intent on the cut (ReasoningCut::trim_utf8: bool, set only in the TMLv0 path at request.rs:384-393) or, at minimum, add && request.incoming.prompt.grammar.is_none() to the gate at runtime.rs:2133. If the format-agnostic behaviour is intended, document it outside the ContentHeaders paragraph and add a non-TML test.
F2 — Minor (Major if byte-fallback tokenizers serve real content): a literal U+FFFD is indistinguishable from a provisional one
helios/src/server/runtime.rs:2136-2139
if self
.frontend
.decode(&tokens[window_start..], false)
.is_ok_and(|text| text.ends_with('\u{FFFD}'))
{
The repo already states this ambiguity needs bytes to resolve — helios/src/server/token_spans.rs:92-93: "Exact byte ranges distinguish a literal U+FFFD from provisional UTF-8 replacement". A byte-fallback tokenizer can emit U+FFFD as genuine content (the <0xEF>/<0xBF>/<0xBD> vocabulary and the "\u{fffd}" text-stop test in helios/src/server/stops.rs:340-355, 454), and such a tail decodes to "…\u{FFFD}" and is truncated from the prompt — content loss, not repair.
Fix: require the trailing tokens' raw bytes (frontend.token_bytes) to form a strict, incomplete UTF-8 prefix before trimming, reusing the exact-range logic token_spans.rs already has.
F3 — Minor: the trim silently gives up in cases its documentation promises to fix
helios/src/server/runtime.rs:2141-2153
let max_trim = 3usize.min(generated_len.saturating_sub(1));
for trim in 1..=max_trim {
let end = tokens.len() - trim;
if end > window_start
&& self
.frontend
.decode(&tokens[window_start..end], false)
.is_ok_and(|text| !text.ends_with('\u{FFFD}'))
{
tokens.truncate(end);
break;
}
}
If the incomplete sequence straddles window_start (runtime.rs:2135, an 8-token window clamped to the prompt length) every candidate fails end > window_start and nothing is trimmed, with no diagnostic. A partial sequence longer than 3 tokens likewise passes through untouched. docs/api.md:821-823 states unconditionally that tail tokens "are trimmed".
Fix: bound the search by incoming.prompt.tokens.len() with a wider window, or document the ≤3-token / window-start bound in docs/api.md.
F4 — Minor: the injected tail is not all-or-nothing on a user token stop
helios/src/server/runtime.rs:1973-1989
for token in sequence {
match request.close_reasoning(token, &self.config.eos_token_ids)
{
Ok(stopped) => {
injected.push(token);
if stopped {
budget_stop = true;
break;
}
}
Err(error) => {
request.incoming.fail(error);
abandon = true;
break;
}
}
}
close_reasoning routes through Active::emit_output (runtime.rs:431-444 → 466-478), which pushes into TokenStops and reports a match. A user token stop that matches <|message_model|> therefore injects the model header and then stops, leaving TmlOutput in State::Header { model: true } (helios/src/output/tml.rs:272-284; MODEL => State::Header { model: true }) and finishing the request with reason "length" (runtime.rs:2055) while the tail was only half emitted — precisely the partial-header shape the 1 + close_tail.len() < after capacity guard exists to prevent.
The PR description claims: "emits cut.close followed by cut.close_tail (all-or-nothing when grammar.is_none() and 1 + cut.close_tail.len() < cut.after)". That is inaccurate.
Impact: a half frame header is left in the parked/terminal state; finish() on an unterminated header only discards it ("An unterminated header carries no content", tml.rs:378-379), so generated_tokens includes 2 hidden tokens while the client sees no content, and the request ends at a Header state.
Fix: pre-check the whole sequence against the request's token stops (allows(..)) before injecting anything, or roll back to close-only and park.
F5 — Minor: per-cut hidden-token accounting triples, and prompt_tokens does not follow
helios/src/server/runtime.rs:1991-1999
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);
}
with runtime.rs:2063:
generated_tokens: request.carried.generated_tokens + generated,
main charged one forced token per cut; this charges up to three into usage.completion_tokens and flare_generated_tokens_total, while prompt_tokens (runtime.rs:2059-2062) does not reflect the three extra tokens added to the prompt. reasoning_budget_cuts_total still counts one, so dashboards built on #541 see generated_tokens inflate relative to cuts without any signal. docs/api.md:823-824 says forced tokens count as generated tokens but not that the per-cut count changed from 1 to 3.
Fix: state the per-cut cost (1–3 tokens) in docs/api.md, or account the tail separately if usage monotonicity per cut is expected.
F6 — Minor: retained decoded history still contains the tokens the trim removed from the prompt
helios/src/server/runtime.rs:2157:
let decoded_sequence = live.decoded_sequence;
The parked continuation keeps the shared decoded-history handle for all tokens including those just truncated from tokens at runtime.rs:2150, so a later cache lookup keyed on the trimmed prompt can be reconciled against a decoded sequence covering tokens no longer in the prompt.
Fix: when the trim fires, resume the continuation without the trimmed tail position (or from Default), so decoded_sequence and prompt.tokens describe the same prefix.
Verified sound (not issues)
output_event_capacity(runtime.rs:68-88) still bounds publications:budget + afterequals the originalmax_new_tokens, andremaining = cut.after.saturating_sub(injected.len() as u32)(runtime.rs:2011) plus at most one event per injected token keeps the total ≤ the original limit.- The context-length invariant in
helios/src/model/admission.rs(validate_prompt) holds because the prompt grows by exactlyinjected.len()whilemax_new_tokensshrinks by the same amount. prompt_metadata::extend_textstrict monotonicity (admission.rs:25-56) holds becausemax_trim = generated_len.saturating_sub(1)always leaves ≥1 generated token, and the gate atruntime.rs:2133requirestokens.len() > live.prompt_tokens.- Preemption never trims:
park_if_preemptedpasses&[](runtime.rs:2121). - The injected pair legally re-enters
Body::Text(tml.rs:263-284:MODEL→Header, then a body marker →Body { kind, model }), andprompt_start(tml.rs:79-93) reads the re-prefilled prompt ending in<|content_text|>asOutputStart::Content, so the continuation parses as a text frame and no visible transition text is emitted. The phase test confirms it end-to-end (phase_tests.rs:781-782, reasoning"a", content"bc"). - No Unix/Windows divergence: nothing in the diff is platform-specific. No wire/proto/captured-graph or core-ABI change —
ReasoningCutis in-process.
2. Unintended system-level consequences
- No new lock, queue, or shared-state contention. The added work is local to the worker thread inside the existing
publish/parkpath;scheduler.record_decoded_token(runtime.rs:1992-1995) is the existing per-token path, now called up to 3× instead of 1×.parkis already the preemption path, so no new head-of-line risk. - Worker-thread CPU cost: up to 4 extra
frontend.decodecalls per forced cut (runtime.rs:2138, 2147) — bounded and only on the cut path, but on the model-serving thread. No benchmark provided; acceptable but undocumented. - Memory: no unbounded buffering.
injectedandsequenceare ≤3 elements. - Failure blast radius:
record_decoded_token(...)?atruntime.rs:1994propagates with?after tokens were already emitted and counted — a failure there leavesgenerated_tokensand the client stream inconsistent with the finished accounting, but this matches the pre-existing single-token behaviour and does not poison peers. - Cross-feature interaction (from the dossier): PR #457 rewrites exactly the
TmlOutput/content-header grammar semantics that this injected unnamed-header sequence depends on; the parser path is not guarded bygrammar.is_none(). Neither PR references the other. #582 edits the sameparkfunction.
3. Architecture, contracts, charter
F7 — Minor: hardcoded content-marker literals in the request layer
helios/src/server/request.rs:543-555
fn tml_text_transition_tokens(frontend: &Frontend, config: &ModelConfig) -> Vec<u32> {
if frontend.prompt_encoder() != crate::frontend::PromptEncoder::TmlV0
|| config.contract.frontend.reasoning.as_ref().map(|r| r.kind)
!= Some(crate::model::contract::ReasoningParserKind::ContentHeaders)
{
return Vec::new();
}
let vocab = frontend.tokenizer().get_added_vocabulary().get_vocab();
match (vocab.get("<|message_model|>"), vocab.get("<|content_text|>")) {
helios already has these literals behind OutputPipeline::envelope_markers(ToolParserKind::TmlJson) and declared_markers, and prepare_output resolves control tokens through frontend.encode. The contract declares reasoning.open/reasoning.close but no text opener, so this is a format-keyed branch in the request layer — friction with the charter's "keep the runtime small and model-agnostic … no per-model special cases" (#267/#334).
Fix: resolve the two openers from the prepared control-token set, or add a declared text-opener to the contract so the knowledge lives in the model recipe.
The API-surface change itself (HTTP 400 → working cap) is implementation of a documented field, consistent with the charter's "Don't silently ignore API fields". No new config keys, flags, or defaults; no captured-graph op added, so no owner sign-off gate applies.
4. Tests & claim accuracy
Coverage that exists: bootstrap validation for TmlV0/ContentHeaders (config.rs, new block), request preparation across plain/tight/tools/tool_choice="none"/grammar/Messages/uncapped (decode.rs:2031-2223), worker-loop injection with capacity accounting and OutputPipeline verification (phase_tests.rs:680-822), and 1-byte/2-byte/complete UTF-8 tails plus the appended-empty continuation (phase_tests.rs:824-879).
Missing tests, one per defect above: (a) no forced cut on a non-TML format (close_tail empty) — F1; (b) no cut with prompt.grammar = Some(..) — the case where F1 bites hardest; (c) no literal-U+FFFD tail — F2; (d) no case where the partial sequence reaches window_start or spans >3 tokens — F3; (e) no user token stop matching mid-tail — F4.
Claim-accuracy deltas versus the actual diff:
- "all-or-nothing" (PR body) — false,
runtime.rs:1973-1981. - "trim incomplete UTF-8 tails on cut … across all reasoning formats" — true but undocumented at that scope (
docs/api.md:817-823scopes it to TMLv0), and untrue for preemption (runtime.rs:2121) and the plain output limit. - "records every injected token in decoded history and progress metrics" — true, but the per-cut
generated_tokensdelta of 1 → 3 is not stated. - Evidence: CPU-only, synthetic tokenizer;
#[ignore]real-checkpoint TML tests (needingFLARE_INKLING2_TEST_SNAPSHOT) and liveflare runnot run; no CI on head2652c06.
Docs left stale (search hits, not opened in full): docs/logprobs-design.md:19 (not opened) still speaks of "the thinking_token_budget close" in the singular; docs/cli-design.md:1337 (not opened)/1367/1417 describe [server] thinking_token_budget without the TMLv0/ContentHeaders case.
Open questions / what could not be found
- Does
<|message_model|><|content_text|>actually keep a real Inkling 2 model in a text frame? Unanswerable from the repo: only synthetic fixtures and the contract JSON exercise it. No curl transcript or sample stream. - Is the format-agnostic trim intended? Nothing in the description or docs says so; if it is, F1 needs a documentation scope change rather than a gate.
- How does the injected unnamed model header interact with #457's "header without content" EOS error path? Both heads would be needed together; the PRs never reference each other.
- Would the U+FFFD heuristic fire reliably against the real tokenizer in batch decode mode? No test asserts the negative branch or a >3-token tail.
- Is dropping up to 3 already-emitted tokens acceptable for every format? Not argued anywhere; no user report of the original HTTP 400 exists in issues either, so the demand side is inferred from the code gap.