Skip to content

[Fix] deepseekv32 detector: tolerate partial non-string param values raising MalformedJSON (stream tear-down) - #28684

Closed
GavinZhu-GMI wants to merge 4 commits into
sgl-project:mainfrom
GavinZhu-GMI:fix/deepseekv32-streaming-partial-malformedjson
Closed

GavinZhu-GMI wants to merge 4 commits into
sgl-project:mainfrom
GavinZhu-GMI:fix/deepseekv32-streaming-partial-malformedjson

Conversation

@GavinZhu-GMI

@GavinZhu-GMI GavinZhu-GMI commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

The DeepSeek-V3.2 / V4 function-call detector tears down streaming responses on certain tool-call payloads. We hit this in production on agentic code-exec traffic (e.g. a tool argument like python3 -c "..."), where the frontend logged a steady trickle of:

ERROR deepseekv32_detector.parse_streaming_increment: Error in parse_streaming_increment: ...
WARN  Stream closed unexpectedly; issuing cancellation

Each error torn an in-flight stream → incomplete response.

Root cause: in DeepSeekV32Detector._parse_parameters_from_xml, the partial-value branch catches only except json.JSONDecodeError. But partial_json_parser raises its own MalformedJSON, which is a ValueError and does not subclass the stdlib json.JSONDecodeError. So when a non-string-typed parameter's streamed prefix is not yet valid JSON (bare text such as python3 -c "... before any closing tag), the exception escapes the narrow except and propagates to the outer except Exception handler in parse_streaming_increment, which:

  1. returns normal_text=current_text — dumping the raw DSML buffer (internal tool-call markers) into user-visible content, and
  2. never clears self._buffer — so the same exception re-fires on every subsequent chunk, wedging/tearing the stream.

Note the sibling complete-value branch a few lines above already catches (json.JSONDecodeError, ValueError); this is just an asymmetry between the two branches.

Modifications

  • python/sglang/srt/function_call/deepseekv32_detector.py: broaden the partial-value except to (json.JSONDecodeError, ValueError), matching the complete-value branch, so a not-yet-valid partial value falls back to the raw string instead of crashing the stream.
  • test/registered/unit/function_call/test_function_call_parser.py: add TestDeepSeekV32Detector.test_streaming_partial_non_string_param_does_not_throw — feeds the bare-text partial value across chunks and asserts no raise, no |DSML| leak into normal_text, and that the tool name is still recovered. The test fails before the fix and passes after.

This also affects DeepSeek-V4, whose detector inherits this method.

Accuracy Tests

N/A — no change to model/kernel forward code. Pure parser robustness fix on the streaming-detect path.

Speed Tests and Profiling

N/A — no hot-path or kernel change.

Checklist

  • Add unit tests (regression test included; red before / green after).
  • Follow the SGLang code style guidance.

CI States

Latest PR Test (Base): ❌ Run #27950909001
Latest PR Test (Extra): ❌ Run #27950908843

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

…that raise MalformedJSON

The streaming partial-parameter branch in `_parse_parameters_from_xml` caught
only `json.JSONDecodeError`, but `partial_json_parser` raises its own
`MalformedJSON` -- a `ValueError` that does NOT subclass the stdlib
`json.JSONDecodeError`. So a partial non-string-typed parameter whose streamed
prefix is not yet valid JSON (e.g. an agentic code-exec argument like
`python3 -c "...`) let the exception escape to the outer handler, which dumped
the entire raw DSML buffer into `normal_text` and never cleared `_buffer` --
re-raising on every subsequent chunk and tearing down the stream.

Broaden the except to `(json.JSONDecodeError, ValueError)`, matching the
complete-value branch a few lines above, so a not-yet-valid partial value
falls back to the raw string instead of crashing the stream.

Adds a regression test asserting no raise, no DSML leak into `normal_text`,
and that the tool name is still recovered.
@GavinZhu-GMI
GavinZhu-GMI force-pushed the fix/deepseekv32-streaming-partial-malformedjson branch from 3a3a875 to e159c64 Compare June 18, 2026 23:06
@shanemort1982

Copy link
Copy Markdown
Contributor

We independently hit this on DeepSeek-V4-Flash in production, triggered by array-valued tool arguments (e.g. an operations: [...] spreadsheet-edit recipe) rather than code strings. Same root cause as the tear-down here: the partial-value branch only catches json.JSONDecodeError, so the partial_json_parser MalformedJSON propagates.

One downstream symptom worth flagging beyond the stream tear-down: in our traces the propagated error also surfaced the raw DSML markup in message content and re-emitted it on every streamed increment (tool_calls empty, finish_reason=stop), ballooning the response to the output-token cap. Widening the except as in this PR fixes the parse and removes that path.

