Skip to content

[Perf] function_call: Stop re-scanning the open DSML invoke on every streamed delta (DeepSeek V3.2/V4/V4.1) - #44940

Open
divyvasal wants to merge 1 commit into
sgl-project:mainfrom
divyvasal:perf/dsml-incremental-streaming-tool-parser
Open

divyvasal wants to merge 1 commit into
sgl-project:mainfrom
divyvasal:perf/dsml-incremental-streaming-tool-parser

Conversation

@divyvasal

@divyvasal divyvasal commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

DeepSeekV32Detector.parse_streaming_increment, which the V4 and V4.1 detectors inherit, keeps a long-form invoke in _buffer until </|DSML|invoke> arrives. On every delta it runs re.search(self.invoke_regex, current_text, re.DOTALL) over the whole buffer, only to find that the invoke is still open and break out of the loop. The (?P<body>.*?)(?P<end>(?:</…invoke>|$)) part lazily walks the entire held body each time. So each delta costs O(n) in the length of the call, and one long tool call costs O(n^2).

We hit this in production serving of DeepSeek V4.1 with long agentic tool calls, where write_file / edit-style calls carry 20-30K tokens of code in one string parameter. On an older build, from before #39632, the same path also re-parsed and diffed the partial arguments on every delta. That capped delivery at about 1-2K tok/s per replica once a few such calls were in flight, and it backed up the tokenizer-manager output path. #39632 removed argument streaming, which cut the cost about 6x, but the re-scan is still quadratic. On current main (14ad64c), a 30K-token call in 18-char deltas costs 3.5 s of CPU, and each delta near the end of the call costs about 1.2 ms. That works out to:

  • about 4K tok/s for one stream near the end of the call;
  • about 12.8K tok/s parse-only ceiling for six concurrent 20K-token calls, on one fast core.

Profile on main (V4.1, 10K-token string parameter, 1,959 deltas): 0.389 s of the 0.406 s total (96%) is re.Pattern.search. Everything else is constant per delta.

Modifications

python/sglang/srt/function_call/deepseekv32_detector.py, +33 lines. Nothing else changes.

  • When the loop breaks on an open long-form invoke, record (buffer, scan_from) in self._open_invoke. scan_from is the start of the invoke body, or len(buffer) - len(invoke_end_token) + 1 if that is later.
  • On the next delta, if self._buffer is still that exact object, search only from scan_from for invoke_end_token:
    • No closer: re-arm and return StreamingParseResult(). This is exactly what the full path returns for an open invoke, and the full path changes no state other than the buffer.
    • Closer found: fall through to the unchanged full path. That path runs the regex once, completes the call, and handles any following invokes.
  • Everything else runs the existing code as before. This covers the first chunk of each invoke, the completion chunk, self-closing invokes, finish(), a buffer replaced from outside (_buffer is not the recorded object), and a subclass that replaces invoke_regex or invoke_end_token after __init__ (the fast path is never armed).

Why this preserves behaviour:

  • The open invoke stays the leftmost match. An earlier start position fails only on header text that was already complete in the old buffer, because the header's [^"]+ name ends at the first ", which lies at or before the open invoke's own header. Adding text cannot change that.
  • A closer can only appear in new text. The body ends at the first closer after the header, or at $. Any closer starting before old_len - len(closer) + 1 would have been entirely inside the old buffer, and it was not there.
  • Nothing else would change. With a closer still missing, the original code returns normal_text="" and no calls, and it changes nothing except the buffer.

test/registered/unit/function_call/test_deepseek_dsml_long_streaming.py (new, CPU), for V3.2, V4 and V4.1. Each transcript is a 3K-char code string parameter that contains <, </, <|DSML| and a partial invoke closer, followed by a JSON-body invoke and a self-closing invoke:

  1. test_incremental_matches_full_rescan: chunk sizes 1, 3, 7 and 18. Per delta, the results and _buffer equal those of a detector whose shortcut is cleared before every delta (the full re-scan). finish() also matches, and the calls and arguments match the expected ones.
  2. test_open_invoke_is_not_rescanned_per_delta: a 60K-char call in 18-char deltas. The total length of strings handed to re.search must stay under 4x the transcript length. This bound does not depend on timing. On main the count is about 216M characters, against a bound of about 0.5M, so the test fails without the fix.

Accuracy Tests

No output changes: streamed normal_text, tool calls, detector state, finish() and detect_and_parse() are identical. That was checked by:

  • sglang's own tests: every file in test/registered/unit/function_call/, plus test/registered/unit/parser/test_reasoning_parser.py, passes with and without the change. This includes the 25 tests in test_deepseekv4_detector.py, test_unexpected_parse_error_fails_closed (the patch.object error path), and the V4.1 encoder round trip through ReasoningParser + FunctionCallParser at chunk sizes 1-1000. The one exception is two subtests in test_iquest_q1_detector.py, which need the full serving stack (fastapi) that was not installed locally. They fail the same way on main.

  • Differential fuzz, main's original detector vs this change: 20,000 generated DSML transcripts across V3.2, V4 and V4.1, 46.8M characters in total. The transcripts include:

    • prose before and after the calls;
    • bare invokes, and 1-4 invokes per block;
    • self-closing invokes;
    • XML and JSON bodies;
    • malformed and duplicate parameters;
    • stray <, </, partial and complete DSML tags inside values and names;
    • nested invoke headers;
    • missing closers and truncated streams;
    • values up to 40K chars.

    Each transcript is replayed under 1-char, random 1-40, token-like and empty-chunk chunkings, plus every 2-way split for short ones. That is 422,412 stream runs and 21.4M deltas, of which 17.8M took the new path. After every delta, the comparison covers normal_text, the calls, logged warnings/errors and the detector state. At the end it also covers finish() and detect_and_parse(). 0 divergences.

  • Hand-written edge cases: 51, including:

    • errors raised while parsing the completed invoke (the fail-closed path);
    • subclasses that override _parse_parameters_from_xml or has_tool_call, or replace invoke_regex with one that also ends an invoke at a blank line, or change invoke_end_token;
    • an instance-level method patch applied mid-stream;
    • outside code replacing _buffer with an equal copy, with "", or with different text.

    0 divergences. Three deliberately broken variants of the change were each caught: one that skips the boundary overlap, one with no invoke_regex guard, and one with no buffer-identity check.

  • A separate adversarial differential fuzzer, with its own generators, chunkers and comparator, also compares raised exceptions: 454K cases and 65.6M deltas (exhaustive short splits, grammar-generated, mutated, random-walk and long values), with 0 counterexamples.

Speed Tests and Profiling

This is CPU time (time.process_time) for one streamed call in 18-char deltas, about 5 tokens each at 3.5 chars/token, on Python 3.13 on an Apple M4 Pro, single thread. "identical" means the per-delta results are equal between the two versions.

detector body tokens deltas main this PR speedup identical
V4.1 XML, string="true" 1,000 209 0.005 s 0.0003 s 17x yes
V4.1 XML, string="true" 5,000 986 0.102 s 0.0016 s 64x yes
V4.1 XML, string="true" 10,000 1,959 0.397 s 0.0043 s 93x yes
V4.1 XML, string="true" 30,000 5,848 3.498 s 0.0201 s 174x yes
V3.2 XML, string="true" 30,000 5,848 3.456 s 0.0206 s 168x yes
V4 XML, string="true" 30,000 5,848 3.487 s 0.0197 s 177x yes
V3.2 JSON body 10,000 2,051 0.457 s 0.0044 s 104x yes
V3.2 JSON body 30,000 6,130 3.833 s 0.0206 s 186x yes
V4.1 XML, string="false" (JSON array) 5,000 1,097 0.124 s 0.0020 s 63x yes
V4.1 XML, string="false" (JSON array) 30,000 6,519 4.334 s 0.0241 s 180x yes
  • Per delta at the end of a 30K-token call: 1,160 µs on main, 4.3 µs with this PR. The one delta that delivers the closer still runs the full parse once, about 1-2 ms for a 105K-char body.
  • Six interleaved 20K-token calls (staggered, steady state), parse-only ceiling: about 12.8K tok/s on main and 1.3-1.8M tok/s with this PR, with identical outputs.
  • Plain prose with no DSML (tools attached, 64K chars of text with <b> / </p> / a<3): 1,537 ns per delta on main, 1,590 ns with this PR, about +3% (~50 ns). That comes from one extra attribute swap and an is check per delta.

