Skip to content

fix: align streamed tool-call and marker cleanup with non-streamed output - #2458

Merged
inureyes merged 7 commits into
mainfrom
fix/issue-2394-stream-filter-parity
Oct 19, 2026
Merged

inureyes merged 7 commits into
mainfrom
fix/issue-2394-stream-filter-parity

Conversation

@inureyes

@inureyes inureyes commented Oct 19, 2026 •

Copy link
Copy Markdown
Member

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.

  • Whitespace after a closed tool call is held until visible text arrives and dropped if another call opens or the stream ends (A<tool_call>..</tool_call>\nB still streams A then \nB).
  • Newlines after a thinking close are trimmed across feed() calls. The trimmed bytes travel in a new FilterOutput::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.
  • Item 3 was not a pure pin: non-streamed clean_content_markers kept Hermes <tool_call> blocks (unclosed, or on a no-tools request) that the stream suppresses. It now drops them, and the stream_filter module doc states the feat(tokenizer): Kimi K3 tiktoken family and native XTML renderer #1743 rule.
  • Aya Vision <|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), through StreamFilter::with_answer_wrapper and strip_answer_wrapper on the non-streamed content. Every other model keeps them as text, and reasoning keeps them on both paths.
  • Kimi-VL appends the <|im_assistant|> id to eos_token_ids, read from tokenizer_config.json added_tokens_decoder or tokenizer.json added_tokens, deduplicated.
  • Harmony: the filter matches <|channel|>...<|message|> headers (with the <|start|>assistant role header) and routes them through a HarmonyRoute classifier shared with try_harmony; <|end|>/<|return|>/<|call|> act only after Harmony output, so Phi-3's <|end|> is untouched. clean_structural_tokens now runs try_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 Muse to= recipients; a literal <|channel|> in a non-Harmony reply is kept as text, as try_harmony keeps it.

Changes during review

  • Security review: the header hold was unbounded, so a literal <|channel|> in prose stalled the stream and made every feed() 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> inside analysis cannot push the rest of the call or the chain-of-thought into content (feat(tokenizer): Kimi K3 tiktoken family and native XTML renderer #1743).
  • Implementation review: an unterminated <|channel|> at end of stream is stripped only after Harmony output, matching try_harmony.
  • Coordinator review: <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_models fails on 5988717c.
  • docs/supported-models.md describes 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 one get_weather(city) function.

Arm main this PR
no tools, stream content <|channel|>analysis<|message|>The user asks: ... So answer: 51.<|end|><|start|>assistant<|channel|>final<|message|>51, no reasoning content 51, reasoning The user asks: ... So answer: 51.
no tools, non-stream content <|channel|>analysis<|message|>...51.<|end|>\n51 content 51, same reasoning
tools, stream content carried the analysis text and commentary to=functions.get_weather <|constrain|>json<|message|>{"city":"Paris"}; tool call correct content empty, reasoning is the analysis text, get_weather {"city":"Paris"}, finish_reason: tool_calls
tools, non-stream already correct unchanged: get_weather {"city":"Paris"}, same reasoning

Re-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)

  • aya-vision-8b: main <|START_RESPONSE|>There are three shapes ...<|END_RESPONSE|>, PR There are three shapes in the image: a square, a circle, and a triangle.
  • glm-4.1v-9b-thinking-4bit: main <answer>There are <|begin_of_box|>3<|end_of_box|> shapes in the image., PR There are 3 shapes in the image.
  • kimi-vl-a3b-thinking-4bit: stops at end of turn (155 tokens, stop). This checkpoint already lists 163586 in config.json eos_token_id, so the smoke cannot tell the two builds apart. The fixture tests cover the added path.

Test plan

  • New 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 with clean_structural_tokens / parse_tool_calls. On main, 10 of the 11 original tests fail; the Phi-3 <|end|> guard passes on both.
  • Kimi-VL eos fixture tests (loading::vlm::kimi_vl_loader)
  • server::, tokenizer::, reasoning_display: 3674 passed, 0 failed; server::tool_calls: 433 passed (test-fast, cuda, head 90331924)
  • cargo clippy --profile test-fast --features cuda -p mlxcel --lib --tests --no-deps -- -D warnings and cargo fmt --check clean

Not covered: Harmony content split over several final/commentary messages is joined with \n by try_harmony but 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 in try_harmony (pre-existing formats.rs gap); under --reasoning-format none gpt-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

@inureyes inureyes added status:review Under review type:bug Bug fixes, error corrections, or issue resolutions priority:medium Medium priority area:inference Generation, sampling, decoding (incl. speculative, DRY) labels Oct 19, 2026
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Make streamed (StreamFilter) and non-streamed chat output agree on tool calls, reasoning, and content for the five #2394 cases, with no control-marker leaks.

