Skip to content

perf(control-ui): avoid reparsing completed code while replies stream - #173264

Merged
steipete merged 4 commits into
mainfrom
steipete/coldload-streaming-render
Oct 15, 2026
Merged

steipete merged 4 commits into
mainfrom
steipete/coldload-streaming-render

Conversation

@steipete

@steipete steipete commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Streaming replies containing ordinary code comparisons repeatedly parse and sanitize completed Markdown as later blocks arrive.

User Impact

Less JavaScript work and long-frame blocking while an answer streams, with identical rendered output. Total renderer CPU remains nearly unchanged because style recalculation dominates; this does not eliminate all streaming jank.

Why This Change Was Made

The cold-load campaign originally measured 14 visual states over roughly 15 seconds for a signed-in dashboard deep-link reload. This lane measures subsequent streaming use.

The renderer already cached completed Markdown, but its HTML guard treated < inside code as possible HTML. Once a comparison arrived, later completed blocks could re-render the entire prefix. The existing streaming owner now uses the shared Markdown code-ownership parser on newly completed text and retains its HTML classification in the existing bounded cache. Actual HTML retains its conservative fallback. The DOM owner also skips unchanged non-media fragments while preserving media lifecycle updates.

The benchmark adds a 15,468-character answer with prose, code comparisons, and tables, delivered cumulatively in 645 deltas at a nominal 30 per second. It measures untraced streaming CPU by message-length quartile, parsing work, LoAF, frame gaps, and trusted composer input latency, and accepts the campaign's generic LoAF/mutation and WebSocket census probes. Native HTML hooks retain string conversion for TrustedHTML inputs omitted by lib.dom's types; the benchmark rejects non-finite character counts.

Evidence

Final-head comparison: seven interleaved baseline/candidate pairs on one quiet AWS Crabbox c7a.4xlarge, lease cbx_70beb3ceff7f: 16 CPUs, AMD EPYC 9R14, about 30.6 GiB RAM, startup load 1.04. Baseline runtime source: e8633bd8930438e3ee165ad934d60e8a1ff9bd63; candidate: 97cda729f353094dfb950a657e52129979b3f9f0. Both production bundles use identical fixture/probes and the repository's Playwright Chromium. Boot profiling ends before the streaming segment; no validation jobs run during the comparison.

Values are median (IQR) across seven runs:

Streaming measurement Baseline Candidate
Last-quarter JavaScript CPU, ms/delta 10.495 (0.086) 8.385 (0.056)
LoAF blocking, ms/stream 5,230.6 (228.2) 4,307.0 (77.4)
Run-level p95 input → next rAF, ms 92.9 (9.6) 91.3 (11.9)
DOMParser/template input, characters 4,322,231 (115,469) 1,312,078 (75,717.5)
Estimated missed 60 Hz frames 774 (12.5) 733 (14)
LoAF count 207 (3.5) 214 (8)
Last-quarter total renderer CPU, ms/delta 33.34 (0.50) 33.28 (0.56)
Last-quarter style recalculation, ms/delta 19.20 (0.32) 21.06 (0.37)
Geometry reads per stream 2,693 (82) 2,897 (52)
Computed-style reads per stream 1,017 (37) 1,110 (21.5)

JavaScript CPU falls 20.1%, LoAF blocking falls 17.7%, and parsed input falls 69.6%. Input latency has overlapping IQRs: this is not a clear input-latency win. LoAF count increases while total blocking decreases. Geometry/style work also increases, and total CPU stays flat. Frame loss is estimated from rAF gaps; input-to-rAF is not a presentation timestamp. CPU counters include the benchmark/probes and native input. The first CPU quartile also includes fixture scheduling overhead.

JavaScript CPU across the four message-length quartiles is 12.44/11.59/10.76/10.50 ms per delta before and 11.83/10.74/9.34/8.38 afterward. Total CPU is 31.01/31.01/32.24/33.34 before and 30.12/31.07/32.22/33.28 afterward. Style work remains the dominant remaining cost. These counters do not prove a strict constant-time total renderer path.

