Subtraction, Simplicity & Conventions — PR #615 @ head 7dde009
Key findings
- The production code is lean. Say so plainly. Five source files, roughly +170/−50, and there is no dead config knob, no new flag, no speculative generality, and no duplicated marker table. The literal framing strings exist exactly once beside the existing marker table (
helios/src/output/tml.rs:25,29withCONTROL_MARKERSat:41-44), the earliertml_text_transition_tokens()/PromptEncoder-keyed branch was correctly deleted, and collapsingReasoningCutto a singleclose: Vec<u32>(helios/src/server/runtime.rs:50-61) removed a field rather than adding one. That is the right direction. - One production line should simply be deleted: the unconditional boot-time
frontend.prepare_token_bytes()?athelios/src/server/config.rs:281warms a cache whose accessor is already a lazyOnceLock(helios/src/frontend/mod.rs:1534-1537). - One helper chain is over-built:
Option<[u32;2]>→.to_vec()→!tail.is_empty()→extendis four representations of at most twou32s spread over three files, with the capacity policy split across two of them (helios/src/output/tml.rs:47-57,helios/src/output/pipeline.rs:29-40,helios/src/server/request.rs:384-390). - The real cost of this PR is test scaffolding, not production code: ~430 of the +614 added lines are tests, and the same TMLv0 test frontend is built three times —
renderer()(helios/src/server/protocol/decode.rs:1035), the new inline copy (decode.rs:2034-2092), andInkling::prepare(helios/src/server/request/tml_tests.rs:32-91) — plus a fourth 32-line tokenizer build in theBootstraptest loop (config.rs:663-694) to assert a singleOption<u32>. - Two findings are
AGENTS.md-convention findings, not style: the silentlet Ok(bytes) = ... else { return; }(runtime.rs:433-435) is exactly the "suppress errors, silently substitute execution paths" and "fallback layers without a concrete requirement" the charter rejects (AGENTS.md:182-186,:188-190); the unconditionalprepare_token_bytes()is an undeclared resource-lifetime change (AGENTS.md:88-94).
1 (high) helios/src/server/config.rs:281 — a warm-the-cache line for a consumer that is already lazy; delete it
let declared = crate::model::declared_control_tokens(&frontend, &model.contract.frontend)?;
let frontend = frontend.with_controls(declared);
frontend.prepare_token_bytes()?;
if frontend_settings
(helios/src/server/config.rs:279-282)
This replaced if model.max_top_logprobs != 0 { frontend.prepare_token_bytes()?; }. The accessor the trim function actually calls initializes the identical OnceLock on demand:
pub fn token_bytes(&self, token: u32) -> Result<&[u8]> {
self.vocabulary_bytes.get_or_init(|| vocabulary::VocabularyBytes::new(&self.tokenizer))
.as_ref().map_err(Clone::clone)?.get(token)
}
(helios/src/frontend/mod.rs:1534-1537)
Remove: line config.rs:281 (and restore the max_top_logprobs != 0 gate only if logprobs still needs the hard failure at boot). What it buys today: moving a one-time build from the first forced cut to process start, at the price of one decoded Vec<u8> per vocabulary entry per core (helios/src/frontend/vocabulary.rs:31-39) on every deployment, including cores that can never arm a ReasoningCut. That is a start-latency and memory change for all users of the binary and it appears nowhere in the description's change list (AGENTS.md:88-94 requires naming resource-lifetime changes). The stated justification in the PR text is "so token-byte lookup never initializes lazily on the worker thread" — that is a preference, not a measurement, and this is precisely the "fallback layer without a concrete requirement" pattern. If lazy init on the worker thread is genuinely measured to matter, the narrow form is to prepare it only when a cut is possible (i.e. thinking_token_budget.is_some() or the core's reasoning kind is ContentHeaders), not unconditionally.
2 (high) Test scaffolding: the same TMLv0 frontend is constructed three times in three files
The new decode test's first 60 lines are a verbatim re-implementation of the module's own helper:
fn tml_content_headers_thinking_budget_prepares_close_and_optional_text_frame_tail() {
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>();
let model = tokenizers::models::bpe::BPE::builder()
.vocab_and_merges(vocabulary, vec![])
.build()
.unwrap();
(helios/src/server/protocol/decode.rs:2033-2046)
Compare the helper that sits ~1,000 lines above it in the same module:
fn renderer(
encoder: PromptEncoder,
template: Option<&str>,
encoding: TemplateEncoding,
) -> (Frontend, GrammarCompiler, crate::model::ModelConfig) {
let mut alphabet: Vec<_> = tokenizers::pre_tokenizers::byte_level::ByteLevel::alphabet()
.into_iter()
.collect();
alphabet.sort_unstable();
(helios/src/server/protocol/decode.rs:1035-1043)
The new body then repeats with_pre_tokenizer / with_decoder / add_special_tokens / temp-file write / Frontend::load_with_settings / std::fs::remove_file / GrammarCompiler::new (decode.rs:2047-2110) — the whole sequence renderer() already performs (decode.rs:1059-1153). A third copy of the same construction lives in helios/src/server/request/tml_tests.rs:32-91 (struct Inkling + Inkling::prepare). The only genuinely new ingredient in the decode test is the added-token list (crate::output::tml::CONTROL_MARKERS, decode.rs:2052-2058) and the tests/support/contracts/inkling2_frontend.json (not opened) contract (decode.rs:2097-2101).
Concretely, do one of two things:
- Preferred — parametrize the existing helper. Add an
added: &[&str]argument torenderer()(it already takes three) and aPromptEncoder::TmlV0path, then reduce the new test to ~30 lines of assertions on top ofrenderer(PromptEncoder::TmlV0, None, TemplateEncoding::Text, &crate::output::tml::CONTROL_MARKERS). This deletes ~80 lines (decode.rs:2034-2092) with no loss of coverage. - Or move the unique assertions next to the other TMLv0 fixtures and drop the duplicated ones. Naming the split honestly:
helios/src/server/request/tml_tests.rs:355-416(thinking_budget_prepares_content_headers_cut) already asserts the same plain/[end_message, model, text], active-tools →[end_message],json_object→[end_message], and omitted-budget-uncapped cases. Whattml_tests.rsdoes not cover, and which is worth keeping, is: the tight-capacity ladder (decode.rs:2146-2155, budgets 29/30/31 →close == [end_message]), thetool_choice: "none"restores the opener case (decode.rs:2166-2173), and the Messagesthinking.budget_tokenscase (decode.rs:2186-2193). So this is ~3 unique assertion groups inside ~165 lines of mostly-rebuilt harness, not a wholesale deletion.
Same class, secondary: helios/src/server/config.rs:663-694 builds a 32-line TML tokenizer inside the Bootstrap fixture loop so that a single line can be asserted:
let loaded = Bootstrap::load(&configured.to_string(), &manifest).unwrap();
assert_eq!(loaded.server.thinking_token_budget, Some(16));
(helios/src/server/config.rs:694-695)
The behavioural claim — "boot accepts a [server] thinking_token_budget on a ContentHeaders core" — is one row in the fixture matrix that loop already iterates (config.rs:697-700). I could not find an existing TML fixture in that test to reuse (searched helios/src for shared test tokenizer builders; only decode.rs:1035 and humanize-style helpers exist), so this one may need some tokenizer; the simplification is to hoist it to one shared per-test-crate helper rather than a fourth bespoke build. Lower confidence than item 2's first half — flag as a "collapse, don't necessarily delete".
3 (medium) Three files and four representations to produce at most two u32s
pub(crate) fn reasoning_close_tail(&self) -> Vec<u32> {
if self.syntax.reasoning.as_ref().map(|r| r.kind)
== Some(ReasoningParserKind::ContentHeaders)
&& self.content.tools.is_empty()
{
super::tml::text_frame_opener(&self.control_tokens)
.map(|tokens| tokens.to_vec())
.unwrap_or_default()
} else {
Vec::new()
}
}
(helios/src/output/pipeline.rs:29-40)
pub(crate) fn text_frame_opener(control_tokens: &[(u32, String)]) -> Option<[u32; 2]> {
let model = control_tokens
.iter()
.find(|(_, marker)| marker == MODEL)
.map(|(id, _)| *id)?;
(helios/src/output/tml.rs:47-51, second .find() at :52-55 for TEXT)
and the sole caller re-tests emptiness and owns the capacity rule:
let mut tokens = vec![close];
if grammar.is_none() {
let tail = output.reasoning_close_tail();
if !tail.is_empty() && tokens.len() + tail.len() < after as usize {
tokens.extend(tail);
}
}
(helios/src/server/request.rs:384-390)
Option<[u32;2]> → Vec<u32> → !is_empty() → extend is four spellings of one value, and the "cap the injected sequence" policy lives in the request layer while the "which tokens" policy lives in the output layer. Replace all three with one method on OutputConfig that returns the finished sequence, taking the inputs it needs and keeping the format knowledge where the force-push correctly put it:
pub(crate) fn reasoning_close(&self, close: u32, after: u32, grammar: bool) -> Vec<u32>
with text_frame_opener kept but returning [u32; 2] (drop the Option/to_vec bridge — the caller decides emptiness once) and matching both markers in one pass. That deletes pipeline.rs:35-36 (the .map().unwrap_or_default()), the !tail.is_empty() re-check and the let mut tokens = vec![close] dance at request.rs:384-390, and gives the 1 + tail.len() < after capacity invariant exactly one home instead of two files that must agree.
4 (medium) helios/src/server/runtime.rs:430-438 — a branch that cannot fire, plus a 25-line re-walk of an algorithm the repo already has
let mut raw = Vec::new();
let mut token_ends = Vec::with_capacity(tokens.len() - window_start);
for &token in &tokens[window_start..] {
let Ok(bytes) = frontend.token_bytes(token) else {
return;
};
raw.extend_from_slice(bytes);
token_ends.push(raw.len());
}
Two subtraction problems in eight lines:
let Ok(bytes) = ... else { return; }(:433-435) is a silent no-op fallback. Afterconfig.rs:281(or after the lazyOnceLockinitializes),token_bytescan only fail on an out-of-range id, which a token the model just generated cannot be — and if it did fail, the function would silently skip the UTF-8 repair, which is the exact behaviour the PR exists to provide.AGENTS.md:182-186rejects "suppress errors, silently substitute execution paths". Either propagate (park()already returnsResult,runtime.rs:2156) or delete the branch.:439-455re-implements the incomplete-UTF-8 scan already inhelios/src/server/token_spans.rs:129-142with the samefrom_utf8/valid_up_to/error_lenprimitives. Because only the final incomplete suffix matters and a UTF-8 character is ≤4 bytes, the wholewhileloop collapses to a singlefrom_utf8overraw:
if let Err(error) = std::str::from_utf8(&raw)
&& error.error_len().is_none()
&& let Some(offset) = token_ends.iter().position(|&end| end > error.valid_up_to())
{
tokens.truncate(window_start + offset);
}
That removes the pos/incomplete_start state machine (runtime.rs:439-451), preserves the exact error_len().is_none() semantics the doc comment at :417-419 promises, and keeps the literal-U+FFFD test cases passing (a valid character makes the first from_utf8 return Ok, so nothing is truncated). Caveat for the correctness lens: std::str::from_utf8(&raw) returns the first error; with raw built from up to 8 tokens that is still the only incomplete-suffix error in practice, but the reviewer should confirm no generated sequence can contain an interior invalid group plus a trailing incomplete suffix. If that matters, keep the loop but drop the unreachable else { return; }.
5 (low) The same invariant is now guarded in two layers
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]),
);
(helios/src/server/runtime.rs:1995-1998)
The rule "a grammar never sees an injected tail" is enforced at preparation (request.rs:385, if grammar.is_none()) and here, where cut.close.len() == 1 silently discards a prepared 3-token close whenever a grammar exists. Keep one: the runtime clause is the better home (it is the layer that emits the tokens and already asks grammar.allows), and dropping the grammar.is_none() gate at request.rs:385 makes the guard un-bypassable by construction. Not a blocker, but two spellings of one invariant drift. Secondary, same block: the forced / abandon / injected triple bookkeeping (runtime.rs:1999-2031) around a loop that already breaks on error and on budget_stop would read better as one fn inject_close(...) -> Result<Option<Vec<u32>>>, folding forced && !abandon into the Ok path.
Checked and clean — explicitly not findings
docs/api.md:817-832— the new wording is tighter than what it replaces and correctly narrows the 400 condition; no duplication of the code contract.ReasoningCutdoc comment (helios/src/server/runtime.rs:50-61) — folded from two fields to one without leaving a staleclose_taildoc.saturating_subatruntime.rs:2042— correct and no dead alternative path beside it.helios/src/server/runtime/phase_tests.rs:405-428and theexercise_text_preemptionupdates — mechanicalclose: u32→Vec<u32>updates, appropriate for a field-type change; not gratuitous churn.use-statement placement inthinking_budget_close(helios/src/server/request.rs:544-545) and the explicitprepare_token_bytescall in the UTF-8 test (phase_tests.rs:813) — legitimate and test-local.- No environment-variable behaviour, no new model-identity flag, no duplicated DSML/marker table, no compatibility shim. The one thing this PR was previously guilty of here (format-specific literals in the request layer) is gone.
Answers to the "done when" bar
Every suggestion above cites file:line, quotes the code verbatim, and states what to remove or replace. Ranked by value per line changed: #1 (delete one line and a whole-VRAM-scale boot cost) > #2 (recover ~80 lines of duplicated harness without losing coverage) > #3 (one method instead of three hops) > #4 (delete an unreachable branch + 17 lines of loop) > #5 (delete one of two guards). Beyond these, I found nothing to subtract: the production surface of this diff is already lean and idiomatic for this repository.
Open questions and what I could not establish
- Is the unconditional
prepare_token_bytes()(config.rs:281) measured, or assumed? Nothing in the PR description, the diff, or the review thread gives a startup-latency or RSS number. Whoever owns multi-core startup cost should answer; without it, the lazyOnceLockis the simpler and strictly cheaper default. - Did the earlier bot review's "subtract" item actually land? One bot review at 19:28 flagged three should-fix groups plus a subtract; the author's 19:53 reply claims all fixed. The subtraction I can still see (
config.rs:281, the duplicated decode harness) suggests the subtract item was not the one addressed. I could not verify which item the bot labelled "subtract" — the review text is not resolvable from the repo, only from the PR comment thread. - Does parametrizing
renderer()actually fit? I readdecode.rs:1035-1075but not the full helper body to:1153; if its added-token list is load-bearing for other tests (DeepSeek/vision markers at:1064-1075), theadded: &[&str]parameter must append rather than replace. Recommend that shape either way. - Should the trim be scoped to the formats that need it? The gate is only
!appended.is_empty()(runtime.rs:2160), so it runs on every forced cut in every format, while preemption (runtime.rs:2152passes&[]) — which has the identical dangling-byte hazard — is untouched. That asymmetry is a scope/simplicity question for the author (one format's fix, all formats' behaviour; one hazard fixed, its twin not). - Is there an existing repo helper for "truncate to the last complete character"? I found the boundary scan in
token_spans.rs:129-142but no function I could call directly; if the author intends to keep the loop, extracting the shared scan intotoken_spansand calling it from both places would remove the duplication rather than just shortening it.