Skip to content

fix(parser): DSV4 reasoning + tool call streaming parser bugs - #34178

Closed
Leoyzen wants to merge 12 commits into
sgl-project:mainfrom
Leoyzen:feat/dsv4-tool-parser-test-coverage
Closed

Leoyzen wants to merge 12 commits into
sgl-project:mainfrom
Leoyzen:feat/dsv4-tool-parser-test-coverage

Conversation

@Leoyzen

@Leoyzen Leoyzen commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes 6 streaming parser bugs in the DSV4 reasoning + tool call parsing pipeline, with 79 new and updated tests covering chunk-size invariance, boundary splits, and MTP/DSpark multi-token batching scenarios.

Motivation

While debugging DSV4-Flash tool calling failures in production, we found 6 parser bugs that silently drop tool calls or leak special tokens into API output. The bugs span two files and affect both the reasoning parser (which routes text between reasoning and normal content) and the tool call parser (which extracts DSML tool call blocks).

No existing PR covers all six bugs together — see Related Issues below.

Modifications

python/sglang/srt/parser/reasoning_parser.py (+26/-3)

Bug Description Fix
Bug 1 DeepSeekV4Detector missing tool_start_token (DSV4-specific) Add tool_start_token=f"<{dsv4_dsml_token}" to __init__. The < prefix is required because the tool call parser's has_tool_call() checks for <|DSML|tool_calls> with the angle bracket. Without it, DSML blocks stay in reasoning_content and the tool call parser never sees them.
Bug 2 Partial token destroyed at chunk boundary (base class, stream_reasoning=True) Replace unconditional self._buffer = "" with partial token holdback. Before clearing, check if current_text ends with a strict prefix of think_end_token or tool_start_token; if so, hold those characters back for recombination. Mirrors _ends_with_partial_token from Apertus2509Detector. Triggerable by MTP/DSpark with stream_interval > 1.
Bug 3 stripped_think_start never reset (base class) Add self.stripped_think_start = False at both reasoning exit paths (think_end_token path and tool_start_token interruption path). Without reset, a second think_start leaks to normal_text in multi-turn cyclic reasoning.
Bug 4 think_start not written back to buffer after strip (base class) Add self._buffer = current_text after think_start strip at line 197. Without it, in stream_reasoning=False mode the unstripped think_start persists in buffer and reaches reasoning_content. Affects all base-class detectors (DeepSeekR1, Qwen3, KimiK2, GLM-4.5, etc.).

python/sglang/srt/function_call/deepseekv32_detector.py (+21/-3)

Bug Description Fix
Bug 5 Preamble before DSML lost in streaming Compute preamble from invoke_match.start() when the first tool call is found, walk back to include bot_token wrapper, and emit it as normal_text. Previously, any prose the model generated before a tool call was silently discarded. Same root cause as PR #31786.
Bug 6 MalformedJSON not caught Broaden except clause to catch MalformedJSON (from partial_json_parser) alongside json.JSONDecodeError. Clear self._buffer on error to prevent corrupted state from persisting. Same root cause as PR #32332.

Tests (+2161 lines, 6 files)

File Tests Coverage
test_dsv4_chunk_invariance.py (NEW) 14 Parametric chunk sizes [1,2,3,5,7,11], think_end/tool_start boundary splits, MTP multi-token batch, detokenizer holdback
test_dsv4_reasoning_integration.py (NEW) 11 Joint reasoning+tool parser integration: Bug 1-4 regression, streaming/non-streaming, multi-think cycling, argument parsing
test_deepseekv4_streaming_robustness.py (NEW) 54 DSML tool parser streaming robustness: wrapper/no-wrapper, partial fragments, nested invoke, exception paths, Bug 5-6 regression
conftest.py ×2 (NEW, untracked) — macOS CPU torch.compile stub

All 79 tests pass (0 failures, 0 expected failures).

Regression Risk

LOW. Bug 2 modifies the base class stream_reasoning=True branch. For detectors without tool_start_token, the holdback only checks think_end_token suffixes — a strict improvement with no behavior change when no partial suffix is present. Apertus2509Detector and KimiK3Detector override _parse_streaming_increment_impl entirely and are unaffected. Bug 4 adds a single self._buffer = current_text assignment after an existing strip operation — only makes stream_reasoning=False consistent with stream_reasoning=True. Bugs 5-6 are scoped to deepseekv32_detector.py. All 79 tests pass including regression tests for pure reasoning and existing config attributes.

Related Issues

Checklist

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 #31326944406
Latest PR Test (Extra): ❌ Run #31326944292

Leoyzen added 9 commits August 9, 2026 11:33
Implement the dsv4-tool-parser-test-coverage OpenSpec change:
- 48 unit tests (CPU) covering REQ-1 through REQ-9: preamble preservation,
  BPE token-boundary splitting, false-positive DSML detection, stream-end
  edge cases, serving-code integration, parameter type conversion (incl.
  anyOf null), multiple sequential calls, bot_token mismatch, and DSPARK
  truncation simulation
- 2 E2E tests (GPU) for streaming vs non-streaming tool call parity
- Behavior-pinning tests for known-open bugs (sgl-project#33813 preamble loss in
  streaming, sgl-project#32332/sgl-project#32167 deferred to fix PRs)
- All opener-split patterns use BPE-accurate tokenizer boundaries (REQ-2.3)
- Serving-code tests exercise real _process_tool_call_stream, no mirror-test
  logic (design D2 compliant)
- Oracle-reviewed: 6 spec compliance gaps fixed (false-positive detection,
  anyOf null, tokenizer splits, D2 mirror-test removal, REQ-8.5 truncation,
  REQ-1.3 normal_text invariant)

Test results: 48 passed, 6 skipped (serving-chat on macOS), 40 subtests passed.
…pecific references

- Rename TestPreambleSameDeltaRegression → TestPreambleSameDelta
- Rename TestFullPipelineProductionBugReproduction → TestStreamEndPartialOpenerIntegration
- Remove regression/PR/production-bug framing from docstrings and comments
- Replace lazy-import guard with direct import (conftest handles triton stub)
- Flip 2 tests to assert correct behavior (fail on main, pass after fix)
- Remove DEFERRED task references from module docstring


- test_dsv4_reasoning_integration.py: 10 tests across 5 classes
  - TestDSV4ToolStartToken: BUG #1 @expectedfailure (tool_start_token not set)
  - TestDSV4ChunkBoundaryBUG2: BUG #2 @expectedfailure (chunk boundary destroys partial think_end)
  - TestDSV4MultiThinkBlockBUG4: BUG #4 @expectedfailure (stripped_think_start never reset)
  - TestDSV4NonStreamingToolRouting: non-streaming DSML routing @expectedfailure
  - TestDSV4ArgumentAssertions: tool call argument parsing @expectedfailure
- conftest.py: macOS torch.compile patch + sgl_kernel stub for parser/function_call dirs
- Uses unittest.TestCase (not CustomTestCase) to avoid heavy import chain
- Chunk-size invariance test for stream_reasoning=False (PASSING baseline)

Per Oracle review: tests expose bugs without fixing them.
Oracle analysis: SGLang has 0 multi-token chunk tests; vLLM has token-ID-aware
Rust parser with chunk invariance testing [1,2,3,5,11,23,None].
DeepSeekV4Detector.__init__ was not passing tool_start_token to the
base class. Without it, DSML tool-call blocks (<|DSML|tool_calls>)
stay in reasoning_content and the tool call parser never sees them.

Fix: pass tool_start_token=f"<{dsv4_dsml_token}" so the reasoning
parser routes DSML blocks to normal_text where the tool call parser
can detect them.
stripped_think_start was set to True when the first think_start token
was seen but never reset when reasoning ended. On a second think
block, the condition 'not self.stripped_think_start' is False, so the
think_start token is not stripped and leaks to normal_text.

Fix: reset stripped_think_start = False at both reasoning exit paths
(think_end_token found and tool_start_token interruption).
When stream_reasoning=True, _parse_streaming_increment_impl cleared
_buffer unconditionally after every reasoning emission. If think_end
or tool_start token was split across chunk boundaries, the partial
fragment was destroyed and _in_reasoning stayed True forever, causing
all subsequent normal text to leak into reasoning_content.

This bug is triggered by MTP/DSpark where stream_interval > 1 batches
multiple tokens, increasing the probability of splitting multi-char
tokens like DSV4's think_end across chunk boundaries.

Fix: before clearing the buffer, check if current_text ends with a
strict prefix of think_end_token or tool_start_token. If so, hold
those characters back in _buffer for recombination on the next chunk.
Mirrors the _ends_with_partial_token pattern already used by
Apertus2509Detector and CohereCommand4Detector.
All 25 tests now pass after applying fixes for BUG #1 (tool_start_token),
BUG #2 (partial token holdback), and BUG #4 (stripped_think_start reset).

Changes:
- Remove 16 @expectedfailure decorators from tests that now pass
- Fix test_partial_tool_holdback_buffered: assert DSML in normal (not reasoning)
  since BUG #1 fix routes tool_start to normal_text
- Fix MTP baseline: strip think_start from stream_reasoning=False reference
  to match stream_reasoning=True output (both correct, different representation)
- Update docstrings to reflect fixed behavior
Line 196 stripped think_start from local var current_text but didn't
write back to self._buffer. In stream_reasoning=False mode the buffer
persists, so think_start leaked into reasoning_text on every subsequent
call. finish() had a _strip_leading_think_start workaround for this.

Fix: add self._buffer = current_text after the strip. Now both
stream_reasoning modes consistently strip think_start from the buffer.

Also remove test normalization (.replace(THINK_START, '')) that was
masking this bug — no longer needed after the fix.
@Leoyzen
Leoyzen requested a review from JustinTong0323 as a code owner August 9, 2026 16:13
@github-actions github-actions Bot added documentation Improvements or additions to documentation deepseek labels Aug 9, 2026
Leoyzen added a commit to Leoyzen/sglang that referenced this pull request Aug 9, 2026
…oject#34178)

Squashed cherry-pick of PR sgl-project#34178 (11 commits):
- reasoning_parser.py: set tool_start_token (BUG 1); hold back partial think_end/tool_start suffix at chunk boundary (BUG 2); reset stripped_think_start on reasoning end (BUG 4); write stripped buffer back after think_start removal (BUG 5).
- deepseekv32_detector.py: preserve preamble before DSML + catch MalformedJSON (Bug sgl-project#31786, sgl-project#32332).
- Includes DSV4 parser/streaming robustness tests.

Replaces the previous 5 ad-hoc DSV4 parser commits (tool_start_token + preamble fix + squashed PR).
…eaming, None chunk size

Oracle review recommendations:
- Add finish() think_start leakage assertion (Bug 4 verification)
- Add think token terminal leakage assertions (streaming + buffered + multi-block)
- Add Bug 6 streaming exception path tests (no-crash + outer handler buffer clear)
- Add None to CHUNK_SIZES as gold-standard reference (vLLM parity)
- Add 23 to CHUNK_SIZES for larger batch boundary testing

32 tests pass (was 25), 0 failures.
@hnyls2002

Copy link
Copy Markdown
Collaborator

Covered by #34458 (5899674), which fixes five of the six issues reported here: the partial-token holdback, tool_start_token on DeepSeekV4Detector, writing the stripped buffer back after removing <think>, preamble preservation, and catching MalformedJSON.

The remaining one — resetting stripped_think_start when reasoning ends — was deliberately left out. Resetting the flag on its own makes the result depend on chunk size, because the think_end branch returns the whole remainder as normal_text in one go and a second <think> in it is never re-scanned. Feeding <think>first</think>mid<think>second</think>end through that version gives ('firstsecond','midend') at chunk size 1, ('firstdsecond','miend') at 11 (the d of mid moves into reasoning), and the original output at every other size. Handling further reasoning blocks correctly needs the think_end exit to re-enter the parse loop and the strip to be anchored at the buffer start; that is a separate change, and the tests in #34458 pin the current single-block behaviour.

You are credited as a co-author on that commit.

If I misread any of the other five and something is still missing, please rebase on main and reopen — happy to take it.

@hnyls2002 hnyls2002 closed this Aug 12, 2026
@Leoyzen

Leoyzen commented Aug 12, 2026

Copy link
Copy Markdown
Contributor Author

@hnyls2002 Nice work on the holdback and chunk-invariance tests — that's the right approach.

I spent some time debugging the "agent stops when it should call tools" issue on this (where tool_start_token="<|DSML|" was first introduced). Found two things #34458 doesn't cover:

1. rstrip character-set bug (pre-existing, not introduced by this PR)

_parse_parameters_from_xml uses str.rstrip(token) to strip partial closing tags, but rstrip treats the argument as a character set, not a substring:

self.prefix_parameter_end_call = ["</", "|DSML|", "parameter"]
# rstrip("parameter") removes trailing chars in {'p','a','r','m','e','t'}

So a streaming value like find /tmp gets truncated to find / in the intermediate prev_tool_call_arr (the final value is correct because parameter_regex bypasses rstrip once the closing tag arrives, but the intermediate streaming output is wrong). Values ending with any of p, a, r, m, e, t are affected — pretty common for file paths.

Fix is straightforward: removesuffix instead of rstrip. Same for the prefix_invoke_end_call loop.

2. potentially_dsml trap in the tool parser

The test_dsv4_reasoning_quoting_dsml_is_chunk_dependent test pins this as an accepted divergence on the reasoning-parser side, which is fair — streaming can't look ahead. But the tool parser side has a separate issue that makes it worse than just a divergence.

When a DSML sub-tag (e.g. <|DSML|parameter>) enters the tool parser buffer without an <|DSML|invoke>, the potentially_dsml check (any(marker in current_text for marker in ["|DSML|", "<|", "</|"])) blocks the early return. No invoke match → break → return (normal_text="", calls=[]). The text stays in the buffer. Every subsequent chunk also hits potentially_dsml=True because the marker is still there. All text gets trapped indefinitely.

At stream end there's no finish() on the tool parser — _check_for_unstreamed_tool_args only flushes remaining tool call arguments, not trapped normal_text. So the buffer is silently discarded. The client gets zero content and zero tool calls.

I verified this with a test: feed <|DSML|parameter name="x">value then Now let me find the file. — the second chunk returns normal_text="" and the buffer grows to 120+ chars. Stream ends → all gone.

I fixed both on deploy/dsv4-integration (commit dce709cd8b):

  • Narrowed potentially_dsml to only match actual tool-call tags (<|DSML|invoke, <|DSML|tool_calls, <|DSML|function_calls) plus their partial prefixes
  • Added finish() to DeepSeekV32Detector and wired it through FunctionCallParser.parse_stream_end() → serving_chat.py
  • rstrip → removesuffix
  • Also narrowed tool_start_token to <|DSML|tool_calls> on the reasoning parser side (the broad match is what creates the false positive in the first place)

The tool_start_token narrowing is the part I'm less sure about — it trades the false-positive problem for a chunk-boundary problem (partial <|DSML|tool prefixes need holdback). The base class holdback logic you added should handle that, but I haven't tested the interaction. Worth thinking about whether the broad match + accepted divergence is better than the narrow match + holdback complexity.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

deepseek documentation Improvements or additions to documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants