Skip to content

fix(parser): harden DSV4 reasoning and tool streaming - #34280

Closed
JustinTong0323 wants to merge 13 commits into
sgl-project:mainfrom
JustinTong0323:fix/pr34178-parser-simplify
Closed

JustinTong0323 wants to merge 13 commits into
sgl-project:mainfrom
JustinTong0323:fix/pr34178-parser-simplify

Conversation

@JustinTong0323

@JustinTong0323 JustinTong0323 commented Aug 10, 2026 •

Copy link
Copy Markdown
Collaborator

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

  1. The multi-think reset models an invalid same-turn sequence. The proposed reset of stripped_think_start assumes 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.
  2. The DSV4 tool interruption marker is too broad. Using <|DSML| as tool_start_token also matches non-tool DSML tags such as parameters. Only <|DSML|tool_calls> should move output from the reasoning parser to the tool parser.
  3. The preamble fix changes whitespace depending on chunking. Stripping trailing newlines before a same-chunk tool call produces different output from a boundary where the preamble arrived in an earlier chunk. Preamble bytes must be preserved exactly.
  4. The test and implementation scope obscures the contract. Four new test files add 2,251 lines, duplicate existing parser suites, include the invalid multi-think case, and carry extensive narration and redundant branches. This PR keeps only focused regressions in the existing test modules.

Modifications

  • Write the stripped reasoning opener back to the buffer so stream_reasoning=false cannot leak <think>.
  • Hold back the longest suffix that is a strict prefix of the reasoning close token or exact DSV4 tool-call opener.
  • Route only <|DSML|tool_calls> out of an unclosed reasoning block.
  • Preserve tool-call preamble text and whitespace exactly across chunk boundaries.
  • Catch MalformedJSON alongside JSONDecodeError and clear failed streaming state without exposing DSML.
  • Keep six focused regression tests in the existing reasoning and function-call parser test modules.
  • Remove the four standalone test files added by fix(parser): DSV4 reasoning + tool call streaming parser bugs #34178.

The final diff relative to the original merge base modifies four existing files: 123 additions and 46 deletions.

Accuracy Tests

Parser tests

  • 313 passed across test_reasoning_parser.py and test_function_call_parser.py on an H200 devbox.
  • All applicable pre-commit hooks passed.
  • git diff --check passed.

Real server validation

Served the public deepseek-ai/DeepSeek-V4-Flash-0731 checkpoint on 4x H200 with TP4, --reasoning-parser deepseek-v4, and --tool-call-parser deepseekv4.

  • Five real OpenAI tool completions returned HTTP 200 and finish_reason=tool_calls.
  • Streaming and non-streaming calls reconstructed identical get_weather names and JSON arguments for Paris and Tokyo.
  • Both stream_reasoning=true and stream_reasoning=false passed without think or DSML marker leakage.
  • Thinking streams covered 89-chunk and 11-chunk responses. Both produced 298 reasoning characters, final answer 17 times 23 equals 391., and finish_reason=stop.
  • Post-inference /health returned 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

  • Format code with pre-commit.
  • Add focused unit tests in the existing suites.
  • Documentation not required because there is no user-facing interface change.
  • Accuracy and speed benchmarks not required; real model serving validation is included above.
  • Follow the SGLang code style guidance.

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.
  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 #31382695302
Latest PR Test (Extra): ❌ Run #31382695162

Leoyzen and others added 13 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.
…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
JustinTong0323 marked this pull request as ready for review August 10, 2026 11:38
@JustinTong0323

Copy link
Copy Markdown
Collaborator Author

/tag-and-rerun-ci

@github-actions github-actions Bot added the run-ci CI: run the baseline test suite on this PR label Aug 10, 2026
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.
@hnyls2002

Copy link
Copy Markdown
Collaborator

Covered by #34458 (5899674): MalformedJSON is caught in _parse_parameters_from_xml, and prose before a tool call is preserved in streaming.

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.

@hnyls2002 hnyls2002 closed this Aug 12, 2026
Leoyzen added a commit to Leoyzen/sglang that referenced this pull request Aug 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

deepseek run-ci CI: run the baseline test suite on this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants