Skip to content

fix: reduce Markdown reparsing during streamed tool-call checks - #195161

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-stream-snapshot-ownership
Nov 8, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-stream-snapshot-ownership

Conversation

@steipete

@steipete steipete commented Nov 8, 2026

Copy link
Copy Markdown
Contributor

What Problem This Solves

Growing stream snapshots repeatedly reparse settled Markdown while checking for plain-text tool calls. Follow-up to #195136.

User Impact

Reduces main-thread allocation and CPU during streaming while preserving text, protected code, tool-call promotion, terminal messages, and replay behavior. No configuration, dependency, schema, or public SDK changes.

Why This Change Was Made

Both stream wrappers now share one per-stream Markdown ownership resolver across pending classification, snapshot scrubbing, promotion, and final results. It carries the canonical parser's mutable-tail boundary forward and reuses settled ranges. Complete source-line boundaries preserve indentation; reference definitions retain their enclosing source context. Replaced or shortened snapshots take the canonical fresh-parse path.

Production delta is +48 lines (+59/-11): 42 lines establish the missing per-stream checkpoint owner and six net lines connect the two wrappers. This retains the existing parser and avoids a second Markdown grammar. Reference-bearing or unresolved blocks can still retain a large tail, and other grammar/snapshot work remains superlinear.

Evidence

Synthetic real-normalizer benchmark: 40 tools, 16-character deltas, cumulative snapshots; five alternating fresh-process pairs. CPU timing and GC-inclusive 4096-byte sampled allocation measured separately. Parent is merged #195136 (306bf7730b01); candidate is this commit. Values are warm medians per complete stream; allocation uses decimal MB.

Fixture (paragraphs) CPU ms before → after Sampled allocation MB before → after Parses before → after Parsed characters before → after
plain (128) 1.274 → 1.298 1.728 → 1.714 0 → 0 0 → 0
inline (128) 1.249 → 1.276 1.706 → 1.741 0 → 0 0 → 0
fences (128) 11.403 → 7.439 26.733 → 15.301 2 → 1 14,336 → 7,168
call (128) 4.183 → 3.479 7.653 → 5.836 17 → 16 9,892 → 6,026
false-prefix (128) 73.458 → 14.290 288.896 → 33.413 64 → 56 227,712 → 7,209
fences (512) 56.699 → 37.546 105.360 → 60.494 2 → 1 57,344 → 28,672
false-prefix (512) 1163.108 → 121.232 4287.785 → 300.984 256 → 224 3,614,208 → 29,001

The long snapshot fixture reduces CPU 89.6%, sampled allocation 93.0%, and parsed characters per delta from 2053.5 to 16.5. Long fences improve CPU 33.8%, recovering the previously reported regression by reusing identical terminal ownership (two full parses become one). Plain/inline medians rise 0.024/0.027 ms (1.9%/2.2%); their parser work remains zero. Unchanged A/A CPU medians vary −1.15% to +5.20%; allocation medians vary −2.24% to +0.29%. Contended samples were retained.

Each 128-paragraph side has 25 warm samples; each 512-paragraph side has five. Long-snapshot CPU p95: 1423.585 → 166.924 ms; long-fence p95: 72.882 → 38.877 ms. These are synthetic owner measurements, not a claim about total production allocation.

Reproduce with node --expose-gc --import ./scripts/tsx.mjs scripts/perf/tool-call-markdown-measure.ts --kind false-prefix --paragraphs 512 --turns 5: stateless baseline by default, candidate with --incremental; repeat with --mode allocation. The normalizer package itself is unchanged from the pinned parent. Work counts wrap the installed fromMarkdown dependency rather than counting whole resolver inputs.

The real embedded-agent wrapper regression fails on exact parent 306bf7730b0108e863a6ecfc549bc8289d9bddc7: 40,768 parsed characters exceed the 13,568 bound. The candidate passes while preserving streamed text, terminal output, and stream.result(). Review also exposed a nested-reference-definition context bug in the first candidate; its regression failed before the correction and passes now.

187 focused tests passed; the affected 78 passed again on the final source. Browser Markdown tests: 3 passed. Streaming UI E2E: 8 passed. Independent comparison: 4,164 exact event replays, 40,451 canonical range queries, and 157,168 scrub projections all match. Codex autoreview is scoped-clean through P2.

The full check:changed run completed. After replacing external dependency symlinks with a private clone of the same installed dependencies, every typecheck and lint rerun passes. All other changed guards pass except the exact-parent failures detailed below. This is not a claim of an all-green check run.

Exact-parent main regressions reproduced during changed checks

These remain unresolved main regressions; no check was weakened:

SDK/dead-export checks reproduced against byte-identical exact-parent source; changelog checks used an exact-parent archive. Introducing commits and raw-parent patches were inspected. These need separate owner repairs.

Ready for review; intentionally not merged.

@clawsweeper

clawsweeper Bot commented Nov 8, 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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-08T09:59:15.903132Z fb3c5a0 PR opened
ℹ️ 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.

@openclaw-barnacle openclaw-barnacle Bot added scripts Repository scripts agents Agent runtime and tooling size: M labels Nov 8, 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. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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. labels Nov 8, 2026
@clawsweeper

clawsweeper Bot commented Nov 8, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR shares incremental Markdown code-region ownership across tool-call checks within each provider or embedded-agent stream.