All 14 captures have valid parsing counters, 645 delivered deltas, 24 headings, 24 code blocks, and 24 tables. Rendered HTML is identical across every capture after removing reconciler comments (SHA-256 5ecca9b6c7c28a6469d221875934598ef42efe24534f37fbe7a51140a35b9291). The focused regression separately checks byte-identical streamed/full renderer output at each completed section.

Validation

  • The strengthened existing regression failed before the parser fix: 4,042,462 sanitizer-input characters for a 16,630-character reply exceeded its 332,600-character budget. Afterward, all 18 streaming tests pass, including actual HTML, reference definitions, containers, locale/options/source changes, and truncation. pnpm test ui/src/components/markdown-streaming.test.ts --maxWorkers=1: 18 passed, final-head AWS wall time 10.58 s.
  • pnpm test ui/src/components/markdown-dom-ref.test.ts --maxWorkers=1: 4 passed, final-head AWS wall time 4.92 s, covering DOM retention and media cleanup.
  • Independent Codex review is clean through P2, with full owner modules supplied as context. The final rebase changed none of the reviewed owner context.
  • Final-head scoped UI/scripts lint and pnpm tsgo:ui / pnpm tsgo:scripts passed. Full UI e2e passed on the final head: 803 files / 3,500 tests passed, one existing file/test skipped, zero failures. Command: node scripts/run-vitest.mjs run --config test/vitest/vitest.ui-e2e.config.ts --maxWorkers=6; AWS wall time 3,978.19 s. The skipped file is ui/src/e2e/desktop-resize.real-gateway.e2e.test.ts (existing platform-specific skip). All eight archived check exit codes are zero. The full pass/skip list is retained in the lane proof artifacts.
  • Native preflight and the full suite both passed all three previously affected files (preflight: 11 tests): automation-management, cron-duration-save, and quota-reset-status. Main's pending-catalog discovery fix and obsolete cron-dismissal removal were integrated before this proof. Chromium/WebKit tooltip activation and native Workboard coverage both passed; task-owned checkout ancestors are non-group-writable and artifacts stay inside the repository, satisfying the existing fixture contracts.
  • Exact-head PR CI run 38800144117: green for 97cda729f353.

Scope and size

Runtime: +27 lines (31 added, 4 removed) across the three existing Markdown owners. The additional classification preserves the actual-HTML invalidation contract while allowing literal code to stay cached. No persistent state, server schema, configuration, dependency, or transport changes.

Benchmark/probe tooling: +369 net lines. The requested git diff --stat origin/main...HEAD -- ':!*.test.ts' ':!*test-support*' ':!docs/*' includes that tooling: 402 added, 6 removed, +396 net lines. Six files total, including the one-line regression edit.

Release-note context: Control UI keeps completed Markdown cached when streamed code contains comparisons, reducing repeated rendering work without changing the answer.

Synthetic before / after

The captures below show the completed baseline and candidate reply on the final-head comparison. Both were inspected in full and contain only the synthetic benchmark fixture.

before-streaming

after-streaming

@clawsweeper

clawsweeper Bot commented Oct 15, 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 app: web-ui App: web-ui scripts Repository scripts size: M labels Oct 15, 2026
@steipete
steipete force-pushed the steipete/coldload-streaming-render branch from 7b44680 to 3c4db60 Compare October 15, 2026 16:25
@clawsweeper clawsweeper Bot added 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. labels Oct 15, 2026
@clawsweeper

clawsweeper Bot commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR reuses completed Markdown containing code comparisons, skips unchanged DOM fragments, and extends the streaming benchmark.

Example: A streamed TypeScript answer contains value &lt; 100 inside a completed fenced block, followed by additional paragraphs.

  • Before: The comparison disables incremental prefix rendering, so subsequent completed blocks repeatedly render the accumulated prefix.
  • After: Parser-owned code comparisons allow completed content to remain cached while later blocks render.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The focused implementation and regression contract are credible, with no discrete introduced defect identified; performance confidence remains limited to reported test evidence.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored experiment is outside the ordinary contributor proof gate; supplied evidence exercises renderer and DOM owners in tests, while the production-browser streaming comparison is explicitly pending.
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 answers containing ordinary code comparisons can repeatedly process already completed content and make the chat less responsive.
Reason: The maintainer-authored direction addresses a concrete existing work-budget failure with narrow runtime changes; the two new flags belong only to the opt-in benchmark.

