Skip to content

fix(function_call): buffer complete DeepSeek DSML invokes - #39632

Merged
ch-wan merged 18 commits into
sgl-project:mainfrom
kflansburg:kflansburg/fix-dsv4-buffer-complete-invokes
Sep 22, 2026
Merged

ch-wan merged 18 commits into
sgl-project:mainfrom
kflansburg:kflansburg/fix-dsv4-buffer-complete-invokes

Conversation

@kflansburg

@kflansburg kflansburg commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

DeepSeek V3.2/V4 streaming tool parsing can corrupt function.arguments when a partial non-string parameter changes serialization shape. The current detector emits a common prefix of provisional serializations, then slices the final serialization using the number of bytes already sent. If malformed inner JSON changes from an array/object to the raw-string fallback, the emitted bytes are no longer a prefix of the final value and the slice drops bytes from the middle.

This has been observed with large nested array arguments. It can produce syntactically invalid calls without raising an exception. vLLM avoids this class of failure by buffering a complete DSML invoke before parsing and serializing it.

A second problem surfaced once complete invokes were validated: when a closed invoke could not be parsed, the detector returned the raw DSML block as assistant content and dropped the call. In production this branch fired for roughly 4-6% of tool-bearing DeepSeek V4 requests, so agents received tool markup as text with no tool call, and that markup then poisoned the following turns. The detector now fails closed instead.

Supersedes the narrower partial-value fix in #36748 and provides a conservative alternative to #36339.

Modifications

  • Buffer each DeepSeek DSML invoke until </|DSML|invoke> arrives.
  • Parse and serialize arguments once, then emit one ToolCallItem containing both the name and complete arguments.
  • Validate the full XML or direct-JSON invoke body before mutating streaming state.
  • Reject malformed outer parameter syntax and non-standard JSON constants.
  • Fail closed on a malformed closed invoke: discard that invoke on its own, keep parsing, and let well-formed invokes before and after it still become calls with contiguous indexes. The prose ahead of the block is still released; DSML is never surfaced as content, in streaming, non-streaming, finish(), or the unexpected-exception path.
  • Keep main's tolerance for stray prose inside an invoke body (text around the parameter tags is ignored and the call is still emitted). An invoke is only treated as malformed when the leftover text contains a DSML fragment, i.e. a parameter tag that did not match (unclosed, self-closing, missing string=), or when the body has no parameter tags at all. In those cases emitting the call would silently drop an argument, which main did; this PR drops the call instead.
  • Hold trailing whitespace in the streaming buffer so the blank line ahead of a DSML block is trimmed regardless of delta boundaries, instead of leaking as content.
  • Drop incomplete invokes at stream end while preserving preamble text.
  • Reasoning parser: the DeepSeek V4 detector ended reasoning at the first <|DSML|, so a mid-sentence mention of <|DSML|tool_calls> while thinking (the system prompt shows the model that tag) cut the block and returned the rest of the reasoning, tag included, as content. Add an opt-in tool_start_at_line_start to the base reasoning detector; DeepSeek V4 now interrupts only on the full <|DSML|tool_calls> tag at a line start, matching the reference parser's \n\n<|DSML|tool_calls split. Streaming remembers the last streamed reasoning character so a tag at the head of a chunk still counts. Replaces the previously "accepted divergence" test with a chunk-invariance test. Tradeoff: a block that neither follows </think> nor starts a line stays in reasoning; that double format violation is not tolerated by the reference parser either, and a test documents it.
  • When --reasoning-parser is configured, strip the reasoning detector's think start/end tokens from the free-text excludes of any tool-call structural tag. xgrammar's builtin tags forbid <think>/</think> in free text, but DeepSeek V4 sometimes emits an empty </think> before prose in non-thinking requests; with SGLANG_TOOL_STRICT_LEVEL set the grammar rejected that token, and under PD disaggregation (prefill samples unconstrained, decode enforces) the request aborted with Grammar accept_token failed. Observed in production. Consistent with the existing rule that the reasoning parser, not xgrammar, owns the reasoning prefix.
  • Keep final-flush bookkeeping synchronized so arguments are not emitted twice.

Accuracy Tests

No model output changes. Valid streaming calls are required to match non-streaming parsing. Malformed non-string values retain the existing complete-parse fallback to JSON strings. Malformed invoke structure now yields no call and no DSML rather than raw markup.

Behavior on the shapes discussed in review, for the same input at every chunk width:

Invoke body main this PR
<parameter name="text" string="true">SF</parameter> followed by stray prose emit({"text": "SF"}) emit({"text": "SF"})
<parameter name="text">SF</parameter> (missing string=) emit({}), argument silently lost no call, no DSML in content
<parameter name="text" string="true">SF (unclosed) emit with truncated, invalid arguments {"text": "SF no call, no DSML in content
prose only, no parameter tags emit({}) no call, no DSML in content

test_reasoning_parser.py covers the DSML mention inside reasoning (one-shot and every chunk width), a mention followed by a real block, a line-start block without </think>, and the mid-line tradeoff case.

test_structural_tag_excludes.py covers stripping only think tokens across nested free-text sections and, when xgrammar builtin tags are available, that the deepseek_v4 auto tag no longer excludes them.

CPU-only parser coverage includes valid nested arrays, malformed nested values, every fixed chunk width for both valid and malformed invokes, multiple invokes, malformed first and later invokes alongside valid ones, stray prose inside the body, unmatched parameter tags, direct JSON, incomplete stream finalization, unexpected parser exceptions, and non-standard constants.

22 passed (test_deepseekv4_detector.py)
3 passed (test_structural_tag_excludes.py)
137 passed (test_reasoning_parser.py)

Command:

python3 -m pytest -q test/registered/unit/function_call/test_deepseekv4_detector.py test/registered/unit/function_call/test_structural_tag_excludes.py test/registered/unit/parser/test_reasoning_parser.py

Speed Tests and Profiling

No model-forward or GPU impact. The parser removes repeated partial JSON parsing, serialization, and common-prefix scans. Tool-call arguments are intentionally delayed until the invoke closes.

Checklist

  • Format your code according to the pre-commit guidance.
  • Add unit tests.
  • Update documentation. No user-facing option or API was added.
  • Provide accuracy and speed impact.
  • Follow the SGLang code style guidance.

Review and Merge Process

  1. Ping Merge Oncalls to start the process.
  2. Get approvals from CODEOWNERS and other reviewers.
  3. Trigger CI tests.
  4. After green CI and required approvals, ask Merge Oncalls to merge.

CI States

Latest PR Test (Base): ✅ Run #35691428058
Latest PR Test (Extra): ❌ Run #35691427677
Latest PR Test (AMD ROCm 10): ❌ Run #35691427923

agent added 6 commits September 14, 2026 21:46
DeepSeek streaming currently serializes partial DSML parameters and slices the final serialization by the number of bytes already sent. When a malformed non-string value changes serialization shape, that stale offset drops bytes from the completed arguments.

Buffer each invoke until its closing tag, validate the complete body, and emit its name and serialized arguments together. Drop incomplete invokes at stream end while preserving preamble text.

Accuracy: model output is unchanged. Valid streaming calls now match non-streaming parsing; malformed outer DSML is rejected instead of becoming an executable partial call.

Speed: removes repeated partial JSON parsing and serialization. Tool-call arguments are delayed until the invoke closes.

Tests: python3 -m pytest -q test/registered/unit/function_call/test_deepseekv4_detector.py
Exercise valid and malformed non-string values across every chunk width, complete-item emission, multiple calls, malformed outer syntax, and end-of-stream truncation. Update existing streaming expectations to one complete item per invoke.
Validate complete arguments before creating streaming bookkeeping, preserve completed calls when a later invoke is malformed, and reject non-standard JSON constants.
Verify malformed first calls leave no flush state, malformed later calls preserve completed calls, and direct JSON rejects non-standard constants.
Use the strict JSON constant parser for XML non-string parameters too, falling back to a JSON string instead of serializing NaN or infinity.
agent added 6 commits September 15, 2026 18:33
Motivation: when a closed invoke could not be parsed, the detector returned
the raw DSML block as assistant content and dropped the call. Production
pods logged this branch for roughly 4-6% of tool-bearing requests, so agents
received tool markup as text and no tool call. Whitespace between DSML tags
could also leak as content when it arrived as its own delta.

Modifications:
- Drop a malformed invoke on its own and keep parsing; well-formed invokes
  before and after it still become calls, and the prose ahead of the block
  is still released.
- On an unexpected parser error, emit only the prose ahead of the first DSML
  tag; never surface DSML as content.
- finish() withholds everything from the first DSML tag onward.
- Hold trailing whitespace in the buffer so the blank line ahead of a block
  is trimmed consistently regardless of chunk boundaries.

Tests: test/registered/unit/function_call/test_deepseekv4_detector.py
Motivation: the malformed-parameter check rejected any non-whitespace text
between or after parameter tags, which is stricter than the previous parser
and drops recoverable calls (e.g. a note the model writes after the last
parameter). Reported as a regression against main.

Modifications: stray prose around parameter tags is ignored again. The
invoke is still rejected when the leftover text contains a DSML fragment,
meaning a parameter tag that did not match (unclosed, self-closing, missing
`string=`), since emitting the call without that argument would be worse
than emitting no call. A body with no parameter matches and non-blank text
is not the parameter format and is rejected as well.

Tests: test/registered/unit/function_call/test_deepseekv4_detector.py
…al tags

Motivation: xgrammar's builtin tool-call structural tags forbid the model's
think tokens in free text. When --reasoning-parser is configured SGLang
already passes reasoning=False so the tag only describes the post-reasoning
suffix, but the exclusion still applies from the first token in non-thinking
requests. DeepSeek V4 sometimes emits an empty `</think>` before prose in
that mode, and the grammar rejects it. In PD disaggregation the prefill
side samples that token unconstrained and decode aborts the request with
a 500 (`Grammar accept_token failed ... Tokens not accepted`).

Modifications: after building a structural_tag constraint, strip the
configured reasoning detector's think start/end tokens from every free-text
`excludes` list. Other excludes (e.g. nested tool-call markers) are kept.

Tests: test/registered/unit/function_call/test_structural_tag_excludes.py
@kflansburg
kflansburg marked this pull request as ready for review September 16, 2026 16:43
agent and others added 5 commits September 16, 2026 10:16
…start

Motivation: the DeepSeek V4 reasoning detector ends the reasoning block at
the first `<|DSML|`. The system prompt shows the model that tag, so its
reasoning sometimes mentions `<|DSML|tool_calls>` mid-sentence; the block
was cut there and the rest of the reasoning, tag included, was returned as
assistant content. Observed on 3 of 40 adversarial requests in production.

Modifications: add `tool_start_at_line_start` to the base detector. When
set, only a tool_start_token that begins a line interrupts reasoning; the
streaming path remembers the last streamed reasoning character so a tag at
the head of the buffer still counts when its newline streamed earlier.
DeepSeek V4 uses the full `<|DSML|tool_calls>` tag with this anchor,
matching the reference parser's `\n\n<|DSML|tool_calls` split.

Tests: test/registered/unit/parser/test_reasoning_parser.py
Resolve the deepseekv32_detector.py conflict with sgl-project#39665 (dsv4.1 tool
parsing): keep the parameterized tag-name class attributes from main and
drop partial_parameter_regex / prefix_*_end_call, whose only consumer was
the allow_partial streaming path this PR removes.

Also align the remaining hardcoded DSML markers with the class attributes
(_text_before_dsml, leftover-fragment check, streaming marker/prefix
lists), and give the deepseek-v41 reasoning parser its own tool-start
anchor: V4.1's calls block uses the spaced <|DSML| calls> tag, which the
unspaced V4 anchor introduced here would never interrupt.
…k V4 tool-start

With tool_start_at_line_start, a tool_calls block at absolute position 0
(force_reasoning with zero preceding reasoning chars) was not detected,
so the whole DSML block flushed into reasoning_content and the tool call
became invisible to the downstream tool parser on both streaming and
non-streaming paths.
… leak

- detect_and_parse now honors the invoke completion flag, so an invoke
  missing its closing tag inside a closed wrapper is dropped instead of
  executed (matching the streaming path).
- Bare invokes without the outer tool_calls wrapper are parsed in
  non-streaming too, instead of leaking raw DSML as content; malformed
  ones fail closed.
- A calls-block opener truncated at EOS (line start, generation cut
  before '>') is stripped from the reasoning flush on both the
  streaming finish() and one-shot paths, for V4 and V4.1.

@JustinTong0323 JustinTong0323 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@JustinTong0323 JustinTong0323 added the run-ci CI: run the baseline test suite on this PR label Sep 21, 2026
@JustinTong0323

Copy link
Copy Markdown
Collaborator

/rerun-failed-ci

@JustinTong0323

Copy link
Copy Markdown
Collaborator

/rerun-failed-ci

Alex-Wengg added a commit to Alex-Wengg/sglang that referenced this pull request Oct 14, 2026
…SML parser

DeepSeekV32Detector (and the V4 / V4.1 subclasses) pass tool-call parameters
through verbatim. When the model wraps the real parameters in a spurious
top-level "arguments"/"input" key -- {"arguments": {"path": "/x"}},
{"arguments": "cmd"}, {"input": {...}}, or the XML
<parameter name="arguments" ...> form -- the wrapper reaches the client in
function.arguments, so schema-validating clients reject the call.

Unwrap it back to the tool's declared parameters:
- _unwrap_wrapped_arguments() is a no-op unless the object is exactly one
  wrapper key that is not itself a declared property. It unwraps a dict value
  directly, decodes a JSON-object string (the double-encoded string="true"
  sub-case), and remaps a bare scalar onto the tool's sole property. Ambiguous
  cases are left untouched rather than guessed.
- Applied once per complete invoke in both detect_and_parse and
  parse_streaming_increment. Since sgl-project#39632 the streaming path buffers a whole
  invoke before emitting, so no partial-prefix handling is needed.

Fixes sgl-project#38924
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