What remains O(n) per delta is self._buffer += new_text, a C-level copy that the buffer contract already requires. For a 105K-char buffer it is a few µs.

Checklist

  • Format your code according to the Format code with pre-commit. (pre-commit run on the changed files: isort 7.0.0, ruff 0.15.1 check + format, codespell 2.4.1 and the repo's local hooks all pass)
  • Add unit tests according to the Run and add unit tests. (test/registered/unit/function_call/test_deepseek_dsml_long_streaming.py, CPU)
  • Update documentation according to Write documentations. (N/A, internal behaviour only)
  • Provide accuracy and speed benchmark results according to Test the accuracy and Benchmark the speed. (Outputs are unchanged by construction and checked by differential fuzzing; CPU benchmarks are above.)
  • Follow the SGLang code style guidance.

Pre-existing streaming-parser behaviours found while fuzzing, which this PR deliberately does not change, are filed separately: #44941

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 to do so.
    • Common commands include /tag-and-rerun-ci, /tag-run-ci-label, /rerun-failed-ci
  4. After green CI and required approvals, ask Merge Oncalls or people with Write permission to merge the PR.

🤖 Generated with Claude Code


CI States

Latest PR Test (Base): ❌ Run #39091707139
Latest PR Test (Extra): ❌ Run #39091706896
Latest PR Test (AMD ROCm 10): ❌ Run #39091706967

…delta

DeepSeekV32Detector.parse_streaming_increment (also used by the V4 and
V4.1 detectors) holds a long-form invoke in _buffer until its closer
arrives, and re-runs invoke_regex over the whole buffer on every delta to
find out that it is still open. The lazy body scan makes each delta O(n)
in the length of the call, so a long tool call (e.g. a file write) costs
O(n^2): about 3.5 s of CPU for a 30K-token call in 18-char deltas, with
deltas near the end costing ~1.2 ms each.

While the invoke is open, the result is always empty and only the buffer
changes. The open invoke stays the leftmost match, since its header is
complete, and any closer starting before the old end minus the closer
length was already ruled out. So remember the open invoke and search only
the newly arrived text for the closer; when it appears, or the buffer was
replaced from outside, or a subclass replaced invoke_regex /
invoke_end_token, fall through to the unchanged full path. Output is
identical; the 30K-token call drops to ~20 ms.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@YangChen-pro

Copy link
Copy Markdown
Contributor

+1, we ran into the same thing serving DeepSeek V4. Sometimes the model gets stuck repeating inside a string arg, e.g. a Bash command that keeps growing to a few hundred k chars until max_tokens. With the rescan on every delta, that one request blocks the event loop and every other request times out, health checks too. We made pretty much the same fix on our side and the hang went away.

One more thing, not blocking. self._buffer += new_text still copies the whole buffer on every delta (CPython's in-place concat doesn't kick in for attributes). It doesn't matter at the sizes in your table, but it adds up when the model loops. 4-char deltas into a string param:

chars in the open invoke this PR also keep deltas out of _buffer until the closer
120,000 0.28s 0.13s
480,000 5.31s 0.52s
1,920,000 98.15s 2.05s

Each delta is still well under 1ms, so it's not a hang, just more total CPU. The catch is _buffer falls behind while the invoke is open, so your per-delta _buffer check would need to change. Happy to send it as a small follow-up after this lands, if you want.

@divyvasal

Copy link
Copy Markdown
Contributor Author

Thanks, glad it matched what you saw. Good catch on _buffer += new_text. Keeping the deltas out of _buffer while the invoke is open makes sense, and yes, a follow-up after this lands would be great. Heads-up that #44940 will first be rebased onto #44956 (one hunk in the same function), so it's worth basing the follow-up on that.

@divyvasal

Copy link
Copy Markdown
Contributor Author

@hnyls2002 friendly ping on this one. It removes the quadratic re-scan of an open DSML invoke in the DeepSeek V3.2/V4/V4.1 streaming detector: on main, a single 30K-token tool call costs about 3.5 s of event-loop CPU, and @YangChen-pro hit the same hang in production. It needs run-ci. It should land after #44956, since both touch parse_streaming_increment, and I'll rebase it onto #44956 once that merges.

This branch has not been deployed

No deployments
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.

2 participants