Skip to content

fix(server): close the streamed vs non-streamed parity gaps from #2458 - #2500

Merged
adrysn merged 5 commits into
mainfrom
fix/issue-2464-stream-parity-gaps
Oct 20, 2026
Merged

adrysn merged 5 commits into
mainfrom
fix/issue-2464-stream-parity-gaps

Conversation

@adrysn

@adrysn adrysn commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

Summary

Closes the eight streamed vs non-streamed parity gaps #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

  • 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.
  • 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.
  • 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 #2464

PR #2458 left eight cases where a client saw different content or reasoning depending on whether it streamed. The non-streamed cleaner is the reference except where both paths change.

- StreamFilter holds trailing content whitespace until visible text decides it, so whitespace before a final tool call (`<tool_call>`, `<|python_tag|>`) never streams and nothing is retracted; whitespace after a leading call is dropped as leading whitespace.
- Harmony bodies are trimmed and joined with a newline in the stream, for content and `analysis` reasoning, as try_harmony joins them; reasoning_tokens stay equal on Responses.
- A `to=` recipient in the Harmony role header is a tool call in try_harmony and in the filter, via a shared `harmony_role_suffix`.
- Kimi-VL `◁think▷` / `◁/think▷` route to reasoning on both paths; a MiniMax M3 block leaves no namespace token in no-tools content.
- Under `--reasoning-format none`, thoughts reach content only inside a delimited block (`ThinkingDelimiterEcho::thoughts_in_content`, used by routes/chat.rs and both router_front paths), so gpt-oss returns the answer only, matching the non-streamed reply.

Each item has a parity test in stream_parity_tests.rs across all chunkings; all eight fail with the main sources. Ten filter unit tests now pin the held trailing space.

Refs #2464
@adrysn adrysn 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 20, 2026
The #2464 trailing-whitespace hold dropped whitespace that followed a thinking close marker when no answer came after it, so under `--reasoning-format none` a reply such as `<think>r</think>  \n` streamed as `<think>r</think>` while the non-streamed reply kept the trailing run. The same loss hit `</think> <tool_call>...</tool_call>B`, where the space before the call was dropped as leading whitespace.

StreamFilter now records which part of the held whitespace directly follows a thinking close, bounded by the next delimiter, and reports it as `post_thinking_gap` when that whitespace is dropped at end of stream or after a tool call, matching `post_close_whitespace`. Content output is unchanged.

A route-level parity test covers spaces after the close, mixed newlines and spaces, an answer after the gap, and the tool-call cases, fed at every fragment count. It fails without the fix. The tool_calls, routes, responses, router_front, muse_atem and reasoning_echo suites, clippy and fmt pass.

Refs #2464
@adrysn

adrysn commented Oct 20, 2026

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Close the eight streamed vs non-streamed parity gaps listed in #2464 (six in the body, items 7 and 8 from the thread).

Findings Addressed

  • Under --reasoning-format none, whitespace after a thinking close with no answer after it (<think>r</think> \n) was dropped by the new trailing-whitespace hold, and the space before a call in </think> <tool_call>..</tool_call>B was lost too. The filter now reports that run as post_thinking_gap, bounded by the next delimiter. Route-level parity test added (1edd991). (HIGH)

Remaining Items

  • Consecutive whitespace-only tokens (newline then indentation before code) are held until the next visible character, so latency can exceed one token for that run. Nothing is retracted. (LOW)

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

@adrysn

adrysn commented Oct 20, 2026

Copy link
Copy Markdown
Member Author

Security and performance pass on the #2464 parity fixes, with model output treated as untrusted. No CRITICAL or HIGH findings, so no commits were added.

MEDIUM: streamed tool-call arguments leak into delta.content for a role-header recipient with non-standard whitespace. <|start|>assistant to=functions.f<|channel|>commentary json<|message|>{"a":1}<|call|> (two spaces, or \t / \n before to=) fed per character streams <|start|>assistant to=functions.f\n{"a":1} as content; after earlier Harmony output it streams {"a":1}. A whole feed and parse_tool_calls both return one call and empty content. Only the exact <|start|>assistant to= (Muse) prefix is held while streaming, so the role text drains before <|channel|> arrives, harmony_role_header finds no role, and the message routes as commentary content. Suggested fix: hold <|start|>assistant followed by whitespace and no <| (the harmony_role_suffix shape) for up to MAX_HEADER_HOLD in unterminated_header_start / safe_emit_length. The single-space form gpt-oss emits is fine.

LOW: role-header lookback window vs try_harmony. The stream searches only the last 274 bytes before <|channel|>; try_harmony searches the whole gap, so a longer role suffix routes differently. Unrealistic output.

Measured, no finding:

  • Whitespace hold-back is linear: 1 MiB of spaces fed one byte per token takes 3.6 s, the same as a 1 MiB a baseline, with each quarter at about 0.9 s. Fed whole it takes 5 ms. Release and drop are O(1) per call. held_ws grows with output length, as the routes' accumulated raw text already does, so memory is not amplified.
  • 50k Harmony messages (2.8 MB) stream in 0.47 s and replay through collect_reasoning_chunked in 0.09 s. The bounded role-header scan and the per-message join are linear.
  • Fuzzing 20k random multibyte inputs (Kimi ◁think▷ pieces, Hangul, emoji, U+3000, U+00A0, all marker families, and padding that puts the 274-byte lookback inside a multibyte char) found no panics. Outside the gap above and the existing MAX_HEADER_HOLD cutoff, every chunking matched the whole feed.

Pre-existing, not from this PR: try_harmony is quadratic in message count because each body searches to the end for absent terminators (18 s at 50k messages, about 40 ms at 32k tokens). A single whole feed() of 50k role-header calls takes 42 s; production replays in 128-byte chunks (0.09 s).

Gates: server::tool_calls::, server::routes::, server::responses, server::router_front, server::muse_atem, server::reasoning_echo, clippy --lib --tests -D warnings, and cargo fmt --check pass.

Security review of #2500: the stream held only the exact Muse `<|start|>assistant to=` prefix, so a role header with two spaces, a tab or a newline before `to=` drained as content before its `<|channel|>` arrived, and the call arguments then streamed as content too. `unterminated_header_start` (and through it `safe_emit_length`) now also holds `<|start|>assistant` followed by whitespace and no `<|`, optionally ending in a partial `<|channel|>`, the shape `harmony_role_suffix` accepts.

The role suffix is now capped at `HARMONY_MAX_ROLE_SUFFIX` (256 bytes) in `harmony_role_suffix`, the same bound the stream holds and looks back, so `try_harmony` and the filter accept the same role headers.

New parity test `harmony_role_header_with_unusual_whitespace_is_held_until_it_resolves` covers double space, tab and newline across all chunkings; it failed before the fix with the arguments in streamed content.

Refs #2464
… notes

Add the Unreleased/Fixed entry for the eight streamed vs non-streamed gaps. Extend the #2464 paragraph in docs/supported-models.md with the Muse to=self rule under --reasoning-format none, end-of-stream whitespace trimming, and the router_front non-streamed none output now carrying the thinking markers.

Validation: tool_calls, routes, responses and router_front lib tests pass with MLXCEL_BUILD_METAL=0; clippy --lib --tests -D warnings and cargo fmt --check are clean.

Refs #2464
@adrysn adrysn added status:done Completed and removed status:review Under review labels Oct 20, 2026
@adrysn
adrysn merged commit dea9cee into main Oct 20, 2026
28 checks passed
@adrysn
adrysn deleted the fix/issue-2464-stream-parity-gaps branch October 20, 2026 14:07
@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(server): close remaining streamed vs non-streamed output gaps

2 participants