Repository navigation
fix(parser): harden DSV4 reasoning and tool streaming - #34280
Closed
JustinTong0323 wants to merge 13 commits into
Closed
JustinTong0323 wants to merge 13 commits into
JustinTong0323 wants to merge 13 commits into
Conversation
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.
…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.
JustinTong0323
marked this pull request as ready for review
August 10, 2026 11:38
Collaborator
Author
|
/tag-and-rerun-ci |
Leoyzen
added a commit
to Leoyzen/sglang
that referenced
this pull request
Aug 11, 2026
…#34280) Port of PR sgl-project#34280 with broad tool_start_token (<|DSML|) instead of narrow (<|DSML|tool_calls>) to also catch bare invoke blocks without the tool_calls wrapper. Fixes: - Bug #1: DeepSeekV4Detector missing tool_start_token (broad match) - Bug #2: Partial token destroyed at chunk boundary in stream_reasoning - Bug #4: think_start not written back to buffer after strip - Bug sgl-project#5: Preamble before DSML lost in streaming - Bug sgl-project#6: MalformedJSON not caught + buffer clear on error Deliberately excludes Bug #3 (stripped_think_start reset) per PR sgl-project#34280 rationale: multi-think reset models an invalid same-turn sequence.
Collaborator
|
Covered by #34458 (5899674): You are credited as a co-author on that commit. If I misread what this PR does and part of it is still missing, please rebase on main and reopen — happy to take it. |
3 of 5 tasks
Leoyzen
added a commit
to Leoyzen/sglang
that referenced
this pull request
Aug 14, 2026
…-project#34280)" This reverts commit d6b9418.
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.
Motivation
This is a focused replacement for #34178. That PR identified real DSV4 streaming failures, but it also mixed valid fixes with an invalid parser-lifecycle assumption and 2,251 lines of new tests. The resulting change was much larger than the behavior being fixed.
Problems in #34178
stripped_think_startassumes one assistant turn can produce<think>A</think>answer1<think>B</think>answer2. After the reasoning close token, the remainder belongs to the final answer. A later assistant turn gets a new parser instance. Resetting the flag makes tag-like final content eligible to be reclassified as reasoning, so this PR removes that behavior.<|DSML|astool_start_tokenalso matches non-tool DSML tags such as parameters. Only<|DSML|tool_calls>should move output from the reasoning parser to the tool parser.Modifications
stream_reasoning=falsecannot leak<think>.<|DSML|tool_calls>out of an unclosed reasoning block.MalformedJSONalongsideJSONDecodeErrorand clear failed streaming state without exposing DSML.The final diff relative to the original merge base modifies four existing files: 123 additions and 46 deletions.
Accuracy Tests
Parser tests
313 passedacrosstest_reasoning_parser.pyandtest_function_call_parser.pyon an H200 devbox.git diff --checkpassed.Real server validation
Served the public
deepseek-ai/DeepSeek-V4-Flash-0731checkpoint on 4x H200 with TP4,--reasoning-parser deepseek-v4, and--tool-call-parser deepseekv4.finish_reason=tool_calls.get_weathernames and JSON arguments for Paris and Tokyo.stream_reasoning=trueandstream_reasoning=falsepassed without think or DSML marker leakage.17 times 23 equals 391., andfinish_reason=stop./healthreturned HTTP 200. The successful server log contained no scheduler traceback, CUDA error, OOM, illegal memory access, or NCCL failure.The functional run disabled CUDA graph and exhaustive DeepGEMM precompilation. It retained on-demand DeepGEMM because DSV4 MHC requires it. These settings change startup and throughput, not the parser paths under test.
Speed Tests and Profiling
Not applicable. This changes Python response parsing and does not modify model forward or kernels.
Checklist
Review and Merge Process
CI States
Latest PR Test (Base): ❌ Run #31382695302
Latest PR Test (Extra): ❌ Run #31382695162