Repository navigation
fix: align streamed tool-call and marker cleanup with non-streamed output - #2458
Merged
Merged
Conversation
10 tasks done
Member
Author
Implementation Review SummaryIntent
Findings Addressed
Remaining Items
Verification
|
Member
Author
|
Security and performance review, fixed in 6cb57cd (test-first; the five new parity tests fail on 155804f):
Remaining, not fixed here:
|
…tput The streaming StreamFilter and the non-streamed cleanup disagreed on several outputs, and both leaked model control markers. - Whitespace after a closed tool call is held until visible text arrives, and dropped when another call opens or the stream ends, so two adjacent calls no longer stream a bare "\n" as content. - Newlines after a thinking close are trimmed across feed() calls. The trimmed bytes are reported as FilterOutput::post_thinking_gap so --reasoning-format none still streams them after the close marker (#1470). - The non-streamed cleanup now drops Hermes <tool_call> blocks (closed or unclosed) that were not parsed into calls, matching what the stream suppresses (#1743 rule, now stated in the stream_filter module doc). - Aya Vision <|START_RESPONSE|>/<|END_RESPONSE|> and GLM-4.xV <|begin_of_box|>/<|end_of_box|> are stripped on both paths. - Kimi-VL adds the <|im_assistant|> tokenizer id to its stop set when the tokenizer defines it. - gpt-oss Harmony: the filter routes <|channel|> headers through the same HarmonyRoute classifier try_harmony uses, and clean_structural_tokens runs try_harmony, so a no-tools reply no longer carries analysis text and channel markup in content (confirmed on gpt-oss-20b before the fix). Parity tests feed each case whole, per character, at fixed widths and at every two-piece split, and compare against the non-streamed result. Closes #2394
The real-checkpoint smoke on glm-4.1v-9b-thinking-4bit showed that once the box markers were stripped, the reply still opened with a literal <answer> (the stop token ends generation before </answer>). Both are dedicated tokenizer tokens (151347/151348) like the model's <think> pair, so they are stripped globally in CHAT_DELIMITERS and clean_content_markers, with a parity test built from the recorded output. Refs #2394
At end of stream the filter stripped an unterminated `<|channel|>` header together with everything after it, even when no Harmony message had been seen. `try_harmony` declines a reply that never reaches `<|message|>`, so the non-streamed content keeps such a mention, and a non-Harmony model that wrote the marker in plain text lost the rest of its streamed answer. The strip now applies only once Harmony output is active, which is the case `try_harmony` actually drops. The parity harness also asserts the logprob bookkeeping on every chunking: no output suppresses more positions than it consumes, and the feeds plus the flush report each fed position exactly once. Refs #2394
The pending-header hold added for Harmony and Muse had no length limit. A literal `<|channel|>` or `<|start|>assistant to=` that never reaches `<|message|>` (a non-Harmony model mentioning the marker, which a prompt can induce) held every later byte until end of generation, so the client saw nothing more and every feed() rescanned a buffer that grew with the reply. A header now holds for at most MAX_HEADER_HOLD (256) bytes. Past that, before any Harmony output it is plain text and the scan moves on to the next `<|channel|>`; after Harmony output it is suppressed with what follows, as try_harmony drops a header with no `<|message|>`. Once Harmony output has been seen, the generic delimiter table and ATEM openers no longer drive the filter. A `</tool_call>` inside `to=` call arguments ended suppression and streamed the rest of the call as content, and a `</think>` in the `analysis` channel streamed the remaining chain-of-thought as content (#1743). try_harmony treats both as text, so streamed and non-streamed now agree. The Muse role-recipient matcher stays live so `<|start|>assistant to=NAME<|channel|>...` calls remain suppressed. Five new parity tests fail on the previous head and pass now: buffer-bound assertions for both literal markers and an overlong post-Harmony header, plus the two Harmony leak cases. server::tool_calls (429), routes::chat, router_front, and in_process pass. Refs #2394
Add unit tests for formats::harmony_route (analysis, final, commentary, unknown channels, and a to= recipient on any channel) and for strip_hermes_tool_blocks (closed, unclosed, and stray close-tag cases). Document the unified streamed and non-streamed chat content cleanup, Harmony reasoning split, and the Kimi-VL stop token in docs/supported-models.md. Validation: - cargo fmt --check clean - server::tool_calls lib tests: 431 passed, 0 failed Refs #2394
0b8b3f4 stripped <answer>/</answer> from every model's output on both paths. Unlike the <|...|> markers, these are ordinary text that prompts and eval harnesses ask models to write, so every other model lost them silently. The wrapper now lives outside CHAT_DELIMITERS and clean_content_markers. tool_calls::answer_wrapper_enabled is true when the tokenizer defines both tags as added tokens, as the GLM-4.1V checkpoints do. The chat, responses, anthropic, router front and in-process routes pass it to StreamFilter::with_answer_wrapper and apply strip_answer_wrapper to the non-streamed content, so both paths stay in parity. Only content is unwrapped; reasoning keeps the tags on both paths. The other marker strips are unchanged. Tests: answer_tags_are_ordinary_text_for_other_models fails on 5988717; the GLM gating and tokenizer tests use the new gate, so they do not compile there. server::tool_calls passes 433. Refs #2394
inureyes
force-pushed
the
fix/issue-2394-stream-filter-parity
branch
from
October 19, 2026 07:43
9033192 to
ea1b28c
Compare
This was referenced Oct 20, 2026
3 tasks done
sustainabilities
pushed a commit
to sustainabilities/mlxcel
that referenced
this pull request
Oct 21, 2026
…up#2458 (lablup#2500) ## Summary Closes the eight streamed vs non-streamed parity gaps lablup#2458 left (issue items 1-6 plus 7 and 8 from the comment). The non-streamed cleaner is the reference; items 2, 5 and 6 change both paths. The fixes sit in `StreamFilter`, the parsers, and the live routes (`routes/chat.rs`, both `router_front.rs` paths). **Item 1 decision:** Harmony has no canonical thinking-marker pair, so under `--reasoning-format none` gpt-oss returns the answer only, streamed or not, as the non-streamed reply already did. The new `ThinkingDelimiterEcho::thoughts_in_content` puts thoughts in content only inside a delimited block (an echoed open marker). Muse `to=self` reasoning, which also has no pair, now follows the same rule. ## Behavior changes a client can see - Item 8: trailing content whitespace is held until visible text follows, for every family. A whitespace-only token reaches the client with the next word. Whitespace before a final tool call or at end of stream never streams, and nothing is retracted. - Items 3, 4, 7: whitespace after a leading tool call is dropped. Harmony content and `analysis` bodies are trimmed and joined with `\n` in the stream. Responses `reasoning_tokens` stay equal. - Item 2: a `to=functions.X` recipient in the Harmony role header is a tool call on both paths (shared `harmony_role_suffix`). - Items 5, 6: no `]<]minimax[>[` residue in no-tools content. Kimi-VL `◁think▷`/`◁/think▷` go to reasoning. - router_front non-streamed under `none` now carries the markers and the post-close gap, where it used to append bare reasoning. ## Changes during review - **Whitespace after `</think>` under `none`** (`1edd9916`). The item 8 hold dropped whitespace after a thinking close when no answer followed (`<think>r</think> \n`), and dropped the space in `</think> <tool_call>..</tool_call>B`. A new `post_close_ws` span in `StreamFilter` reports that whitespace as `post_thinking_gap` when it is dropped, matching the non-streamed `post_close_whitespace`. Test: `whitespace_after_the_close_marker_with_no_answer_survives`. - **Role-header recipient with unusual whitespace** (`8adab292`). With two spaces, a tab or a newline before `to=`, the stream drained `<|start|>assistant to=functions.f` as content and leaked the call arguments. `pending_harmony_role_header` now holds `<|start|>assistant` plus whitespace (no `<|`) up to 256 bytes. `formats::HARMONY_MAX_ROLE_SUFFIX` caps the role suffix for both `try_harmony` and the stream, so both accept the same headers. Test: `harmony_role_header_with_unusual_whitespace_is_held_until_it_resolves`. - **Docs** (`2dfca808`): `CHANGELOG.md` and `docs/supported-models.md`. **Measured (security review):** the whitespace hold is linear (1 MiB of spaces fed per byte costs the same as 1 MiB of letters). `held_ws` has no cap, but the routes already keep the full raw text. 50k Harmony messages stream in 0.47 s. 20k random multibyte inputs produced no panics. **Known, not in this PR:** `try_harmony` is quadratic in message count (pre-existing; about 40 ms at 32k tokens). Whitespace at the very start of a generation still streams. A prompt that already ends with `<|start|>assistant` leaves a bare ` to=functions.X` that neither path reads. A primed Kimi-VL `◁think▷` close is not recognized by `primed_open_thinking_close_marker`. ## Test plan - [x] One parity test per item in `stream_parity_tests.rs`, across `chunkings()`. All eight fail when run against the main sources: source hunks stashed, test file kept, plus a temporary main-equivalent `thoughts_in_content` for item 1. - [x] Narrow `--lib` targets: `server::tool_calls::` (468), `server::routes::` (461), `server::responses`, `server::router_front`, `server::muse_atem`, `server::reasoning_echo`, `server::in_process`, `server::chat_request`, `server::anthropic`. All pass on a CPU build. - [x] `cargo clippy -p mlxcel --lib --tests -- -D warnings` and rustfmt on touched files are clean. - Ten filter unit tests now pin the held trailing space instead of an immediate one. Resolves lablup#2464
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Streamed and non-streamed chat output now agree on tool calls, reasoning, and visible content for the five cases in #2394, and neither path leaks the listed control markers.
A<tool_call>..</tool_call>\nBstill streamsAthen\nB).feed()calls. The trimmed bytes travel in a newFilterOutput::post_thinking_gap, which the chat route and the router front re-emit after the close marker under--reasoning-format none/deepseek-legacy, so the fix(server): implement assistant prefill, reasoning-budget message, and completion echo #1470 byte-for-byte test still holds.clean_content_markerskept Hermes<tool_call>blocks (unclosed, or on a no-tools request) that the stream suppresses. It now drops them, and thestream_filtermodule doc states the feat(tokenizer): Kimi K3 tiktoken family and native XTML renderer #1743 rule.<|START_RESPONSE|>/<|END_RESPONSE|>and GLM-4.xV<|begin_of_box|>/<|end_of_box|>are stripped on both paths. The GLM smoke also showed a literal<answer>;<answer>/</answer>are stripped only when the tokenizer defines both as added tokens (tool_calls::answer_wrapper_enabled, true for GLM-4.1V), throughStreamFilter::with_answer_wrapperandstrip_answer_wrapperon the non-streamed content. Every other model keeps them as text, and reasoning keeps them on both paths.<|im_assistant|>id toeos_token_ids, read fromtokenizer_config.jsonadded_tokens_decoderortokenizer.jsonadded_tokens, deduplicated.<|channel|>...<|message|>headers (with the<|start|>assistantrole header) and routes them through aHarmonyRouteclassifier shared withtry_harmony;<|end|>/<|return|>/<|call|>act only after Harmony output, so Phi-3's<|end|>is untouched.clean_structural_tokensnow runstry_harmony, which fixes the no-tools non-streamed reply too. A header still waiting for<|message|>is held past the partial-match window for at most 256 bytes (MAX_HEADER_HOLD), which also covers long Museto=recipients; a literal<|channel|>in a non-Harmony reply is kept as text, astry_harmonykeeps it.Changes during review
<|channel|>in prose stalled the stream and made everyfeed()rescan a growing buffer; it is now capped. Once Harmony output has been seen, other families' markers no longer change state, so a</tool_call>inside call arguments or a</think>insideanalysiscannot push the rest of the call or the chain-of-thought intocontent(feat(tokenizer): Kimi K3 tiktoken family and native XTML renderer #1743).<|channel|>at end of stream is stripped only after Harmony output, matchingtry_harmony.<answer>/</answer>were first stripped for every model, which silently removed tags that prompts and eval harnesses ask for. They are now gated on the tokenizer;answer_tags_are_ordinary_text_for_other_modelsfails on5988717c.docs/supported-models.mddescribes the cleanup rules.gpt-oss runtime check (item 5)
mlxcel-server -m models/mlx/gpt-oss-20b-mxfp4, temperature 0. No-tools request:{"messages":[{"role":"user","content":"What is 17 times 3? Answer briefly."}],"max_tokens":256}. Tool request:"What is the weather in Paris right now? Use the tool."with oneget_weather(city)function.<|channel|>analysis<|message|>The user asks: ... So answer: 51.<|end|><|start|>assistant<|channel|>final<|message|>51, no reasoning51, reasoningThe user asks: ... So answer: 51.<|channel|>analysis<|message|>...51.<|end|>\n5151, same reasoningcommentary to=functions.get_weather <|constrain|>json<|message|>{"city":"Paris"}; tool call correctget_weather {"city":"Paris"},finish_reason: tool_callsget_weather {"city":"Paris"}, same reasoningRe-run on the final head after the review fixes: same results on all four arms.
Real-checkpoint smoke (image prompt, streamed and non-streamed identical in every run)
<|START_RESPONSE|>There are three shapes ...<|END_RESPONSE|>, PRThere are three shapes in the image: a square, a circle, and a triangle.<answer>There are <|begin_of_box|>3<|end_of_box|> shapes in the image., PRThere are 3 shapes in the image.stop). This checkpoint already lists 163586 inconfig.jsoneos_token_id, so the smoke cannot tell the two builds apart. The fixture tests cover the added path.Test plan
stream_parity_tests: each case is fed whole, one character at a time, at widths 2/3/5/7, and split at every boundary, then compared withclean_structural_tokens/parse_tool_calls. On main, 10 of the 11 original tests fail; the Phi-3<|end|>guard passes on both.loading::vlm::kimi_vl_loader)server::,tokenizer::,reasoning_display: 3674 passed, 0 failed;server::tool_calls: 433 passed (test-fast, cuda, head90331924)cargo clippy --profile test-fast --features cuda -p mlxcel --lib --tests --no-deps -- -D warningsandcargo fmt --checkcleanNot covered: Harmony content split over several
final/commentarymessages is joined with\nbytry_harmonybut streamed back-to-back; trailing whitespace inside a Harmony body is trimmed only on the non-streamed side; a recipient placed in the role header (<|start|>assistant to=functions.x<|channel|>...) is a tool call in the stream but commentary intry_harmony(pre-existingformats.rsgap); under--reasoning-format nonegpt-oss streams analysis plus answer as content while the non-streamed form returns only the answer, because Harmony has no canonical thinking marker pair. Kimi-VL's◁think▷markers still reach content on both paths; they are outside this issue.Closes #2394