Skip to content

🐛 FIX: Make anchors and tasklists linear on repeated input - #179

Open
ramykamil wants to merge 1 commit into
executablebooks:masterfrom
ramykamil:fix-quadratic-anchors-tasklists
Open

ramykamil wants to merge 1 commit into
executablebooks:masterfrom
ramykamil:fix-quadratic-anchors-tasklists

Conversation

@ramykamil

Copy link
Copy Markdown

Problem

Two plugins take quadratic time when a construct is repeated, so a small document can tie up a server that renders untrusted Markdown:

Input Size Before After
"# a\n" * 8000 with anchors_plugin 32 KB 6.74 s 0.21 s
"- [ ] a\n" * 8000 with tasklists_plugin 64 KB 11.75 s 0.54 s
"# a\n" * 32000 with anchors_plugin 128 KB (minutes) 0.85 s
"- [ ] a\n" * 32000 with tasklists_plugin 256 KB (minutes) 1.91 s
  • anchors: unique_slug restarts its search at a-1 for every duplicate heading, so the N-th # a tries N suffixes.
  • tasklists: parent_token scans backwards to the list opener for every task item, so the N-th item scans N tokens.

The existing test_redos.py uses one long run inside a single construct, so it doesn't catch quadratic behavior from repeating a construct.

Fix

  • unique_slug takes an optional next_suffix dict that remembers the next suffix to try for each base slug. Slugs are never removed from the set, so every skipped suffix is still taken, and the result is the same as before. Calls without the new argument behave exactly as before.
  • tasklists records the last token seen at each nesting level while scanning forward, which gives the same parent as the backward scan in O(1).

Tests

  • Added test_plugin_is_linear_in_repeats to tests/test_redos.py (10,000 repeats, 1 s budget). It times out on the old code and passes with the fix.
  • Rendered 16,000 random documents (duplicate headings, explicit {#id}s, nested and ordered task lists, label/label_after options) with the old and new code: the output is identical.
  • The full suite passes: 732 passed, 3 skipped, 1 xfailed.

🤖 Generated with Claude Code

unique_slug restarted its suffix search at 1 for every duplicate heading, and
tasklists scanned back to the list opener for every task item, so N duplicate
headings or N task items took O(N^2) time (8,000 '# a' lines: 6.7s; 8,000
'- [ ] a' lines: 11.8s). Remember the next suffix per slug, and track the last
token seen at each nesting level while scanning forward. Rendered output is
unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant