Skip to content

fix: reduce Markdown reparsing during tool-call streaming - #195136

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-stream-normalizer-markdown-reparse-20260919
Nov 8, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-stream-normalizer-markdown-reparse-20260919

Conversation

@steipete

@steipete steipete commented Nov 8, 2026

Copy link
Copy Markdown
Contributor

What Problem This Solves

Streaming plain-text tool-call repair repeatedly parses accumulated Markdown when literal call-like prose arrives in small chunks, creating avoidable CPU and allocation pressure.

User Impact

Literal Markdown, tool-call promotion, and event replay stay byte-for-byte equivalent in the exercised streams while inline-code prose and false call prefixes allocate substantially less. No configuration, dependency, schema, or public API change.

Why This Change Was Made

One candidate scan view now owns lazy code protection for sequence and trailing-prefix classification. Invalid prose no longer eagerly asks for Markdown ownership; already-resolved code ranges still skip grammar work. The existing carried fence scanner can reach a blank paragraph boundary before judging the first candidate, and can judge an unambiguous unfinished line without reparsing all prior output.

This does not replace the canonical Markdown parser or add a cross-delta cache. Cumulative snapshot scrubbing and real-call payload ownership still perform full parses. Runtime production code is net −4 lines; the two regression cases add 18 test lines with a matching scoped allocation, and the rerunnable benchmark adds 229 lines.

Evidence

Baseline: 60b66097c5a6b39f40924a081e20c16842e11dc5. Committed workload: scripts/perf/tool-call-markdown-measure.ts, using the real normalizer, real promotion/scrubbing, canonical mdast resolver, 40 tool names, 16-character deltas, cumulative partials, authoritative text end, and terminal snapshots.

Acceptance before measurement: exact replay, lower parsed characters/allocation on the affected workload, and no >20% CPU regression. Five interleaved fresh processes per side × five measured streams for each fixture; timing and allocation runs separate. Allocation uses the inspector sampler at 4 KiB with objects collected by major and minor GC included. MB below is decimal sampled allocation per complete stream, not retained heap.

Fixture CPU median / p95 ms, before → after Sampled MB/stream, before → after mdast calls/stream Parsed chars/delta
Plain prose 1.285 / 1.825 → 1.292 / 1.506 1.802 → 1.745 0 → 0 0.00 → 0.00
Inline-code prose 6.752 / 7.469 → 1.326 / 1.481 15.489 → 1.709 2 → 0 32.00 → 0.00
Fenced examples 12.809 / 18.061 → 12.088 / 17.576 27.100 → 26.882 2 → 2 32.00 → 32.00
True plain-text call 4.054 / 5.112 → 4.023 / 4.900 7.571 → 7.612 17 → 17 40.88 → 40.88
Literal call-like prose 138.423 / 166.262 → 76.051 / 100.525 541.730 → 288.172 154 → 64 1003.67 → 517.53

For the 7,040-character literal-prefix stream, parsed work falls 441,616 → 227,712 characters, allocation 46.8%, and median CPU 45.1%. The admission fallback contributes no full parses after the fix; 64 cumulative-snapshot parses remain. The larger 28,160-character version still has superlinear snapshot work (6,835,264 → 3,614,208 parsed characters), with roughly 2.09 s → 1.14 s CPU. This is a bounded waste-removal change, not a claim of fully incremental parsing.

Tradeoff: the 28 KiB fenced-example workload is about 8% slower in CPU (roughly 52 → 56 ms); the 7 KiB fenced case improves. The larger-case cost is disclosed, stays inside the prewritten CPU limit, and is not called a universal speedup. True-call allocation is +0.54% with overlapping sampled ranges; its parse work is unchanged.

A/A controls covered all five fixtures. The unchanged false-prefix controls were 144.991 / 143.977 ms CPU and 542.00 / 541.92 MB allocation. One small-sample candidate true-call tail reached 8.458 ms CPU; separate quiet 250-stream controls gave median/p95 2.908/3.897 → 2.928/3.885 ms and max 4.384 → 4.701 ms. An initial +9.7% fenced-allocation regression was diagnosed and removed before this final measurement.

Validation: both new real-stream regressions fail on the exact base (18 unwanted Markdown parses versus zero; three same-text parses versus two), then pass. 254 focused package/provider/agent tests passed, with the final three owner suites rerun (89 tests). Independent synthetic replay matched all 4,164 streams, including code, malformed calls, reference/image ownership, reordered content blocks, thinking events, and stop/length/error/EOF. Selected browser tests (3) and streaming E2E tests (8) passed. Knip production/full-tree unused-file scans passed.

pnpm check:changed completed with one inherited failure, and every other selected check passed: changelog attribution rejects 20 historical credit lines. It reproduces using changelogs archived from exact base 60b66097c5a6; #194364 (266a7aa0fe69) added the offending forbidden-handle exclusions without reconciling historical records. Examples: CHANGELOG/records/2026.6.8.md:71 and CHANGELOG/records/2026.10.6.md:254. This is an unresolved main regression, not a passing check.

Fresh Codex autoreview of the complete final staged change against the pinned base: scoped-clean through P2, no accepted/actionable findings. No live deployment or production data was accessed; this is synthetic owner-boundary proof, not a full Gateway/database load test. The owner performs no database or workspace I/O, so those inventory sizes are not fixture inputs.

