Skip to content

fix(agents): cap DSML recovery buffer to prevent unbounded memory growth - #86637

Closed
SebTardif wants to merge 3 commits into
openclaw:mainfrom
SebTardif:fix/deepseek-dsml-tool-call-recovery
Closed

SebTardif wants to merge 3 commits into
openclaw:mainfrom
SebTardif:fix/deepseek-dsml-tool-call-recovery

Conversation

@SebTardif

@SebTardif SebTardif commented May 25, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #90015

Summary

The createDeepSeekDsmlToolCallRecoverer() accumulates text in a buffer while waiting for a DSML close token. A malicious or buggy provider response could send an extremely large DSML body without ever closing it, causing unbounded memory growth.

Add a 256 KB cap (MAX_DSML_RECOVERY_BUFFER_BYTES) that discards the current DSML block as plain text when the buffer exceeds the limit. This matches the existing 256 KB caps used for native tool call argument buffers (MAX_TOOL_CALL_ARGUMENT_BUFFER_BYTES) and post-tool-call text buffers (MAX_POST_TOOL_CALL_BUFFER_BYTES).

Changed files

  • src/agents/openai-transport-stream.ts -- add MAX_DSML_RECOVERY_BUFFER_BYTES constant with UTF-8 byte-accurate measurement (Buffer.byteLength) in createDeepSeekDsmlToolCallRecoverer() when no close token is found
  • src/agents/openai-transport-stream.test.ts -- regression tests: oversized DSML block discarded as text (ASCII), and multibyte UTF-8 payload that exceeds byte cap despite fitting in string length

Real behavior proof

  • Behavior or issue addressed: The DSML recovery buffer in createDeepSeekDsmlToolCallRecoverer() grows without bound when a provider sends a DSML open token followed by a large body that never closes. Additionally, the byte-named cap was enforced using .length (UTF-16 code units), which undercounts multibyte UTF-8 text, allowing payloads above the intended 256 KB byte limit to bypass the guard.

  • Real environment tested: macOS 15.5, Node v22.19, OpenClaw built from patched source at /tmp/wt-86637.

  • Exact steps or command run after this patch:

Step 1. Built from branch and installed deps:

cd /tmp/wt-86637
pnpm install --frozen-lockfile
pnpm build

Step 2. Verified the fix uses byte-accurate measurement in the compiled production bundle:

node -e "
const chunk = require('fs').readFileSync('dist/openai-transport-stream-DRlicd4V.js', 'utf8');
const capMatch = chunk.match(/MAX_DSML_RECOVERY_BUFFER_BYTES\s*=\s*([\d.e]+)/);
console.log('DSML recovery buffer cap:', eval(capMatch[1]) + ' bytes');
const usesBytes = chunk.includes('Buffer.byteLength(buffer, \"utf8\") > MAX_DSML_RECOVERY_BUFFER_BYTES');
const usesLength = chunk.includes('buffer.length > MAX_DSML_RECOVERY_BUFFER_BYTES');
console.log('Uses Buffer.byteLength:', usesBytes);
console.log('Uses string .length:', usesLength);
const ascii = 'x'.repeat(200000);
const multibyte = '\u00E9'.repeat(200000);
console.log('ASCII 200K chars:     .length=' + ascii.length + ',   bytes=' + Buffer.byteLength(ascii, 'utf8'));
console.log('Multibyte 200K chars: .length=' + multibyte.length + ', bytes=' + Buffer.byteLength(multibyte, 'utf8'));
console.log('With old .length check, multibyte 200K would pass cap (200000 < 256000): BUG');
console.log('With new byte check, multibyte 200K exceeds cap (400000 > 256000): FIXED');
"

Step 3. Ran the DSML oversized buffer tests (both ASCII and multibyte regression) to verify behavioral correctness.

  • Evidence after fix: terminal output from the patched build:

Production bundle now uses Buffer.byteLength for the DSML recovery cap, matching the existing sibling caps:

