Skip to content

fix: avoid stalls and tool-call leaks in streamed replies - #174353

Merged
steipete merged 6 commits into
openclaw:mainfrom
JasonBuildAI:fix/stream-normalizer-scrub-reuse-p4w9
Oct 17, 2026
Merged

steipete merged 6 commits into
openclaw:mainfrom
JasonBuildAI:fix/stream-normalizer-scrub-reuse-p4w9

Conversation

@JasonBuildAI

@JasonBuildAI JasonBuildAI commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #174345

What Problem This Solves

Fixes replies that stall while streaming after a recognized plain-text tool call: each cumulative partial reparses the whole reply. Also fixes the proposed cache's two invalidation errors, which could expose an incomplete unmarked Harmony call or retain a call after a Markdown reference definition revokes inline-code protection.

User Impact

Long replies containing a scrubbed call stream with substantially less parsing work. Visible prose and literal code stay intact, and cumulative partial, error, and final snapshots retain canonical scrubbing. No configuration or migration is required.

Why This Change Was Made

Keep settled removal ranges only after their consumed line boundaries are complete. Reuse checks the appended suffix with the existing call grammar and trusts protected ownership only when the existing fence scanner proves it. Ambiguous inline/image-reference Markdown and custom protection resolvers take the full canonical path. Empty trailing text blocks also force a fresh scan because they introduce a structural call boundary. This removes call-end bookkeeping, invalid cache entries, and per-append range rebuilding.

Snapshot scanning, projection, and cache eligibility now share stream-normalizer-snapshot.ts; event orchestration stays in the normalizer, and the existing exported helper path is preserved. This keeps the oversized normalizer below its prior line count.

Thanks @JasonBuildAI for the original performance repair and reproduction. This branch preserves the contributor commits and merges main without rebasing or force-pushing.

Evidence

The two reported counterexamples reproduce against the original contributor head: Harmony leaks into error.partial, and both Markdown terminal variants emit the stale cumulative partial. Three of four new output regressions fail before repair and all four pass afterward, using the real normalizer and production Markdown owner. A further review counterexample exposes an unmarked header through an interleaved thinking event after an empty trailing text block; its output regression fails before the boundary guard and passes afterward. The focused suite passes 79/79 (23.14s command wall, 14.30s Vitest). CI then caught a missing entry for the extracted snapshot module in the trusted PR wrapper copy inventory. Adding that one entry fixes both extraction regressions: both fail before the entry and pass afterward (78.43s command wall, 70.01s Vitest). The follow-up changes only the copy inventory; the compiled runtime implementation and its proof remain unchanged.

Matched local macOS normalizer replay: 40,000 characters in 10,000 four-character deltas, identical 9,995 output events and final text, zero forbidden snapshots:

Work Main Repaired
Markdown resolutions 10,005 1,263
Characters reparsed 200,060,064 25,065,204
Wall time 122.009s 27.817s

Timings reflect a shared Mac under changing load; the deterministic parsing reduction is about 7.9×. The contributor's 40,045-byte fixture retains essentially the same resolver budget after the correctness repair (1,259 → 1,260).

Compiled CLI proof on the unchanged runtime implementation on macOS: all four scripted SSE cases (Harmony/Markdown × error/final) pass through pnpm openclaw --profile scrub-cache-proof agent --local, with 16 cumulative snapshots checked and no invalid leaks. Observed cases use the supported Node runtime with an observation-only preload that forwards events unchanged; each took 51–56s including fresh isolated-state startup. Non-retryable synthetic errors exit 1 as expected, and final fixtures include the normal length-limit notice. A separate uninstrumented default-Bun replay delivers the full fenced reply from 40,927 input bytes in 10,232 frames, removing the initial call; 29.336s CLI wall / 4.047s agent duration.

Live local-model control on the default Bun runtime: qwen3:4b through the same shipped local-agent entry and existing Ollama server returned 5,059 visible characters / 1,489 output tokens, with no tool executions. Relay inference took 25.346s, reported agent duration 28.483s, and whole CLI wall 54.601s including isolated startup. The model smoke is a live latency/control check; deterministic fixtures establish the cache regressions.

Validation: full pnpm build, pnpm tsgo:core, scoped oxlint and formatting, line-cap, assertion-safety, test-timeout-race, test-mock-exports, config-doc and plugin-inventory checks pass. Independent Codex autoreview is scoped-clean with no actionable P0–P2 findings. The max-lines check reports three inherited UI suppressions; their source blobs and baseline file exactly match the merged main base. No unrelated baseline edits were made.

Production TypeScript delta against the merged main base: +608/-401 (net +207); wrapper inventory +1; tests +163/-0. The bounded cache is necessary growth for this performance fix. Removing redundant cache machinery pays for the required owner extraction and the additional boundary guard; the final TypeScript delta matches the original contributor patch while fixing all three counterexamples.

Limitation: ambiguous Markdown deliberately remains on the canonical full-scan path; this does not promise linear work for every possible stream. All runtime proof is on local macOS.

…l text

An admitted plain-text tool call made every following delta re-walk the whole reply (findCodeRegions + removal scan) to rebuild the scrubbed partial. Keep the last forced-scrub ranges per content record and reuse them while the next partial strictly appends and the suffix cannot open a call construct, fence, or code span; removed line ends are recomputed at reuse.

40 KB reply in 4-byte deltas: forced re-scrubs 10017 -> 1259, CPU 84.7 s -> 11.6 s; emitted event streams unchanged (4080-stream differential against an unpatched copy).

Refs openclaw#174345
@clawsweeper

clawsweeper Bot commented Oct 16, 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.

JasonBuildAI added a commit to JasonBuildAI/openclaw that referenced this pull request Oct 16, 2026
@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. 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 16, 2026
@clawsweeper

clawsweeper Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Reuses settled tool-call removal ranges across appended reply snapshots and includes the extracted snapshot module in the trusted wrapper inventory.

Example: A recognized read call precedes a 40,000-character fenced reply delivered in four-character chunks.

  • Before: Cumulative snapshots repeatedly parse the growing reply, delaying streaming.
  • After: The supplied comparison reports Markdown resolutions falling from 10,005 to 1,263 with identical visible output.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A focused, source-supported performance repair with shipped-entry-point evidence, concrete invalidation regressions, and no actionable findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The PR records macOS compiled local-agent CLI runs through real SSE handling for Harmony and Markdown error/final cases, with 16 cumulative snapshots checked and no invalid leaks, plus an uninstrumented Bun fenced-reply replay; the latest inventory-only commit leaves that runtime implementation unchanged.
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 replies can stall after recognized textual tool-call syntax activates repeated cumulative parsing.
Reason: The measured parsing reduction addresses a source-supported user delay while retaining the existing grammar, Markdown protection, configuration, and terminal policies.

Merge readiness

✅ Ready for maintainer review

This PR fixes a current streaming performance defect while preserving canonical tool-call scrubbing; no actionable introduced defects were found, and exact-head CI remains pending.

Priority: P2
Reviewed head: 1794b765c8ae86df45dc4a941bccb42b12ce78c8

Before merge

None.

Findings

None.

Agent review details

How this fits together

The shared tool-call repair package receives provider and embedded-agent stream events and emits scrubbed partials, preserved prose, and normalized terminal messages.

flowchart TD
  A[Provider stream] --> B[Shared stream normalizer]
  C[Embedded agent stream] --> B
  B --> D[Snapshot projection and bounded reuse]
  D --> E[Canonical call grammar and Markdown protection]
  D --> F[Scrubbed partials and terminal messages]
Loading

Technical review

Best possible solution:

Land the bounded snapshot reuse with canonical fallback after the existing exact-head CI gates pass.

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

Current-main source establishes repeated whole-snapshot scanning after scrubbing activates, and the report supplies a matching cumulative-delta benchmark; this read-only review ran no target code.

Is this the best way to solve the issue?

