Skip to content

perf(markdown): reduce CPU work in streamed and chunked replies - #133152

Merged
steipete merged 1 commit into
mainfrom
codex/perf50-markdown-reuse
Aug 30, 2026
Merged

steipete merged 1 commit into
mainfrom
codex/perf50-markdown-reuse

Conversation

@steipete

@steipete steipete commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Streamed replies and channel-sized Markdown chunks repeat parsing and rendering work. Code-heavy replies scan earlier fences at every character, unchanged text is indexed several times within one tag-filter call, accepted chunks are rendered again before delivery, and final-tag cleanup repeatedly copies the changing string.

Why This Change Was Made

Keep the existing parsing, rendering, and transport boundaries while carrying their prepared results forward:

  • Advance once through the scanner's ordered, disjoint fences.
  • Reuse a code index only for identical text and unchanged starting state within the same streaming call.
  • Retain accepted rendered payloads with the exact source that produced them. Whitespace merging uses raw IR so temporary message-boundary annotations cannot survive after they stop applying.
  • Assemble final-tag output once using the original tag offsets and code-region decisions.

No cross-call cache, provider policy, schema, configuration, persistence, or protocol change. The Markdown guide now distinguishes source-text and rendered-payload limits and removes an obsolete blanket claim about channels without IR styling.

User Impact

The same visible text, formatting, links, and streaming state require less CPU work. Exact nonmonotonic rendered-size search, surrogate boundaries, whitespace behavior, single-character escape behavior, and the uncapped path are preserved.

Production LOC: +67/−49 (net +18). Tests: +31. Docs: +17/−12. The growth retains the raw/prepared source distinction and measured payload through coalescing; it does not add a persistent cache or a second rendering policy.

Evidence

Paired, uninstrumented Node 26.8.1 measurements in two fresh processes with opposite starting orders; all raw samples and source hashes retained locally. Baseline owner source is 3afccb4e7f4bf5ef9737adb1edda2f3461d8dd58; the affected Markdown/shared-text/subscriber sources were unchanged when integrated onto 357078cf7087534443dac92eb86e8aa32abb7b08.

Workload Before After
Short plain streaming chunk 1.72–1.74 µs 0.64–0.65 µs
1,000 plain streaming deltas 1.161–1.162 ms 0.583–0.586 ms
10 KB reply with 64 fences 1.071–1.081 ms 0.0535–0.0537 ms
Short escaped-marker chunk rendering 4.27–4.31 µs 2.24–2.32 µs
Final-tag cleanup, 256 fragments / 20 KB 0.593–0.615 ms 0.202–0.203 ms

Long plain rendering and overflow-heavy marker rendering are effectively unchanged. Empty streaming controls vary by a few nanoseconds. These are owner-level measurements, not a claim about provider/network latency or a memory reduction.

  • Streaming differential: 5,740 scanner-state cases, 537,560 position checks, and 182,420 chunk transitions across 5,692 scenarios; exact output and carried state matched across both isolated optimizations and their combination.
  • Rendering differential: 8,000 cases and 18,658 source-identity checks. Six real header-promotion/whitespace-demotion witnesses restore links and reject six prepared-source merge mutants. An initial plain-role-label fixture did not exercise the header grammar; that gap was corrected, and its old timing remains only an ordinary text control.
  • Final-tag differential: 3,216 cases in each fresh process, covering strict/preserve, trim/scope, code literals, malformed tags, and mixed syntax.
  • 363 unique tests passed across 16 owner/subscriber/channel files, including SMS, Signal, Google Chat, Slack, Telegram, and WhatsApp. The new durable test protects final text, restored links, attributed ranges, and exact source identity without asserting intermediate render calls.
  • Changed production and test/docs gates passed, including core and test typechecks, lint, import-cycle/boundary guards, and dead exports. MDX, internal links, and glossary checks passed.
  • Independent source reviews and fresh automated Codex review completed with no accepted findings at the configured P0 threshold. The reviewers' concrete header-proof gap was addressed before publication.

The fresh candidate build at dae9afedf9d70617410d8abb394be5874277eb16 passed in 166.97 seconds. Its isolated real-OpenAI Gateway completed READY, sessions_list, web_fetch, and native web search; all 30 assertions across 14 read-only RPCs passed, including exact baseline titles/previews, tool inventories, and model catalog. CPU profiles and terminal/tool receipts were retained. These live timings are observational and do not establish a provider/network latency improvement.