Findings Addressed

  • At end of stream the filter stripped an unterminated <|channel|> header and everything after it even with no Harmony output seen; try_harmony declines such text, so a non-Harmony reply mentioning the marker lost the rest of its streamed answer. The strip is now gated on Harmony output being active (155804f, MEDIUM). Side effect: a gpt-oss generation cut off inside its first header now shows <|channel|>analysis on the stream too, matching the non-streamed path.
  • Parity harness now asserts the logprob bookkeeping under every chunking: consumed_positions >= suppressed_positions per output, and feeds plus flush report each position exactly once. All cases pass.

Remaining Items

  • --reasoning-format none / deepseek-legacy with gpt-oss: Harmony has no canonical thinking pair, so the stream puts analysis text plus final text into content with no markers, while non-streamed content is the final text only (MEDIUM). Needs a decision on what none should look like for Harmony; suggest a follow-up issue.
  • routes/chat.rs flush path does not emit post_thinking_gap (router_front.rs does); same class as the existing flush path not echoing thinking_close (LOW).
  • Held whitespace positions are reported when released or dropped, so a Strip delimiter arriving while whitespace is held is paired with the wrong logprob entry. Counts stay correct (LOW).
  • <tool_call>..</tool_call>\nB with no text before the call streams \nB, non-streamed gives B; a narrower case of the existing leading-whitespace difference (LOW).
  • A non-Harmony reply that writes a literal <|channel|> still holds the rest of its text until end of stream; content is now correct, only latency is affected (LOW).
  • Out of scope but changed surface: strip_hermes_tool_blocks cuts <tool_call> out of MiniMax M3 ]<]minimax[>[<tool_call> blocks on the no-tools path, leaving namespace residue (M3 no-tools parity is excluded by the issue).

Verification

  • All stated requirements implemented
  • No placeholder/mock code remaining
  • Integrated into project code flow
  • Project conventions followed
  • Existing modules reused where applicable
  • No unintended structural changes
  • Tests pass (server::tool_calls 424, routes::chat 71, loading::vlm::kimi 9; test-fast, cuda)

@inureyes

inureyes commented Oct 19, 2026 •

Copy link
Copy Markdown
Member Author

Security and performance review, fixed in 6cb57cd (test-first; the five new parity tests fail on 155804f):

  • HIGH: the pending Harmony/Muse header hold was unbounded. A literal <|channel|> or <|start|>assistant to= with no <|message|> stalled the stream until end of generation and made each feed() rescan the whole reply. Headers now hold for at most 256 bytes.
  • HIGH: inside Harmony output, generic markers still changed state, so </tool_call> in call arguments or </think> in analysis streamed the rest of the call or the chain-of-thought as content (feat(tokenizer): Kimi K3 tiktoken family and native XTML renderer #1743). Only Harmony markers and the Muse role recipient act once Harmony output is seen, so wrapper tokens inside a final body are now kept on both paths.

Remaining, not fixed here:

  • MEDIUM (pre-existing): try_harmony reads to= only from the channel header. A role-position recipient (<|start|>assistant to=functions.X<|channel|>commentary json<|message|>) routes the arguments to non-streamed content. Streaming suppresses it through the Muse matcher.
  • LOW: <answer> / </answer> are stripped globally on both paths, so literal text in any model's reply loses them.
  • LOW (known divergence): before any Harmony output, a <|channel|> whose <|message|> comes more than 256 bytes later is literal text in the stream, but try_harmony still parses it as a header. This only happens with pathological input.
  • LOW: whitespace held after a tool call is unbounded, but it is linear in output size.
  • LOW: Kimi-VL reads the ~20 MB tokenizer.json into a String once per load. Ids are range-checked, so nothing blocks.

@inureyes inureyes added status:done Completed and removed status:review Under review labels Oct 19, 2026
…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
inureyes force-pushed the fix/issue-2394-stream-filter-parity branch from 9033192 to ea1b28c Compare October 19, 2026 07:43
@inureyes
inureyes merged commit 93b15cb into main Oct 19, 2026
52 of 53 checks passed
@inureyes
inureyes deleted the fix/issue-2394-stream-filter-parity branch October 19, 2026 08:22
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
@inureyes inureyes added this to the 0.8 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:inference Generation, sampling, decoding (incl. speculative, DRY) priority:medium Medium priority status:done Completed type:bug Bug fixes, error corrections, or issue resolutions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix: Align streamed tool-call and marker cleanup with non-streamed output

1 participant