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,8 @@
<!--
Copyright (C) 2026 Intel Corporation
SPDX-License-Identifier: Apache-2.0
-->

### Fixed

- **`memory lint` of an index with thousands of reference definitions no longer takes minutes** — it joined the lines of the paragraph for every definition to look for a closing title, and walked back to the start of the paragraph for every line: an index of 2000 lines `[li]: fi.md` took 14.5 s, 8 times what 1000 took. Each title is now read line by line and the paragraph start is tracked down the text, so the time doubles when the index does. The links and definitions found are unchanged.
93 changes: 70 additions & 23 deletions dokimi/dokimi/memory/store.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from bisect import bisect_right
from collections.abc import Callable
from dataclasses import dataclass, field
from functools import cache, partial
from html import unescape
from pathlib import Path
from urllib.parse import unquote
Expand Down Expand Up @@ -45,6 +46,12 @@
_BLANKS = re.compile(_WS)
_ANGLE_LINK = re.compile(r"\]\(" + _WS + r"<[^<>\n]*>(?:\s+(?:\"[^\"]*\"|'[^']*'|\([^()]*\)))?" + _WS + r"\)") # the title grammar of _MD_LINK
_TITLE_CLOSED = re.compile(r"[ \t]+(?:\"(?:\\.|[^\"\\])*\"|'(?:\\.|[^'\\])*'|\((?:\\.|[^()\\])*\))\s*$")
_TITLE_CLOSER = {'"': '"', "'": "'", "(": ")"}
_TITLE_BODY = { # what _TITLE_CLOSED reads between the opener and the closer, one line at a time
'"': re.compile(r"(?:\\.|[^\"\\])*"),
"'": re.compile(r"(?:\\.|[^'\\])*"),
"(": re.compile(r"(?:\\.|[^()\\])*"),
}


class MemoryStoreError(ValueError):
Expand Down Expand Up @@ -156,7 +163,9 @@
in_list = False
code = False # the previous line was an indented code line
close_ahead = _close_ahead(lines)
start = 0 # the line the paragraph of line i begins at

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

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: bump-int `0` -> `1`
for i, line in enumerate(lines):
start = _paragraph_start(lines, i, start)
opener = _fence_opener(line)
if fence:
if _closes_fence(line, fence):
Expand Down Expand Up @@ -185,7 +194,8 @@
if hidden and not pos:
out.append(" " * len(line))
continue
line, comment, run = _blank_inline(line, close_ahead[i], pos, _paragraph_above(lines, out, i))
above = cache(partial(_paragraph_above, out, start, i)) # joined only when a link check reads it, and once
line, comment, run = _blank_inline(line, close_ahead[i], pos, above)
line, span = _open_span(lines, i, line, run)
out.append(line)
return out
Expand Down Expand Up @@ -220,16 +230,34 @@
out = []
for k, d in defs.items():
joined = d.end() > len(lines[k]) # the destination, and so the title, is on line k + 1
for end in range(k + 1 + joined, len(lines) + 1): # a title may run over later lines, up to a blank line
head = "\n".join(lines[k:end])
if _TITLE_CLOSED.match(head[d.end(2):]):
out.append((begin[k] + d.end(2), begin[k] + len(head)))
break
if end == len(lines) or not lines[end].strip():
break
col = d.end(2) - (len(lines[k]) + 1 if joined else 0)
if (last := _title_last_line(lines, k + joined, col)) is not None:
out.append((begin[k] + d.end(2), begin[last] + len(lines[last])))
return out


def _title_last_line(lines: list[str], row: int, col: int) -> int | None:
"""The line where the title that starts after ``col`` on ``lines[row]`` closes, as ``_TITLE_CLOSED`` reads it.

Each line is read once, up to a blank line. The first closer decides: only blanks may follow it on its line.
"""
rest = lines[row][col:]
text = rest.lstrip(" \t") # the destination ends at a blank, so the opener follows one
if text[:1] not in _TITLE_CLOSER:
return None
body, closer = _TITLE_BODY[text[0]], _TITLE_CLOSER[text[0]]
pos = col + len(rest) - len(text) + 1
while True:
line = lines[row]
stop = body.match(line, pos).end() # type: ignore[union-attr] # the body may be empty: it always matches
if stop < len(line): # a closer, or what no title holds: a `(`, or a backslash that ends the line
return row if line[stop] == closer and not line[stop + 1:].strip() else None
row += 1
if row == len(lines) or not lines[row].strip():
return None
pos = 0


