Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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).
Original file line number Diff line number Diff line change
@@ -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).
43 changes: 39 additions & 4 deletions dokimi/dokimi/memory/store.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,8 +116,12 @@
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]):

Check warning on line 124 in dokimi/dokimi/memory/store.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: shift-boundary `m.start() < title_ends[i]` -> `m.start() <= title_ends[i]`

Check warning on line 124 in dokimi/dokimi/memory/store.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: drop-clause `i >= 0 and m.start() < title_ends[i]` -> `(i >= 0)`
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
Expand Down Expand Up @@ -465,15 +469,16 @@
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)
elif (above := defs.get(k - 1)) and above.end() > len(lines[k - 1]):
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
Comment thread
antonwolfy marked this conversation as resolved.
Resolved
escaped = _escaped(line, m.start()) # \[label] opens no reference
Expand Down Expand Up @@ -542,6 +547,36 @@
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]:

Check warning on line 555 in dokimi/dokimi/memory/store.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: shift-boundary `lo <= ends[-1]` -> `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"):

Check warning on line 568 in dokimi/dokimi/memory/store.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: drop-clause `i == 0 or text[i - 1] == "\n"` -> `(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)
Expand Down
84 changes: 84 additions & 0 deletions dokimi/tests/test_blank_inline.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import random
import re
from functools import partial
from pathlib import Path

import pytest

Expand Down Expand Up @@ -202,3 +203,86 @@ 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(("text", "used"), [
("[a](<b [c]>)", []), ('[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):
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)
Loading