Merge readiness

✅ Ready for maintainer review

Keep open as a maintainer-owned experiment addressing repeated streaming-render work still present on main; respect the explicit draft merge hold.

Priority: P2
Reviewed head: 3c4db60feccac9bbdff8cb78824856edd9dcd801

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The declared browser baseline/candidate streaming campaign remains pending, so end-to-end latency improvement and unchanged visible output are not yet demonstrated for this head.
Agent review details

How this fits together

Control UI receives cumulative assistant text, splits stable Markdown from the growing tail, parses and sanitizes rendered fragments, and reconciles them into retained chat DOM with separate media lifecycle handling.

flowchart TD
  A[Assistant text updates] --> B[Streaming Markdown owner]
  B --> C[Code ownership parser]
  B --> D[Stable prefix and live tail]
  D --> E[Markdown parser and sanitizer]
  E --> F[DOM reconciler]
  F --> G[Chat content and media]
Loading

Technical review

Best possible solution:

Reuse completed code-bearing Markdown through the existing renderer and DOM owners while preserving conservative HTML handling and media refresh.

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

Current-main source shows that a fenced comparison disables prefix reuse, and the PR reports a before-fix sanitizer-budget failure; this read-only review ran no target code.

Is this the best way to solve the issue?

The implementation addresses the conservative guard in its existing owner, reuses the established code parser, and preserves sanitization and media updates without adding a parallel rendering path.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

  • Pinned introduced change: The merge-base-to-head diff contains the code-aware HTML check, cached classification, unchanged-fragment shortcut, regression-fixture adjustment, and benchmark additions. (3c4db60fecca)
  • Current-main performance path: Current main rejects incremental stable-prefix rendering whenever the prefix includes &lt;, including literal comparisons inside completed code fences. (ui/src/components/markdown.ts:690, f1e5b8d4c831)
  • Existing ownership and sanitization: The new classification consumes existing parser-owned code ranges; rendered appends still pass through renderSanitizedMarkdown, and unchanged fragments with media still reconcile. (ui/src/components/markdown.ts:682, 3c4db60fecca)
  • Focused regression contract: The existing rich-reply test now includes a code comparison and retains both completed-section output parity and its sanitizer-work bound; the body reports failure before the fix and success afterward. (ui/src/components/markdown-streaming.test.ts:65, 3c4db60fecca)
  • Original renderer intent: The earlier prefix-cache change deliberately preserved raw-HTML semantics, while the renderer-neutral extraction preserved canonical DOM and media lifecycle ownership. (ui/src/lib/markdown-dom-reconciler.ts:329, 7bdba03c22d3)
  • Explicit experimental status: The full PR body explicitly says performance validation is pending and requests that the draft not merge; both discussion comments are review-status messages. (3c4db60fecca)

Likely related people:

  • Peter Steinberger: Raw commit ebd12a0 adds ui/src/components/markdown.ts:703 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: ebd12a0dfa9e; files: ui/src/components/markdown.ts)

PR surface

Source +27, Tests +244, Other +99. Total +370 across 6 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 3 31 4 +27
Tests 2 245 1 +244
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 101 2 +99
Total 6 377 7 +370

Labels

Label changes:

  • add P2: Repeated parsing affects responsiveness of long code-containing Control UI replies, with a focused repair and limited blast radius.
  • 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: Repeated parsing affects responsiveness of long code-containing Control UI replies, with a focused repair and limited blast radius.
  • 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.

  • Complete the declared interleaved browser comparison and publish redacted streaming-work, composer-latency, and rendered-output results.

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 October 15, 2026, 12:43 PM ET / 16:43 UTC.