def _angle_link_end(line: str, pos: int, before: str = "") -> int | None:
"""End, on ``line``, of the ``](<...>)`` link whose destination holds ``pos``: a backtick there is text, and opens no span.

Expand Down Expand Up @@ -281,16 +309,21 @@
return None


def _paragraph_above(lines: list[str], out: list[str], i: int) -> str:
"""The blanked lines above ``i`` in its paragraph, joined. A raw blank line or fence ends it; a line blanked to spaces does not."""
k = i
while k > 0 and lines[k - 1].strip() and not _FENCE.match(lines[k - 1]): # a fence ends a paragraph too
k -= 1
return "\n".join(out[k:i])
def _paragraph_start(lines: list[str], i: int, start: int) -> int:
"""The line the paragraph of line ``i`` begins at, given ``start`` for line ``i - 1``: a raw blank line or fence ends one."""
return i if i and (not lines[i - 1].strip() or _FENCE.match(lines[i - 1])) else start

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

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: drop-clause `i and (not lines[i - 1].strip() or _FENCE.match(lines[i - 1]))` -> `(i)`

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

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: take-branch `i if i and (not lines[i - 1].strip() or _FENCE.match(lines[i - 1])) else start` -> `(start)`

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

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: take-branch `i if i and (not lines[i - 1].strip() or _FENCE.match(lines[i - 1])) else start` -> `(i)`

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

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: return-none `i if i and (not lines[i - 1].strip() or _FENCE.match(lines[i - 1])) else start` -> `None`


def _paragraph_above(out: list[str], start: int, i: int) -> str:
"""The blanked lines of the paragraph that starts at line ``start``, up to line ``i``, joined."""
return "\n".join(out[start:i])

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

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: return-none `"\n".join(out[start:i])` -> `None`

def _unpaired_run(line: str, before: str = "") -> re.Match | None:

def _unpaired_run(line: str, before: str | Callable[[], str] = "") -> re.Match | None:
"""The first backtick run left on ``line`` whose first backtick is not escaped and not in a ``<...>`` destination."""
if not _BACKTICK_RUN.search(line):
return None # the paragraph above is read only for a run
before = before() if callable(before) else before
head = before + "\n" if before else ""
text = head + line
opens = [m.start() for m in re.finditer(r"\]\(", text)]
Expand Down Expand Up @@ -373,28 +406,38 @@
reads the text before it, and it builds the blanked line when a ``](`` the blanks left may open a link.
"""

def __init__(self, line: str, before: str) -> None:
def __init__(self, line: str, before: str | Callable[[], str]) -> None:
self.line = line
self.before = before
self.ranges: list[tuple[int, int]] = []
self._prefix_text = before + "\n" if before else "" # the paragraph above, newline-terminated, built once
self._head = len(self._prefix_text)
self._found = [m.start() for m in re.finditer(r"\]\(", self._prefix_text + line)]
self._prefix_text = "" # the paragraph above, newline-terminated, built once, when a blank or a link check first reads it

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

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: delete-statement `self._prefix_text = ""` -> `pass`
self._head = 0

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

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: bump-int `0` -> `1`

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

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: delete-statement `self._head = 0` -> `pass`
self._found: list[int] | None = None
self._next = 0
self._last: int | None = None # the last ``](`` before the scan point that no blank touched
self._links = _LinkCache(final=False)
self._prefix = "" # the blanked line up to ``_ends``, for the ranges before ``_seen``
self._ends = 0
self._seen = 0

def _opens(self) -> list[int]:
if self._found is None:
before = self.before() if callable(self.before) else self.before
self._prefix_text = before + "\n" if before else ""

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

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: take-branch `before + "\n" if before else ""` -> `(before + "\n")`
self._head = len(self._prefix_text)
self._found = [m.start() for m in re.finditer(r"\]\(", self._prefix_text + self.line)]
return self._found

def _advance(self, upto: int) -> None:
while self._next < len(self._found) and self._found[self._next] + 2 <= upto + self._head:
self._last = self._found[self._next]
found = self._opens()
while self._next < len(found) and found[self._next] + 2 <= upto + self._head:
self._last = found[self._next]
self._next += 1