A fifth live literal-tag check failed: final delivery removes <final> inside a code fence even though the raw assistant answer retains it. The delivery sanitizer and final-tag helper are byte-identical to the pre-PR baseline, and an actual-owner replay reproduces the loss. Named follow-up: preserve literal final tags through the final delivery sanitizer. This PR does not claim that existing behavior is fixed.

ClawSweeper’s current-main/latest-review refresh request was completed: all six touched files remain unchanged on main 41dccabf179 relative to the recorded base, and the latest review has no concrete source finding. The first hosted run inherited main’s stale side-effect-owner import. #133155 is now merged as be5e79ca4713c33a11ccd56b2d728c19f0779f3d. The PR was rebased onto that repair as 576a7a2dfaebd511df00ffef6366e9acdb748de2; its complete six-file patch is byte-identical to the locally tested/live-tested head above. Fresh exact-head CI is run 33299554989; landing remains gated on its result.

The current head 576a7a2dfaebd511df00ffef6366e9acdb748de2 has green exact-head CI (run 33299554989). The refreshed ClawSweeper review found no actionable defect; its rank-up request to finish checks and obtain maintainer acceptance is satisfied. Accepted for landing under the maintainer-authorized performance campaign. Native prepare gates passed.

@clawsweeper

clawsweeper Bot commented Aug 30, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling size: S maintainer Maintainer-authored PR labels Aug 30, 2026
@clawsweeper clawsweeper Bot added P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. 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. labels Aug 30, 2026
@clawsweeper

clawsweeper Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 30, 2026, 3:47 AM ET / 07:47 UTC.

ClawSweeper review

What this changes

The PR reuses code-span indexes and already-rendered Markdown chunks during streamed replies and channel-size chunking, adds a boundary-annotation regression test, and updates the Markdown formatting guide.

Merge readiness

⚠️ Ready for maintainer review - 2 items remain

No blocking correctness or security defect was found in the introduced patch. This is a focused behavior-preserving performance refactor that remains absent from the fetched current-main source, but it is maintainer-authored and carries the protected maintainer label, so it needs explicit maintainer acceptance after exact-head CI completes.

Priority: P3
Reviewed head: 576a7a2dfaebd511df00ffef6366e9acdb748de2
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, source-consistent optimization with relevant regression coverage and no actionable correctness or security finding; current CI completion remains the merge gate.
Proof confidence 🌊 off-meta tidepool Not applicable: This repository-member PR is exempt from the external-contributor proof gate; its supplied benchmark and gateway evidence is supplementary, while the review verified the changed parsing, rendering, and stream-owner boundaries from source.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This repository-member PR is exempt from the external-contributor proof gate; its supplied benchmark and gateway evidence is supplementary, while the review verified the changed parsing, rendering, and stream-owner boundaries from source.
Evidence reviewed 8 items Introduced rendered-payload ownership: The new candidate pairs raw IR with the exact rendered payload, while whitespace coalescing merges raw IR and rerenders only changed candidates; this preserves the source/payload relationship rather than adding a cache or alternate renderer.
Fence ordering supports the scanner optimization: The fence scanner advances through the buffer in order and appends completed or open spans as it encounters them, supporting the introduced one-way fence cursor.
Stream reuse is equality- and state-bound: The stream path reuses the initial code index only when the scanned text is byte-identical to the fence input; otherwise it rebuilds from the same captured starting state. Existing session-harness tests cover literal tags in code fences and stale fence-state cases.
Findings None None.
Security None None.

How this fits together

Outbound reply text is parsed into Markdown IR, rendered for each transport, and split to that transport’s size limit. The agent stream path separately scans code fences and reasoning/final tags before it sends visible partial or block replies.

flowchart LR
  Reply[Assistant reply stream] --> Scan[Code and tag scanning]
  Scan --> Visible[Visible streamed text]
  Reply --> IR[Markdown intermediate representation]
  IR --> Chunk[Rendered-size chunking]
  Chunk --> Render[Channel-specific rendering]
  Render --> Delivery[Outbound payload]
Loading

Decision needed

Question Recommendation
After exact-head CI completes, should this behavior-preserving Markdown performance refactor be accepted for main? Accept after green CI: Accept the focused reuse refactor once the current head’s required checks complete successfully.

Why: The code review found no concrete blocker, but the PR is authored by a repository member and marked maintainer, which requires explicit maintainer handling rather than automated closure or repair.

Before merge

  • Resolve merge risk (P1) - Exact-head CI is still incomplete, so merge readiness cannot yet be established from the available check state.
Agent review details

Security

None.

PR surface

Source +18, Tests +31, Docs +5. Total +54 across 6 files.

View PR surface stats
Area Files Added Removed Net
Source 4 67 49 +18
Tests 1 31 0 +31
Docs 1 17 12 +5
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 6 115 61 +54

