Skip to content

[Tool Call] Fix DeepSeekV32Detector streaming corrupting tool-call arguments - #36339

Closed
Xiang-Wang-Panda wants to merge 1 commit into
sgl-project:mainfrom
Xiang-Wang-Panda:fix/deepseekv32-streaming-arguments-prefix
Closed

Xiang-Wang-Panda wants to merge 1 commit into
sgl-project:mainfrom
Xiang-Wang-Panda:fix/deepseekv32-streaming-arguments-prefix

Conversation

@Xiang-Wang-Panda

@Xiang-Wang-Panda Xiang-Wang-Panda commented Aug 25, 2026 •

Copy link
Copy Markdown

Motivation

With --tool-call-parser deepseekv32 (or deepseekv4, which subclasses the same
detector) in streaming mode, function.arguments intermittently arrives as
invalid JSON with a run of bytes missing out of the middle. Measured on
DeepSeek-V4 over 433 calls through a production gateway:

request shape calls malformed rate
stream=false 80 0 0.0%
stream=true 80 4 5.0%
stream=true, temperature=0.7 81 3 3.7%
stream=true, ~30k-token prompt 80 2 2.5%
stream=true, tool_choice pinned to the function 64 3 4.7%

Same weights, same prompts — only stream matters. Per tool it concentrates
where the arguments are biggest: 13.8% of calls to a planner tool whose argument
is a nested array of objects, 0% on a single-string search tool. Pinning
tool_choice, which puts the grammar backend in the loop, does not help, because
the arguments string the client receives is not generated by the model at all —
the detector builds it out of the DSML tags.

A representative broken payload, with the seam visible mid-string:

…"description": "…并据此调优"medium", "estimated_minutes": …
                          ^ jumps from mid-description into the next key's tail

plus stray \" escapes stranded inside an otherwise structural blob.

Root cause

parse_streaming_increment() re-serialises the whole arguments object on every
chunk and emits common_prefix(current, previous)[sent_len:], then
current_params[sent_len:] once the closing tag arrives. That is sound only if
every byte already emitted is still a prefix of the finished serialisation,
and it is not: a parameter has two possible serialised shapes, and which one you
get depends on how much of it has arrived.

# complete value
try:    parameters[name] = json.loads(value.strip())
except: parameters[name] = value.strip()                      # -> one JSON string

# partial value
try:    parameters[name] = _partial_json_loads(value, Allow.ALL)[0]
except: parameters[name] = value.strip()                      # -> one JSON string

The structural shape {"tasks": [{…}]} and the string shape
{"tasks": "[{\"…\"}]"} diverge from the first byte of the value and have
different lengths. When the fallback fires at a different moment than it did on
the previous chunk, sent_len no longer indexes the same string, so the
closing-tag slice starts too far in and drops exactly the bytes that were
over-sent.

The trigger is the model writing slightly invalid JSON inside a parameter,
which nothing constrains — the structural tag pins the DSML tags and the function
name, not the parameter interior. A trailing comma, an unescaped quote or a
single-quoted key is enough.

Modifications

Stop emitting bytes that can still change, rather than trying to reconcile
two partial serialisations after the fact. _streamable_prefix() returns the
longest prefix of the final arguments JSON that is settled:

  • a parameter whose closing tag has arrived is settled — include it;
  • the parameter still arriving is not settled when it is a non-string type,
    because its shape is only decided once the whole value is in hand — stop before
    its value;
  • when it is a string type the shape is known: json.dumps escapes character
    by character, so the serialisation only grows by appending. Stream its content,
    minus the closing quote.

The emit is then current[len(sent):] guarded by current.startswith(sent),
which logs a warning rather than corrupting the payload if the invariant is ever
broken again.

Argument streaming is preserved. This deliberately does not buffer everything
until the closing tag — string parameters keep flowing incrementally, so it does
not reintroduce #11888. A 3000-char string parameter still arrives in 154 deltas.

Also replaces the two rstrip() tail trims. str.rstrip takes a character set,
not a suffix, so rstrip("oke") ate any trailing run of o, k and e — a
parameter value ending in note came back as not.
_strip_partial_tag_suffix() matches a real prefix of the closing tag, and runs
before whitespace is stripped, because the other order lets the tag's leading
< shield whitespace that then gets streamed and later vanishes when the tag
completes (an off-by-one-byte prefix violation).

_direct_json_body() and _complete_parameters() are extraction, not new
behaviour: they exist so _streamable_prefix() and _parse_parameters_from_xml()
cannot drift apart. _parse_parameters_from_xml()'s own behaviour is unchanged;
it now has no caller inside the class and is kept for subclasses, with a
docstring note that its partial result is not prefix-safe.