@steipete steipete changed the title experiment(control-ui): streaming Markdown fragment reuse [do not merge] perf(control-ui): avoid reparsing completed code while replies stream Oct 15, 2026
@steipete
steipete marked this pull request as ready for review October 15, 2026 16:55
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-15T20:18:16.961589Z 97cda72 New commits
ℹ️ 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.

@steipete
steipete force-pushed the steipete/coldload-streaming-render branch 2 times, most recently from 8369153 to e186656 Compare October 15, 2026 17:45
@steipete
steipete force-pushed the steipete/coldload-streaming-render branch from e186656 to 97cda72 Compare October 15, 2026 20:13

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 97cda729f3

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +684 to +686
const hasHtml = append
? previous.hasHtml || hasStreamingMarkdownHtml(stableMarkdown.slice(previous.markdown.length))
: hasStreamingMarkdownHtml(stableMarkdown);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reparse cross-block raw tags in progress cards

When toStreamingMarkdownParts is called with progressBars: true, treating every < inside code as safe breaks streaming/full-render parity. stripProgressCardRawContentBlocks scans the entire raw message without respecting Markdown code ownership and can pair an opener and closer across completed blocks—for example, fenced blocks containing <script> and later </script>. This cache path renders each block separately and retains both, while a full or final render removes the paired range. Disable this optimization for progress-card rendering or classify according to that whole-message preprocessor.

Useful? React with 👍 / 👎.

@steipete
steipete merged commit a522893 into main Oct 15, 2026
143 checks passed
@steipete
steipete deleted the steipete/coldload-streaming-render branch October 15, 2026 22:18
steipete added a commit that referenced this pull request Oct 15, 2026
The benchmark added four production-suppression entries in a522893
(#173264), failing the main lint-suppressions gate. Keep the allowlist intact.
Give captured native DOM functions explicit receiver contracts and accept
native HTML inputs as unknown so TrustedHTML-like values are still coerced
for character counts without changing the actual parser/setter inputs.

No application imports or behavior change; the only consumer is the opt-in
cold-load benchmark. There are no importing tests. Its serialized probe passed
an isolated jsdom smoke for native receivers, HTML coercion, and exact finite
counters. lint-suppressions.test.ts: 3 passed, 12.34s command wall (before:
1 failed/2 passed). UI and owning ui-other test types, type-aware/boundary
oxlint, format, and P2 autoreview passed.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 16, 2026
…s a literal < (openclaw#173264)

The streaming Markdown renderer reuses completed blocks only when the stable prefix contains no raw HTML, but it tested for any '<' character, so a code span or fence with a comparison like `value < 100` disabled the cache and re-parsed/re-sanitized the whole growing reply on every delta. HTML detection now ignores '<' inside code spans and fences (tracked incrementally for appended text), and the DOM reconciler skips unchanged non-media nodes. Streamed and non-streamed output stay byte-identical (regression test).

Seven interleaved AWS pairs with a long synthetic streamed reply (prose, fenced TypeScript, tables): late-stream JS 10.5 -> 8.4 ms per delta, LoAF blocking 5,231 -> 4,307 ms per stream, Markdown input parsed 4.32M -> 1.31M characters. Runtime +27 LOC; the rest is the streaming bench/probe. Full UI 3,500 tests passed; exact-head CI green.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 16, 2026
The benchmark added four production-suppression entries in 913599c
(openclaw#173264), failing the main lint-suppressions gate. Keep the allowlist intact.
Give captured native DOM functions explicit receiver contracts and accept
native HTML inputs as unknown so TrustedHTML-like values are still coerced
for character counts without changing the actual parser/setter inputs.

No application imports or behavior change; the only consumer is the opt-in
cold-load benchmark. There are no importing tests. Its serialized probe passed
an isolated jsdom smoke for native receivers, HTML coercion, and exact finite
counters. lint-suppressions.test.ts: 3 passed, 12.34s command wall (before:
1 failed/2 passed). UI and owning ui-other test types, type-aware/boundary
oxlint, format, and P2 autoreview passed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app: web-ui App: web-ui 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