Example: Stream 512 paragraphs of literal call-like prose in 16-character deltas with cumulative snapshots.

  • Before: The reported benchmark parses 3,614,208 characters and consumes 1163.108 ms of median CPU.
  • After: The reported benchmark parses 29,001 characters and consumes 121.232 ms while preserving output.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The focused implementation and owner-level measurements are convincing, with confidence limited to the exercised boundary and incomplete CI attribution.
Proof confidence 🦐 gold shrimp (3/6) The ordinary contributor proof gate does not apply to this maintainer-authored PR; supplied evidence exercises the real normalizer and embedded wrapper with synthetic events, while reported browser tests do not establish the changed Gateway path.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Long streamed replies spend avoidable CPU and allocation reparsing settled Markdown.
Reason: The maintainer-authored direction targets measured waste while preserving text and public contracts; conservative large tails are explicitly disclosed.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR addresses remaining repeated Markdown parsing on current main, preserves the existing parser contract, and has no identified introduced defects; CI admission remains unresolved.

Priority: P2
Reviewed head: fb3c5a021ab287db5c0166cc1f38f825804b40cf

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The supplied evidence does not demonstrate this checkpoint change through a shipped CLI or Gateway streaming path.
Agent review details

How this fits together

Provider events enter the shared tool-call normalizer, which uses canonical Markdown ownership to preserve literal examples while scrubbing or promoting genuine calls; normalized events and terminal messages leave it.

flowchart TD
A[Provider stream] --> B[Provider or embedded wrapper]
B --> C[Shared tool-call normalizer]
C --> D[Per-stream code-region resolver]
D --> E[Canonical Markdown parser]
C --> F[Visible text and tool-call events]
C --> G[Terminal message]
Loading

Technical review

Best possible solution:

Retain one canonical-parser checkpoint resolver per stream across both wrappers, preserving exact output and fresh parsing after source replacement.

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

Current-main wrappers repeatedly use the stateless resolver, and the supplied exact-parent regression and benchmark identify the excess parsing; no target code was executed during this review.

Is this the best way to solve the issue?

The change addresses repeated work at the shared ownership boundary without replacing the parser, and the existing richer ownership resolver does not provide this two-tail checkpoint contract.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Provider and embedded tool-call protection keeps the original intent (a1c689e: Preserve literal Markdown tool-call examples while continuing to normalize genuine calls.)
  • Incremental Markdown ownership keeps the original intent (c6a601f: Reuse canonical ownership checkpoints to prevent repeated inline-code paragraphs stalling streaming.)
  • Benchmark measurement keeps the original intent (306bf77: Measure real normalizer work and replay equivalence; the updated instrumentation counts parser suffixes rather than whole resolver inputs.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

PR surface

Source +48, Tests +63, Other +30. Total +141 across 7 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 59 11 +48
Tests 2 64 1 +63
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 2 76 46 +30
Total 7 199 58 +141

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Review metrics

Metric Value Why it matters
Production versus regression growth Production +59/-11; tests +64/-1 The growth supplies bounded stream-local checkpoint ownership and distinct work-budget and Markdown-context regressions.

Labels

Label changes:

  • add P2: This is a focused improvement to streaming CPU and allocation with demonstrated owner-level savings and no established urgent regression.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: This is a focused improvement to streaming CPU and allocation with demonstrated owner-level savings and no established urgent regression.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Demonstrate the cumulative-snapshot workload through an isolated shipped streaming entry point.

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.

Reviewed November 8, 2026, 5:13 AM ET / 10:13 UTC.

@steipete
steipete merged commit 61eaeca into main Nov 8, 2026
266 of 295 checks passed
@steipete
steipete deleted the steipete/perf-stream-snapshot-ownership branch November 8, 2026 11:04
vincentkoc added a commit that referenced this pull request Nov 8, 2026
…tooling-lint-selection-20261108

* commit 'b0e90e6a4b359fff7756698067fdce4758b1907b': (38 commits)
  fix(android): Talk button demands a realtime provider on a native Talk setup (#191194)
  chore: trace first-run Gateway work and verify later replies (#195185)
  fix(knowledge): keep deleted messages out of reply previews (#195126)
  fix(agents): preserve streamed replies across Gateway restarts (#195164)
  perf(ci): reuse SDK transport path boundaries (#195180)
  fix(sandbox): avoid pauses for unchanged command checkpoints (#195120)
  fix(test): make retention checks portable across runtimes (#195091)
  fix(knowledge): clarify temporal kind filters (#194995)
  improve: reduce Gateway allocation while draining SQLite receipts (#195129)
  fix: reduce streaming CPU after reply and voice directives (#195145)
  fix: reduce Markdown reparsing during streamed tool-call checks (#195161)
  fix: restore the main dead-export gate (#195158)
  improve(ci): pack small UI selections into fewer jobs (#195107)
  fix(muse): quota and sign-in failures end with no reply (#195148)
  fix: allow first release push with shipped patch bytes (#195174)
  fix(ci): narrow single-config tooling selections (#195147)
  fix(packaging): reject incompatible prepublish plugin cohorts (#195152)
  fix(ci): prepare verified Bun before parity checks (#195155)
  fix: Incognito agent turns stall before execution (#195005)
  fix: credentialed search and speech providers work without picking a provider (#195169)
  ...
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 9, 2026
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. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts 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.

1 participant