def blank(self, start: int, end: int) -> None:
self._advance(start)
while self._next < len(self._found) and self._found[self._next] < end + self._head:
found = self._opens()
while self._next < len(found) and found[self._next] < end + self._head:
self._next += 1 # a ``](`` the blank touches is gone
self.ranges.append((start, end))

Expand Down Expand Up @@ -423,9 +466,13 @@
return end - self._head if end is not None else None


def _blank_inline(line: str, closes_ahead: bool, pos: int = 0, before: str = "") -> tuple[str, str, re.Match | None]:
def _blank_inline(
line: str, closes_ahead: bool, pos: int = 0, before: str | Callable[[], str] = ""
) -> tuple[str, str, re.Match | None]:
"""Blank the code spans and the comments of ``line``, left to right: whichever starts first holds the text after it.

``before`` is the paragraph above, or a call that builds it: it is called only when a link check needs it.

Returns the line, the kind of a comment it leaves open, and a backtick run left unpaired on the line (its
span may close on a later line). A comment opened mid-line with no ``-->`` in its paragraph
(``closes_ahead`` False) is plain text, as Markdown reads it, so the scan goes on past it.
Expand Down
170 changes: 170 additions & 0 deletions dokimi/tests/test_memory_index_definitions_linear.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
# Copyright (C) 2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

"""``index_targets`` on an index of many reference definitions reads each line a bounded number of times (#1263).

The title scan reads each line of a title once instead of joining the lines per candidate end, and the
paragraph above a line is found by a start tracked down the text, not by a walk back per line. The work is
counted, not timed.
"""

from __future__ import annotations

import random
from collections.abc import Callable
from pathlib import Path

import pytest

from dokimi.memory import store
from dokimi.memory.store import MemoryEntry, MemoryStore, _definitions, _title_spans
from tests.work_count import WORK_LIMIT, count_calls, count_pattern, work_ratio


def _targets(text: str) -> list[tuple[int, str, bool]]:
return MemoryStore(Path("/x"), MemoryEntry("MEMORY.md", text, text, None), []).index_targets()


def _plain(n: int) -> str:
return "".join(f"[l{i}]: f{i}.md\n" for i in range(n))


def _unclosed(n: int) -> str:
return "".join(f"[l{i}]: f{i}.md 'a\n" for i in range(n))


REPROS = [pytest.param(_plain, id="no-title"), pytest.param(_unclosed, id="unclosed-title")]


def _old_title_spans(lines: list[str], begin: list[int], defs: dict) -> list[tuple[int, int]]:
"""The version that joined ``lines[k:end]`` for each candidate ``end`` and matched ``_TITLE_CLOSED`` on the join."""
out = []
for k, d in defs.items():
joined = d.end() > len(lines[k])
for end in range(k + 1 + joined, len(lines) + 1):
head = "\n".join(lines[k:end])
if store._TITLE_CLOSED.match(head[d.end(2):]):
out.append((begin[k] + d.end(2), begin[k] + len(head)))
break
if end == len(lines) or not lines[end].strip():
break
return out


def _every_definition(lines: list[str]) -> dict:
"""The definitions the pattern matches, with no check that a title closes: the scan is also handed these."""
out = {}
for k, line in enumerate(lines):
m = store._MD_REF_DEF.match(line) or (k + 1 < len(lines) and store._MD_REF_DEF.match(line + "\n" + lines[k + 1]))
if m:
out[k] = m
return out


def _spans_both(text: str, every: bool = False) -> tuple[list[tuple[int, int]], list[tuple[int, int]]]:
lines = text.split("\n")
begin = [0]
for line in lines:
begin.append(begin[-1] + len(line) + 1)
defs = _every_definition(lines) if every else _definitions(lines)
return _title_spans(lines, begin, defs), _old_title_spans(lines, begin, defs)


AWKWARD = [
"[a]: f.md 'x'",
'[a]: f.md "x"',
"[a]: f.md (x)",
"[a]: f.md 'x' y",
"[a]: f.md 'x' ",
"[a]: f.md\t'x'",
"[a]: f.md'x'",
"[a]: f.md 'x\ny'",
"[a]: f.md 'x\ny' z",
"[a]: f.md 'x\ny\nz'",
"[a]: f.md 'x\n\ny'",
"[a]: f.md 'x\n \ny'",
"[a]: f.md (x\n(y)",
"[a]: f.md (x(y)",
"[a]: f.md (x\ny)",
"[a]: f.md 'x\\'\ny'",
"[a]: f.md 'x\\\ny'",
"[a]: f.md 'x\\\\\ny'",
"[a]: f.md 'x\\",
"[a]: f.md \"x'\ny'\"",
"[a]:\nf.md 'x'",
"[a]:\nf.md 'x\ny'",
"[a]:\nf.md 'x\ny' z",
"[a]:\nf.md",
"[a]: f.md 'x'\n[b]: g.md 'y'",
"[a]: f.md 'x\n[b]: g.md 'y'",
"[a]: f.md 'x\n[b]: g.md \"y\"\nz'",
"[a]: f.md 'x\n[b]: g.md 'y",
"[a]: f.md 'x\n\n[b]: g.md 'y'",
"[a]: f.md\n'x'",
"[a]: f.md '",
"[a]: f.md 'x\n",
]


@pytest.mark.parametrize("every", [False, True], ids=["checked-definitions", "every-match"])
@pytest.mark.parametrize("text", AWKWARD)
def test_the_line_scan_gives_the_spans_of_the_join_scan_on_awkward_paragraphs(text: str, every: bool) -> None:
new, old = _spans_both(text, every)
assert new == old, text


def test_a_two_line_title_is_a_span_that_holds_the_links_on_both_lines() -> None:
text = "[a]: f.md 'x [l](one.md)\ny [m](two.md)'\n[n](three.md)\n"
assert _spans_both(text)[0] == [(9, 39)]
assert [target for _, target, _ in _targets(text)] == ["f.md", "three.md"]


def test_a_title_that_cannot_close_is_no_span_and_its_links_stay() -> None:
text = "[a]: f.md 'x [l](one.md)\ny' z\n"
assert _spans_both(text)[0] == []
assert "one.md" in [target for _, target, _ in _targets(text)]


def test_the_line_scan_gives_the_spans_of_the_join_scan_on_random_paragraphs() -> None:
rng = random.Random(1263)
pieces = ["[a]: f.md", "[b]:", "g.md", " ", " ", "'", "'", '"', "(", ")", "\\", "x", "y", "\n", "\n", "\n\n", " ", "\t"]
differing = []
for _ in range(3000):
text = "".join(rng.choice(pieces) for _ in range(rng.randint(1, 24)))
for every in (False, True):
new, old = _spans_both(text, every)
if new != old:
differing.append(text)
assert not differing[:3]


@pytest.mark.parametrize("shape", REPROS)
def test_a_title_is_matched_on_its_own_lines_not_on_a_join_per_candidate_end(monkeypatch: pytest.MonkeyPatch, shape: Callable[[int], str]) -> None:
tally = count_pattern(monkeypatch, store, "_TITLE_CLOSED")
text = shape(960)
_targets(text)
assert tally.size <= len(text) # the join scan reads the paragraph again for every candidate end of every definition


@pytest.mark.parametrize("shape", REPROS)
def test_the_paragraph_start_is_tracked_not_found_by_a_walk_back_per_line(monkeypatch: pytest.MonkeyPatch, shape: Callable[[int], str]) -> None:
tally = count_pattern(monkeypatch, store, "_FENCE")
assert work_ratio(tally, lambda n: _targets(shape(n)), 60) < WORK_LIMIT


@pytest.mark.parametrize("shape", REPROS)
def test_the_paragraph_above_is_not_joined_for_a_line_with_no_code_span_or_comment(monkeypatch: pytest.MonkeyPatch, shape: Callable[[int], str]) -> None:
tally = count_calls(monkeypatch, store, "_paragraph_above", size=lambda *args, **kwargs: 1)
_targets(shape(200))
assert tally.calls == 0


def test_the_paragraph_above_is_joined_once_for_a_line_that_reads_it_twice(monkeypatch: pytest.MonkeyPatch) -> None:
tally = count_calls(monkeypatch, store, "_paragraph_above", size=lambda *args, **kwargs: 1)
_targets("[x]: a.md\n`a` `\n") # the span is blanked, then the backtick left over is checked against the links above
assert tally.calls == 1


def test_the_index_of_definitions_gives_its_targets() -> None:
assert _targets(_plain(3)) == [(1, "f0.md", False), (2, "f1.md", False), (3, "f2.md", False)]
assert _targets(_unclosed(2)) == [(1, "f0.md", False)] # the last definition opens a title that never closes: no definition
Loading