From d3c0acaff103b64de507d14325529aaa7aa0125f Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Mon, 30 Nov 2026 11:01:33 +0000 Subject: [PATCH 1/2] fix(memory): find the opener of every index link in one pass (#1262) index_targets called _has_opener once per link, and the scan back runs to the start of the paragraph whenever a link has no unmatched `[` before it (`a](b)`, an escaped `\[`), so an index of many such links took quadratic time in that step. It also tested each link against every definition title with a linear any(). The openers are now found by one left-to-right pass (_closing_openers) with a count of open brackets, reset at a blank line, with the same answers as _has_opener (a differential test pins that over a table and 400 seeded random strings). The title test is a bisect over the sorted, merged title spans. _has_opener stays for the per-span lookups of _blank_inline. Signed-off-by: Anton Volkov --- ...0261130_120000_memory-index-opener-walk.md | 3 + dokimi/dokimi/memory/store.py | 38 +++++++++- dokimi/tests/test_blank_inline.py | 69 +++++++++++++++++++ 3 files changed, 108 insertions(+), 2 deletions(-) create mode 100644 dokimi/changelog.d/20261130_120000_memory-index-opener-walk.md diff --git a/dokimi/changelog.d/20261130_120000_memory-index-opener-walk.md b/dokimi/changelog.d/20261130_120000_memory-index-opener-walk.md new file mode 100644 index 000000000..12e508168 --- /dev/null +++ b/dokimi/changelog.d/20261130_120000_memory-index-opener-walk.md @@ -0,0 +1,3 @@ +### Fixed + +- **A memory index with many links no longer takes quadratic time to lint** — `memory lint` found the `[` of each link by scanning back to the start of its paragraph, and tested each link against every definition title; it now walks the text once and looks a title up by bisection, with the same links found (#1262). diff --git a/dokimi/dokimi/memory/store.py b/dokimi/dokimi/memory/store.py index 4766ab414..1516d8a68 100644 --- a/dokimi/dokimi/memory/store.py +++ b/dokimi/dokimi/memory/store.py @@ -116,8 +116,12 @@ def index_targets(self) -> list[tuple[int, str, bool]]: starts = [m.start() for m in re.finditer("\n", text)] # a link may run over a line break: find its line by offset begin = [0, *(s + 1 for s in starts)] titles = _title_spans(lines, begin, defs) # a closed title holds no link - for m in _MD_LINK.finditer(text): - if _has_opener(text, m.start()) and not any(lo <= m.start() < hi for lo, hi in titles): + matches = list(_MD_LINK.finditer(text)) + opened = _closing_openers(text, {m.start() for m in matches}) + title_starts, title_ends = _merged(titles) + for m in matches: + i = bisect_right(title_starts, m.start()) - 1 + if m.start() in opened and not (i >= 0 and m.start() < title_ends[i]): found.append((bisect_right(starts, m.start()) + 1, m.group(1), True)) defined: set[str] = set() for k, m in sorted(defs.items()): # the first definition of a label is the one Markdown uses @@ -542,6 +546,36 @@ def _has_opener(text: str, close: int) -> bool: return False +def _merged(spans: list[tuple[int, int]]) -> tuple[list[int], list[int]]: + """The starts and ends of ``spans`` (half-open) with the overlapping ones joined, sorted, for a bisect lookup.""" + starts: list[int] = [] + ends: list[int] = [] + for lo, hi in sorted(spans): + if ends and lo <= ends[-1]: + ends[-1] = max(ends[-1], hi) + else: + starts.append(lo) + ends.append(hi) + return starts, ends + + +def _closing_openers(text: str, closes: set[int]) -> set[int]: + """The offsets in ``closes`` for which ``_has_opener`` is true, from one left-to-right pass over ``text`` (#1262).""" + found: set[int] = set() + open_count = 0 + for i, c in enumerate(text): + if c == "\n" and (i == 0 or text[i - 1] == "\n"): + open_count = 0 # a blank line ends the paragraph + elif c == "[" and not _escaped(text, i): + open_count += 1 + elif c == "]" and not _escaped(text, i): + if open_count: + if i in closes: + found.add(i) + open_count -= 1 + return found + + def _fence_opener(line: str) -> str: """The fence marker that ``line`` opens, or ``""``: an info string holds no backtick.""" m = _FENCE.match(line) diff --git a/dokimi/tests/test_blank_inline.py b/dokimi/tests/test_blank_inline.py index 3e5dbefa6..20f8b52e4 100644 --- a/dokimi/tests/test_blank_inline.py +++ b/dokimi/tests/test_blank_inline.py @@ -9,6 +9,7 @@ import random import re from functools import partial +from pathlib import Path import pytest @@ -202,3 +203,71 @@ def test_scanning_past_many_comment_openers_with_no_close_grows_linearly() -> No ratio, result = growth(lambda k: partial(_blank_inline, _unclosed(k), False), 2000) assert ratio < GROWTH_LIMIT assert result[0] == _unclosed(32000) + + +def _index(text: str) -> store.MemoryStore: + return store.MemoryStore(Path("."), store.MemoryEntry("MEMORY.md", text, text, None), []) + + +def _shapes() -> list[str]: + fixed = ["[a](b)", "a](b)", "[[a]](b)", "\\[a](b)", "[a\\](b)", "[a\n](b)", "[a\n\n](b)", "\n[a](b)", "[a](b) [c](d)\n\n[e](f) ](g)", + "[a](b) ](c) [d](e)", "]](x) [[[y]](z)", "\\\\[a](b)", "\\\\\\[a](b)", "[a]\n\n[b](c)"] + rng = random.Random(1262) + return fixed + ["".join(rng.choice("[]()\\\na") for _ in range(rng.randint(1, 40))) for _ in range(400)] + + +def test_the_closes_found_in_one_pass_are_those_the_backward_scan_finds() -> None: + """``index_targets`` must give the same links as before: each ``]`` it asks about is answered as ``_has_opener`` does.""" + for text in _shapes(): + closes = {m.start() for m in re.finditer(r"\]", text)} + assert store._closing_openers(text, closes) == {i for i in closes if store._has_opener(text, i)}, text + + +@pytest.mark.parametrize(("text", "found"), [ + ("[a](b)", ["b"]), ("a](b)", []), ("[[a]](b)", ["b"]), ("\\[a](b)", []), ("[a\\](b)", []), ("[a\n](b)", ["b"]), + ("[a\n\n](b)", []), ("\n[a](b)", ["b"]), ("[a](b) ](c) [d](e)", ["b", "e"]), + ('[a](b)\n\n[d]: x "see [e](f)"\n', ["b", "x"]), +]) +def test_the_index_links_are_as_before(text: str, found: list[str]) -> None: + assert [t for _, t, _ in _index(text).index_targets()] == found + + +def test_title_spans_are_sorted_and_the_overlapping_ones_joined() -> None: + assert store._merged([(5, 9), (1, 3), (2, 6), (20, 21)]) == ([1, 20], [9, 21]) + assert store._merged([(4, 5), (1, 2)]) == ([1, 4], [2, 5]) + + +def test_index_targets_asks_no_opener_per_link(monkeypatch: pytest.MonkeyPatch) -> None: + calls: list[tuple] = [] + + def has_opener(*args) -> bool: + calls.append(args) + return True + + monkeypatch.setattr(store, "_has_opener", has_opener) + assert len(_index("[a](b) " * 50).index_targets()) == 50 + assert calls == [] + + +def _spaced(n: int) -> str: + return "[ " + "a](b) " * n # one opener, then links with none: each scan back ran to the paragraph's start + + +def _lined(n: int) -> str: + return "[\n" + "a](b)\n" * n + + +def _slashed(n: int) -> str: + return "\\[a](b) " * n + + +@pytest.mark.parametrize("shape", [_spaced, _lined, _slashed]) +def test_finding_the_openers_of_many_links_grows_linearly(shape) -> None: + def timed(k: int): + text = shape(k) + closes = {m.start() for m in re.finditer(r"\]\(", text)} + return partial(store._closing_openers, text, closes) + + ratio, result = growth(timed, 2000) + assert ratio < GROWTH_LIMIT + assert len(result) == (0 if shape is _slashed else 1) From a144aa92eae693fd1cc46a7bdd4d5dc447c2e9bc Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Mon, 30 Nov 2026 11:29:42 +0000 Subject: [PATCH 2/2] fix(memory): look up the link span of a label by bisection (#1262) After the opener walk, index_targets on `"[a](b) " * n` was still quadratic: _used_labels tested every label of a line against every link span of the line with `any(...)`, and a line of n links has n spans and n labels. The spans are now sorted and merged once per line and each label is looked up with bisect_right, with the same answer as the any() test. Measured, `"[a](b) " * n` takes 0.001, 0.003, 0.005 s at n = 500, 1000, 2000. `"[a](b)\n" * n` is not changed here: its time is in prose_lines/_blank_blocks (#1261). Signed-off-by: Anton Volkov --- .../20261130_130000_memory-used-labels-bisect.md | 3 +++ dokimi/dokimi/memory/store.py | 5 +++-- dokimi/tests/test_blank_inline.py | 15 +++++++++++++++ 3 files changed, 21 insertions(+), 2 deletions(-) create mode 100644 dokimi/changelog.d/20261130_130000_memory-used-labels-bisect.md diff --git a/dokimi/changelog.d/20261130_130000_memory-used-labels-bisect.md b/dokimi/changelog.d/20261130_130000_memory-used-labels-bisect.md new file mode 100644 index 000000000..fc6b6ad43 --- /dev/null +++ b/dokimi/changelog.d/20261130_130000_memory-used-labels-bisect.md @@ -0,0 +1,3 @@ +### Fixed + +- **A memory index with many links on one line no longer takes quadratic time to lint** — `memory lint` tested each label of a line against every link span of that line; it now looks the label up by bisection in the sorted spans, with the same labels counted as used (#1262). diff --git a/dokimi/dokimi/memory/store.py b/dokimi/dokimi/memory/store.py index 1516d8a68..004ae2e90 100644 --- a/dokimi/dokimi/memory/store.py +++ b/dokimi/dokimi/memory/store.py @@ -469,7 +469,7 @@ def _used_labels(lines: list[str], source: list[str], defs: dict[int, re.Match]) used: set[str] = set() # the label that opens a definition is not a use of itself for k, line in enumerate(lines): d = defs.get(k) - spans = [m.span() for m in _MD_LINK.finditer(line)] # a label inside a destination or title is no use + span_starts, span_ends = _merged([m.span() for m in _MD_LINK.finditer(line)]) # a label inside a destination or title is no use begin = d.end() if d else 0 if d and d.end() > len(line): # the destination is on the next line: the label line holds no use begin = len(line) @@ -477,7 +477,8 @@ def _used_labels(lines: list[str], source: list[str], defs: dict[int, re.Match]) begin = above.end() - len(lines[k - 1]) - 1 # the rest of that definition's line is its title labels = list(_MD_LABEL.finditer(line, begin)) for j, m in enumerate(labels): - inside = any(start <= m.start() < end for start, end in spans) + at = bisect_right(span_starts, m.start()) - 1 + inside = at >= 0 and m.start() < span_ends[at] text_of_explicit = j + 1 < len(labels) and labels[j + 1].start() == m.end() # [text][label]: text is no use two = line + "\n" + lines[k + 1] if k + 1 < len(lines) else line # a destination may start on the next line escaped = _escaped(line, m.start()) # \[label] opens no reference diff --git a/dokimi/tests/test_blank_inline.py b/dokimi/tests/test_blank_inline.py index 20f8b52e4..d945bc95d 100644 --- a/dokimi/tests/test_blank_inline.py +++ b/dokimi/tests/test_blank_inline.py @@ -261,6 +261,21 @@ def _slashed(n: int) -> str: return "\\[a](b) " * n +@pytest.mark.parametrize(("text", "used"), [ + ("[a]()", []), ('[a](b "see [c]") [d]', ["d"]), ("[a](b) [c](d) [e]", ["e"]), ("[a](b)[c]", ["c"]), + ("[x] [a](b [c]) [y]", ["a", "c", "x", "y"]), ("[a](b) x [c] [d](e)", ["c"]), +]) +def test_a_label_inside_a_link_destination_or_title_is_no_use(text: str, used: list[str]) -> None: + lines = text.split("\n") + assert sorted(store._used_labels(lines, lines, store._definitions(lines))) == used + + +def test_index_targets_of_many_links_on_one_line_grows_linearly() -> None: + ratio, result = growth(lambda k: _index("[a](b) " * k).index_targets, 500) + assert ratio < GROWTH_LIMIT + assert len(result) == 8000 + + @pytest.mark.parametrize("shape", [_spaced, _lined, _slashed]) def test_finding_the_openers_of_many_links_grows_linearly(shape) -> None: def timed(k: int):