$ grep -n 'MAX_DSML_RECOVERY_BUFFER_BYTES\|MAX_TOOL_CALL_ARGUMENT_BUFFER\|MAX_POST_TOOL_CALL_BUFFER' dist/openai-transport-stream-DRlicd4V.js
2841:const MAX_POST_TOOL_CALL_BUFFER_BYTES = 256e3;
2842:const MAX_TOOL_CALL_ARGUMENT_BUFFER_BYTES = 256e3;
3189:const MAX_DSML_RECOVERY_BUFFER_BYTES = 256e3;
$ grep -n 'Buffer.byteLength.*MAX_DSML' dist/openai-transport-stream-DRlicd4V.js
3226:if (final || Buffer.byteLength(buffer, "utf8") > MAX_DSML_RECOVERY_BUFFER_BYTES) {

Byte-accounting verification demonstrates the fix correctly handles multibyte text:

$ node -e "<proof script above>"
DSML recovery buffer cap: 256000 bytes
Uses Buffer.byteLength: true
Uses string .length: false

ASCII 200K chars:     .length=200000,   bytes=200000
Multibyte 200K chars: .length=200000, bytes=400000

With old .length check, multibyte 200K would pass cap (200000 < 256000): BUG
With new byte check, multibyte 200K exceeds cap (400000 > 256000): FIXED

Both DSML oversized buffer tests pass, including the new multibyte regression test that only passes with byte-accurate measurement:

$ node scripts/run-vitest.mjs src/agents/openai-transport-stream.test.ts -t "discards oversized DeepSeek DSML"
 ✓ |agents-core| openai-transport-stream.test.ts (242 tests | 240 skipped) 25ms
 ✓ |agents-support| openai-transport-stream.test.ts (242 tests | 240 skipped) 24ms
 Test Files  2 passed (2)
      Tests  4 passed | 480 skipped (484)

The 4 passed tests are: "discards oversized DeepSeek DSML recovery buffer as text" (ASCII, 300K chars) and "discards oversized DeepSeek DSML recovery buffer with multibyte UTF-8 text" (200K two-byte chars = 400K bytes), each running in both agents-core and agents-support suites. The multibyte test verifies the cap correctly rejects a payload whose .length (200000) is under the limit but whose UTF-8 byte size (400000) exceeds it.

  • Observed result after fix: The compiled production bundle at dist/openai-transport-stream-DRlicd4V.js:3226 uses Buffer.byteLength(buffer, "utf8") instead of buffer.length for the DSML recovery cap. This matches the existing byte-measurement pattern used by sibling caps (measureUtf8Bytes at line 2858). A 200K-character multibyte payload (400K bytes) is correctly rejected, where the old .length check would have allowed it through.

  • What was not tested: Live DeepSeek model streaming with actual oversized DSML output (requires a DeepSeek API key and a provider that sends >256 KB multibyte DSML bodies without closing).

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S proof: supplied External PR includes structured after-fix real behavior proof. labels May 25, 2026
@clawsweeper

clawsweeper Bot commented May 25, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed June 26, 2026, 2:17 AM ET / 06:17 UTC.

Summary
The PR adds a 256,000-byte UTF-8-counted DeepSeek DSML recovery-buffer cap and tests for oversized ASCII and multibyte DSML blocks.

PR surface: Source +11, Tests +121. Total +132 across 2 files.

Reproducibility: yes. Source inspection on current main shows an opened DSML block remains buffered across chunks until a close token or final flush, with no size cap before then.

Review metrics: 1 noteworthy metric.

  • New stream buffer cap: 1 added; 2 existing sibling caps. The new threshold is the behavior change that decides when oversized DSML stops being recoverable as a tool call.

Root-cause cluster
Relationship: fixed_by_candidate
Canonical: #90015
Summary: This PR is the candidate fix for the canonical DSML recovery-buffer issue; related DSML parser and filtering work is adjacent but does not replace this cap.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge readiness
Overall: 🐚 platinum hermit
Proof: 🦞 diamond lobster
Patch quality: 🐚 platinum hermit
Result: ready for maintainer review.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • [P2] Confirm maintainer acceptance of the 256 KB oversized-DSML threshold before merge.

Risk before merge

  • [P2] The cap changes oversized split DSML handling: a tool intent whose open block exceeds 256,000 UTF-8 bytes before its close token is no longer recoverable and flows through the text/filter path instead.

Maintainer options:

  1. Accept The Sibling-Aligned Cap (recommended)
    Land with the 256 KB DSML cap because it matches the existing stream-buffer limits and bounds provider-controlled memory growth.
  2. Pause For Runtime Owner Confirmation
    Ask an agent-runtime owner to confirm the threshold and the oversized-DSML failure mode before merge if that tradeoff needs explicit ownership.

Next step before merge

  • No automated repair is needed; a maintainer should accept or adjust the 256 KB cap tradeoff before merge.

Security
Cleared: The diff adds no dependency, workflow, package, secret, or new code-execution surface and narrows provider-controlled memory growth.

Review details

Best possible solution:

Land this PR or an equivalent UTF-8 byte-counted recoverer cap after maintainers accept the 256 KB oversized-DSML behavior.

Do we have a high-confidence way to reproduce the issue?

Yes. Source inspection on current main shows an opened DSML block remains buffered across chunks until a close token or final flush, with no size cap before then.

Is this the best way to solve the issue?

Yes, pending maintainer acceptance of the threshold. The recoverer is the narrow owner of the unbounded buffer, and a UTF-8 byte cap matching sibling stream caps is more maintainable than downstream-only filtering.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 4fc504d321b6.

Label changes

Label justifications:

  • P1: The PR fixes a provider-controlled unbounded buffer in core agent streaming that can threaten gateway availability.
  • merge-risk: 🚨 message-delivery: The cap changes whether oversized split DSML text can still be recovered into a tool call or is discarded from the recovery path.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The PR body includes terminal proof from a patched production build plus targeted oversized DSML tests passing after the fix.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body includes terminal proof from a patched production build plus targeted oversized DSML tests passing after the fix.
Evidence reviewed

PR surface:

Source +11, Tests +121. Total +132 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 19 8 +11
Tests 1 121 0 +121
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 140 8 +132

What I checked:

Likely related people:

  • steipete: Authored and merged Fix live model inference edge cases #88946, which added the DeepSeek DSML recovery path containing the uncapped buffer. (role: feature introducer and recent area contributor; confidence: high; commits: 9ead0ae9219e; files: src/agents/openai-transport-stream.ts, src/agents/openai-transport-stream.test.ts)
  • hansraj316: Authored the merged parser-performance work in the same DSML helper area in perf(agents): memoize XML attribute regex in DSML stream parser #92034. (role: recent DSML parser contributor; confidence: medium; commits: 91cc69d70e6c; files: src/agents/openai-transport-stream.ts, src/agents/openai-transport-stream.test.ts)
  • samzong: Authored the merged DeepSeek DSML filtering work that composes with the recovery path after non-recovered text is emitted. (role: adjacent DSML filtering contributor; confidence: medium; commits: 280798166931; files: src/agents/deepseek-text-filter.ts, src/agents/openai-transport-stream.ts, src/agents/openai-transport-stream.test.ts)
  • vincentkoc: Authored and merged adjacent OpenAI-compatible stream buffering work used as the sibling cap precedent, and merged the later DSML parser helper PR. (role: adjacent stream-buffer contributor and merger; confidence: medium; commits: 68502c90d1fb, 91cc69d70e6c; files: src/agents/openai-transport-stream.ts, src/agents/openai-transport-stream.test.ts)
  • osolmaz: Live GitHub metadata currently shows this PR assigned to osolmaz, making them a likely routing contact for maintainer review. (role: assigned follow-up owner; confidence: medium; files: src/agents/openai-transport-stream.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

How this review workflow works
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. labels May 25, 2026
@clawsweeper

clawsweeper Bot commented May 25, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper PR egg

🎁 Pass real behavior proof to wake the egg and unlock a hatchable treat.

Where did the egg go?
  • The egg game starts only after the PR passes the real-behavior proof check.
  • Before that, no creature or rarity is rolled. The treat waits for real proof.
  • This is still just collectible flavor: proof affects review readiness, not creature quality.

@openclaw-barnacle openclaw-barnacle Bot added triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. proof: supplied External PR includes structured after-fix real behavior proof. and removed proof: supplied External PR includes structured after-fix real behavior proof. triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. labels May 26, 2026
@SebTardif
SebTardif force-pushed the fix/deepseek-dsml-tool-call-recovery branch from bd5f478 to 32b4bda Compare May 26, 2026 22:12
@SebTardif
SebTardif requested review from a team and steipete as code owners May 26, 2026 22:12
@github-actions github-actions Bot added the dependencies-changed PR changes dependency-related files label May 26, 2026
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation channel: discord Channel integration: discord channel: googlechat Channel integration: googlechat channel: imessage Channel integration: imessage channel: line Channel integration: line channel: matrix Channel integration: matrix channel: mattermost Channel integration: mattermost labels May 26, 2026
@SebTardif

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@SebTardif

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jun 3, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@SebTardif

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jun 14, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@openclaw-barnacle

Copy link
Copy Markdown

This assigned pull request has been automatically marked as stale after being open for 27 days.
Please add updates or it will be closed.

1 similar comment
@openclaw-barnacle

Copy link
Copy Markdown

This assigned pull request has been automatically marked as stale after being open for 27 days.
Please add updates or it will be closed.

@SebTardif

Copy link
Copy Markdown
Contributor Author

Refreshed on latest main (3d6127f7e4).

Rebuilt as a single clean commit on current main (dropped the intermediate merge commit). Still targets #90015; main still has no MAX_DSML_RECOVERY_BUFFER_BYTES on createDeepSeekDsmlToolCallRecoverer().

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@openclaw-barnacle

Copy link
Copy Markdown

This assigned pull request has been automatically marked as stale after being open for 27 days.
Please add updates or it will be closed.

@SebTardif

Copy link
Copy Markdown
Contributor Author

Refreshed on latest main (d23977edbc). Rebased cleanly, single commit preserved. CI was green on prior run; new run will follow the force-push.

@openclaw-barnacle

Copy link
Copy Markdown

This assigned pull request has been automatically marked as stale after being open for 27 days.
Please add updates or it will be closed.

Add a 256 KB UTF-8 byte-accurate cap on the DeepSeek DSML tool-call
recovery buffer, matching existing tool-call argument and post-tool-call
buffer limits. Oversized unclosed DSML blocks are discarded as plain text.

Signed-off-by: Sebastien Tardif <[email protected]>
@SebTardif

Copy link
Copy Markdown
Contributor Author

Refreshed on latest main (0da26499da).

Improvement: replaced the per-chunk Buffer.byteLength(buffer) full-buffer scan with incremental byte tracking (bufferBytes). This matches the pattern used by MAX_TOOL_CALL_ARGUMENT_BUFFER_BYTES and MAX_POST_TOOL_CALL_BUFFER_BYTES elsewhere in the same file, and avoids O(buffer) work on every chunk in the guard check (now O(1)). No behavioral change; existing tests still cover both ASCII and multibyte overflow paths.

…loop-condition

The emitAndSlice() and clearBuffer() closures modify the buffer
variable, but oxlint cannot trace mutations through closures and
flags the while(buffer) loop condition as unmodified. Inline the
assignments so the linter can see direct buffer mutation in the
loop body.

Signed-off-by: Sebastien Tardif <[email protected]>
@openclaw-barnacle

Copy link
Copy Markdown

This assigned pull request has been automatically marked as stale after being open for 27 days.
Please add updates or it will be closed.

@openclaw-barnacle

Copy link
Copy Markdown

Closing due to inactivity.
If you believe this PR should be revived, post in #clawtributors on Discord to talk to a maintainer.
That channel is the escape hatch for high-quality PRs that get auto-closed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. proof: supplied External PR includes structured after-fix real behavior proof. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S stale Marked as stale due to inactivity status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

DSML recovery buffer grows without bound on unclosed DSML blocks

3 participants