We additionally added a fail-safe in parse_streaming_increment: on any error while the buffer still holds tool-call markup, it returns empty normal_text and keeps the buffer (so a still-arriving invoke isn't dropped) instead of emitting the raw markup. Validated with a streamed regression fixture built from real sanitised leaked bytes, fed at chunk sizes 1/7/64 (fails unpatched, passes fixed). Happy to share the fixture if it's useful for the test suite here.

@GavinZhu-GMI

Copy link
Copy Markdown
Contributor Author

Thanks, this is a great catch — we've added exactly the fail-safe you described.

Confirmed your ballooning symptom on our side too: the outer except in parse_streaming_increment returned the raw buffer as normal_text, and since _buffer is retained across increments it re-emitted the whole thing every chunk (tool_calls empty, finish_reason=stop) → the response grows to the output-token cap. The one-line except widening removes today's trigger but leaves that handler as a leaking footgun for the next malformation — so I pushed a second commit (62280c3) that, while the buffer still holds tool-call markup, emits empty normal_text and keeps buffering instead of surfacing the DSML.

Verified red→green on lmsysorg/sglang:nightly-dev-cu13-20260617: without the fail-safe the outer handler dumps <|DSML|…>{"ops":[ into normal_text; with it, normal_text == "" and the buffer is retained so a still-arriving invoke can complete on a later chunk.

And yes please — I'd love the fixture. The guard I added forces a parse error mid-markup deterministically (monkeypatched _parse_parameters_from_xml), but a streamed fixture from real sanitised leaked bytes at chunk sizes 1/7/64 is a stronger regression; happy to fold it into test_function_call_parser.py with attribution. Drop it here or as a PR against the branch, whichever's easier.

@GavinZhu-GMI

Copy link
Copy Markdown
Contributor Author

@shanemort1982 — sounds like we're hitting the same problem from two sides: we're on DeepSeek-V4-Pro, you're on Flash, same root cause (yours via array-valued operations:[...] args, ours via the code-string prefix). Does 62280c3 cover your case? The fail-safe is trigger-agnostic, so I'd expect it to resolve both the tear-down and the raw-markup re-emit, but good to confirm against your Flash traces.

Also, credit where it's due: you independently reported this and proposed the exact fail-safe, so I'd like to add a Co-authored-by: trailer to that commit (or Reported-by:/Suggested-by: if you prefer) — and a Co-authored-by: on the fixture commit if you share it. Just let me know the name/email you'd like used, or say the word if you'd rather not be tagged.

@shanemort1982

Copy link
Copy Markdown
Contributor

@GavinZhu-GMI cheers for the credit, much appreciated. And yeah, confirmed: 62280c3 fixes our V4-Flash case too. Same behaviour on our side, normal_text stays empty, buffer is kept, and the invoke completes on a later chunk.

For the trailers: Reported-by + Suggested-by on 62280c3 is the accurate one since you wrote that commit. Co-authored-by on the fixture commit is grand.

Reported-by: shanemort1982 [email protected]
Suggested-by: shanemort1982 [email protected]
Co-authored-by: shanemort1982 [email protected]

Will share the fixture separately. Easier if I paste it here, or want a PR against the branch?

@GavinZhu-GMI
GavinZhu-GMI force-pushed the fix/deepseekv32-streaming-partial-malformedjson branch from 62280c3 to 3bf9591 Compare June 22, 2026 01:31
…r leaks raw DSML markup

The outer except in parse_streaming_increment returned the raw buffer as
normal_text on any error. Because _buffer is retained across increments, that
both leaks the DSML markers into user-visible content and re-emits the whole
buffer on every subsequent chunk -- ballooning the response to the output-token
cap (tool_calls empty, finish_reason=stop). Reported independently on
DeepSeek-V4-Flash, triggered by array-valued tool arguments rather than the
code-string prefix the partial-value fix addresses; same root cause, one layer up.

While the buffer still holds tool-call markup, emit empty normal_text and keep
buffering so a still-arriving invoke can complete on a later chunk, instead of
surfacing the markup. Adds a regression test forcing a parse error mid-markup
and asserting no leak and a retained buffer.

Co-authored-by: shanemort1982 <[email protected]>
@GavinZhu-GMI
GavinZhu-GMI force-pushed the fix/deepseekv32-streaming-partial-malformedjson branch from 3bf9591 to 2476acb Compare June 22, 2026 01:34
@GavinZhu-GMI

Copy link
Copy Markdown
Contributor Author

@shanemort1982 — please open the fixture as a PR against this branch (GavinZhu-GMI:fix/deepseekv32-streaming-partial-malformedjson); that keeps you as the author with full commit attribution rather than me pasting it in. I'll merge it into the PR. Targeting test_function_call_parser.py with your 1/7/64 chunk-size streamed fixture would be ideal.

I've also pushed the credit: the fail-safe commit (62280c3 → now 2476acb) carries Co-authored-by: shanemort1982, and the Co-authored-by: on the fixture will come from your own commit once you open the PR.

Thanks again for the independent V4-Flash confirmation and the fail-safe suggestion.

Add TestDeepSeekV32Detector.test_streaming_array_recipe_partial_value_chunked_1_7_64.

Replays a complete tool call whose non-string `operations` parameter carries a
spreadsheet-edit recipe emitted with Python-style single quotes, so its streamed
prefix is not-yet-valid JSON and partial_json_parser raises MalformedJSON (a
ValueError, not a stdlib json.JSONDecodeError). Feeding the payload at chunk
sizes 1, 7 and 64 asserts no raise, no DSML-marker leak into normal_text, and
that the tool name is still recovered. Fails on the unpatched detector at every
chunk size; passes with the partial-value except widening plus the outer
fail-safe on this branch.
…rray-recipe-fixture

test(deepseekv32): streamed array-recipe fixture at chunk sizes 1/7/64
@hnyls2002

Copy link
Copy Markdown
Collaborator

Heads-up: #34458 (5899674) landed and includes the exception fix from this PR — _parse_parameters_from_xml now catches (json.JSONDecodeError, MalformedJSON, ValueError), so a partial non-string parameter falls back to the raw string instead of escaping to the outer handler.

Not closing this, because the early-return guard you added is not in the merged version. I checked the case it targets and a partial DSML marker no longer reaches normal_text on main (it stays buffered), but you know the original failure better than I do — if there is a case that still leaks, please rebase and keep that hunk.

@github-actions

Copy link
Copy Markdown
Contributor

Thanks @GavinZhu-GMI. Closing this because it has had no updates in 91 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 12, 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.

3 participants