Skip to content

[Fix] Harden DeepSeek-V4 tool-call streaming - #34600

Closed
Leoyzen wants to merge 1 commit into
sgl-project:mainfrom
Leoyzen:feat/dsv4-parser-streaming-fixes
Closed

Leoyzen wants to merge 1 commit into
sgl-project:mainfrom
Leoyzen:feat/dsv4-parser-streaming-fixes

Conversation

@Leoyzen

@Leoyzen Leoyzen commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

#34458 made DeepSeek-V4 reasoning and tool-call streaming parsing chunk-invariant. Four additional streaming robustness bugs remain on top of that work, causing tool call loss, value truncation, text trapping, and DSML tag leakage in production serving. This PR fixes all four.

Modifications

Bug 1: Exception handler clears buffer — tool call permanently lost

DeepSeekV32Detector.parse_streaming_increment's except handler set self._buffer = "", permanently discarding the in-progress tool call text. The next chunk could not retry parsing.

Fix: Retain self._buffer; reset transient tool state (current_tool_id, current_tool_name_sent, prev_tool_call_arr, streamed_args_for_tool) so the next chunk retries with a clean slate. Return only preamble (text before the first DSML tag) as normal_text.

Files: python/sglang/srt/function_call/deepseekv32_detector.py

Bug 2: str.rstrip(token) character-set truncation

rstrip(token) treats the argument as a character set, not a substring. rstrip("parameter") truncated streaming values ending with any char in {p, a, r, m, e, t} — e.g. "find /tmp" became "find /".

Fix: Use str.removesuffix(token) in both the JSON partial and XML partial paths.

Files: python/sglang/srt/function_call/deepseekv32_detector.py

Bug 3: potentially_dsml trap + missing finish() flush

The broad potentially_dsml check (any |DSML| marker in buffer) trapped all subsequent text when a non-tool-call DSML sub-tag (e.g. <|DSML|parameter>) appeared in response prose. Additionally, DeepSeekV32Detector had no finish() override, so text trapped in the buffer at stream end was silently discarded.

Fix:

  • Narrow potentially_dsml to tool-call tags only (invoke, tool_calls, function_calls — opening and closing variants), extracted as _DSML_TOOL_TAGS class constant.
  • Narrow ends_with_prefix to check partial prefixes against the same tag list using rfind("<") + startswith.
  • Add finish(self, tools) override to DeepSeekV32Detector that flushes trapped buffer text at stream end, stripping DSML delimiters using earliest-position logic across _DSML_TOOL_TAGS (so partial tags without > are also stripped).

Files: python/sglang/srt/function_call/deepseekv32_detector.py

Bug 4: Broad tool_start_token causes premature reasoning termination

tool_start_token = "<|DSML|" matched any DSML sub-tag in reasoning content, causing premature reasoning-to-normal transition when <|DSML|parameter> or similar appeared in explanatory text.

Fix:

Files: python/sglang/srt/parser/reasoning_parser.py

Tokenizer Alignment

Verified with the DeepSeek-V4-Flash tokenizer:

  • |DSML| is a single special token (id=128825)
  • No full DSML tags are special tokens — <|DSML|tool_calls> is 6 regular tokens
  • Both tool_calls (V4) and function_calls (V32) block names exist
  • _DSML_TOOL_TAGS covers both variants + invoke (opening and closing)

Accuracy Tests

This PR fixes streaming parsing logic, not model forward code. No model output accuracy impact — the fixes ensure tool calls that were previously lost/truncated are now correctly parsed. All 38 unit tests pass:

test/registered/unit/function_call/test_deepseekv4_detector.py — 4 passed
test/registered/unit/function_call/test_function_call_parser.py::TestDeepSeekV4Detector — 17 passed
test/registered/unit/parser/test_reasoning_parser.py — 17 passed (TestDeepSeekV4Detector + TestBufferLossBugFix + TestStreamingChunkSizeInvariance)

Test breakdown:

Speed Tests and Profiling

No inference speed impact — changes are in streaming text parsing only (no GPU kernels, no model forward modifications).

Checklist

Relationship to Prior Work