Review metrics

Metric Value Why it matters
Production versus test/docs delta production +67/-49 (net +18); tests +31/-0; docs +17/-12 (net +5) The modest production growth is tied to preserving the raw-source versus rendered-payload invariant while avoiding a second rendering pass.

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    Retain the one-way scanner and raw-IR/rendered-payload pairing, then land this focused optimization after exact-head checks finish green and a maintainer accepts the performance tradeoff.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Technical review

Best possible solution:

Retain the one-way scanner and raw-IR/rendered-payload pairing, then land this focused optimization after exact-head checks finish green and a maintainer accepts the performance tradeoff.

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

Not applicable: this PR optimizes existing deterministic Markdown and stream-processing paths rather than fixing a separately reported user failure.

Is this the best way to solve the issue?

Yes. The change keeps parsing, renderer, and transport ownership intact, carries only prepared results within a call, and avoids a broader cache or duplicate rendering policy.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against c04bee452e70.

Labels

Label justifications:

  • P3: This is a targeted CPU-efficiency improvement with no source evidence of a user-facing regression or availability impact.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This repository-member PR is exempt from the external-contributor proof gate; its supplied benchmark and gateway evidence is supplementary, while the review verified the changed parsing, rendering, and stream-owner boundaries from source.

Evidence

What I checked:

  • Introduced rendered-payload ownership: The new candidate pairs raw IR with the exact rendered payload, while whitespace coalescing merges raw IR and rerenders only changed candidates; this preserves the source/payload relationship rather than adding a cache or alternate renderer. (packages/markdown-core/src/render-aware-chunking.ts:40, 576a7a2dfaeb)
  • Fence ordering supports the scanner optimization: The fence scanner advances through the buffer in order and appends completed or open spans as it encounters them, supporting the introduced one-way fence cursor. (packages/markdown-core/src/fences.ts:22, 576a7a2dfaeb)
  • Stream reuse is equality- and state-bound: The stream path reuses the initial code index only when the scanned text is byte-identical to the fence input; otherwise it rebuilds from the same captured starting state. Existing session-harness tests cover literal tags in code fences and stale fence-state cases. (src/agents/embedded-agent-subscribe.stream-rendering.ts:151, 576a7a2dfaeb)
  • Final-tag rewrite retains ordered-match semantics: The new single-pass string assembly relies on final-tag matches being ordered; the matcher builds its array by iterating the source text with matchAll, so non-code tags are removed in increasing offset order while code literals remain untouched. (src/shared/text/final-tags.ts:115, 576a7a2dfaeb)
  • Focused regression coverage: The added test exercises the previously risky case where chunk-boundary annotation changes link/range behavior after whitespace coalescing, and asserts final text, restored link offsets, empty attributed ranges, and source identity. (packages/markdown-core/src/render-aware-chunking.test.ts:103, 576a7a2dfaeb)
  • Current-main comparison: The fetched current-main version still finalizes raw Markdown IR and renders it again after coalescing, so the central optimization has not already landed on main. (packages/markdown-core/src/render-aware-chunking.ts:91, c04bee452e70)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

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

  • Wait for the exact-head checks currently in progress, then obtain maintainer acceptance of the protected maintainer-authored PR.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (2 earlier review cycles)
  • reviewed 2026-08-30T07:15:34.341Z sha dae9afedf9d70617410d8abb394be5874277eb16 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-30T07:30:44.676Z sha dae9afedf9d70617410d8abb394be5874277eb16 :: needs maintainer review before merge. :: none

@steipete
steipete force-pushed the codex/perf50-markdown-reuse branch from dae9afe to 576a7a2 Compare August 30, 2026 07:35
@steipete
steipete merged commit a6d94f2 into main Aug 30, 2026
247 checks passed
@steipete
steipete deleted the codex/perf50-markdown-reuse branch August 30, 2026 07:54
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 31, 2026
shakkernerd added a commit that referenced this pull request Sep 7, 2026
Preserve literal final tags in delivered Markdown code examples while removing model final-answer markers outside code. Document the sanitization boundary and share it with reasoning cleanup.

Refs #133152.
Reviewed-by: @shakkernerd
Co-authored-by: Shakker <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 8, 2026
…#138989)

Preserve literal final tags in delivered Markdown code examples while removing model final-answer markers outside code. Document the sanitization boundary and share it with reasoning cleanup.

Refs openclaw#133152.
Reviewed-by: @shakkernerd
Co-authored-by: Shakker <[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 docs Improvements or additions to documentation maintainer Maintainer-authored PR P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S 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