Skip to content

perf(markdown): make list parsing O(n) (was O(n²)) - #1025

Merged
steipete merged 3 commits into
openclaw:mainfrom
anagnorisis2peripeteia:fix/markdown-list-quadratic
Jul 19, 2026
Merged

steipete merged 3 commits into
openclaw:mainfrom
anagnorisis2peripeteia:fix/markdown-list-quadratic

Conversation

@anagnorisis2peripeteia

@anagnorisis2peripeteia anagnorisis2peripeteia commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #1024.

ChatMarkdownAstBuilder (md4c port) parsed list-heavy markdown in O(n²): GetCurrentBlockLineStart() scanned all prior blocks on every block close (once per list item). A 40k-item flat list took ~5.5s; gateway chat renders through ChatMarkdownRenderer, so a crafted message could stall the chat UI (bounded by MaxInputBytes=256KB to ~5–6s/message).

Fix

Replace both call sites with the O(1) tail computation blockLines.Count - NLines — the same value ConsumeLinkReferenceDefinitions already uses for its reference-def removal — and drop the redundant scan.

Diffstat

File + −
src/OpenClaw.Shared/Markdown/Md4c/Md4cParser.Block.cs 6 17
tests/OpenClaw.Shared.Tests/MarkdownParserFuzzTests.cs 69 0
Total (2 files) 75 17

Gates / verification

  • Perf: 40k-item flat list 5468 ms → 47 ms (~116×); scaling is now linear (10k=7 ms, 20k=19 ms, 40k=47 ms) vs the prior quadratic (350 / 1346 / 5468 ms).
  • Correctness: full OpenClaw.Shared.Tests suite (2957 tests) passes with zero new failures vs the pre-existing baseline; every markdown-parser test is unchanged — the change is behaviour-preserving (the same tail computation was already relied on at the reference-def removal site).
  • Regression guard: MarkdownParserFuzzTests asserts a 40k-item list parses in <500 ms, plus a pathological-input suite (nested brackets, emphasis runs, deep blockquotes, tables, backticks) — all <20 ms.
  • Env: verified on .NET SDK 10 (macOS). The change is confined to OpenClaw.Shared (net10.0); the WinUI project isn't built locally (Windows App SDK unavailable) and is covered by CI.

Real-behavior proof

Per @clawsweeper (proof unranked → needs execution evidence). Executed on the PR head (29d0d77, clean — only this change), macOS + .NET SDK 10; paths redacted.

Scaling — the list-heavy case actually runs, now linear (pre-fix was quadratic: 350 / 1346 / 5468 ms):

deep-list: 99996 chars parsed in 17 ms
list items 10k=7ms 20k=19ms 40k=40ms 80k=0ms   (linear≈2x/step, quadratic≈4x/step)

40k-item flat list: 5468 ms (pre-fix) → 40 ms (~137×). Build_ManyListItems_ScalingCurve (asserts 40k < 500 ms) and the Build_PathologicalInput_IsBoundedAndDoesNotCrash suite pass.

Shared-test suite (covers the changed OpenClaw.Shared code):

Failed!  - Failed: 29, Passed: 2884, Skipped: 31, Total: 2944 - OpenClaw.Shared.Tests.dll (net10.0)

The 29 failures are the pre-existing macOS-environmental baseline (HttpListener / ExecApprovalsCoordinator, etc.), identical on a clean checkout — zero new failures; every markdown-parser test is unchanged.

./build.ps1 + tray-test: require Windows (WinUI / Windows App SDK) and aren't runnable on this macOS host; the change is confined to OpenClaw.Shared (net10.0), fully exercised by the shared-test proof above, and the Windows build + e2e run in CI on this PR.

ChatMarkdownAstBuilder (md4c port) parsed list-heavy markdown in O(n^2):
GetCurrentBlockLineStart() scanned all prior blocks on every block close,
called once per list item. A 40k-item flat list took ~5.5s; since gateway
chat messages render through ChatMarkdownRenderer, a crafted message could
stall the chat UI (bounded by MaxInputBytes=256KB to ~5-6s/message).

Replace both call sites with the O(1) tail computation
blockLines.Count - NLines (the same value ConsumeLinkReferenceDefinitions
already uses for the reference-def removal) and drop the redundant scan.
40k items now parse in ~47ms (~116x). All markdown-parser tests unchanged;
adds a regression test asserting a 40k-item list parses in <500ms.
@clawsweeper clawsweeper Bot added 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. P2 Normal priority bug or improvement with limited blast radius. labels Jul 18, 2026
@clawsweeper

clawsweeper Bot commented Jul 18, 2026 •

Copy link
Copy Markdown

Codex review: needs maintainer review before merge. Reviewed July 18, 2026, 10:20 PM ET / July 19, 2026, 02:20 UTC.

Summary
The branch replaces repeated markdown block-line scans with constant-time tail-offset calculations and adds large-list scaling and pathological-input regression coverage.

Reproducibility: yes. The linked report supplies a focused list-construction benchmark, and the PR identifies the repeated block-close scan and its two call sites as the current-main reproduction path; this review did not execute it locally.

Review metrics: 2 noteworthy metrics.

  • Patch scope: 2 files affected; 78 additions, 17 deletions. The change is limited to the md4c parser path and focused shared regression coverage.
  • Measured list parsing: 40k items: about 5.5s to 40ms. The supplied real-runtime measurement directly targets the user-visible chat-render stall described by the linked report.

Merge readiness
Overall: 🐚 platinum hermit
Proof: 🦞 diamond lobster
Patch quality: 🐚 platinum hermit
Result: ready for maintainer review.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • none.

Next step before merge

  • No concrete mechanical repair is indicated; the remaining action is normal maintainer review of this proof-positive candidate while its existing CI completes.

Security
Cleared: The parser-and-test-only diff adds no dependency, secret, permission, downloader, workflow, or external execution surface.

Review details

Best possible solution:

Merge the narrow O(1) parser repair after normal maintainer review and completion of the existing Windows CI, retaining the bounded list-scaling regression coverage.

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

Yes. The linked report supplies a focused list-construction benchmark, and the PR identifies the repeated block-close scan and its two call sites as the current-main reproduction path; this review did not execute it locally.

Is this the best way to solve the issue?

Yes. Reusing the existing tail-offset representation removes the repeated scan without adding a new surface, and the focused scaling test protects the intended complexity boundary.

AGENTS.md: found and applied where relevant.

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

Label changes

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • remove rating: 🦞 diamond lobster: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.

Label justifications:

  • P2: The reported bounded quadratic parser path can stall chat rendering but does not indicate a crash, data loss, or security-boundary failure.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The PR body includes redacted terminal-style after-fix list-scaling output and shared-test results that directly demonstrate the repaired parser path; the subsequent commits refine test input size rather than the parser implementation.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body includes redacted terminal-style after-fix list-scaling output and shared-test results that directly demonstrate the repaired parser path; the subsequent commits refine test input size rather than the parser implementation.
Evidence reviewed

What I checked:

Likely related people:

  • steipete: Authored the two latest commits that refine the markdown performance-test input to the render limit. (role: recent area contributor; confidence: medium; commits: 7e660f55f8c7, a41fe8695cc0; files: tests/OpenClaw.Shared.Tests/MarkdownParserFuzzTests.cs)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

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.

How this review workflow works
  • 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.
Review history (3 earlier review cycles)
  • reviewed 2026-07-18T23:00:39.116Z sha 29d0d77 :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-18T23:09:07.663Z sha 29d0d77 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-18T23:50:28.739Z sha 29d0d77 :: needs maintainer review before merge. :: none

@anagnorisis2peripeteia

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review — added real-behavior proof (executed list-scaling on the PR head + full shared-test suite) to the PR body.

@clawsweeper

clawsweeper Bot commented Jul 18, 2026 •

Copy link
Copy Markdown

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient Contributor real behavior proof is sufficient. 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. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. 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. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Jul 18, 2026
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. labels Jul 19, 2026
@steipete
steipete merged commit 93174b2 into openclaw:main Jul 19, 2026
12 checks passed
@anagnorisis2peripeteia
anagnorisis2peripeteia deleted the fix/markdown-list-quadratic branch September 9, 2026 00:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 Normal priority bug or improvement with limited blast radius. proof: sufficient Contributor real behavior proof is sufficient. 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.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Quadratic O(n²) list-markdown parsing in ChatMarkdownAstBuilder (md4c port)

2 participants