Skip to content

fix: avoid Gateway stalls after streamed tool-call XML - #181397

Merged
steipete merged 4 commits into
mainfrom
fix/xml-stream
Oct 23, 2026
Merged

steipete merged 4 commits into
mainfrom
fix/xml-stream

Conversation

@steipete

@steipete steipete commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes long streamed replies consuming quadratic parser work after a model leaks or quotes tool-call XML outside code.

Closes #175156. Thanks @JasonBuildAI for the report and transition regressions from #175161; the commit preserves contributor credit.

User Impact

Long replies continue streaming without repeatedly parsing their settled XML prefix. Literal code examples, partial payloads, and later Markdown corrections keep the canonical output.

Why This Change Was Made

The XML parser now records whether its current decisions are settled. Reuse also checks canonical Markdown ownership for both the raw reply and the input to parameter unwrapping, because removing XML can itself expose a link, image reference, or incomplete tag. Code-free continuations retain a bounded delimiter boundary instead of comparing the growing reply. New tags and unsettled ownership still take the canonical path.

Runtime: +202/-80 lines (net +122); regressions: +227/-1 (net +226); opt-in Gateway proof tooling: +543. The added runtime state preserves the existing parsing phases and pre-trim directive coordinates rather than introducing another parser or configuration surface. The Gateway also skips block snapshots when no block-delivery callback exists, and the reply-directive resolver retains canonical pre-trim XML projection state across appends and source replacements.

Evidence

  • CI passes on the final head, including openclaw/ci-gate.
  • Base regression is red: 78,971,760 regex-input characters versus a 609,280 budget. The fixed regression passes.
  • All four extended projection/token/mixed/XML sweeps pass: 2,153,592 checks, zero streamed-text or delta-replay divergences. Includes every prefix, the original split [re + f]: /u, truncated quoted attributes, assembled syntax after XML removal, nested lists/tables/quotes, and CRLF.
  • Ten focused files / 380 distinct tests pass: the original six-file XML owner set (13.76 s wrapper wall) plus the final five-file consumer set (147 tests, 33.09 s, with one shared file). Core and affected consumer types, changed-file lint/format, and all seven required ratchets/checks pass. The new four-provider work regression fails before the caller repair at 3.26–3.64 million Markdown-input characters against a 28,880 budget and passes afterward.
  • Production projector, four-character appends: 32 KB regex input falls from 903,415,914 to 267,414 characters; 64 KB falls from 3,596,122,868 to 524,935. Process CPU falls from 878 to 11 ms and 3970 to 18 ms respectively (single runs).

Built isolated Gateway on port 19900, using a 32,768-character fixture in 8,192 four-character SSE chunks, five warm samples per head:

Measurement Base Fixed
XML input characters per reply (median) 416,333,981 593,729
XML transform calls per reply (median) 25,608 72
Gateway CPU, median / p95 7,053 / 7,463 ms 1,087 / 1,710 ms
Elapsed, median / p95 6,376 / 6,610 ms 821 / 1,118 ms

All ten measured fixture replies matched exactly, including fenced XML preservation. A real native Ollama qwen2.5:7b turn through the same built Gateway returned the exact requested control text in 4.55 seconds; the proxy verified /api/chat, HTTP 200, streaming, and the model identity. These numbers came from a one-off Gateway proof harness that is kept with the proof artifacts rather than committed; the committed tool-call-xml.streaming-parity and tool-call-xml.streaming-work tests guard the behavior.

The first candidate reduced parser work only partially: built call-stack evidence exposed unused block snapshots and repeated raw directive transforms. The final change removes both bypasses. Isolated Codex branch review of the final head is scoped-clean with no actionable P0–P2 findings.

Active callback-driven block-delivery snapshots retain canonical reconciliation. This change does not claim bounded parsing for that separate delivery path.

Proof is local macOS arm64 / Node 26.12.1. Baseline and candidate builds are sequential, not ABAB; Gateway CPU includes instrumentation and background work, so deterministic parser counts are the primary evidence. Ambiguous/new XML or mutable Markdown deliberately falls back to the canonical transform; this does not claim a universal bound for repeatedly changing syntax.

steipete and others added 2 commits October 22, 2026 22:44
Reuse settled XML output only while the canonical parser and Markdown
ownership evidence allow it. Track ownership for both the raw reply and
the parameter-unwrapping input, since removing XML can expose new Markdown
syntax. Keep truncated tags, payload prefixes, and parameter boundaries
on the canonical path.

Cover the original append transitions and assembled syntax, and add a
bounded-work regression plus a reproducible isolated Gateway workload.

Fixes #175156
Co-authored-by: JasonBuildAI <[email protected]>
Skip per-delta block snapshots when there is no block-delivery consumer. Retain canonical pre-trim XML projection state in the reply-directive resolver so whitespace restoration does not restart parsing.

Keep active block delivery and terminal batch behavior unchanged. Cover missing consumers, held directive frames, and source replacements.
@clawsweeper

clawsweeper Bot commented Oct 23, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@steipete
steipete marked this pull request as ready for review October 23, 2026 06:01
@openclaw-barnacle openclaw-barnacle Bot added scripts Repository scripts agents Agent runtime and tooling size: XL labels Oct 23, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-23T06:31:29.841861Z 2b72d36 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

Adapt asynchronous HTTP handlers to the server callback contract and require a spawned Gateway PID before process-group cleanup. This resolves the scripts lint failures reported by CI.
@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: bb96942ca3

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread scripts/proof-tool-call-xml-stream.mjs Outdated
execFileSync("lsof", ["-t", `-iTCP:${port}`, "-sTCP:LISTEN"], { encoding: "utf8" }).trim(),
);
const initial = await snapshot();
assert.equal(initial.node, "26.12.1");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Badge Allow every supported Node runtime in the proof script

Running this newly documented proof on Node 24.22.1+ or on any newer Node 26 patch aborts after starting the Gateway, even though package.json explicitly supports >=24.22.1 <25 || >=26.12.1. Record the runtime version or validate the supported range instead of requiring exactly 26.12.1, so maintainers can reproduce the benchmark on supported environments.

Useful? React with 👍 / 👎.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Oct 23, 2026
@clawsweeper

clawsweeper Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR reuses settled XML sanitization results and removes unnecessary per-delta parsing from Gateway reply streaming.

Example: A 32,768-character reply contains unfenced tool-call XML followed by prose streamed in four-character chunks.

  • Before: The supplied built-Gateway measurements report 416,333,981 XML input characters processed per reply.
  • After: The same workload processes 593,729 characters while preserving the exact expected reply and fenced XML examples.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful, narrowly scoped performance repair with supplied Gateway evidence, meaningful invalidation regressions, resolved prior findings, and passing current-head CI.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The supplied built-Gateway workload exercises XML-bearing replies through streaming SSE on macOS arm64/Node 26.12.1, records reduced parsing work and exact expected output, and includes a native Ollama control; timing claims remain limited by sequential sampling.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Long replies containing tool-call XML delay streaming and other work sharing the Gateway event loop.
Reason: The measured reduction addresses an owned defect without new settings or intended output changes, and the supplied maintainer-authored direction is already approved.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR addresses a remaining current-main performance defect, and no actionable patch defects remain. Both prior findings are resolved by removing the one-off proof scripts, and the current-head CI gate passes.

Priority: P2
Reviewed head: 2b72d3679a324e99257e28251347174d02f5e3a4

Before merge

None.

Findings

None.

Agent review details

How this fits together

Model text enters the assistant message-update pipeline as snapshots and deltas; text projections remove internal tool markup, preserve Markdown examples, and produce visible replies and delivery metadata.

flowchart LR
A[Model text deltas] --> B[Message update owner]
B --> C[Text projections]
C --> D[XML sanitizer]
D --> E[Markdown ownership]
C --> F[Reply directive resolver]
F --> G[Visible reply delivery]
Loading

Technical review

Best possible solution:

Reuse settled results within the existing XML and Markdown owners while preserving canonical fallback, pre-trim directive coordinates, and callback-driven block delivery.

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

Current-main source establishes whole-reply parsing after activation, and the linked report supplies deterministic work-count reproduction; this read-only review ran no target code.

Is this the best way to solve the issue?

The patch fixes the measured owner and consumer costs without a parallel parser, preserves canonical invalidation, and removes the unnecessary proof scripts; no smaller complete repair was established.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 3ff4a6cb2781.

Provenance checked

  • XML sanitizer and streaming activation keeps the original intent (fix: serialized tool-call XML leaks into chat replies #138204: Hide serialized tool scaffolding while preserving literal code, terminal text, and transcript bytes; later optimizations retained canonical parsing for uncertain candidates.)
  • Raw directive coordinates and streaming projection keeps the original intent (e35bdeb: Carry certified append facts while retaining correction, boundary, and final-settlement semantics.)
  • Optional block-delivery snapshots keeps the original intent (8ab6ad1: Preserve visible answer ordering and canonical snapshot reconciliation across tools and reasoning; the patch retains that reconciliation when its consumer exists.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit b656d96 adds src/shared/text/tool-call-xml.ts:8 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: b656d96a421c; files: src/shared/text/tool-call-xml.ts)
  • Jason Cat: Raw commit edbe9a2 adds src/shared/text/tool-call-xml.ts:8 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: edbe9a2ca910; files: src/shared/text/tool-call-xml.ts)

PR surface

Source +122, Tests +226. Total +348 across 8 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 3 202 80 +122
Tests 5 227 1 +226
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 8 429 81 +348

Review metrics

Metric Value Why it matters
Production versus regression code Production +202/-80; tests +227/-1 Runtime growth carries parser settlement and Markdown invalidation facts in existing owners; the tests cover output parity, replacement transitions, and bounded parsing work.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #175156
Summary: This PR repairs the residual unfenced XML parsing cost documented by the canonical report and builds on the earlier contributor's transition cases.

Members:

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

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: Specific streamed XML shapes cause excessive synchronous parsing and delayed Gateway work, with a focused repair boundary.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (1 earlier review cycle)
  • reviewed 2026-10-23T06:24:01.243Z sha bb96942 :: needs changes before merge. :: [P2] Allow supported Node versions to run the proof | [P2] Construct the proof proxy URL from a fixed origin

Reviewed October 23, 2026, 2:38 AM ET / 06:38 UTC (Revision 2).

The one-off Gateway proof harness and its metrics helper were only used to
produce the PR evidence; the committed streaming parity and work-count tests
guard the behavior. Keep the harness with the proof artifacts instead of
adding 543 lines of unowned scripts.
@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@openclaw-barnacle openclaw-barnacle Bot added size: L and removed scripts Repository scripts size: XL labels Oct 23, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. proof: sufficient ClawSweeper judged the real behavior proof convincing. labels Oct 23, 2026
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 23, 2026
@steipete
steipete merged commit 37e5e6c into main Oct 23, 2026
142 of 147 checks passed
@steipete
steipete deleted the fix/xml-stream branch October 23, 2026 06:45
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 24, 2026
* fix: avoid repeated parsing after streamed tool-call XML

Reuse settled XML output only while the canonical parser and Markdown
ownership evidence allow it. Track ownership for both the raw reply and
the parameter-unwrapping input, since removing XML can expose new Markdown
syntax. Keep truncated tags, payload prefixes, and parameter boundaries
on the canonical path.

Cover the original append transitions and assembled syntax, and add a
bounded-work regression plus a reproducible isolated Gateway workload.

Fixes openclaw#175156
Co-authored-by: JasonBuildAI <[email protected]>

* fix: reuse XML projections through Gateway streaming

