Skip to content

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

Closed

Description

@anagnorisis2peripeteia

Summary

ChatMarkdownAstBuilder.Build() (the vendored md4c C# port) parses list-heavy markdown in O(n²) in the
number of list items. Since incoming gateway chat messages are rendered natively through
ChatMarkdownRenderer → ChatMarkdownAstBuilder.Build(), a chat message that is one long flat list makes the
parse cost grow quadratically. It's bounded — MaxInputBytes = 256 KB truncates oversized input — but at the
256 KB boundary a single message takes ~5–6 seconds to parse, and the parse runs on the render path, so a
gateway sending such messages repeatedly can keep the chat UI stalled. Availability/UX only; no crash, no code
execution, no data exposure.

Reproduction

string md = string.Concat(Enumerable.Repeat("  - x\n", items));
var sw = Stopwatch.StartNew();
new ChatMarkdownAstBuilder().Build(md);
sw.Stop();  // items -> ms

Measured (before fix): 10k=350ms, 20k=1346ms, 40k=5468ms — each size-doubling ~4× the time = quadratic. Every
other pathological input at 100k chars (nested brackets, emphasis runs, deep blockquotes, tables, backticks)
parses in <20 ms, so it is specific to the list path.

Root cause

Md4cParser.Block.cs GetCurrentBlockLineStart() performs a full linear scan over all prior blocks to
compute the current block's line-start offset. It is called from EndCurrentBlock() on every block close —
which happens once per list item — so N items × O(N) scan = O(N²). The value it computes is exactly the tail
offset blockLines.Count - CurrentBlock.NLines, which the same file already uses elsewhere
(ConsumeLinkReferenceDefinitions, the reference-def removal at what was line 658), so the scan is redundant.

Fix (see accompanying PR)

Replace the O(N) GetCurrentBlockLineStart() scan at both call sites with the O(1) tail computation
blockLines.Count - NLines and delete the now-unused method. This makes the list path O(N): a 40k-item list
drops from ~5468 ms to ~47 ms (~116×), all markdown-parser tests still pass, and the full OpenClaw.Shared.Tests
suite is unchanged. A regression test asserts a 40k-item list parses in <500 ms.

Severity

Low / hardening — CWE-407 (Inefficient Algorithmic Complexity). Bounded by the existing MaxInputBytes cap
(worst case ~5–6 s per 256 KB message, not an unbounded hang) and requires the connected gateway to send the
crafted content. Filing as a normal issue + perf fix rather than a security advisory.

Environment

openclaw/openclaw-windows-node, current main @ 258f838 (verified on macOS, .NET SDK 10).

Activity

  1. moved this from Backlog to Local Gateway in Windows Companion Appon Jul 18, 2026
  2. added
    P2
    impact:ux-friction
    impact:other
    issue-rating: 🐚 platinum hermit
    clawsweeper:needs-live-repro
    clawsweeper:linked-pr-open
    clawsweeper:no-new-fix-pr
    on Jul 18, 2026
  3. clawsweeper commented on Jul 18, 2026

    @clawsweeper

    Codex review: keeping this open for maintainer follow-up; there is still a little grit to resolve. Reviewed July 18, 2026, 6:59 PM ET / 22:59 UTC.

    Summary
    This issue remains necessary because the concrete fix is owned by an open linked pull request; it should stay open until that implementation is reviewed and merged. Likely related people: anagnorisis2peripeteia is the active fix author (low-confidence ownership routing; current-main history inspection was sandbox-blocked).

    Reproducibility: yes. source-reproducible from the supplied harness: parse increasingly large flat lists and compare scaling. Independent current-main execution and source inspection were unavailable because the read-only review sandbox failed before commands ran.

    Root-cause cluster
    Relationship: canonical
    Canonical: #1024
    Summary: This is the canonical report, with one directly linked open pull request as the candidate fix.

    Members:

    Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

    Next step
    The open linked PR already proposes a focused implementation, so dispatching a second repair would duplicate active contributor work.

    Review details

    Best possible solution:

    Review and merge the linked narrow parser fix with semantic parser coverage and a stable performance regression guard; GitHub can then close this issue through the existing closing reference.

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

    Yes, source-reproducible from the supplied harness: parse increasingly large flat lists and compare scaling. Independent current-main execution and source inspection were unavailable because the read-only review sandbox failed before commands ran.

    Is this the best way to solve the issue?

    Yes in principle: replacing a redundant full scan with the existing tail-offset invariant is the narrowest maintainable fix, pending review of both call sites and the linked regression test.

    AGENTS.md: found and applied where relevant.

    Remaining risk / open question:

    • If the report is confirmed, a bounded 256 KB flat-list message can occupy the native chat render path for several seconds; the linked PR's performance assertion should be checked for correctness and stability on supported hardware before merge.

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

    Label changes

    Label changes:

    • add P2: The report describes a bounded but user-visible multi-second chat-render stall from crafted list-heavy gateway content.
    • add impact:ux-friction: The affected Markdown renderer can temporarily stall the interactive chat flow.
    • add impact:other: The concrete effect is bounded render-path performance degradation, which has no more specific owned impact label.
    • add issue-rating: 🐚 platinum hermit: Current issue advisory state selects this label.
    • add clawsweeper:needs-live-repro: Current issue advisory state selects this label.
    • add clawsweeper:linked-pr-open: Current issue advisory state selects this label.
    • add clawsweeper:no-new-fix-pr: Current issue advisory state selects this label.

    Label justifications:

    • P2: The report describes a bounded but user-visible multi-second chat-render stall from crafted list-heavy gateway content.
    • impact:ux-friction: The affected Markdown renderer can temporarily stall the interactive chat flow.
    • impact:other: The concrete effect is bounded render-path performance degradation, which has no more specific owned impact label.
    Evidence reviewed

    What I checked:

    • Open implementation PR: The supplied GitHub timeline and closing-reference metadata show a clean, open PR explicitly targeting this issue with the same reported O(n²) list-parsing path; an open fixing PR is not grounds to close its issue before merge. (29d0d771e926)
    • Issue-level reproduction detail: The report supplies a concrete benchmark harness, measurements at 10k/20k/40k list items, the suspected parser method, and an O(1) replacement based on an existing offset invariant. (src/OpenClaw.Shared/Chat/Markdown/Md4cParser.Block.cs, 277936553135)
    • Read-only inspection blocked: The review shell could not start any inspection command because its sandbox failed while configuring loopback networking, so current-main source, tests, VISION.md, maturity output, and git provenance could not be independently read during this review.

    Likely related people:

    • anagnorisis2peripeteia: Authored the linked focused implementation candidate; no independent current-main feature-history trail could be collected because read-only shell inspection was blocked. (role: active fix author; confidence: low; commits: 29d0d771e926; files: src/OpenClaw.Shared/Chat/Markdown/Md4cParser.Block.cs)
    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.
  4. moved this from Local Gateway to Channels in Windows Companion Appon Jul 19, 2026
  5. locked as resolved and limited conversation to collaborators on Jul 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P2clawsweeper:linked-pr-openclawsweeper:needs-live-reproclawsweeper:no-new-fix-primpact:otherimpact:ux-frictionissue-rating: 🐚 platinum hermit

    Type

    No type

    Fields

    Priority

    None yet

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions