Skip to content

Commit 93174b2

Browse files
perf(markdown): make list parsing O(n) (was O(n²)) (#1025)
* perf(markdown): make list parsing O(n) (was O(n^2)) 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. * test: keep markdown perf input below render cap Co-authored-by: Cameron Beeley <[email protected]> --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent 2779365 commit 93174b2

2 files changed

Lines changed: 78 additions & 17 deletions

File tree

‎src/OpenClaw.Shared/Markdown/Md4c/Md4cParser.Block.cs‎

Lines changed: 6 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -631,7 +631,11 @@ private int ConsumeLinkReferenceDefinitions()
631631
Debug.Assert(currentBlockIndex >= 0);
632632

633633
int nLines = CurrentBlock.NLines;
634-
int lineStart = GetCurrentBlockLineStart();
634+
// O(1) line-start: the current block's lines are the tail of blockLines — the same computation
635+
// the reference-def removal below (blockLines.Count - nLines) already relies on. Replaces the
636+
// former GetCurrentBlockLineStart() per-block-close O(n) scan over all prior blocks, which made
637+
// list parsing O(n^2) (one close per list item).
638+
int lineStart = blockLines.Count - nLines;
635639
int n = 0;
636640

637641
while (n < nLines)
@@ -675,7 +679,7 @@ private int EndCurrentBlock()
675679
if (CurrentBlock.Type == MarkdownBlockType.P ||
676680
(CurrentBlock.Type == MarkdownBlockType.H && (CurrentBlock.Flags & BLOCK_SETEXT_HEADER) != 0))
677681
{
678-
int lineStart = GetCurrentBlockLineStart();
682+
int lineStart = blockLines.Count - CurrentBlock.NLines;
679683
if (lineStart < blockLines.Count)
680684
{
681685
var span = CollectionsMarshal.AsSpan(blockLines);
@@ -761,21 +765,6 @@ private ref Block CurrentBlock
761765
get => ref CollectionsMarshal.AsSpan(blocks)[currentBlockIndex];
762766
}
763767

764-
private int GetCurrentBlockLineStart()
765-
{
766-
int lineIdx = 0;
767-
var span = CollectionsMarshal.AsSpan(blocks);
768-
for (int i = 0; i < currentBlockIndex; i++)
769-
{
770-
ref Block b = ref span[i];
771-
if ((b.Flags & BLOCK_CONTAINER) != 0)
772-
continue;
773-
if (b.Type != MarkdownBlockType.Code && b.Type != MarkdownBlockType.Html)
774-
lineIdx += b.NLines;
775-
}
776-
return lineIdx;
777-
}
778-
779768
// ── Line Analysis ────────────────────────────────────────────────────
780769

781770
private bool IsHrLine(int beg, out int pEnd, out int pKiller)
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
using System;
2+
using System.Diagnostics;
3+
using System.Linq;
4+
using OpenClaw.Shared.Markdown;
5+
using Xunit;
6+
using Xunit.Abstractions;
7+
8+
namespace OpenClaw.Shared.Tests;
9+
10+
// #5 fuzz probe: the node parses untrusted gateway chat markdown via ChatMarkdownAstBuilder.
11+
// Pathological (not merely large) inputs must not crash or blow up super-linearly (CPU DoS).
12+
public class MarkdownParserFuzzTests
13+
{
14+
private readonly ITestOutputHelper _out;
15+
public MarkdownParserFuzzTests(ITestOutputHelper o) => _out = o;
16+
17+
public static TheoryData<string, string> Pathological()
18+
{
19+
const int n = 100_000;
20+
return new TheoryData<string, string>
21+
{
22+
{ "many-asterisks", new string('*', n) },
23+
{ "emphasis-backtrack", string.Concat(Enumerable.Repeat("*a", n / 2)) }, // *a*a*a...
24+
{ "open-brackets", new string('[', n) },
25+
{ "nested-link", string.Concat(Enumerable.Repeat("[", n / 2)) + string.Concat(Enumerable.Repeat("]", n / 2)) },
26+
{ "image-bang-brackets", string.Concat(Enumerable.Repeat("![", n / 2)) },
27+
{ "deep-blockquote", string.Concat(Enumerable.Repeat("> ", n / 2)) },
28+
{ "deep-list", string.Concat(Enumerable.Repeat(" - x\n", n / 6)) },
29+
{ "backticks", new string('`', n) },
30+
{ "underscores", new string('_', n) },
31+
{ "mixed-markers", string.Concat(Enumerable.Repeat("*_`[~", n / 5)) },
32+
{ "table-pipes", "|" + string.Concat(Enumerable.Repeat("a|", n / 2)) },
33+
};
34+
}
35+
36+
[Fact]
37+
public void Build_ManyListItems_ScalingCurve()
38+
{
39+
string ListMd(int items) => string.Concat(Enumerable.Repeat(" - x\n", items));
40+
long Time(int items)
41+
{
42+
var md = ListMd(items);
43+
new ChatMarkdownAstBuilder().Build(md); // warm
44+
var sw = Stopwatch.StartNew();
45+
new ChatMarkdownAstBuilder().Build(md);
46+
sw.Stop();
47+
return sw.ElapsedMilliseconds;
48+
}
49+
const int largestItemCount = 30_000;
50+
Assert.True(ListMd(largestItemCount).Length < ChatMarkdownAstBuilder.MaxInputBytes);
51+
52+
long t1 = Time(10_000), t2 = Time(20_000), t3 = Time(largestItemCount);
53+
_out.WriteLine($"list items 10k={t1}ms 20k={t2}ms 30k={t3}ms");
54+
// Regression guard: a 30k-item flat list parsed in seconds with the O(n^2) bug and tens of milliseconds after
55+
// the O(1) line-start fix. Assert it stays well under 500ms so the quadratic can't silently return.
56+
Assert.True(t3 < 500, $"30k flat list items must parse near-linearly (<500ms). Curve: 10k={t1} 20k={t2} 30k={t3}ms");
57+
}
58+
59+
[Theory]
60+
[MemberData(nameof(Pathological))]
61+
public void Build_PathologicalInput_IsBoundedAndDoesNotCrash(string label, string markdown)
62+
{
63+
var sw = Stopwatch.StartNew();
64+
var doc = new ChatMarkdownAstBuilder().Build(markdown); // must not throw
65+
sw.Stop();
66+
_out.WriteLine($"{label}: {markdown.Length} chars parsed in {sw.ElapsedMilliseconds} ms");
67+
68+
Assert.NotNull(doc);
69+
// A 100 KB message parsing must be near-linear; >3s indicates super-linear (quadratic) blowup — DoS.
70+
Assert.True(sw.ElapsedMilliseconds < 3000, $"{label} took {sw.ElapsedMilliseconds} ms (super-linear blowup?)");
71+
}
72+
}

0 commit comments

Comments
 (0)