Skip to content

fix: long HTML answers still stall Gateway streaming at partial tag boundaries - #180765

Merged
steipete merged 4 commits into
openclaw:mainfrom
JasonBuildAI:fix/html-partial-tag-stream-reparse-m8c4
Oct 23, 2026
Merged

steipete merged 4 commits into
openclaw:mainfrom
JasonBuildAI:fix/html-partial-tag-stream-reparse-m8c4

Conversation

@JasonBuildAI

@JasonBuildAI JasonBuildAI commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes: a long streamed ordinary HTML reply can still spend 4.8-5.2 seconds of blocking Gateway CPU at a delta boundary that leaves a partial tag prefix such as <p, delaying every channel, session, cron turn, and tool call in the same process. Fixes #180720.

This is a follow-up to #175472 and its source report #175439. The merged optimization skips complete ordinary tags and partial prefixes inside settled fences. Outside those cases, <p is still a prefix of <parameter>, so every four-character delta that ends there sends the whole accumulated reply through the canonical Markdown ownership resolver again.

User Impact

User impact: long HTML, JSX, XML, SVG, and comparison-heavy answers no longer stall unrelated Gateway work at partial tag boundaries. On a 64 KB fixture streamed in four-character deltas, the shipped createAssistantVisibleStreamText() path drops from 4,840.5 / 5,175.8 ms to 655.0 / 631.0 ms (multiline / single-line) on the same Windows host. The deterministic 16 KB regression drops from 5,417,280 parsed characters against a 31,980-character budget (169x over) to within budget. Tool-call stripping, fenced-code ownership, and one-shot output remain unchanged.

Why This Change Was Made

Streaming mode now holds only an unresolved tag prefix just long enough to see whether the next delta completes it. Ordinary markup is released to the existing projector; a completed tool-call candidate still goes through the canonical resolver. The carried protection scan disables holding for fences, ambiguous paragraph ownership, and structural uncertainty, preserving the existing Markdown semantics.

The fast path also disables itself permanently once any complete tool-call candidate is found, so later deltas cannot hide or reorder tool-call XML.

Evidence

Pre-fix regression on upstream code:

expected 5417280 to be less than 31980

Post-fix regression and the same real-entry probe on final head 093313d4b43 (rebased to bee83199e15):

multiline chars=65520 wallMs=655.0 cpuMs=563.0 visible=65519
single chars=65536 wallMs=631.0 cpuMs=673.0 visible=65536

The same probe on the pre-fix code produced:

multiline chars=65520 wallMs=4840.5 cpuMs=4891.0 visible=65519
single chars=65536 wallMs=5175.8 cpuMs=5188.0 visible=65536

Validation run on final head:

  • Independent review found one remaining interaction: a fenced literal <tool_call> example permanently disabled the fast path. The new regression failed first with expected 5447844 to be less than 32082, then passed after the fix in 093313d4b43.
  • 3 Vitest shards, 157 tests passed, including all shared-text and embedded-agent-utils owners.
  • pnpm tsgo:core exited 0.
  • node scripts/run-format.mts --check src/shared/text/tool-call-xml.ts src/shared/text/tool-call-xml.streaming-work.test.ts: All matched files use the correct format.
  • git diff --check upstream/main...HEAD: no output, exit 0.
  • Targeted type-aware node scripts/run-oxlint.mjs ... exited 0.
  • A differential check over 2,500 complete HTML/JSX/XML documents with randomized 1-9 character chunks produced identical final text to the pre-fix streaming projector.

Validation gap: targeted oxlint used the wrapper-supported OPENCLAW_OXLINT_SKIP_PREPARE=1 path because this Windows host timed out while generating plugin-SDK boundary declarations at both 300 seconds and 900 seconds. The same declaration preparation completed successfully before the rebase, and the rebase did not touch either target file. PR CI will rerun the full declaration and lint lanes.

AI disclosure: this change was drafted with AI assistance at my request, under my direction and review.

Maintainer follow-up

The unfinished-indented-line regression is fixed at the XML projection owner. The final implementation classifies a copy of the current protection state before retaining a trailing prefix, and only takes that shortcut when the candidate lies on the unfinished current line, so literal indented/inline/fenced code keeps canonical ownership. It retains prefixes in the existing conditional projector and removes the second output buffer and separate fence scan. Ambiguous Markdown continues through the canonical resolver. The generic projector is unchanged; the broader hold API proposed in #180775 is not needed and was not merged.

The bounded regression covers 236 adversarial variants (59 seeds with unchanged, LF, CRLF, and double-LF endings) in both modes, every two-chunk split (including empty chunks), and one-character/four-character streams: 15,414 schedules and 46,620 prefix comparisons, with delta reconstruction checked as well. It covers indentation/tabs/list continuation, fences, inline code, HTML blocks/tags, partial <p/<pre/tool/function tags, entities, references, malformed adjacent candidates, and CRLF. The committed sweep took 4.068 s; the complete owner file passed 9 tests in 14.308 s wall time. A standalone run of the same corpus took 1.313 s. Two larger independent diagnostics against the actual production source performed 1,226,506 prefix checks with zero divergences (separate 4.799 s and 28.248 s runs; these are not added to CI). The original regressions were red against both original owners: main fails the work budgets and list/fence parity; contributor 093313d4b43 loses <p from <p. The expanded table also reproduced the later completed-line finding on 205117ed252: <\n lost its literal prefix. All are green with this repair.

Local validation: 240 targeted tests passed, including the visible-text projection and embedded-agent delivery consumers (consumer run: 129.928 s wall across three shards). Core and shared-test typechecks, scoped type-aware lint, formatting, max-lines, line-cap, assertion-safety, timeout-race, mock-export, config-doc and plugin-inventory checks pass. Source +28/-28 (net 0); tests +155/-0, relative to the tested main base 87aada17522b.

Built Gateway proof used the same 65,536-byte HTML fixture in 16,384 four-character provider SSE deltas per request, through the public /v1/chat/completions endpoint in separate clean builds of baseline 87aada17522b and final head fa146ed3293. Source, streamed delivery, and batch delivery match byte-for-byte on both heads (SHA-256 0f7afdd7770dca424be28c5353056d58fe9f0132122a5101d7fd00f19ee6d7c1). Across each stream/batch pair:

Ownership work Baseline Final head
Resolver calls 1,474 1,046
Resolver input characters 52,538,312 37,384,108
Parser calls 1,472 1,044
Parser input characters 52,538,200 37,383,996

This is 28.84% less ownership-parser input through the built delivery path, including deliberately ambiguous Markdown that still uses canonical parsing. In-memory instrumentation counted the resolver and actual parser across the Gateway and its workers without modifying source or build artifacts. Both runtimes verified Node 26.12.1. Final build passed in 12m53s wall time. Instrumented request samples were 68.043s / 9.541s baseline and 31.071s / 8.389s final (streamed / batch); these include Gateway/session/provider overhead on a shared host and are not an isolated projector benchmark. The final receipt contains complete timings and provider request metadata.

Final-head Qwen HTML smoke: failed. The exact built Gateway routed to native Ollama qwen2.5-coder:1.5b-instruct (requested and response model verified, HTTP 200). The first final-head control delivered 1,913 bytes / 416 SSE frames in 41.244 s, but they contained repetitive pseudo-tool JSON rather than the requested paragraph/preformatted HTML. A single sampling-control retry verified native options.temperature=0; it again emitted pseudo-tool JSON, then exhausted the Gateway's visible-answer continuation and ended in an SSE internal error. Both runs retained three advertised tools despite deny-all/code-mode-off configuration. No further model retries or production changes were made. An earlier 205117ed252 literal-HTML control delivered 112 HTML bytes successfully, while two earlier prompts failed similarly; this model-control variability remains a limitation, and no final-head HTML-smoke pass or tool-free-provider claim is made.

Fresh Codex branch autoreview on the final follow-up returned scoped-clean: no actionable P0–P2 findings with the complete owning modules supplied. The separate full-module review and executed parity tests provide additional coverage.

The existing contributor commits are preserved, with JasonBuildAI credited in the maintainer commit. This is a macOS arm64 / Node 26.12.1 proof; request timings are instrumented, single cold/warm samples on a shared host, and include Gateway/session/provider overhead. Work counts and exact delivered bytes are the primary comparison. Conservatively unclassified Markdown still uses full ownership parsing.

A streaming delta ending in a partial ordinary tag prefix such as <p still triggered findCodeRegions() on the whole accumulated reply. Hold the unresolved prefix in the streaming projector until it resolves, while keeping fences and ambiguous Markdown on the canonical resolver.

Fixes openclaw#180720
@clawsweeper

clawsweeper Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@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. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 22, 2026
A literal tool-call tag protected inside Markdown code no longer disables the partial-prefix hold for the rest of the stream. Add a deterministic regression for a fenced <tool_call> example followed by ordinary HTML.
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 22, 2026
@clawsweeper

clawsweeper Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR avoids repeated Markdown parsing for unresolved streamed HTML prefixes while preserving canonical code ownership and tool-call stripping.

Example: A 65,536-byte HTML reply arrives through the built Gateway in four-character provider deltas.

  • Before: The supplied stream/batch comparison records 52,538,200 parser input characters.
  • After: The final head records 37,383,996 parser input characters, with byte-identical delivered text.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused repair with meaningful ownership regressions and supplied final-head Gateway evidence; performance timing samples remain limited.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The supplied final-head proof exercises the built Gateway's public /v1/chat/completions endpoint on macOS arm64 with Node 26.12.1 and a deterministic HTML SSE provider, showing reduced actual parser work and byte-identical streamed and batch delivery. The separate Qwen control did not produce the requested HTML and supplies no HTML-model proof; timing samples are limited, so work counts support the performance conclusion.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Long streamed HTML answers consume avoidable Gateway CPU and delay other work sharing the process.
Reason: The reported failure is concrete, the supplied built-Gateway comparison shows reduced work with unchanged output, and the repair adds no configuration or public API.

Merge readiness

✅ Ready for maintainer review

This PR addresses a concrete performance defect still present on current main. The prior completed-line ownership finding is fixed, and this review found no further actionable code defects.

Priority: P2
Reviewed head: fa146ed32937388aac8d9c29ff66ce435fb3842f

Before merge

None.

Findings

None.

Agent review details

How this fits together

Provider text enters the shared assistant-visible-text projection pipeline; its XML filter hides tool scaffolding while Markdown Core protects literal code, then visible text reaches Gateway clients.

flowchart LR
  A[Provider text deltas] --> B[Assistant text projection]
  B --> C[XML candidate scanner]
  C --> D[Carried protection state]
  C --> E[Canonical Markdown ownership]
  D --> F[Visible text projection]
  E --> F
  F --> G[Gateway client delivery]
Loading

Technical review

Best possible solution:

Land the focused XML-owner optimization with its work-budget and code-ownership regressions once the exact-head merge gates pass.

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

Current-main source exposes the reported repeated parsing path, and the linked issue supplies deterministic four-character chunk reproduction; this read-only review executed no target code.

Is this the best way to solve the issue?

The patch fixes the existing XML projection owner, reuses its shared protection scanner and conditional projector, and preserves canonical parsing whenever ownership is uncertain.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 88380613fb52.

Provenance checked

  • Incremental XML activation and canonical ownership keeps the original intent (fix: avoid per-token Markdown parsing after quoted tool XML #171573: Avoid reparsing after quoted tool XML while retaining canonical handling for unprotected and ambiguous markup.)
  • Ordinary-markup and settled-fence optimization keeps the original intent (2ad3797: Remove full Markdown parsing for ordinary markup without losing literal-code protection.)

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:446 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 2ad3797 adds src/shared/text/tool-call-xml.streaming-work.test.ts:36 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 2ad3797ef1cf; files: src/shared/text/tool-call-xml.streaming-work.test.ts)

PR surface

Source 0, Tests +155. Total +155 across 2 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 28 28 0
Tests 1 155 0 +155
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 183 28 +155

Review metrics

Metric Value Why it matters
Production versus regression code Production +28/-28; tests +155/-0 Production growth is zero; added coverage protects recurring parse-work failures and incremental-versus-canonical ownership parity.

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 🦞 diamond lobster.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🦪 silver shellfish: 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: Long markup-heavy replies incur avoidable shared Gateway CPU work, with a concrete reproduction and a focused repair.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🦞 diamond lobster.
  • 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-23T03:35:12.599Z sha 205117e :: needs changes before merge. :: [P2] Preserve candidate-line ownership across trailing newlines

Reviewed October 23, 2026, 12:09 AM ET / 04:09 UTC (Revision 2).

Classify unfinished lines with the shared protection scanner before
withholding a trailing prefix. Keep uncertain ownership canonical and
retain prefixes in the existing projector instead of a second buffer.

Replace the separate fence scan and cover every split of 54 adversarial
inputs, including unfinished indented code and list continuation fences.

Co-authored-by: JasonBuildAI <[email protected]>
@steipete
steipete requested a review from a team as a code owner October 23, 2026 03:24
@steipete

Copy link
Copy Markdown
Contributor

@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 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 channel: msteams Channel integration: msteams channel: nextcloud-talk Channel integration: nextcloud-talk channel: nostr Channel integration: nostr channel: signal Channel integration: signal labels Oct 23, 2026
@steipete

Copy link
Copy Markdown
Contributor

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

Keep partial-prefix shortcuts within the current unfinished line so a trailing newline cannot discard literal indented code. Sweep LF, CRLF, and blank-line suffixes at every chunk split.
@steipete

Copy link
Copy Markdown
Contributor

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@steipete

Copy link
Copy Markdown
Contributor

Merged via squash.

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

Labels

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: M 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]: partial HTML tag prefixes still re-parse the whole streamed reply

2 participants