cc @hnyls2002 (reviewer of #34458)

Review and Merge Process

  1. Ping Merge Oncalls to start the process. See the PR Merge Process.
  2. Get approvals from CODEOWNERS and other reviewers.
  3. Trigger CI tests with comments or contact authorized users to do so.
    • Common commands include /tag-and-rerun-ci, /tag-run-ci-label, /rerun-failed-ci
  4. After green CI and required approvals, ask Merge Oncalls or people with Write permission to merge the PR. **

CI States

Latest PR Test (Base): ❌ Run #31620389452
Latest PR Test (Extra): ❌ Run #31620389222

…p fix, finish() flush, tool_start_token narrowing

Four bugs caused tool call loss, value truncation, text trapping, and
DSML tag leakage in DeepSeek-V4 streaming parsing. All four are present
in the current main (post sgl-project#34458) and are fixed here:

Bug 1 - Exception handler cleared self._buffer, permanently losing tool
call text. Fix: retain buffer, reset transient tool state instead.

Bug 2 - str.rstrip(token) treated the argument as a character set, not a
substring. rstrip("parameter") truncated streaming values ending with
chars in {p,a,r,m,e,t}. Fix: use removesuffix.

Bug 3 - Broad potentially_dsml check trapped all subsequent text when a
DSML sub-tag appeared without an invoke. Fix: narrow to tool-call tags
only; add finish() override to DeepSeekV32Detector.

Bug 4 - Broad tool_start_token matched any DSML sub-tag in reasoning.
Fix: narrow to tool_calls; add holdback at think_end and non-reasoning
boundaries using _ends_with_partial_token.

Tests: 12 new regression tests + 2 existing sgl-project#34458 tests updated.
All 39 tests pass.

Co-authored-by: Leoyzen <[email protected]>
Leoyzen added a commit to Leoyzen/sglang that referenced this pull request Aug 14, 2026
…rdening

Cherry-pick and squash of three PRs:
- sgl-project#34262 infra: BaseFormatDetector.finish(), FunctionCallParser.parse_stream_end(),
  flush param in serving_chat._process_tool_call_stream
- sgl-project#34458: chunk-invariance — partial token holdback, _ends_with_partial_token,
  tool_start_token for DeepSeekV4Detector, MalformedJSON catch, preamble preservation
- sgl-project#34600: hardening — buffer retention on error, rstrip→removesuffix, narrow
  potentially_dsml to tool-call tags, finish() override on DeepSeekV32Detector,
  narrow tool_start_token to <|DSML|tool_calls, holdback at think_end boundary

Co-authored-by: hnyls2002 <[email protected]>
Co-authored-by: Leoyzen <[email protected]>
legekka pushed a commit to legekka/sglang that referenced this pull request Aug 21, 2026
…rsing onto v0.5.16

Merged upstream fix (2026-08-12) for the streaming tool-call parser
dropping text that precedes the DSML tag when it arrives in the same
detokenizer increment as the tag (batched detok under speculative
decoding). Previously the invoke loop returned normal_text="" once the
buffer looked DSML-ish, silently discarding the preamble; non-streaming
parsing kept it, so stream and non-stream disagreed.

- deepseekv32_detector.py: recover preamble for the first tool call
  (back to the bot_token, same trailing-newline trim as detect_and_parse);
  multi-section non-streaming parse via findall; MalformedJSON tolerance;
  exception path re-emits verbatim instead of swallowing the turn.
- Known upstream limitation (tracked by open sgl-project#34518/sgl-project#34600): prose between
  or after multiple tool-call sections stays buffered.
- reasoning_parser.py hunks of sgl-project#34458 NOT ported: 0.5.16 maps deepseek-v4
  to _DeepSeekV3Detector (no dsv4 subclass); different base structure.
Chronostasys pushed a commit to MindLab-Research/sglang that referenced this pull request Aug 24, 2026
…4600 — reasoning leak, effort mapping, tool-call streaming

Three upstream fixes ported to b300-glm52 (v0.5.15 base):

1. sgl-project#28288 — SGLANG_DEFAULT_THINKING ignored by dsv4 reasoning parser
   Root cause: prompt encoder reads SGLANG_DEFAULT_THINKING but reasoning
   parser does not, so thinking prompt produces output that parser treats
   as non-thinking → reasoning text +  leaks into content.
   Fix: _process_messages persists thinking=envs.SGLANG_DEFAULT_THINKING
   onto chat_template_kwargs so both prompt encoder and parser agree.

2. sgl-project#33140 — reasoning_effort mapped one level off (high is no-op)
   Root cause: encoding_dsv4.py only supports max/None/high (preview
   profile). Official profile has 3 levels: low (empty), high, max.
   Fix: add _detect_dsv4_reasoning_effort_profile() that reads
   encoding/encoding_dsv4.py from model path to detect official vs
   preview. Official profile accepts low/high/max; preview accepts
   high/max. Override via SGLANG_DSV4_REASONING_EFFORT_PROFILE env.

3. sgl-project#34600 — Harden DeepSeek-V4 tool-call streaming (4 bugs)
   Bug 1: exception handler clears self._buffer → tool call permanently lost
   Bug 2: rstrip(token) truncates values ending with same chars
   Bug 3: bare '|DSML|' marker traps response text mentioning DSML tags
   Bug 4: finish() leaks partial DSML tags into normal_text
   Fix: _DSML_TOOL_TAGS (specific tags), removesuffix, targeted trap check,
   finish() strips partial tags.
@github-actions

Copy link
Copy Markdown
Contributor

Thanks @Leoyzen. Closing this because you have 8 PRs open and none updated in 7 days, over our soft cap of 5 for idle PRs.

Reopen the two or three you most want reviewed - a short active set moves faster than a long idle one.

Some directories moved recently, so an older branch may need retargeting:
sgl-kernel/ -> python/sglang/kernels/aot/, python/sglang/jit_kernel/
-> python/sglang/kernels/jit/, docs/ -> docs/docs/ (.mdx),
bench_serving.py -> benchmark/serving.py, test/srt/ -> test/registered/.

@github-actions github-actions Bot closed this Sep 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant