diff --git a/CHANGELOG.md b/CHANGELOG.md index 7a8d414..ab5ef55 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Change Log +## Unreleased + +- 🐛 FIX: `anchors` and `tasklists` no longer take quadratic time on many duplicate headings or long task lists. + ## 0.7.0 - 2026-11-10 A security and bug-fix release. diff --git a/mdit_py_plugins/anchors/index.py b/mdit_py_plugins/anchors/index.py index 7fca0d5..1cff422 100644 --- a/mdit_py_plugins/anchors/index.py +++ b/mdit_py_plugins/anchors/index.py @@ -78,6 +78,7 @@ def _anchor_func(state: StateCore) -> None: for token in state.tokens if token.type == "heading_open" and (heading_id := token.attrGet("id")) } + next_suffix: dict[str, int] = {} for idx, token in enumerate(state.tokens): if token.type != "heading_open": continue @@ -93,7 +94,7 @@ def _anchor_func(state: StateCore) -> None: ) slug = token.attrGet("id") if not slug: - slug = unique_slug(slug_func(title), slugs) + slug = unique_slug(slug_func(title), slugs, next_suffix) token.attrSet("id", slug) if permalink: @@ -132,11 +133,23 @@ def slugify(title: str) -> str: return re.sub(r"[^\w\u4e00-\u9fff\- ]", "", title.lower().replace(" ", "-")) -def unique_slug(slug: str, slugs: set[str]) -> str: +def unique_slug( + slug: str, slugs: set[str], next_suffix: dict[str, int] | None = None +) -> str: + """Return ``slug``, or ``slug-1``, ``slug-2``, ... if taken, and add it to ``slugs``. + + :param next_suffix: if given, remembers the next suffix to try for each base slug, + so that many headings with the same title take linear rather than quadratic time. + """ uniq = slug - i = 1 - while uniq in slugs: + i = 1 if next_suffix is None else next_suffix.get(slug, 1) + if uniq in slugs: uniq = f"{slug}-{i}" + while uniq in slugs: + i += 1 + uniq = f"{slug}-{i}" i += 1 + if next_suffix is not None: + next_suffix[slug] = i slugs.add(uniq) return uniq diff --git a/mdit_py_plugins/tasklists/__init__.py b/mdit_py_plugins/tasklists/__init__.py index 81a9bd4..b27778e 100644 --- a/mdit_py_plugins/tasklists/__init__.py +++ b/mdit_py_plugins/tasklists/__init__.py @@ -57,6 +57,11 @@ def tasklists_plugin( def fcn(state: StateCore) -> None: tokens = state.tokens + # index of the most recent token seen at each nesting level, kept up to date + # as we scan forward, so finding a list item's parent is O(1) rather than + # a backward scan (which made long task lists quadratic) + last_at_level: dict[int, int] = {} + scanned = 0 for i in range(2, len(tokens) - 1): if is_todo_item(tokens, i): todoify(tokens[i]) @@ -64,19 +69,15 @@ def fcn(state: StateCore) -> None: "class", "task-list-item" + (" enabled" if not disable_checkboxes else ""), ) - tokens[parent_token(tokens, i - 2)].attrSet( - "class", "contains-task-list" - ) + # record every token before the list item + while scanned < i - 2: + last_at_level[tokens[scanned].level] = scanned + scanned += 1 + parent = last_at_level.get(tokens[i - 2].level - 1, -1) + tokens[parent].attrSet("class", "contains-task-list") md.core.ruler.after("inline", "github-tasklists", fcn) - def parent_token(tokens: list[Token], index: int) -> int: - target_level = tokens[index].level - 1 - for i in range(1, index + 1): - if tokens[index - i].level == target_level: - return index - i - return -1 - def is_todo_item(tokens: list[Token], index: int) -> bool: return ( is_inline(tokens[index]) diff --git a/tests/test_redos.py b/tests/test_redos.py index cfc1320..83799dc 100644 --- a/tests/test_redos.py +++ b/tests/test_redos.py @@ -162,3 +162,38 @@ def test_plugin_is_redos_safe(case: Case) -> None: f"{case.id} took {elapsed:.3f}s on a {_RUN}x{filler!r} run; " "likely catastrophic backtracking (ReDoS)" ) + + +# Plugins that post-process the whole token stream can also go quadratic when a +# construct is *repeated* many times, rather than when one construct holds a long run. +_REPEATED_CASES = [ + Case( + "anchors-duplicate-headings", + lambda md: md.use(anchors_plugin), + lambda line: line * _REPEATS, + ), + Case( + "tasklists-long-list", + lambda md: md.use(tasklists_plugin), + lambda line: line * _REPEATS, + ), +] +_REPEATED_LINES = { + "anchors-duplicate-headings": "# a\n", + "tasklists-long-list": "- [ ] a\n", +} +_REPEATS = 10_000 + + +@pytest.mark.timeout(10) +@pytest.mark.parametrize("case", _REPEATED_CASES, ids=lambda case: case.id) +def test_plugin_is_linear_in_repeats(case: Case) -> None: + md = MarkdownIt("commonmark") + case.configure(md) + source = case.payload(_REPEATED_LINES[case.id]) + start = time.perf_counter() + md.render(source) + elapsed = time.perf_counter() - start + assert elapsed < _BUDGET_SECONDS, ( + f"{case.id} took {elapsed:.3f}s on {_REPEATS} repeats; likely quadratic" + )