Recommendation: Changes Requested
This PR cleanly closes a real feature gap by enabling thinking_token_budget (and [server] thinking_token_budget) on ContentHeaders cores, and its core accounting, output_event_capacity, prompt_metadata::extend_text, and TmlOutput state transitions are verified sound. However, changes are requested before merge for three verified issues: the UTF-8 tail trim in Worker::park() uses a '\u{FFFD}' decode heuristic that drops legitimately generated literal U+FFFD tokens and silently fails to trim when <= 3 tokens were generated since the last admission/preemption, tml_text_transition_tokens() duplicates already-resolved TML control tokens with a per-format branch in request.rs, and the central behavioral claim (that <|message_model|><|content_text|> keeps a real Inkling 2 model in a text frame) currently has synthetic-only evidence with no real-checkpoint or live GPU verification.
Merge Risk
Level: Medium
helios/src/server/runtime.rs(Worker::publishandWorker::park) is a shared hot path used by every reasoning format and every parked/preempted continuation; the new UTF-8 trim runs on all forced reasoning cuts across all formats (not onlyContentHeaders).Worker::park()executes up to 4 synchronousfrontend.decodecalls on the worker thread per forced cut, with no real-checkpoint or live serving validation yet confirming the injected<|message_model|><|content_text|>continuation behavior on Inkling 2 models.- No wire/ABI, captured-graph, scheduler state-machine, or lock/contention changes are introduced; preemption (
park_if_preemptedpassing&[]) and uncapped requests are unaffected.
Walkthrough
helios/src/server/request.rs(381-401,543-578): Widensthinking_budget_close()to acceptOutputStart::RecipientFrameandOutputStart::RecipientHeaderwhenReasoningParserKind::ContentHeadershas a single-token close delimiter, and addstml_text_transition_tokens()to attach[<|message_model|>, <|content_text|>]asReasoningCut::close_tailwhenPromptEncoder::TmlV0+ContentHeadersis active, no tools or grammar are active, and1 + tail.len() < after.helios/src/server/runtime.rs(50-61,1956-2017,2129-2156): ExtendsReasoningCutwithclose_tail, injects[close, ...close_tail]sequentially throughActive::close_reasoning()inWorker::publish()(recording each injected token in decoded history andmetrics.progress, and subtractinginjected.len()fromcut.after), and adds a trailing-'\u{FFFD}'trim loop (up to 3 generated tokens within an 8-token window) inWorker::park()whenappendedis non-empty.docs/api.md(813-842): DocumentsContentHeadersbudget support, silent<|message_model|><|content_text|>injection when tools and grammar are absent, UTF-8 tail trimming on forced cuts, and updated HTTP 400 wording.helios/src/server/config.rs(663-710),helios/src/server/protocol/decode.rs(2032-2222),helios/src/server/runtime/phase_tests.rs(415-420,680-879): Adds unit and worker-loop tests covering bootstrap validation, request preparation across plain/tight-capacity/tools/tool_choice="none"/grammar/Messages/uncapped cases,close_tailinjection andOutputPipelinedecoding, and byte-level incomplete UTF-8 trimming versus plain continuation.
Pre-merge Checks
- [PASS] Security / malicious screen: No prompt-injection attempts, unsafe code, external I/O, or credential/trust-boundary changes.
- [WARN] Charter & value fit: Implementing a documented API field (
thinking_token_budget) onContentHeaderscores aligns with the API-support goal, but hardcoding<|message_model|>/<|content_text|>behind aPromptEncoder::TmlV0check inhelios/src/server/request.rs:543-555adds a format-specific branch whereoutput.control_tokensalready carries those validated markers. - [PASS] Related / duplicate / conflict check: Additive over #167 with no competing PRs and no file or behavioral conflicts with open #457 or #582 (verified against both PRs' diffs and file lists).
- [WARN] Tests & verification evidence: No CI checks on head
2652c06, and all reported tests are CPU-only with synthetic tokenizers; real-checkpoint#[ignore]tests (helios/src/server/request/tml_tests.rs) and live Inkling 2 serving were not run to verify the injected text-frame continuation.
Blockers
None.
Should Fix
- Replace the
'\u{FFFD}'decode heuristic inWorker::park()with exact token-byte UTF-8 boundary checking and fix the unnecessarygenerated_len - 1trim floor (helios/src/server/runtime.rs:2129-2155,helios/src/server/config.rs:281).- False positive on literal
U+FFFD: Decoding a window and checkingtext.ends_with('\u{FFFD}')(runtime.rs:2136-2139) cannot distinguish an incomplete trailing UTF-8 byte prefix from a legitimately generated literalU+FFFDcharacter ([0xEF, 0xBF, 0xBD])—an ambiguity the codebase already calls out inhelios/src/server/token_spans.rs:92-93. A literal'\u{FFFD}'at the budget boundary is silently deleted from the continuation prompt. - Silent failure on small/post-preemption passes (
generated_len <= 3):let max_trim = 3usize.min(generated_len.saturating_sub(1))andend > window_start(runtime.rs:2141-2144) fail to trim whenever a budget cut occurs with 1–3 tokens generated since the last admission (for example, a request preempted with 2 budget tokens remaining that generates[0xE2, 0xAC]of a 3-byte char:generated_len = 2->max_trim = 1-> trimming 1 token leaves[0xE2]which still ends inU+FFFD, so nothing is trimmed). The comment atruntime.rs:2131-2132claims at least one generated token must be retained forextend_text, which is unnecessary:tokens.extend_from_slice(appended)runs atruntime.rs:2156beforeextend_text(runtime.rs:2167-2168) with!appended.is_empty(), guaranteeingtokens.len() >= live.prompt_tokens + 1 > incoming.prompt.tokens.len(), andextend_textitself only requiresafter >= before(helios/src/model/admission.rs:26). - Fix: Use
Frontend::token_bytes()(helios/src/frontend/mod.rs:1534, backed byhelios/src/frontend/vocabulary.rs:11-45) on the trailing tokens and validate withstd::str::from_utf8(as inhelios/src/server/token_spans.rs:129-141), trimming generated tokens at index>= live.prompt_tokensonly whenUtf8Error::error_len().is_none()(a true incomplete UTF-8 suffix, never a literalU+FFFD). Ensurefrontend.prepare_token_bytes()?is called at bootstrap (helios/src/server/config.rs:281currently gates it onmodel.max_top_logprobs != 0) soVocabularyBytesis never lazily built on the worker thread during a cut. Add regression tests for a literalU+FFFDtoken at the cut boundary and a 2-byte incomplete tail withgenerated_len == 2.
- False positive on literal
- Delete
tml_text_transition_tokens()and resolve the TML text-frame opener from the already-validatedoutput.control_tokens(helios/src/server/request.rs:384-393, 543-555).- Contract validation already enforces the biconditional
ToolParserKind::TmlJson <=> ReasoningParserKind::ContentHeaders(helios/src/model/contract.rs:895-899), soprepare_output()(helios/src/model/prompt.rs:315-328,helios/src/output/pipeline.rs:131-142) has already encoded every marker inhelios/src/output/tml.rs:41-44(CONTROL_MARKERS, includingMODELandTEXT), validated each occupies one token, and stored them inoutput.control_tokensregardless of whether requesttoolsare empty. tml_text_transition_tokens()re-checksPromptEncoder::TmlV0+ContentHeaders, hardcodes the marker strings again inrequest.rs, and reaches intotokenizer().get_added_vocabulary().get_vocab()withoutprepare_output's single-token guarantee.- Fix: Expose a small helper on
OutputConfig/helios/src/output/(reusingtml::MODELandtml::TEXTagainstoutput.control_tokenswhenContentHeadersis active) and deletetml_text_transition_tokens()fromrequest.rs.
- Contract validation already enforces the biconditional
- Supply real-checkpoint / live Inkling 2 verification for the injected
<|message_model|><|content_text|>continuation.- Every test in this PR scripts the post-cut continuation tokens (
[1, 2]inhelios/src/server/runtime/phase_tests.rs:760), so nothing yet demonstrates against an actual Inkling 2 checkpoint that injecting<|message_model|><|content_text|>after<|end_message|>keeps the model generating in the text frame rather than immediately closing it or reopening<|content_thinking|>. - Fix: Run the real-tokenizer
tml_tests.rssuite (and add athinking_token_budgetcase there) plus at least one liveflare runtranscript on an Inkling 2 core demonstrating a hit onthinking_token_budgetcontinuing cleanly intocontent(both plain and with tools active).
- Every test in this PR scripts the post-cut continuation tokens (
Subtract / Simplify
- Collapse
ReasoningCut { close, close_tail }into one token sequence and delete the redundant runtimeinclude_tailre-check (helios/src/server/runtime.rs:50-61, 1962-1972,helios/src/server/request.rs:384-400).request.rs:384-393already checksoutput.content.tools.is_empty() && grammar.is_none()and1 + tail.len() < after. None ofprompt.grammar,cut.after, orcut.close_tailcan change between preparation andWorker::publish(), so theinclude_tailre-derivation andVecrebuild atruntime.rs:1962-1972duplicate an already-decided invariant.- Replacing
close+close_tailwith a single non-empty sequence (built once inrequest.rswhen1 + tail.len() < after as usize) removes ~20 lines of duplicated policy and the repeatedu64::from(1 + ... as u32) < u64::from(after)casts. (phase_tests.rs:786-800Case 2 only tests that duplicated runtime guard; request-level tight-capacity coverage already exists atdecode.rs:2161-2171.)
Nits
helios/src/server/runtime.rs:70: Update the stale singular comment"A reasoning cut's forced token is part of 'after'"to plural"forced tokens".docs/api.md:821-823: Clarify that incomplete UTF-8 tail trimming on forced cuts applies to all reasoning formats (not onlyContentHeaders), since the sentence currently sits inside the TMLv0ContentHeadersexplanation.helios/src/server/config.rs:667-682andhelios/src/server/protocol/decode.rs:2054-2069: Reusecrate::output::tml::CONTROL_MARKERSinstead of re-spelling the 14 marker strings inline in both tests.
Dropped on verification
- PR #582 edit conflict on
Worker::park()(from Dossier / Value Prop): Verified false. PR #582 changes 7 files inscheduleranddocs/; it does not modifyhelios/src/server/runtime.rsat all (a review comment on #582 merely citedruntime.rs:2106-2121for explanation). - PR #457 conflict on
<|message_model|><|content_text|>(from Dossier / Value Prop / Correctness): Verified false. PR #457'sHeaderWithoutContentEOS error only fires when a non-empty model header (model && at > 0) closes on<|end_message|>or<|content_model_end_sampling|>with no emitted answer, and explicitly preserves empty model headers and external terminations (UserStop,OutputLimit). Injecting<|message_model|><|content_text|>immediately entersState::Body { kind: Body::Text, model: true }(helios/src/output/tml.rs:277-281) and touches none of #457's files. - Correctness F1 — "Blocker-adjacent: UTF-8 trim diverges active JSON grammar state; no non-TML test; hidden scope": Verified false. Trimming only runs when
forced == true, which requiresreasoning_open() == trueandgrammar.allows(cut.close)(runtime.rs:1951-1958)—generation cannot be inside a JSON string answer whilereasoning_open()is true, andllguidance's/(?s:.+)/reasoning region (helios/src/grammar.rs:462-466) enforces UTF-8 boundaries before accepting the close token. Furthermore, the PR description explicitly states "across all reasoning formats" andphase_tests.rs:825-879explicitly tests a non-TML (ThinkTags) cut viabudget_cut(4, 3)(phase_tests.rs:408-428). Only thedocs/api.mdparagraph placement survives as a nit. - Correctness F4 — "User token stop mid-tail leaves
TmlOutputinState::Headerand finishes withreason = \"length\"": Verified false. Whenbudget_stopis true,user_stopis true andruntime.rs:2055setsreason = "stop"withTermination::UserStop, not"length". Moreover,TokenStops::push(helios/src/server/stops.rs:32-44) strips the matched stop token so<|message_model|>is never delivered toTmlOutput, and honoring an explicit user stop token is documented behavior (docs/api.md:828). - Correctness F5 — "Hidden-token accounting triples and
prompt_tokensdoes not follow": Dropped.docs/api.md:823-824already documents that forced close tokens count as generated tokens within the output limit, andprompt_tokensintentionally tracks the original user prompt across all parks/continuations rather than absorbing generated or injected tokens. - Correctness F6 — "
decoded_sequencemismatch breaks prefix cache reconciliation": Dropped as low-signal / misframed.DecodedHistory(helios/src/scheduler/decoded_history.rs:48-145) is only an advisory copy-draft n-gram index for verified speculative proposals (not KV prefix caching), and keeping the emitted stream there has no correctness impact. - Subtraction S4 (partial) — "
decode.rstest can reuserenderer(PromptEncoder::TmlV0, ...)and drops temp-file cleanup": Verified false.renderer()(decode.rs:1035-1154) does not add the 14 TML control tokens and uses DeepSeek's EOS token, anddecode.rs:2106does remove its temp file (std::fs::remove_file(path).unwrap()). Retained only theCONTROL_MARKERSarray reuse as a nit. - Stale companion docs
docs/logprobs-design.md:19anddocs/cli-design.md:1337,1367,1417: Verified false.docs/logprobs-design.md:19already uses plural"Forced tokens", anddocs/cli-design.mddoes not enumerate supported reasoning formats.