Reproduce a fixture with node --expose-gc --import ./scripts/tsx.mjs scripts/perf/tool-call-markdown-measure.ts --kind false-prefix --paragraphs 128 --turns 5; repeat with --mode allocation, and compare a pinned package source using --owner <baseline>/packages/tool-call-repair/src/index.ts. Run exact event comparison separately with --compare-owner so loading both implementations does not perturb timing.

Requested outcome: ready PR, not merged.

Share lazy ownership within candidate classification and carry paragraph settlement through incoming chunks before the first candidate. Preserve literal code, promotion, and event replay while avoiding redundant full parses. Add work-count regressions and a real-normalizer allocation/CPU benchmark.
@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.

@openclaw-barnacle openclaw-barnacle Bot added scripts Repository scripts size: M labels Nov 8, 2026
@steipete
steipete marked this pull request as ready for review November 8, 2026 08:43
@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-08T08:46:21.710105Z 1165b19 Draft marked ready
ℹ️ 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.

@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 lazy Markdown protection within candidate classification and lets the existing fence scanner settle preceding paragraphs before checking candidates.

Example: Stream 7,040 characters of literal call-like prose in 16-character chunks.

  • Before: The supplied measurements report 441,616 parsed characters and 138.423 ms median CPU per stream.
  • After: They report 227,712 parsed characters and 76.051 ms median CPU, with identical emitted events.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) A focused, useful patch with detailed owner-boundary measurements and no concrete findings; supplied proof remains in process and required CI is unresolved.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor proof gate; supplied evidence covers the real normalizer, promotion, scrubbing, and canonical Markdown resolver through a synthetic event source, without claiming a deployed Gateway run.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Literal call-like Markdown arriving in small chunks consumes avoidable CPU and allocations while the reply streams.
Reason: The maintainer-authored direction has measurable workload gains, retains existing owners and behavior, and explicitly accepts the disclosed larger fenced-case slowdown.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it removes measurable parsing waste still present on main, and no concrete introduced correctness or security defect was found; required CI remains unresolved.

Priority: P2
Reviewed head: 1165b19ee329a621704eac09cbfd1ffd2da85a59

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The supplied benchmark exercises the real normalizer in process, but does not demonstrate this workload through a shipped CLI, Gateway, or provider transport.
Agent review details

How this fits together

The shared tool-call repair package receives provider events and cumulative assistant snapshots, preserves literal Markdown examples, and emits scrubbed text or recoverable tool-call events for agent consumers.

flowchart LR
  A[Provider stream events] --> B[Stream normalizer]
  B --> C[Candidate scan view]
  C --> D[Canonical call grammar]
  C --> E[Markdown protection]
  B --> F[Snapshot projection]
  F --> G[Agent stream consumers]
  B --> G
Loading

Technical review

Best possible solution:

Keep lazy protection in the existing candidate view and reuse the existing fence scanner while preserving canonical fallback for uncertain ownership.

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

Current main eagerly resolves Markdown separately during candidate and trailing-prefix scans and declines unfinished-line admission; the supplied benchmark and reported base-failing regressions target those paths, but this review executed no target code.

Is this the best way to solve the issue?

The defect is repeated ownership parsing; the invariant is identical literal text, scrubbing, promotion, and replay, and sharing one lazy scan view while extending the existing conservative fence scan is a small, coherent repair.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Fence fast-path admission changes intended behavior with a stated reason (a84a915: Avoid quadratic full-response Markdown parsing while conservatively deferring uncertain code ownership to the canonical resolver.)
  • Candidate sequence and trailing-prefix classification keeps the original intent (d649dba: Keep recognized calls private and preserve mutable Markdown ownership while projecting cumulative snapshots.)
  • Settled snapshot reuse keeps the original intent (4cc5638: Carry fence state with settled removal ranges without trusting uncertain suffixes or custom resolvers.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Harjoth Khara: Raw commit a84a915 adds packages/tool-call-repair/src/protection-fast-path.ts:164 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/protection-fast-path.ts)
  • Jason Cat: Raw commit d649dba adds packages/tool-call-repair/src/stream-normalizer-snapshot.ts:98 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: d649dbab56aa; files: packages/tool-call-repair/src/stream-normalizer-snapshot.ts)
  • Peter Steinberger: Raw commit 862c39a adds packages/tool-call-repair/src/stream-normalizer.ts:538 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 862c39a5af2b; files: packages/tool-call-repair/src/stream-normalizer.ts)

PR surface

Source -4, Tests +18, Other +231. Total +245 across 6 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 52 56 -4
Tests 1 18 0 +18
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 2 231 0 +231
Total 6 301 56 +245

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
Runtime versus regression-test LOC Runtime net −4 lines; tests +18 lines The two focused work-count regressions cover recurring parsing waste without adding production instrumentation or another cache owner.

Labels

Label changes:

  • add P2: The measured CPU and allocation reduction improves streamed replies, with limited scope and no demonstrated urgent availability incident for this workload.
  • 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: The measured CPU and allocation reduction improves streamed replies, with limited scope and no demonstrated urgent availability incident for this workload.
  • 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.

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, 4:01 AM ET / 09:01 UTC.

@steipete
steipete merged commit 306bf77 into main Nov 8, 2026
233 of 243 checks passed
@steipete
steipete deleted the steipete/perf-micro-stream-normalizer-markdown-reparse-20260919 branch November 8, 2026 09:08
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 9, 2026
…95136)

Share lazy ownership within candidate classification and carry paragraph settlement through incoming chunks before the first candidate. Preserve literal code, promotion, and event replay while avoiding redundant full parses. Add work-count regressions and a real-normalizer allocation/CPU benchmark.
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. 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