Reusing settled ranges within the existing projection owner addresses the repeated parsing without duplicating grammar or changing promotion policy, while conservative fallback preserves ambiguous cases.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Canonical snapshot scanning and projection keeps the original intent (05ebaf4: Consolidate serialized-call recognition and preserve bounded suppression, surrounding text, native blocks, and content indexes.)
  • Markdown code protection keeps the original intent (a1c689e: Preserve literal tool-call examples in user-visible code regions.)
  • Incremental protection fast path keeps the original intent (a84a915: Avoid repeated whole-response Markdown parsing when carried fence state proves protection, retaining canonical fallback elsewhere.)
  • Split markers and call-prose-call ordering keeps the original intent (e085c3f: Hide recognized calls consistently while releasing decided prose and retaining incomplete candidate tails.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 05ebaf4 adds packages/tool-call-repair/src/stream-normalizer.ts:46 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 05ebaf41f6ee; files: packages/tool-call-repair/src/stream-normalizer.ts)
  • Jason Cat: Raw commit e085c3f adds packages/tool-call-repair/src/stream-normalizer.ts:799 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: e085c3fb261e; files: packages/tool-call-repair/src/stream-normalizer.ts)
  • Harjoth Khara: Raw commit a84a915 adds packages/tool-call-repair/src/stream-normalizer.ts:1496 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: a84a915b67bd; files: packages/tool-call-repair/src/stream-normalizer.ts)
  • Vincent Koc: Raw commit a1c689e adds packages/tool-call-repair/src/stream-normalizer.ts:52 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: a1c689e375ec; files: packages/tool-call-repair/src/stream-normalizer.ts)

PR surface

Source +207, Tests +163, Other +1. Total +371 across 5 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 2 608 401 +207
Tests 2 163 0 +163
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 0 +1
Total 5 772 401 +371

Review metrics

Metric Value Why it matters
Production versus test TypeScript Production +608/-401; tests +163/-0 Net production growth funds bounded reuse and canonical cache eligibility while moving existing projection code into one owner; tests cover work reduction and concrete invalidation regressions.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Long replies following recognized textual tool calls can suffer substantial parsing delays, with a specific trigger and a focused repair.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster 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 (2 earlier review cycles)
  • reviewed 2026-10-16T15:29:38.293Z sha 5ab0246 :: needs real behavior proof before merge. :: [P2] Invalidate reuse for newly introduced unmarked Harmony prefixes | [P2] Respect mutable Markdown ownership before reusing scrub ranges
  • reviewed 2026-10-16T23:33:48.563Z sha 30cf9c7 :: needs maintainer review before merge. :: none

Reviewed October 16, 2026, 7:51 PM ET / 23:51 UTC (Revision 3).

@steipete steipete changed the title perf(tool-call-repair): stop whole-reply re-parses on every streamed chunk fix: avoid stalls and tool-call leaks in streamed replies Oct 16, 2026
@steipete

Copy link
Copy Markdown
Contributor

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@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. proof: sufficient ClawSweeper judged the real behavior proof convincing. and removed 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. labels Oct 16, 2026
@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. 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 16, 2026
@steipete

Copy link
Copy Markdown
Contributor

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@openclaw-barnacle openclaw-barnacle Bot added the scripts Repository scripts label Oct 16, 2026
@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. 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 16, 2026
@steipete
steipete merged commit d649dba into openclaw:main Oct 17, 2026
129 of 132 checks passed
@steipete

Copy link
Copy Markdown
Contributor

Merged via squash.

JasonBuildAI added a commit to JasonBuildAI/openclaw that referenced this pull request Oct 17, 2026
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 17, 2026
…74353)

* perf(tool-call-repair): reuse settled scrubs while streaming tool-call text

An admitted plain-text tool call made every following delta re-walk the whole reply (findCodeRegions + removal scan) to rebuild the scrubbed partial. Keep the last forced-scrub ranges per content record and reuse them while the next partial strictly appends and the suffix cannot open a call construct, fence, or code span; removed line ends are recomputed at reuse.

40 KB reply in 4-byte deltas: forced re-scrubs 10017 -> 1259, CPU 84.7 s -> 11.6 s; emitted event streams unchanged (4080-stream differential against an unpatched copy).

Refs openclaw#174345

* fix: keep streamed tool-call scrub reuse safe

* refactor: isolate tool-call snapshot scrubbing

* fix: recheck empty text-block scrub boundaries

* fix: include scrub snapshot in PR wrapper inventory

---------

Co-authored-by: Peter Steinberger <[email protected]>
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: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. scripts Repository scripts size: XL 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.

perf: streaming plain-text tool-call scrub re-parses the whole reply per delta (85 s of CPU for one 40 KB reply)

2 participants