Subtraction, Simplicity & Conventions review — PR #615 (helios: support thinking_token_budget for ContentHeaders …)
Key findings
The diff is small and mostly lean: production code is roughly +156/−25, it adds no config keys, no CLI flags, and no dead code, and it reuses the existing thinking_budget_close / ReasoningCut / park machinery from #167 rather than building a parallel path. Three things do deserve subtraction, in value order:
- S1 (highest value):
ReasoningCut { close, close_tail }plus theinclude_tailre-check inpublish()express "one token, sometimes followed by two" twice. Collapse to a singlesequence: Vec<u32>and delete the runtime re-check — it re-tests operands that are immutable between preparation and publish, so it is dead defensive code (~25 lines). - S2: the new
tml_text_transition_tokens()(request.rs:543-555) is a second, weaker lookup for two ids the model layer already resolved, and it puts aTmlV0/ContentHeadersbranch into the helios request layer (the charter's "no per-model special cases" rule). The whole function should be deleted. - S3: the UTF-8 repair in
Worker::park()(runtime.rs:2129-2155) is a 27-line U+FFFD heuristic with magic constants (8-token window, 3-token cap, up to 4decodecalls on the worker thread) where the repo has exact token bytes; it should be made exact (~8 lines) or dropped and fixed at the decoder, especially since preemption keeps the identical hazard.
S4 (test-fixture duplication of helpers that exist in the same modules) and S5 (a stale invariant comment left behind by this PR) are minor. None of this is recommendation-blocking; the feature gating and tests are otherwise idiomatic.
S1 — close + close_tail should be one sequence; the runtime re-check is redundant (high)
helios/src/server/runtime.rs:50-61 introduces a two-field cut:
#[derive(Clone)]
pub struct ReasoningCut {
pub close: u32,
/// Optional follow-on control tokens injected immediately after `close`
/// when remaining output capacity permits (for example TMLv0
/// `<|message_model|><|content_text|>` to open a model text frame without
/// inserting visible transition text).
pub close_tail: Vec<u32>,
helios/src/server/request.rs:384-393 spends a four-branch nested if/else whose only job is to produce an empty Vec:
let close_tail = if output.content.tools.is_empty() && grammar.is_none() {
let tail = tml_text_transition_tokens(frontend, config);
if !tail.is_empty() && u64::from(1 + tail.len() as u32) < u64::from(after) {
tail
} else {
Vec::new()
}
} else {
Vec::new()
};
and helios/src/server/runtime.rs:1962-1972 re-derives the same decision:
if forced {
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);
let mut sequence = Vec::with_capacity(
1 + if include_tail { cut.close_tail.len() } else { 0 },
);
sequence.push(cut.close);
if include_tail {
sequence.extend_from_slice(&cut.close_tail);
}
Every operand of that re-check is fixed at preparation time: prompt.grammar is the Prompt built in request.rs (advanced at runtime.rs:1822, never replaced), and cut.after/cut.close_tail come from the same ReasoningCut. tools.is_empty() && grammar.is_none() was already consulted at request.rs:384, so include_tail can only ever agree with "close_tail is non-empty" — it is not a live guard, it is a duplicated policy decision that has to be kept in sync forever.
Replace with: pub sequence: Vec<u32> (close first) on ReasoningCut; in request.rs build it once with std::iter::once(close).chain(tail).collect(), leaving one max_new_tokens = budget; in runtime.rs delete lines 1962-1972 entirely and use cut.sequence (only sequence[0] is consulted by close_allowed at 1951-1956, which already exists). This also retires let remaining = cut.after.saturating_sub(injected.len() as u32) (runtime.rs:2011) as a partial-tail guard, and the forced/injected/abandon triple at runtime.rs:1957-1999 collapses to injected.is_empty()/abandon. Net: roughly 25 lines removed and one whole duplicated decision.
S2 — delete tml_text_transition_tokens(); the ids are already resolved upstream (high)
helios/src/server/request.rs:543-554 (entire function):
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|>")) {
(Some(&model), Some(&text)) => vec![model, text],
_ => Vec::new(),
}
}
Three separate problems, all subtractive:
- Duplication. The caller is inside a block already holding
output: &OutputConfig, whosecontrol_tokens: Vec<(u32, String)>(helios/src/output/pipeline.rs:23) was built moments earlier bycrate::model::prepare_output(helios/src/model/prompt.rs:315-328) fromOutputPipeline::envelope_markers(ToolParserKind::TmlJson), which returnssuper::tml::CONTROL_MARKERS(pipeline.rs:135), i.e.MODEL = "<|message_model|>"andTEXT = "<|content_text|>"(helios/src/output/tml.rs:25,:29). The ids, the marker table and the TmlJson association are already in hand. - Weaker validation.
prepare_outputrejects a marker that is not exactly one token (helios/src/model/prompt.rs:322-325, "output envelope delimiters must each occupy one tokenizer token"); the new helper silently returnsVec::new()instead. Or, if a direct encode is preferred, the in-tree helpercrate::model::reasoning_delimiter_tokens(&frontend, &config.contract.frontend)(already used athelios/src/server/protocol/decode.rs:2121) is the established way to turn contract-declared literals into ids — noget_added_vocabulary().get_vocab()reach-in needed. - Charter friction. It is the only per-format branch this PR adds to helios request preparation, keyed on
PromptEncoder::TmlV0+ReasoningParserKind::ContentHeaders(charter: "keep the runtime small and model-agnostic … no per-model special cases or flags", #267/#334). Deleting the function removes that predicate entirely with no loss of capability.
Replace with (inside the existing block, request.rs:384):
let tail: Vec<u32> = ["<|message_model|>", "<|content_text|>"]
.map(|name| output.control_tokens.iter().find(|(_, m)| m == name).map(|&(id, _)| id))
.into_iter()
.collect::<Option<Vec<u32>>>()
.unwrap_or_default();
One caveat worth asserting in the new test rather than assuming: control_tokens carries the 14 TML markers because the contract declares the TmlJson tool parser (prompt.rs:344, content_headers = syntax.tools…kind == TmlJson), independent of whether the request sends tools — so the no-tools case still populates it. An assert! on prepared.output.unwrap().control_tokens in the existing decode test would pin that.
S3 — the UTF-8 tail trim is a heuristic where the repo has exact bytes (high)
helios/src/server/runtime.rs:2129-2155 (the new block; quoted head):
// When injecting forced close tokens at a reasoning cut, drop up to 3 trailing
// generated tokens that leave an incomplete multi-byte UTF-8 sequence (U+FFFD)
// in the re-prefilled prompt context. Retaining at least one generated token
// guarantees `tokens.len() > incoming.prompt.tokens.len()` for `extend_text`.
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);
if self
.frontend
.decode(&tokens[window_start..], false)
.is_ok_and(|text| text.ends_with('\u{FFFD}'))
then a for trim in 1..=3 loop re-decoding at each step. Costs: two magic constants (an 8-token window and a 3-token cap — nothing bounds a partial character to 3 tokens for byte-fallback or fused pieces), up to four full frontend.decode calls per forced cut on the worker thread inside park, .is_ok_and silently reading a decode error as "clean" in one branch and "dirty" in the other, and an inability to distinguish a genuinely generated literal U+FFFD from a provisional partial — an ambiguity the repo already calls out in helios/src/server/token_spans.rs:92-93 ("Exact byte ranges distinguish a literal U+FFFD from provisional UTF-8 replacement").
The exact answer already exists: Frontend::token_bytes (helios/src/frontend/mod.rs:1534) via VocabularyBytes (helios/src/frontend/vocabulary.rs:11-45) returns each token's pre-decode bytes, and str::from_utf8 reports the partial sequence — the in-tree precedent is helios/src/server/token_spans.rs:129-141:
let error = std::str::from_utf8(&raw[source..]).err();
let valid = error.map_or(raw.len() - source, |e| e.valid_up_to());
...
if let Some(error) = error {
source += error.error_len().unwrap_or(raw.len() - source);
Replace with: collect token_bytes for the trailing generated tokens, std::str::from_utf8 the tail, truncate the trailing tokens whose end lies past err.valid_up_to() when error_len() == None. No window, no cap, no decode calls, no sentinel ambiguity — about 8 lines instead of 27.
Or delete it. The same hazard is untouched at preemption (runtime.rs:2121 still calls self.park(slot, &[], remaining) and appends nothing but leaves a mid-character tail in the re-prefilled prompt) and at the plain output limit, so this is a one-call-site repair rather than the root-cause fix the charter asks for (#397). Under this lens the honest options are "make it exact" or "drop it and fix the one decode path", not "keep a U+FFFD guess".
S4 — new tests hand-roll fixtures that exist in the same modules (medium)
helios/src/server/protocol/decode.rs:2034-2042, in the new test, rebuilds byte-level BPE from scratch:
let mut alphabet: Vec<_> = tokenizers::pre_tokenizers::byte_level::ByteLevel::alphabet()
.into_iter()
.collect();
alphabet.sort_unstable();
let vocabulary = alphabet
.into_iter()
.enumerate()
.map(|(id, c)| (c.to_string(), id as u32))
.collect::<tokenizers::models::bpe::Vocab>();
The same file already has renderer(encoder, template, encoding) at decode.rs:1035-1154 doing exactly this dance (alphabet sort, BPE build, ByteLevel::new(false, true, false), byte-level decoder, temp-file FrontendAssets, Frontend::load_with_settings, temp-file cleanup) — the new test even keeps a FrontendSettings/FrontendAssets block (decode.rs:2079-2105) that is a near-copy of decode.rs:1095-1137 minus the cleanup. Use renderer(PromptEncoder::TmlV0, None, TemplateEncoding::Text) and then swap in the TML contract, which the test already does at decode.rs:2115 (config.contract.frontend = serde_json::from_value(contracts["text"]…)).
Separately, the 14-marker array is re-spelled verbatim in at least two new places — helios/src/server/protocol/decode.rs:2053-2069 and helios/src/server/config.rs (~666-682, per diff), plus a subset in helios/src/server/runtime/phase_tests.rs:687-693 — while helios::output::tml::CONTROL_MARKERS (helios/src/output/tml.rs:41-44) is the canonical list and is already imported by tests (grammar/strict.rs:2804 (not opened) byte_tokenizer_with(&CONTROL_MARKERS), protocol/tests.rs:2161). Also available and unused: crate::grammar::tests::byte_tokenizer_with(added) (helios/src/grammar.rs:925-954). This is the drift that later lets a fixture and the production marker table disagree; it is not test nitpicking. (phase_tests.rs otherwise does the right thing, reusing Fixture::with_template at phase_tests.rs:71-154.)
S5 — leftovers this PR makes stale (low)
helios/src/server/runtime.rs:68-71, left behind by the 1-token → 3-token change:
fn output_event_capacity(&self, minimum: usize, observed: bool) -> Result<usize> {
// Each generated token produces at most one presentation event and one
// optional observation. A reasoning cut's forced token is part of `after`.
"forced token" → "forced tokens". The invariant itself survives because after is reduced by injected.len(), so only the comment is wrong.
And tied to S1: u64::from(1 + cut.close_tail.len() as u32) < u64::from(cut.after) appears at both request.rs:386 and runtime.rs:1964-1965 to avoid an overflow that a ≤3-token tail cannot produce; folding to one site makes it a plain sequence.len() < cut.after as usize. docs/logprobs-design.md:19 (not opened) likewise still speaks of "the thinking_token_budget close" in the singular (companion doc to the updated docs/api.md:813-842; not opened here).
Open questions / not verified
- Whether deriving the tail from
output.control_tokens(S2) is safe for everyContentHeaderscore depends on the contract always declaring theTmlJsontool parser; the shared fixturehelios/tests/support/contracts/inkling2_frontend.json(not opened) does, but I did not enumerate contracts for every Inkling variant. Assertingcontrol_tokensin the existing decode test would settle it. - The exact
token_bytesAPI shape for a batch of trailing tokens (S3) was located by signature (frontend/mod.rs:1534,vocabulary.rs:11-45) but not exercised; a couple of lines may differ from the sketch. - I did not run or compile anything; all line numbers are from the PR head as read.
- Behavioural correctness items (mid-tail truncation on a user token stop, per-token
generated_tokensinflation, interaction with #457's header-without-content EOS error) are deliberately left to the Correctness & Contracts lens.
Verdict: lean in spirit and safe to keep as-is at a push; S1 and S2 together remove ~40 lines and the only per-format branch the PR adds to helios request preparation, and S3 is the single place where a heuristic should become either exact or gone.