Skip per-delta block snapshots when there is no block-delivery consumer. Retain canonical pre-trim XML projection state in the reply-directive resolver so whitespace restoration does not restart parsing.

Keep active block delivery and terminal batch behavior unchanged. Cover missing consumers, held directive frames, and source replacements.

* fix: handle async errors in the XML stream proof

Adapt asynchronous HTTP handlers to the server callback contract and require a spawned Gateway PID before process-group cleanup. This resolves the scripts lint failures reported by CI.

* chore(text): keep the XML streaming proof harness out of tree

The one-off Gateway proof harness and its metrics helper were only used to
produce the PR evidence; the committed streaming parity and work-count tests
guard the behavior. Keep the harness with the proof artifacts instead of
adding 543 lines of unowned scripts.

---------

Co-authored-by: JasonBuildAI <[email protected]>
RomneyDa pushed a commit that referenced this pull request Oct 26, 2026
…aming (#175472)

fix(text): stop re-parsing streamed Markdown for ordinary HTML/JSX markup

While a long reply streamed, the tool-call XML filter parsed the whole growing Markdown text for every ordinary less-than sign, so long HTML/JSX answers burned a lot of Gateway CPU. The Markdown ownership check now runs only for text that could start a tool-call tag.

Thanks @JasonBuildAI.

Release adaptation: the stable filter predates main's streaming-prefix hold
(#174376), isToolCallTagPrefix, isInsideSettledBlockCode, and the protection
fast-path scanner. Ported the fix logic onto the stable loop instead: the
Markdown ownership parse (findCodeRegions) now runs only for a complete
tool-call tag candidate, and an unfinished trailing tag name (e.g. "<p") is
rescanned on the next append without any parse, which covers the
partial-boundary stall fixed on main by edbe9a2 (#180765). Both
outcomes previously returned false, so the projection output is unchanged.
Ported the #175472 and #180765 work-count and chunk-boundary parity tests
(without main's streaming flag). 37e5e6c (#181397, stall after a real
tool-call XML activates the filter) is a separate bug that depends on
main-only ownership reuse (#175328) and diverged stream handlers; not
included.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit 2ad3797)
Includes fix logic from commit edbe9a2
RomneyDa added a commit that referenced this pull request Oct 28, 2026
* fix: avoid repeated parsing after streamed tool-call XML

Reuse settled XML output only while the canonical parser and Markdown
ownership evidence allow it. Track ownership for both the raw reply and
the parameter-unwrapping input, since removing XML can expose new Markdown
syntax. Keep truncated tags, payload prefixes, and parameter boundaries
on the canonical path.

Cover the original append transitions and assembled syntax, and add a
bounded-work regression plus a reproducible isolated Gateway workload.

Fixes #175156
Co-authored-by: JasonBuildAI <[email protected]>

* fix: reuse XML projections through Gateway streaming

Skip per-delta block snapshots when there is no block-delivery consumer. Retain canonical pre-trim XML projection state in the reply-directive resolver so whitespace restoration does not restart parsing.

Keep active block delivery and terminal batch behavior unchanged. Cover missing consumers, held directive frames, and source replacements.

* fix: handle async errors in the XML stream proof

Adapt asynchronous HTTP handlers to the server callback contract and require a spawned Gateway PID before process-group cleanup. This resolves the scripts lint failures reported by CI.

* chore(text): keep the XML streaming proof harness out of tree

The one-off Gateway proof harness and its metrics helper were only used to
produce the PR evidence; the committed streaming parity and work-count tests
guard the behavior. Keep the harness with the proof artifacts instead of
adding 543 lines of unowned scripts.

---------

Co-authored-by: JasonBuildAI <[email protected]>

(cherry picked from commit 37e5e6c)

Co-authored-by: RomneyDa <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: L 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.

[Bug]: streaming a reply that quotes or leaks tool-call XML outside code re-parses the whole reply per delta (quadratic Gateway CPU)

2 participants