Repository navigation
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.
…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.
…sgl-project#34178)" This reverts commit 9b9bdbb.
|
Covered by #34458 (5899674), which fixes five of the six issues reported here: the partial-token holdback, The remaining one — resetting 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 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 1.
self.prefix_parameter_end_call = ["</", "|DSML|", "parameter"]
# rstrip("parameter") removes trailing chars in {'p','a','r','m','e','t'}So a streaming value like Fix is straightforward: 2. The When a DSML sub-tag (e.g. At stream end there's no I verified this with a test: feed I fixed both on
The |
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)DeepSeekV4Detectormissingtool_start_token(DSV4-specific)tool_start_token=f"<{dsv4_dsml_token}"to__init__. The<prefix is required because the tool call parser'shas_tool_call()checks for<|DSML|tool_calls>with the angle bracket. Without it, DSML blocks stay inreasoning_contentand the tool call parser never sees them.stream_reasoning=True)self._buffer = ""with partial token holdback. Before clearing, check ifcurrent_textends with a strict prefix ofthink_end_tokenortool_start_token; if so, hold those characters back for recombination. Mirrors_ends_with_partial_tokenfromApertus2509Detector. Triggerable by MTP/DSpark withstream_interval > 1.stripped_think_startnever reset (base class)self.stripped_think_start = Falseat both reasoning exit paths (think_end_tokenpath andtool_start_tokeninterruption path). Without reset, a secondthink_startleaks tonormal_textin multi-turn cyclic reasoning.think_startnot written back to buffer after strip (base class)self._buffer = current_textafterthink_startstrip at line 197. Without it, instream_reasoning=Falsemode the unstrippedthink_startpersists in buffer and reachesreasoning_content. Affects all base-class detectors (DeepSeekR1, Qwen3, KimiK2, GLM-4.5, etc.).python/sglang/srt/function_call/deepseekv32_detector.py(+21/-3)preamblefrominvoke_match.start()when the first tool call is found, walk back to includebot_tokenwrapper, and emit it asnormal_text. Previously, any prose the model generated before a tool call was silently discarded. Same root cause as PR #31786.MalformedJSONnot caughtexceptclause to catchMalformedJSON(frompartial_json_parser) alongsidejson.JSONDecodeError. Clearself._bufferon error to prevent corrupted state from persisting. Same root cause as PR #32332.Tests (+2161 lines, 6 files)
test_dsv4_chunk_invariance.py(NEW)test_dsv4_reasoning_integration.py(NEW)test_deepseekv4_streaming_robustness.py(NEW)conftest.py×2 (NEW, untracked)All 79 tests pass (0 failures, 0 expected failures).
Regression Risk
LOW. Bug 2 modifies the base class
stream_reasoning=Truebranch. For detectors withouttool_start_token, the holdback only checksthink_end_tokensuffixes — a strict improvement with no behavior change when no partial suffix is present.Apertus2509DetectorandKimiK3Detectoroverride_parse_streaming_increment_implentirely and are unaffected. Bug 4 adds a singleself._buffer = current_textassignment after an existing strip operation — only makesstream_reasoning=Falseconsistent withstream_reasoning=True. Bugs 5-6 are scoped todeepseekv32_detector.py. All 79 tests pass including regression tests for pure reasoning and existing config attributes.Related Issues
DeepSeekBaseDetectorclass; our approach is a one-line addition to the existing__init__.<|DSML|invoke>without wrapper. Our robustness tests cover this case.kMaxMTPDraftTokenshardcode / mHC einsum symmetric pool), but same symptom family.Checklist
Review and Merge Process
/tag-and-rerun-ci,/tag-run-ci-label,/rerun-failed-ciCI States
Latest PR Test (Base): ❌ Run #31326944406
Latest PR Test (Extra): ❌ Run #31326944292