Deliberately out of scope

  • Invalid inner JSON is still coerced into a string. When the model's own JSON
    does not parse, both paths store the blob as one JSON string, so the client
    gets syntactically valid JSON whose array-typed parameter is a string. This PR
    makes streaming and non-streaming agree; it does not change what they agree
    on, which is a separate decision.
  • A direct-JSON body that opens { and never closes still yields
    arguments: "{}". Changing that changes what a client receives on that path.
  • Direct-JSON bodies stream the model's own whitespace while the
    non-streaming path re-serialises compactly via parse_base_json. Both parse to
    the same value.

Accuracy Tests

Not applicable — no model output changes; this is a serialisation-path fix.
Verified separately that the same 433-call probe that produced the table above
returns 0/433 malformed against a patched engine, with reasoning parsing,
tool calling, streaming framing and prefix caching all unchanged.

Speed Tests and Profiling

No measurable effect. Per chunk the work is the same regex scan plus one
json.dumps of the settled parameters; the code being replaced did a
json.dumps plus a _find_common_prefix over the whole string. Nothing new runs
per token, and non-string parameters now serialise less often, not more.

Checklist

Tests

Added to test/registered/unit/function_call/test_deepseekv4_detector.py, the
file that already covers this detector's streaming behaviour: 5 fixtures x 9
chunk boundary sets (per-char and 8 fixed widths), asserting that streamed
arguments parse and equal the non-streaming result, and that at every
truncation point the bytes streamed so far are a prefix of what the finished
stream produces — the invariant the old code assumed but did not hold to. Plus a
guard that a long string parameter still arrives in many deltas, and a unit test
for the rstrip fix.

before this change:  480 failed, 9 passed
after:               10 passed, 970 subtests passed

Run without a GPU:

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

CI States

Latest PR Test (Base): ❌ Run #32864233420
Latest PR Test (Extra): ❌ Run #32864232953
Latest PR Test (AMD ROCm 7.2): ❌ Run #32864233177

…guments

parse_streaming_increment() rebuilds the whole arguments string on every
chunk and emits common_prefix(current, previous)[sent_len:], then
current_params[sent_len:] once the closing tag arrives. That is only sound
if every byte already emitted is still a prefix of the finished
serialisation, and it is not: a non-string parameter serialises as a
structure while _partial_json_loads succeeds and as a quote-escaped JSON
string when it falls back to value.strip(). The two shapes diverge from the
first byte of the value and have different lengths, so when the fallback
fires at a different moment than it did on the previous chunk, sent_len no
longer indexes the same string and the closing-tag slice starts too far in
— dropping a run of bytes out of the middle and handing the client invalid
JSON.

Measured on DeepSeek-V4 with --tool-call-parser deepseekv4 (which inherits
this detector) over 433 calls: 0/80 malformed with stream=false, 4/80 with
stream=true, and 13.8% on the one tool whose arguments are a nested array.
Pinning tool_choice does not help, because the arguments string is built
here rather than generated by the model.

Stop emitting bytes that can still change. _streamable_prefix() returns the
longest prefix of the final arguments JSON that is settled: parameters whose
closing tag has arrived, plus the in-flight one only when it is a string
type, whose serialisation grows by appending because json.dumps escapes
character by character. Non-string parameters are held until their tag
closes. The emit is then guarded by current.startswith(sent), which logs
instead of corrupting the payload if the invariant is ever broken again.

Argument streaming is preserved for string parameters, so this does not
reintroduce sgl-project#11888.

Also replaces the two rstrip() tail trims: str.rstrip takes a character
set, not a suffix, so rstrip("oke") ate any trailing run of "o", "k" and
"e" — a parameter value ending in "note" came back as "not".
_strip_partial_tag_suffix() matches a real prefix of the closing tag, and
runs before whitespace is stripped, because the other order lets the tag's
leading "<" shield whitespace that is then streamed and later vanishes.

Tests: 970 subtests over 5 fixtures x 9 chunk boundary sets assert that
streamed arguments parse and equal the non-streaming result, and that at
every truncation point the bytes streamed so far are a prefix of what the
finished stream produces. 480 of them fail before this change.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

@Xiang-Wang-Panda Xiang-Wang-Panda left a comment

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

@JustinTong0323 CODEOWNERS for srt/function_call — tagging you for review.

From our production practice , Streaming half of #14695: parse_streaming_increment() assumed every byte it had
already emitted was still a prefix of the finished arguments JSON. A non-string
parameter breaks that, so the closing-tag slice starts at a stale offset and drops
a run out of the middle. stream=false is clean on the same prompts.

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

480 subtests fail on main, 970 pass here. String params still stream
incrementally, so #11888 isn't reintroduced.

pr-gate failures are the gate, not the tests — can someone run /tag-and-rerun-ci?

@github-actions

Copy link
Copy Markdown
Contributor

Thanks @Xiang-Wang-Panda. Closing this because it has had no updates in 92 days.

Reopen it if the work is still relevant.

Some directories moved recently, so an older branch may need retargeting:
sgl-kernel/ -> python/sglang/kernels/aot/, python/sglang/jit_kernel/
-> python/sglang/kernels/jit/, docs/ -> docs/docs/ (.mdx),
bench_serving.py -> benchmark/serving.py, test/srt/ -> test/registered/.

@github-actions github-actions Bot closed this Nov 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant