From 0b8913e3a45326f2b67a9a9e2a96b8db81281f71 Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Mon, 30 Nov 2026 11:07:37 +0000 Subject: [PATCH 1/6] fix(memory): lint a paragraph of many lines in linear time (#1261) _blank_blocks joined the blanked paragraph above for every line (_paragraph_above walked back to the paragraph start and joined the rows), _BlankedLine scanned that text again for every ](, and _unpaired_run built it a second time, so a paragraph of n lines cost O(n^2): "word `a` word\n" * n took 0.011, 0.036, 0.129 and 0.486 s at n = 250, 500, 1000 and 2000. _blank_blocks now keeps an _Above for the paragraph: the start of the paragraph (reset after a raw blank line or a fence line, not after a line blanked to spaces), the offset of each row and the last ](. _BlankedLine, _unpaired_run and _angle_link_end read the last ]( of the rows above and the ]( of the line, and the opener of a ]( is looked up by offset through _Text, which reads the rows without joining them. The text of a link is joined from the row of its ]( on, only when a ]( that may still match is read. _blank_inline, _unpaired_run and _angle_link_end still take the paragraph above as a string, and the output is unchanged. test_blank_inline.py: the test that counted a newline appended to the paragraph above (twice) now asserts that the text read for a link on the line holds no row above, under the name test_the_paragraph_above_is_not_copied_for_a_link_on_the_line. Test-narrowed: test_the_paragraph_above_is_copied_with_its_newline_once_not_once_per_span is renamed, not removed: the paragraph above is no longer passed as a string that a newline is appended to, so the test now checks that no row above is joined to the line. tests/test_blank_paragraph.py pins the growth in the lines of a paragraph and the output against the joined paragraph, with counterexamples and seeded random texts. Signed-off-by: Anton Volkov --- ...20261130_100000_memory-paragraph-linear.md | 8 + dokimi/dokimi/memory/store.py | 152 +++++++++++++----- dokimi/tests/test_blank_inline.py | 25 ++- dokimi/tests/test_blank_paragraph.py | 117 ++++++++++++++ 4 files changed, 249 insertions(+), 53 deletions(-) create mode 100644 dokimi/changelog.d/20261130_100000_memory-paragraph-linear.md create mode 100644 dokimi/tests/test_blank_paragraph.py diff --git a/dokimi/changelog.d/20261130_100000_memory-paragraph-linear.md b/dokimi/changelog.d/20261130_100000_memory-paragraph-linear.md new file mode 100644 index 000000000..4580a8558 --- /dev/null +++ b/dokimi/changelog.d/20261130_100000_memory-paragraph-linear.md @@ -0,0 +1,8 @@ + + +### Fixed + +- **`dokimi memory` reads a paragraph of many lines in time linear in its lines** — the memory lint joined the blanked paragraph above for every line and scanned it again, so `"word `a` word\n" * 2000` took 0.49 s, 3.7 times what 1000 lines took. It now keeps the start of the paragraph and the offsets it needs as it goes, with the same output. diff --git a/dokimi/dokimi/memory/store.py b/dokimi/dokimi/memory/store.py index 4766ab414..b0f1261bf 100644 --- a/dokimi/dokimi/memory/store.py +++ b/dokimi/dokimi/memory/store.py @@ -16,6 +16,7 @@ from dataclasses import dataclass, field from html import unescape from pathlib import Path +from typing import Protocol from urllib.parse import unquote import yaml @@ -156,7 +157,9 @@ def _blank_blocks(lines: list[str]) -> list[str]: in_list = False code = False # the previous line was an indented code line close_ahead = _close_ahead(lines) + above = _Above(out) for i, line in enumerate(lines): + above.reach(lines, i) opener = _fence_opener(line) if fence: if _closes_fence(line, fence): @@ -185,7 +188,7 @@ def _blank_blocks(lines: list[str]) -> list[str]: 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)) + line, comment, run = _blank_inline(line, close_ahead[i], pos, above) line, span = _open_span(lines, i, line, run) out.append(line) return out @@ -230,17 +233,89 @@ def _title_spans(lines: list[str], begin: list[int], defs: dict[int, re.Match]) return out -def _angle_link_end(line: str, pos: int, before: str = "") -> int | None: +def _angle_link_end(line: str, pos: int, before: str | _Above = "") -> int | None: """End, on ``line``, of the ``](<...>)`` link whose destination holds ``pos``: a backtick there is text, and opens no span. Its ``]`` must close an opener in the paragraph, which may begin on the lines above (``before``). """ - head = before + "\n" if before else "" - text = head + line - p = len(head) + pos - i = text.rfind("](", 0, p) - end = _LinkCache(final=True).end(lambda: text, i, p) if i >= 0 else None - return end - len(head) if end is not None else None + above = _above(before) + found = line.rfind("](", 0, pos) + at = above.head + found if found >= 0 else above.last_open + if at is None: + return None + # mutation-ok[flip-bool]: the cache lives for this one call, and ``final`` only marks a ``](`` dead for the next + end = _LinkCache(final=True).end(lambda: _Text(above, line), at, above.head + pos) + return end - above.head if end is not None else None + + +class _Above: + """The blanked lines above a line in its paragraph: the shared list ``rows``, which ends there, from ``start``. + + The text a link check reads is ``"\\n".join(rows)``, a newline and the line. This keeps what a check needs of + it as the scan goes (the offset of each row, the last ``](``), so the rows are never joined or scanned per line. + """ + + def __init__(self, rows: list[str]) -> None: + self.rows = rows + self.start = 0 + self.begins = [0] # the offset of each row scanned in the text, then of the line after them + self.last_open: int | None = None # the offset of the last ``](`` in the rows scanned + + @classmethod + def of(cls, before: str) -> _Above: + # mutation-ok[take-branch]: a leading empty row only moves every offset by one + above = cls(before.split("\n") if before else []) + above.sync() + return above + + @property + def head(self) -> int: + """The offset of the line in the text.""" + return self.begins[-1] + + def reach(self, lines: list[str], i: int) -> None: + """Move to line ``i``: a raw blank line or a fence line above it ends the paragraph; a line blanked to spaces does not.""" + if i and (not lines[i - 1].strip() or _FENCE.match(lines[i - 1])): # mutation-ok[drop-clause]: a reset at line 0 changes nothing + self.start = i + self.begins = [0] + self.last_open = None + self.sync() + + def sync(self) -> None: + """Scan the rows not scanned yet, once each.""" + for j in range(self.start + len(self.begins) - 1, len(self.rows)): + row = self.rows[j] + if (k := row.rfind("](")) >= 0: + self.last_open = self.begins[-1] + k + self.begins.append(self.begins[-1] + len(row) + 1) + + +def _above(before: str | _Above) -> _Above: + return before if isinstance(before, _Above) else _Above.of(before) + + +class _Text: + """The text of the paragraph above and ``line``, read by offset without joining the rows.""" + + def __init__(self, above: _Above, line: str) -> None: + self.above = above + self.line = line + + def __getitem__(self, i: int) -> str: + above = self.above + if i >= above.head: + return self.line[i - above.head] + t = bisect_right(above.begins, i) - 1 + row = above.rows[above.start + t] + return row[i - above.begins[t]] if i - above.begins[t] < len(row) else "\n" + + def tail(self, i: int) -> tuple[str, int]: + """The text from the row that holds offset ``i`` to the end of the line, and the offset of that row.""" + above = self.above + if i >= above.head: + return self.line, above.head + t = bisect_right(above.begins, i) - 1 + return "\n".join(above.rows[above.start + t:]) + "\n" + self.line, above.begins[t] class _LinkCache: @@ -258,7 +333,7 @@ def __init__(self, final: bool) -> None: self._opened: set[int] = set() self._ends: dict[int, int] = {} - def end(self, text_of: Callable[[], str], i: int, p: int) -> int | None: + def end(self, text_of: Callable[[], _Text], i: int, p: int) -> int | None: """The end of the link the ``](`` at ``i`` starts when it is past ``p``; ``text_of`` builds the text, only when it is read.""" if i in self._dead: return None @@ -270,34 +345,29 @@ def end(self, text_of: Callable[[], str], i: int, p: int) -> int | None: self._dead.add(i) return None self._opened.add(i) - m = _ANGLE_LINK.match(text, i) + tail, shift = text.tail(i) # the ``](`` and what follows it: the rows above it are not read + m = _ANGLE_LINK.match(tail, i - shift) if m: - self._ends[i] = m.end() - return m.end() if m.end() > p else None - blanks = _BLANKS.match(text, i + 2) - j = blanks.end() if blanks else i + 2 - if self.final or (j < p and not text.startswith("<", j)): + self._ends[i] = m.end() + shift + return self._ends[i] if self._ends[i] > p else None + blanks = _BLANKS.match(tail, i - shift + 2) # mutation-ok[swap-addsub]: a wrong j only marks the ``](`` dead later or never + # mutation-ok[take-branch]: _BLANKS matches the empty string, so there is always a match + j = blanks.end() if blanks else i - shift + 2 + # mutation-ok[drop-clause]: a ``](`` not marked dead is read again, with the same answer + if self.final or (j + shift < p and not tail.startswith("<", j)): self._dead.add(i) 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 _unpaired_run(line: str, before: str = "") -> re.Match | None: +def _unpaired_run(line: str, before: str | _Above = "") -> re.Match | None: """The first backtick run left on ``line`` whose first backtick is not escaped and not in a ``<...>`` destination.""" - head = before + "\n" if before else "" - text = head + line - opens = [m.start() for m in re.finditer(r"\]\(", text)] + above = _above(before) + text = _Text(above, line) + opens = ([] if above.last_open is None else [above.last_open]) + [above.head + m.start() for m in re.finditer(r"\]\(", line)] links = _LinkCache(final=True) def in_link(pos: int) -> bool: - p = len(head) + pos + p = above.head + pos k = bisect_right(opens, p - 2) - 1 return k >= 0 and links.end(lambda: text, opens[k], p) is not None @@ -373,13 +443,12 @@ class _BlankedLine: 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, above: _Above) -> None: self.line = line - self.before = before + self.above = above 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._head = above.head + self._found = ([] if above.last_open is None else [above.last_open]) + [self._head + m.start() for m in re.finditer(r"\]\(", line)] self._next = 0 self._last: int | None = None # the last ``](`` before the scan point that no blank touched self._links = _LinkCache(final=False) @@ -419,11 +488,11 @@ def angle_link_end(self, pos: int) -> int | None: self._advance(pos) if self._last is None: return None - end = self._links.end(lambda: self._prefix_text + self._so_far(), self._last, self._head + pos) + end = self._links.end(lambda: _Text(self.above, self._so_far()), self._last, self._head + pos) 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 | _Above = "") -> 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. Returns the line, the kind of a comment it leaves open, and a backtick run left unpaired on the line (its @@ -431,7 +500,8 @@ def _blank_inline(line: str, closes_ahead: bool, pos: int = 0, before: str = "") (``closes_ahead`` False) is plain text, as Markdown reads it, so the scan goes on past it. """ scan = CodeSpanScanner(line, pos, stop=LINE_BREAK) - blanked = _BlankedLine(line, before) + above = _above(before) + blanked = _BlankedLine(line, above) start = line.find("`` is left from a comment start on: none is left from a later one while True: @@ -440,7 +510,7 @@ def _blank_inline(line: str, closes_ahead: bool, pos: int = 0, before: str = "") start = line.find(" `a` `b`", + "](<`a`>) `b`", ] @@ -142,23 +143,19 @@ def counting(text: str, close: int) -> bool: assert len(calls) == 2 # once while the spans are blanked, once for the unpaired run left at the end -class _CountingBefore(str): - """A paragraph above that counts how often a newline is appended to it, as a copy of the paragraph.""" +def test_the_paragraph_above_is_not_copied_for_a_link_on_the_line(monkeypatch: pytest.MonkeyPatch) -> None: + read: list[int] = [] + real = store._Text.tail - appended = 0 + def counting(self: store._Text, i: int) -> tuple[str, int]: + text, shift = real(self, i) + read.append(len(text) - len(self.line)) # what the text read holds beyond the line + return text, shift - def __add__(self, other: str) -> str: - if other == "\n": - type(self).appended += 1 - return str.__add__(self, other) - - -def test_the_paragraph_above_is_copied_with_its_newline_once_not_once_per_span() -> None: - _CountingBefore.appended = 0 - before = _CountingBefore("[open " + "x" * 1000) - out, _, _ = _blank_inline("]() " + _ticks(500) + "`b", False, 0, before) + monkeypatch.setattr(store._Text, "tail", counting) + out, _, _ = _blank_inline("]() " + _ticks(500) + "`b", False, 0, "[open " + "x" * 1000) assert out.startswith("]() ") - assert _CountingBefore.appended == 2 # one for the blanked line, one for the unpaired run left at the end + assert read and set(read) == {0} # a link on the line is read from the line: no row above is joined to it def test_the_backtick_runs_of_one_destination_are_checked_against_one_lookup_of_its_opener(monkeypatch: pytest.MonkeyPatch) -> None: diff --git a/dokimi/tests/test_blank_paragraph.py b/dokimi/tests/test_blank_paragraph.py new file mode 100644 index 000000000..2034ad57d --- /dev/null +++ b/dokimi/tests/test_blank_paragraph.py @@ -0,0 +1,117 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""``prose_lines`` blanks a paragraph of many lines in time linear in its lines, with the output the joined paragraph gave (#1261).""" + +from __future__ import annotations + +import random +from functools import partial + +import pytest + +from dokimi.memory import store +from dokimi.memory.store import _blank_blocks, _has_opener, prose_lines +from tests import test_blank_inline +from tests.growth_timing import GROWTH_LIMIT, growth + + +def _old_paragraph_above(lines: list[str], out: list[str], i: int) -> str: + """The paragraph above line ``i`` as it was found and joined for every line.""" + k = i + while k > 0 and lines[k - 1].strip() and not store._FENCE.match(lines[k - 1]): + k -= 1 + return "\n".join(out[k:i]) + + +def _ref_angle_link_end(line: str, pos: int, before: str = "") -> int | None: + head = before + "\n" if before else "" + text = head + line + i = text.rfind("](", 0, len(head) + pos) + if i < 0 or not _has_opener(text, i): + return None + m = store._ANGLE_LINK.match(text, i) + return m.end() - len(head) if m and m.end() > len(head) + pos else None + + +def _ref_unpaired_run(line: str, before: str = ""): + for m in store._BACKTICK_RUN.finditer(line): + if not store._escaped(line, m.start()) and _ref_angle_link_end(line, m.start(), before) is None: + return m + return None + + +def _reference(lines: list[str], monkeypatch: pytest.MonkeyPatch) -> list[str]: + """``_blank_blocks`` with the paragraph above joined for every line and scanned as text, with no cache.""" + + def blank_inline(line, closes_ahead, pos, above): + before = above if isinstance(above, str) else _old_paragraph_above(lines, above.rows, len(above.rows)) + return test_blank_inline._rebuilding(line, closes_ahead, pos, before) + + with monkeypatch.context() as mp: + mp.setattr(test_blank_inline, "_angle_link_end", _ref_angle_link_end) + mp.setattr(test_blank_inline, "_unpaired_run", _ref_unpaired_run) + mp.setattr(store, "_blank_inline", blank_inline) + return _blank_blocks(lines) + + +COUNTEREXAMPLES = [ + "[x]() `c`", # a destination that goes on at the next line + "[x]() `c`\n`d` `e`\n[y](<`f`>) `g`", + "[open\n" + "word `a` word\n" * 20 + "x](<`b`>) `c`", # an opener many lines above + "[open\n``` `a`\n](<`b`>) `c`", # a fence ends the paragraph, even one that opens no block + "[open\n```\nx\n```\n](<`b`>) `c`", + "[open\n`x`\n](<`b`>) `c`", # a line blanked to spaces does not end it + "[open\n\n](<`b`>) `c`", + "[open\n\n](<`b`>) `c`", + "".join(f"[x{k}](<`a`>) `b` ](<`c`>)\n" for k in range(12)), # every line holds a ]( + "".join(f"x](<`a{k}`>) `b` [y\n" for k in range(12)), + "[x](\n<`a`>) `b`\n[y](\n<`c`> \"t\n`d`\") `e`", + "`a\nb` [x](<`c`>)\n`d", + "[yyyy](\n\n[x](<`a`>) `b`", # the ]( of the paragraph before is not the one above + "z\n\n[x\ny](\n<`a`>) `b`", # a ]( in the second row of a paragraph that is not the first + "z\n\n[open\n`x`\n](<`b`>) `c`", +] + + +@pytest.mark.parametrize("text", COUNTEREXAMPLES) +def test_a_paragraph_blanks_as_the_joined_paragraph_above_did(text: str, monkeypatch: pytest.MonkeyPatch) -> None: + assert prose_lines(text) == _reference(text.split("\n"), monkeypatch) + + +def test_the_paragraph_above_is_the_lines_after_the_last_raw_blank_line_or_fence() -> None: + assert prose_lines("[open\n``` `a`\n](<`b`>) `c`") == ["[open", "``` ", "](< >) "] # no opener: the link is no link + assert prose_lines("[open\n`x`\n](<`b`>) `c`") == ["[open", " ", "](<`b`>) "] # the opener is in the paragraph + + +def test_a_link_destination_goes_on_at_the_next_line_as_it_did() -> None: + assert prose_lines("[x]() `c`") == ["[x]() "] + assert store._blank_inline("`b`>) `c`", False, 0, "[x]() ", "", None) + + +def test_the_blanked_lines_match_on_short_seeded_random_texts(monkeypatch: pytest.MonkeyPatch) -> None: + rng = random.Random(1261) + pieces = ["`", "``", "`a`", "", "[a](<", ">)", "](", "[", "]", " ", "\\", "x", "\n", "\n", "\n\n", "```\n", "~~~\n", " ", "- ", "# "] + for _ in range(2500): + text = "".join(rng.choice(pieces) for _ in range(rng.randrange(1, 24))) + assert prose_lines(text) == _reference(text.split("\n"), monkeypatch), text + + +def _ticks(k: int) -> str: + return "word `a` word\n" * k + + +def _links(k: int) -> str: + return "[x]() word `a` word\n" * k + + +def _opener_at_the_top(k: int) -> str: + return "[open\n" + _ticks(k) + + +@pytest.mark.parametrize("shape, first", [(_ticks, "word word"), (_links, "[x]() word word"), (_opener_at_the_top, "[open")]) +def test_a_paragraph_of_many_lines_grows_linearly_in_its_lines(shape, first: str) -> None: + ratio, result = growth(lambda k: partial(prose_lines, shape(k)), 200) + assert ratio < GROWTH_LIMIT + assert result[0] == first + assert len(result) == 16 * 200 + 1 + (shape is _opener_at_the_top) From 14c0afea3827c63882ffffd99eedacb47f665c24 Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Mon, 30 Nov 2026 17:31:38 +0000 Subject: [PATCH 2/6] fix(memory): a link the rows above settle is not read again for every line below (#1261) Settles the review thread on `_Above.last_open` and the review summary that found the same growing suffix: the last `](` of the rows above stayed as the paragraph went on, so every later line with a code span or an unpaired backtick joined the rows from that link's row to the line, even when the link had ended on its own row. `"[x]() z\n" + "word `a` word\n" * n` read 1.76, 7.02 and 28.0 million characters at n = 500, 1000 and 2000. `_Above.sync` now drops the last `](` once the rows alone decide it: its link closes in them, or what follows the blanks after it is no `<`. Text added after the rows cannot change either answer, and a link that ends in the rows ends before any line below, so the output is unchanged (the differential test against the joined paragraph passes, with counterexamples for a title that closes rows later and a destination that starts after blanks at the end of the rows). A link still open is read from its own row on, as before. Those lines read no row above now. Test-narrowed: test_the_paragraph_above_is_not_joined_for_a_line_with_no_code_span_or_comment is renamed, not removed: main's `_paragraph_above` join, which it counted, is gone with the merge of this branch's `_Above`, so test_the_paragraph_above_is_not_read_for_a_line_with_no_code_span_or_comment counts the reads of the paragraph above (`_Text.tail`) on the same inputs and asserts none. Test-narrowed: test_the_paragraph_above_is_joined_once_for_a_line_that_reads_it_twice is renamed, not removed: the paragraph above is no longer joined at all for that input, so test_the_paragraph_above_is_not_read_for_a_backtick_left_over_when_no_link_is_above asserts that no row above is read for it. Signed-off-by: Anton Volkov --- dokimi/dokimi/memory/store.py | 23 ++++++- dokimi/tests/test_blank_paragraph.py | 65 +++++++++++++++++++ .../test_memory_index_definitions_linear.py | 2 + 3 files changed, 88 insertions(+), 2 deletions(-) diff --git a/dokimi/dokimi/memory/store.py b/dokimi/dokimi/memory/store.py index dad791b66..bc0415750 100644 --- a/dokimi/dokimi/memory/store.py +++ b/dokimi/dokimi/memory/store.py @@ -276,14 +276,16 @@ class _Above: """The blanked lines above a line in its paragraph: the shared list ``rows``, which ends there, from ``start``. The text a link check reads is ``"\\n".join(rows)``, a newline and the line. This keeps what a check needs of - it as the scan goes (the offset of each row, the last ``](``), so the rows are never joined or scanned per line. + it as the scan goes (the offset of each row, the last ``](`` whose link the rows have not settled), so the + rows are never joined or scanned per line. """ def __init__(self, rows: list[str]) -> None: self.rows = rows self.start = 0 self.begins = [0] # the offset of each row scanned in the text, then of the line after them - self.last_open: int | None = None # the offset of the last ``](`` in the rows scanned + self.last_open: int | None = None # the offset of the last ``](`` in the rows scanned, unless its link is settled + self._open_row = 0 # its row, counted from ``start`` # mutation-ok[bump-int,delete-statement]: read only once last_open is set, with the row @classmethod def of(cls, before: str) -> _Above: @@ -311,7 +313,24 @@ def sync(self) -> None: row = self.rows[j] if (k := row.rfind("](")) >= 0: self.last_open = self.begins[-1] + k + self._open_row = j - self.start self.begins.append(self.begins[-1] + len(row) + 1) + self._settle() + + def _settle(self) -> None: + """Drop the last ``](`` once the rows alone decide its link: it closes in them, or what follows the ``](`` is no ``<``. + + Text added after the rows cannot change either answer, and a link that ends in the rows ends before any line + below them, so no line reads it again. A link still open stays, and is read from its own row on. + """ + if self.last_open is None: + return + tail = "\n".join(self.rows[self.start + self._open_row:]) + i = self.last_open - self.begins[self._open_row] + if _ANGLE_LINK.match(tail, i): + self.last_open = None + elif (j := _BLANKS.match(tail, i + 2).end()) < len(tail) and tail[j] != "<": # type: ignore[union-attr] # _BLANKS matches the empty string + self.last_open = None def _above(before: str | _Above) -> _Above: diff --git a/dokimi/tests/test_blank_paragraph.py b/dokimi/tests/test_blank_paragraph.py index 2034ad57d..3528b4574 100644 --- a/dokimi/tests/test_blank_paragraph.py +++ b/dokimi/tests/test_blank_paragraph.py @@ -6,6 +6,7 @@ from __future__ import annotations import random +import re from functools import partial import pytest @@ -14,6 +15,7 @@ from dokimi.memory.store import _blank_blocks, _has_opener, prose_lines from tests import test_blank_inline from tests.growth_timing import GROWTH_LIMIT, growth +from tests.work_count import WORK_LIMIT, Tally, count_calls, work_ratio def _old_paragraph_above(lines: list[str], out: list[str], i: int) -> str: @@ -71,6 +73,12 @@ def blank_inline(line, closes_ahead, pos, above): "[yyyy](\n\n[x](<`a`>) `b`", # the ]( of the paragraph before is not the one above "z\n\n[x\ny](\n<`a`>) `b`", # a ]( in the second row of a paragraph that is not the first "z\n\n[open\n`x`\n](<`b`>) `c`", + "[x]() z\n`a` ](<`b`>) `c`\n`d` `e`", # a link closed on its own row, then another opener + "[x](y) z\n`a` ](<`b`>) `c`", + "[x]( \"\n`a`\nt\") `b`\n`c` `d`", # a title that closes three rows on holds the code span between + "[x](\n\"t\"\n) `a`\n`b`", + "[x](\n<`a`>) `b`\n`c` `d`", # blanks to the end of the rows: the next row may still open the destination + "[x]( \n \n`a` `b`", ] @@ -109,6 +117,63 @@ def _opener_at_the_top(k: int) -> str: return "[open\n" + _ticks(k) +def _closed_link_at_the_top(k: int) -> str: + return "[x]() z\n" + _ticks(k) + + +def _closed_link_below_the_top(k: int) -> str: + return "intro\nmore\n[x]() z\n" + _ticks(k) + + +def _closed_link_below_the_top_each_row(k: int) -> str: + return "intro\n" + "[x]() z\n" * k + + +def _closed_title_at_the_top(k: int) -> str: + return '[x]( "t\nu") z\n' + _ticks(k) + + +def _plain_destination_at_the_top(k: int) -> str: + return "[x](y) z\n" + _ticks(k) + + +def _closed_link_then_unpaired(k: int) -> str: + return "[x]() z\n" + "word ` word\n" * k + + +@pytest.mark.parametrize( + "shape", [_closed_link_at_the_top, _closed_link_below_the_top, _closed_title_at_the_top, _plain_destination_at_the_top, _closed_link_then_unpaired] +) +def test_a_link_settled_in_the_rows_above_is_not_read_again_for_each_line(monkeypatch: pytest.MonkeyPatch, shape) -> None: + tally = count_calls(monkeypatch, store._Text, "tail", size=lambda self, i: len(self.line)) + prose_lines(shape(50)) + assert tally.calls == 0 # each line below it would join the rows from the link's row on + + +class _WholeText: + """``_ANGLE_LINK`` that adds the whole length of each text it matches on, from its start, not from the match position.""" + + def __init__(self, pattern: re.Pattern[str], tally: Tally) -> None: + self.pattern, self.tally = pattern, tally + + def match(self, text: str, pos: int = 0) -> re.Match[str] | None: + self.tally.size += len(text) + self.tally.calls += 1 + return self.pattern.match(text, pos) + + +def test_a_link_is_settled_from_its_own_row_not_from_the_start_of_the_paragraph(monkeypatch: pytest.MonkeyPatch) -> None: + tally = Tally() + monkeypatch.setattr(store, "_ANGLE_LINK", _WholeText(store._ANGLE_LINK, tally)) + assert work_ratio(tally, lambda n: prose_lines(_closed_link_below_the_top_each_row(n)), 60) < WORK_LIMIT + + +def test_a_link_still_open_in_the_rows_above_is_read_from_its_own_row_on(monkeypatch: pytest.MonkeyPatch) -> None: + tally = count_calls(monkeypatch, store._Text, "tail", size=lambda self, i: len(self.line)) + assert prose_lines('[x]( "\n`a`\nt") `b`\n') == ['[x]( "', " ", 't") ', ""] + assert tally.calls > 0 + + @pytest.mark.parametrize("shape, first", [(_ticks, "word word"), (_links, "[x]() word word"), (_opener_at_the_top, "[open")]) def test_a_paragraph_of_many_lines_grows_linearly_in_its_lines(shape, first: str) -> None: ratio, result = growth(lambda k: partial(prose_lines, shape(k)), 200) diff --git a/dokimi/tests/test_memory_index_definitions_linear.py b/dokimi/tests/test_memory_index_definitions_linear.py index eae21df99..5d281cc5c 100644 --- a/dokimi/tests/test_memory_index_definitions_linear.py +++ b/dokimi/tests/test_memory_index_definitions_linear.py @@ -154,12 +154,14 @@ def test_the_paragraph_start_is_tracked_not_found_by_a_walk_back_per_line(monkey @pytest.mark.parametrize("shape", REPROS) def test_the_paragraph_above_is_not_read_for_a_line_with_no_code_span_or_comment(monkeypatch: pytest.MonkeyPatch, shape: Callable[[int], str]) -> None: + # Test-narrowed: renamed, not removed: `_paragraph_above` is gone, so it counts the reads of the paragraph above. tally = count_calls(monkeypatch, store._Text, "tail", size=lambda *args, **kwargs: 1) _targets(shape(200)) assert tally.calls == 0 def test_the_paragraph_above_is_not_read_for_a_backtick_left_over_when_no_link_is_above(monkeypatch: pytest.MonkeyPatch) -> None: + # Test-narrowed: renamed, not removed: the paragraph above is not joined at all now, so no row of it is read. tally = count_calls(monkeypatch, store._Text, "tail", 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 == 0 From 2ce5c7ff461ca3a65a9edc704562363913e83ab7 Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Tue, 1 Dec 2026 10:31:42 +0000 Subject: [PATCH 3/6] fix(memory): a line with no backtick does not read the link left open above it (#1261) Settles the review point that `[x](` followed by plain lines made each line join the rows from the open link on: the scan settled the link in `_Above.sync` for every line, so the work grew with the square of the lines. `_Above.last_open` now settles the link when it is read, and the readers (`_BlankedLine` through a lazy `_found`, `_unpaired_run` after a backtick check) ask only for a line that holds a backtick or reads a link. A plain line never joins the rows. A new test counts the angle-link matches over such a paragraph and expects none; the settled-from-its-own-row test now uses rows with a code span, since only those read the link. Signed-off-by: Anton Volkov --- dokimi/dokimi/memory/store.py | 34 ++++++++++++++++++++-------- dokimi/tests/test_blank_paragraph.py | 9 +++++++- 2 files changed, 33 insertions(+), 10 deletions(-) diff --git a/dokimi/dokimi/memory/store.py b/dokimi/dokimi/memory/store.py index bc0415750..81611a828 100644 --- a/dokimi/dokimi/memory/store.py +++ b/dokimi/dokimi/memory/store.py @@ -14,6 +14,7 @@ from bisect import bisect_right from collections.abc import Callable from dataclasses import dataclass, field +from functools import cached_property from html import unescape from pathlib import Path from typing import Protocol @@ -284,8 +285,8 @@ def __init__(self, rows: list[str]) -> None: self.rows = rows self.start = 0 self.begins = [0] # the offset of each row scanned in the text, then of the line after them - self.last_open: int | None = None # the offset of the last ``](`` in the rows scanned, unless its link is settled - self._open_row = 0 # its row, counted from ``start`` # mutation-ok[bump-int,delete-statement]: read only once last_open is set, with the row + self._open: int | None = None # the offset of the last ``](`` in the rows scanned, until a read settles its link + self._open_row = 0 # its row, counted from ``start`` # mutation-ok[bump-int,delete-statement]: read only once _open is set, with the row @classmethod def of(cls, before: str) -> _Above: @@ -304,7 +305,7 @@ def reach(self, lines: list[str], i: int) -> None: if i and (not lines[i - 1].strip() or _FENCE.match(lines[i - 1])): # mutation-ok[drop-clause]: a reset at line 0 changes nothing self.start = i self.begins = [0] - self.last_open = None + self._open = None self.sync() def sync(self) -> None: @@ -312,10 +313,18 @@ def sync(self) -> None: for j in range(self.start + len(self.begins) - 1, len(self.rows)): row = self.rows[j] if (k := row.rfind("](")) >= 0: - self.last_open = self.begins[-1] + k + self._open = self.begins[-1] + k self._open_row = j - self.start self.begins.append(self.begins[-1] + len(row) + 1) + + @property + def last_open(self) -> int | None: + """The offset of the last ``](`` in the rows whose link they do not settle, or ``None``. + + A line that reads no link (no backtick, no ``](``) never asks, so it never joins the rows. + """ self._settle() + return self._open def _settle(self) -> None: """Drop the last ``](`` once the rows alone decide its link: it closes in them, or what follows the ``](`` is no ``<``. @@ -323,14 +332,14 @@ def _settle(self) -> None: Text added after the rows cannot change either answer, and a link that ends in the rows ends before any line below them, so no line reads it again. A link still open stays, and is read from its own row on. """ - if self.last_open is None: + if self._open is None: return tail = "\n".join(self.rows[self.start + self._open_row:]) - i = self.last_open - self.begins[self._open_row] + i = self._open - self.begins[self._open_row] if _ANGLE_LINK.match(tail, i): - self.last_open = None + self._open = None elif (j := _BLANKS.match(tail, i + 2).end()) < len(tail) and tail[j] != "<": # type: ignore[union-attr] # _BLANKS matches the empty string - self.last_open = None + self._open = None def _above(before: str | _Above) -> _Above: @@ -404,6 +413,8 @@ def end(self, text_of: Callable[[], _Text], i: int, p: int) -> int | None: def _unpaired_run(line: str, before: str | _Above = "") -> re.Match | None: """The first backtick run left on ``line`` whose first backtick is not escaped and not in a ``<...>`` destination.""" + if "`" not in line: + return None above = _above(before) text = _Text(above, line) opens = ([] if above.last_open is None else [above.last_open]) + [above.head + m.start() for m in re.finditer(r"\]\(", line)] @@ -491,7 +502,6 @@ def __init__(self, line: str, above: _Above) -> None: self.above = above self.ranges: list[tuple[int, int]] = [] self._head = above.head - self._found = ([] if above.last_open is None else [above.last_open]) + [self._head + m.start() for m in re.finditer(r"\]\(", line)] self._next = 0 self._last: int | None = None # the last ``](`` before the scan point that no blank touched self._links = _LinkCache(final=False) @@ -499,6 +509,12 @@ def __init__(self, line: str, above: _Above) -> None: self._ends = 0 self._seen = 0 + @cached_property + def _found(self) -> list[int]: + """The offsets of the ``](`` the scan may need, read only when a span is found: the open one above, then the line's.""" + above = self.above.last_open + return ([] if above is None else [above]) + [self._head + m.start() for m in re.finditer(r"\]\(", self.line)] + 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] diff --git a/dokimi/tests/test_blank_paragraph.py b/dokimi/tests/test_blank_paragraph.py index 3528b4574..b5bdacb67 100644 --- a/dokimi/tests/test_blank_paragraph.py +++ b/dokimi/tests/test_blank_paragraph.py @@ -126,7 +126,7 @@ def _closed_link_below_the_top(k: int) -> str: def _closed_link_below_the_top_each_row(k: int) -> str: - return "intro\n" + "[x]() z\n" * k + return "intro\n" + "[x]() z `a`\n" * k def _closed_title_at_the_top(k: int) -> str: @@ -168,6 +168,13 @@ def test_a_link_is_settled_from_its_own_row_not_from_the_start_of_the_paragraph( assert work_ratio(tally, lambda n: prose_lines(_closed_link_below_the_top_each_row(n)), 60) < WORK_LIMIT +def test_a_line_with_no_backtick_does_not_read_the_link_left_open_above_it(monkeypatch: pytest.MonkeyPatch) -> None: + tally = Tally() + monkeypatch.setattr(store, "_ANGLE_LINK", _WholeText(store._ANGLE_LINK, tally)) + assert prose_lines("[x](\n" + "word word\n" * 50) == ["[x]("] + ["word word"] * 50 + [""] + assert tally.calls == 0 # each plain line would join the rows from the open link on + + def test_a_link_still_open_in_the_rows_above_is_read_from_its_own_row_on(monkeypatch: pytest.MonkeyPatch) -> None: tally = count_calls(monkeypatch, store._Text, "tail", size=lambda self, i: len(self.line)) assert prose_lines('[x]( "\n`a`\nt") `b`\n') == ['[x]( "', " ", 't") ', ""] From 4cd0a130b986d547497f2c3e7dfcb4e374c980be Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Tue, 1 Dec 2026 11:57:54 +0000 Subject: [PATCH 4/6] perf(memory): look up the opener of a link a row at a time, not a character at a time (#1261) Review point: _has_opener read each character of a paragraph through _Text.__getitem__, which does a bisect per character. It now scans the rows above one piece at a time with a regex for the brackets, so the offset of a row is looked up once per call. The test counts the _Text reads of one lookup over 300 rows, and a table checks the same answers on the rows and on the joined text. Signed-off-by: Anton Volkov --- dokimi/dokimi/memory/store.py | 47 +++++++++++++++++++++++------- dokimi/tests/test_blank_inline.py | 48 +++++++++++++++++++++++++++++++ 2 files changed, 85 insertions(+), 10 deletions(-) diff --git a/dokimi/dokimi/memory/store.py b/dokimi/dokimi/memory/store.py index 81611a828..ed848908b 100644 --- a/dokimi/dokimi/memory/store.py +++ b/dokimi/dokimi/memory/store.py @@ -12,7 +12,7 @@ import re from bisect import bisect_right -from collections.abc import Callable +from collections.abc import Callable, Iterator from dataclasses import dataclass, field from functools import cached_property from html import unescape @@ -45,6 +45,7 @@ _BLOCK_START = re.compile(r" {0,3}(?:#{1,6}(?:[ \t]|$)|>)") _BACKTICK_RUN = re.compile(r"(?\n]*>(?:\s+(?:\"[^\"]*\"|'[^']*'|\([^()]*\)))?" + _WS + r"\)") # the title grammar of _MD_LINK _TITLE_CLOSED = re.compile(r"[ \t]+(?:\"(?:\\.|[^\"\\])*\"|'(?:\\.|[^'\\])*'|\((?:\\.|[^()\\])*\))\s*$") _TITLE_CLOSER = {'"': '"', "'": "'", "(": ")"} @@ -369,6 +370,18 @@ def tail(self, i: int) -> tuple[str, int]: t = bisect_right(above.begins, i) - 1 return "\n".join(above.rows[above.start + t:]) + "\n" + self.line, above.begins[t] + def pieces(self, close: int) -> Iterator[str]: + """The text before offset ``close``, one row at a time, the last first; the row ``close`` is on stops at it.""" + above = self.above + if close >= above.head: + yield self.line[:close - above.head] + t = len(above.begins) - 1 + else: + t = bisect_right(above.begins, close) - 1 + yield above.rows[above.start + t][:close - above.begins[t]] + for j in range(above.start + t - 1, above.start - 1, -1): + yield above.rows[j] + class _LinkCache: """What is known of each ``](`` in a paragraph: whether it closes an opener, and the link it starts. @@ -659,21 +672,35 @@ def _escaped(text: _Chars, i: int) -> bool: return n % 2 == 1 -def _has_opener(text: _Chars, close: int) -> bool: +def _pieces(text: str | _Text, close: int) -> Iterator[str]: + """The text before offset ``close``, one line at a time, the last first: the line ``close`` is on stops at it.""" + if isinstance(text, _Text): + yield from text.pieces(close) + return + end = close + while (nl := text.rfind("\n", 0, end)) >= 0: + yield text[nl + 1:end] + end = nl + yield text[:end] + + +def _has_opener(text: str | _Text, close: int) -> bool: """Whether the ``]`` at ``close`` closes a ``[`` in its paragraph: an escaped ``\\[`` or ``\\]`` is literal text.""" if _escaped(text, close): return False depth = 0 - for i in range(close - 1, -1, -1): - c = text[i] - if c == "\n" and (i == 0 or text[i - 1] == "\n"): + for k, piece in enumerate(_pieces(text, close)): + if k and not piece: return False # a blank line ends the paragraph - if c == "]" and not _escaped(text, i): - depth += 1 - elif c == "[" and not _escaped(text, i): - if depth == 0: + for m in reversed(list(_BRACKET.finditer(piece))): + if _escaped(piece, m.start()): + continue + if m.group() == "]": + depth += 1 + elif depth == 0: return True - depth -= 1 + else: + depth -= 1 return False diff --git a/dokimi/tests/test_blank_inline.py b/dokimi/tests/test_blank_inline.py index 425e04b00..06c284ada 100644 --- a/dokimi/tests/test_blank_inline.py +++ b/dokimi/tests/test_blank_inline.py @@ -173,6 +173,54 @@ def counting(text: str, close: int) -> bool: assert len(calls) == 1 +def test_the_opener_of_a_link_in_the_rows_above_is_looked_up_without_reading_each_character(monkeypatch: pytest.MonkeyPatch) -> None: + read: list[int] = [] + real = store._Text.__getitem__ + + def counting(self: store._Text, i: int) -> str: + read.append(i) + return real(self, i) + + monkeypatch.setattr(store._Text, "__getitem__", counting) + above = store._Above.of("\n".join("a](b" for _ in range(300))) + assert not store._has_opener(store._Text(above, "x"), 1001) + assert len(read) < 10 # each row is scanned whole: only the characters before the ``]`` itself are read + + +@pytest.mark.parametrize("above, line, close, expected", [ + ("[a", "b]", 1, True), + ("[a\nb", "c](x", 1, True), + ("[a\n\nb", "c]", 1, False), + ("[a\n", "b]", 1, False), + ("\\[a", "b]", 1, False), + ("[a]\nb", "c]", 1, False), + ("[[a]\nb", "c]", 1, True), + ("[a\nb\\", "]", 0, True), +]) +def test_a_close_bracket_finds_its_opener_across_the_rows_above(above: str, line: str, close: int, expected: bool) -> None: + text = store._Text(store._Above.of(above), line) + joined = above + "\n" + line + assert store._has_opener(text, len(above) + 1 + close) is expected + assert store._has_opener(joined, len(above) + 1 + close) is expected + + +def test_the_text_of_the_rows_above_and_the_line_reads_as_the_joined_text() -> None: + lines = ["o]ld", "", "a[b", "c]", "d]ef", "gh"] + above = store._Above(lines[:5]) + for i in range(6): + above.reach(lines, i) + assert above.start == 2 # the raw blank line above ends the paragraph + text = store._Text(above, lines[5]) + joined = "\n".join(lines[2:]) + assert [text[i] for i in range(len(joined))] == list(joined) + for i in range(len(joined)): + tail, shift = text.tail(i) + assert shift == joined.rfind("\n", 0, i) + 1 # the offset of the row that holds ``i`` + assert tail == joined[shift:] + assert store._has_opener(text, i) == store._has_opener(joined, i) + assert [i for i in range(len(joined)) if store._has_opener(text, i)] == [2, 3, 4, 5] # ``a[`` opens until the ``]`` after the row break closes it + + def test_an_opener_blanked_inside_a_code_span_no_longer_opens_the_link() -> None: assert _blank_inline("`[`](<`a`>) `b`", False) == (" ](< >) ", "", None) assert _blank_inline("[`[`](<`a`>) `b`", False) == ("[ ](<`a`>) ", "", None) From 84cb9ab738b5e429efae37893f1e5e13c3d86603 Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Tue, 1 Dec 2026 13:05:55 +0000 Subject: [PATCH 5/6] fix(memory): move the definition-title scan out of store.py, which the paragraph change pushed past the 800-line cap (#1261) CI on Python 3.14 and the wheel leg failed tests/test_growth_ratchet.py: dokimi/memory/store.py was 817 lines, over the 800 cap, with no baseline entry. The title scan (`title_spans`, `title_last_line` and the two tables they read) moves unchanged to dokimi/memory/titles.py, which leaves store.py at 779 lines. The one test that imported `_title_spans` from store imports `title_spans` from the new module. Signed-off-by: Anton Volkov --- dokimi/dokimi/memory/store.py | 42 +--------------- dokimi/dokimi/memory/titles.py | 48 +++++++++++++++++++ .../test_memory_index_definitions_linear.py | 5 +- 3 files changed, 53 insertions(+), 42 deletions(-) create mode 100644 dokimi/dokimi/memory/titles.py diff --git a/dokimi/dokimi/memory/store.py b/dokimi/dokimi/memory/store.py index cc0590cab..80a0bb462 100644 --- a/dokimi/dokimi/memory/store.py +++ b/dokimi/dokimi/memory/store.py @@ -24,6 +24,7 @@ from dokimi.code_spans import LINE_BREAK, CodeSpan, CodeSpanScanner from dokimi.digest_entries import listed_entries +from dokimi.memory.titles import title_spans INDEX_NAME = "MEMORY.md" ARCHIVE_DIR = "archive" @@ -48,12 +49,6 @@ _BRACKET = re.compile(r"[\[\]]") _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): @@ -124,7 +119,7 @@ def index_targets(self) -> list[tuple[int, str, bool]]: text = "\n".join(lines) 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 + titles = title_spans(lines, begin, defs) # a closed title holds no link matches = list(_MD_LINK.finditer(text)) opened = _closing_openers(text, {m.start() for m in matches}) title_starts, title_ends = _merged(titles) @@ -230,39 +225,6 @@ def _code_span(line: str, pos: int, scan: CodeSpanScanner | None = None) -> Code return None -def _title_spans(lines: list[str], begin: list[int], defs: dict[int, re.Match]) -> list[tuple[int, int]]: - """The offsets in the joined text of each definition's title, for a title closed on its line or the next.""" - out = [] - for k, d in defs.items(): - joined = d.end() > len(lines[k]) # the destination, and so the title, is on line k + 1 - 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 | _Above = "") -> int | None: """End, on ``line``, of the ``](<...>)`` link whose destination holds ``pos``: a backtick there is text, and opens no span. diff --git a/dokimi/dokimi/memory/titles.py b/dokimi/dokimi/memory/titles.py new file mode 100644 index 000000000..76c2da981 --- /dev/null +++ b/dokimi/dokimi/memory/titles.py @@ -0,0 +1,48 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""Where the title of a reference definition ends, for the memory index's link check.""" + +from __future__ import annotations + +import re + +_TITLE_CLOSER = {'"': '"', "'": "'", "(": ")"} +_TITLE_BODY = { # what a closed title holds between the opener and the closer, one line at a time + '"': re.compile(r"(?:\\.|[^\"\\])*"), + "'": re.compile(r"(?:\\.|[^'\\])*"), + "(": re.compile(r"(?:\\.|[^()\\])*"), +} + + +def title_spans(lines: list[str], begin: list[int], defs: dict[int, re.Match]) -> list[tuple[int, int]]: + """The offsets in the joined text of each definition's title, for a title closed on its line or the next.""" + out = [] + for k, d in defs.items(): + joined = d.end() > len(lines[k]) # the destination, and so the title, is on line k + 1 + 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 a closed title 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 diff --git a/dokimi/tests/test_memory_index_definitions_linear.py b/dokimi/tests/test_memory_index_definitions_linear.py index 5d281cc5c..ececd1ad3 100644 --- a/dokimi/tests/test_memory_index_definitions_linear.py +++ b/dokimi/tests/test_memory_index_definitions_linear.py @@ -17,7 +17,8 @@ import pytest from dokimi.memory import store -from dokimi.memory.store import MemoryEntry, MemoryStore, _definitions, _title_spans +from dokimi.memory.store import MemoryEntry, MemoryStore, _definitions +from dokimi.memory.titles import title_spans from tests.work_count import WORK_LIMIT, count_calls, count_pattern, work_ratio @@ -67,7 +68,7 @@ def _spans_both(text: str, every: bool = False) -> tuple[list[tuple[int, int]], 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) + return title_spans(lines, begin, defs), _old_title_spans(lines, begin, defs) AWKWARD = [ From b75f4586143b22ed5881c64c7530761ac66d9fde Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Tue, 1 Dec 2026 13:46:01 +0000 Subject: [PATCH 6/6] fix(memory): look back for a link's opener without reading the brackets before it; move the block helpers to blocks.py (#1261) Review point 4754519307: `_has_opener` listed every bracket of a row before it looked at the one next to the `]`, so a row of many links cost the square of its links. It now walks the row backwards one character at a time and stops at the opener. A test times the opener lookup of every link of a row of `[x](a.md) ` and bounds its growth. Review point 4754598705: after merging main, store.py was over the 800-line cap. The line-level block helpers (fence, list item, paragraph break, indented code, comment resume, the `-->` and span look-ahead) move unchanged, bar their names, to `memory/blocks.py`; nothing else reads them. `tests/test_memory_blocks.py` pins each of them on its own, since the mutation job reads the moved lines as changed. Signed-off-by: Anton Volkov --- dokimi/dokimi/memory/blocks.py | 85 +++++++++++++++++++++ dokimi/dokimi/memory/store.py | 108 ++++++--------------------- dokimi/tests/test_blank_inline.py | 13 ++++ dokimi/tests/test_memory_blocks.py | 114 +++++++++++++++++++++++++++++ 4 files changed, 233 insertions(+), 87 deletions(-) create mode 100644 dokimi/dokimi/memory/blocks.py create mode 100644 dokimi/tests/test_memory_blocks.py diff --git a/dokimi/dokimi/memory/blocks.py b/dokimi/dokimi/memory/blocks.py new file mode 100644 index 000000000..9c5bab6a1 --- /dev/null +++ b/dokimi/dokimi/memory/blocks.py @@ -0,0 +1,85 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""The block structure of a Markdown line, as ``memory.store`` blanks the code in an index: fences, lists, paragraph breaks.""" + +from __future__ import annotations + +import re + +FENCE = re.compile(r" {0,3}(`{3,}|~{3,})") +_LIST_ITEM = re.compile(r" *(?:[-*+]|\d{1,9}[.)])(?:[ \t]|$)") +_BLOCK_START = re.compile(r" {0,3}(?:#{1,6}(?:[ \t]|$)|>)") + + +def fence_opener(line: str) -> str: + """The fence marker that ``line`` opens, or ``""``: an info string holds no backtick.""" + m = FENCE.match(line) + if m and not (m.group(1)[0] == "`" and "`" in line[m.end():]): + return m.group(1) + return "" + + +def closes_fence(line: str, fence: str) -> bool: + """Whether ``line`` closes the fence ``fence``: the same character, at least as long, nothing after it.""" + m = FENCE.match(line) + return bool(m and m.group(1)[0] == fence[0] and len(m.group(1)) >= len(fence) and not line[m.end():].strip()) + + +def span_end(line: str, span: str) -> int: + """The offset just past the backtick run ``span`` that closes a code span on ``line``, or -1.""" + closer = re.search(r"(? tuple[bool, bool, bool]: + """``(in_list, code, hidden)`` after line ``i``: an indented line outside a list item, after a blank line or code, is code.""" + line = lines[i] + if not line.strip(): + return in_list, code, False + prev_blank = i == 0 or not lines[i - 1].strip() + if _LIST_ITEM.match(line) and (in_list or not line.startswith((" ", "\t")) or not (prev_blank or code)): + in_list = True + elif line[0] not in " \t" and (prev_blank or _BLOCK_START.match(line)): + in_list = False + hidden = not in_list and line.startswith((" ", "\t")) and (prev_blank or code) + return in_list, hidden, hidden + + +def paragraph_break(line: str) -> bool: + """Whether ``line`` ends the paragraph before it: blank, a fence, a list item, a heading or a quote.""" + return not line.strip() or bool(fence_opener(line) or _LIST_ITEM.match(line) or _BLOCK_START.match(line)) + + +def close_ahead(lines: list[str]) -> list[bool]: + """For each line, whether a ``-->`` follows it in the same paragraph.""" + ahead = [False] * len(lines) # mutation-ok[flip-bool]: the loop sets every row + seen = False + for i in range(len(lines) - 1, -1, -1): + ahead[i] = seen + if paragraph_break(lines[i]): + seen = False + elif "-->" in lines[i]: + seen = True + return ahead + + +def span_closes_ahead(lines: list[str], i: int, run: str) -> bool: + """Whether a backtick run of the length of ``run`` closes the code span it opens on line ``i``, within its paragraph.""" + closer = re.compile(r"(? tuple[str | None, str, str]: + """``(line, comment, opener)`` for a line met inside a comment; ``line`` is None while the comment holds all of it.""" + if comment == "inline" and paragraph_break(line): # a blank line, a fence or a block start ends it + return line, "", opener + end = line.find("-->") + if end < 0: + return None, comment, opener + return " " * (end + 3) + line[end + 3:], "", "" # the text after the close is prose, not a fence diff --git a/dokimi/dokimi/memory/store.py b/dokimi/dokimi/memory/store.py index 56619404c..0886471bc 100644 --- a/dokimi/dokimi/memory/store.py +++ b/dokimi/dokimi/memory/store.py @@ -24,6 +24,16 @@ from dokimi.code_spans import LINE_BREAK, CodeSpan, CodeSpanScanner from dokimi.digest_entries import listed_entries +from dokimi.memory.blocks import ( + FENCE as _FENCE, + close_ahead, + closes_fence, + fence_opener, + indented_code, + resume_comment, + span_closes_ahead, + span_end, +) from dokimi.memory.titles import title_spans INDEX_NAME = "MEMORY.md" @@ -41,12 +51,8 @@ _MD_ESCAPE = re.compile(r"\\([!-/:-@\[-`{-~])") _WIKILINK = re.compile(r"\[\[([^\]\n]+)\]\]") _SCHEME = re.compile(r"[A-Za-z][A-Za-z0-9+.-]+:") # two letters or more, so a drive path like C:\\x is not a scheme -_FENCE = re.compile(r" {0,3}(`{3,}|~{3,})") -_LIST_ITEM = re.compile(r" *(?:[-*+]|\d{1,9}[.)])(?:[ \t]|$)") -_BLOCK_START = re.compile(r" {0,3}(?:#{1,6}(?:[ \t]|$)|>)") _BACKTICK_RUN = re.compile(r"(?\n]*>(?:\s+(?:\"[^\"]*\"|'[^']*'|\([^()]*\)))?" + _WS + r"\)") # the title grammar of _MD_LINK _TITLE_CLOSED = re.compile(r"[ \t]+(?:\"(?:\\.|[^\"\\])*\"|'(?:\\.|[^'\\])*'|\((?:\\.|[^()\\])*\))\s*$") @@ -171,20 +177,20 @@ def _blank_blocks(lines: list[str]) -> tuple[list[str], list[str]]: span = "" # the backtick run of a code span that runs on over the line break in_list = False code = False # the previous line was an indented code line - closes = _close_ahead(lines) + closes = close_ahead(lines) above = _Above(filled) for i, line in enumerate(lines): filled.extend(out[len(filled):]) # a line blanked whole keeps its spaces: it starts a block of its own above.reach(lines, i) - opener = _fence_opener(line) + opener = fence_opener(line) if fence: - if _closes_fence(line, fence): + if closes_fence(line, fence): fence = "" out.append(" " * len(line)) continue source = line if comment: - rest, comment, opener = _resume_comment(line, comment, opener) + rest, comment, opener = resume_comment(line, comment, opener) if rest is None: out.append(" " * len(line)) continue @@ -195,13 +201,13 @@ def _blank_blocks(lines: list[str]) -> tuple[list[str], list[str]]: continue pos = 0 if span: - pos = _span_end(line, span) + pos = span_end(line, span) if pos < 0: out.append(" " * len(line)) continue line = " " * pos + line[pos:] span = "" - in_list, code, hidden = _indented_code(lines, i, in_list, code and not pos) + in_list, code, hidden = indented_code(lines, i, in_list, code and not pos) # mutation-ok[drop-clause]: a span is open only after a prose line, which clears ``code`` if hidden and not pos: out.append(" " * len(line)) continue @@ -437,84 +443,11 @@ def in_link(pos: int) -> bool: def _open_span(lines: list[str], i: int, line: str, run: re.Match | None) -> tuple[str, str]: """``(line, span)``: an unpaired backtick run that closes in a later line of its paragraph blanks the rest of ``line``.""" - if run and _span_closes_ahead(lines, i, run.group()): + if run and span_closes_ahead(lines, i, run.group()): return line[:run.start()] + " " * (len(line) - run.start()), run.group() return line, "" -def _fence_opener(line: str) -> str: - """The fence marker that ``line`` opens, or ``""``: an info string holds no backtick.""" - m = _FENCE.match(line) - if m and not (m.group(1)[0] == "`" and "`" in line[m.end():]): - return m.group(1) - return "" - - -def _closes_fence(line: str, fence: str) -> bool: - """Whether ``line`` closes the fence ``fence``: the same character, at least as long, nothing after it.""" - m = _FENCE.match(line) - return bool(m and m.group(1)[0] == fence[0] and len(m.group(1)) >= len(fence) and not line[m.end():].strip()) - - -def _span_end(line: str, span: str) -> int: - """The offset just past the backtick run ``span`` that closes a code span on ``line``, or -1.""" - closer = re.search(r"(? tuple[bool, bool, bool]: - """``(in_list, code, hidden)`` after line ``i``: an indented line outside a list item, after a blank line or code, is code.""" - line = lines[i] - if not line.strip(): - return in_list, code, False - prev_blank = i == 0 or not lines[i - 1].strip() - if _LIST_ITEM.match(line) and (in_list or not line.startswith((" ", "\t")) or not (prev_blank or code)): - in_list = True - elif line[0] not in " \t" and (prev_blank or _BLOCK_START.match(line)): - in_list = False - hidden = not in_list and line.startswith((" ", "\t")) and (prev_blank or code) - return in_list, hidden, hidden - - -def _paragraph_break(line: str) -> bool: - """Whether ``line`` ends the paragraph before it: blank, a fence, a list item, a heading or a quote.""" - return not line.strip() or bool(_fence_opener(line) or _LIST_ITEM.match(line) or _BLOCK_START.match(line)) - - -def _close_ahead(lines: list[str]) -> list[bool]: - """For each line, whether a ``-->`` follows it in the same paragraph.""" - ahead = [False] * len(lines) - seen = False - for i in range(len(lines) - 1, -1, -1): - ahead[i] = seen - if _paragraph_break(lines[i]): - seen = False - elif "-->" in lines[i]: - seen = True - return ahead - - -def _span_closes_ahead(lines: list[str], i: int, run: str) -> bool: - """Whether a backtick run of the length of ``run`` closes the code span it opens on line ``i``, within its paragraph.""" - closer = re.compile(r"(? tuple[str | None, str, str]: - """``(line, comment, opener)`` for a line met inside a comment; ``line`` is None while the comment holds all of it.""" - if comment == "inline" and _paragraph_break(line): # a blank line, a fence or a block start ends it - return line, "", opener - end = line.find("-->") - if end < 0: - return None, comment, opener - return " " * (end + 3) + line[end + 3:], "", "" # the text after the close is prose, not a fence - - class _BlankedLine: """``line`` with ranges blanked to spaces, collected as the scan goes and joined once. @@ -709,10 +642,11 @@ def _has_opener(text: str | _Text, close: int) -> bool: for k, piece in enumerate(_pieces(text, close)): if k and not piece: return False # a blank line ends the paragraph - for m in reversed(list(_BRACKET.finditer(piece))): - if _escaped(piece, m.start()): + for at in range(len(piece) - 1, -1, -1): # backwards, and stops at the opener: the brackets before it are not read + c = piece[at] + if c not in "[]" or _escaped(piece, at): continue - if m.group() == "]": + if c == "]": depth += 1 elif depth == 0: return True diff --git a/dokimi/tests/test_blank_inline.py b/dokimi/tests/test_blank_inline.py index 6e23310ae..f3a5724d0 100644 --- a/dokimi/tests/test_blank_inline.py +++ b/dokimi/tests/test_blank_inline.py @@ -8,6 +8,7 @@ import itertools import random import re +from collections.abc import Callable from functools import partial from pathlib import Path @@ -191,6 +192,18 @@ def counting(self: store._Text, i: int) -> str: assert len(read) < 10 # each row is scanned whole: only the characters before the ``]`` itself are read +def test_the_opener_of_each_link_of_one_row_is_found_without_reading_the_brackets_before_it() -> None: + def every_link(k: int) -> Callable[[], list[bool]]: + row = "[x](a.md) " * k + text = store._Text(store._Above.of(""), row) + closes = [i for i, c in enumerate(row) if c == "]"] + return lambda: [store._has_opener(text, i) for i in closes] + + ratio, result = growth(every_link, 2000) + assert ratio < GROWTH_LIMIT + assert all(result) + + @pytest.mark.parametrize("above, line, close, expected", [ ("[a", "b]", 1, True), ("[a\nb", "c](x", 1, True), diff --git a/dokimi/tests/test_memory_blocks.py b/dokimi/tests/test_memory_blocks.py new file mode 100644 index 000000000..0e6e04363 --- /dev/null +++ b/dokimi/tests/test_memory_blocks.py @@ -0,0 +1,114 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""The block rules ``memory.store`` blanks an index by: which lines are fences, code, list items, and where a paragraph ends.""" + +from __future__ import annotations + +import pytest + +from dokimi.memory.blocks import ( + close_ahead, + closes_fence, + fence_opener, + indented_code, + paragraph_break, + resume_comment, + span_closes_ahead, + span_end, +) + + +@pytest.mark.parametrize("line, opener", [("```py", "```"), (" ~~~~", "~~~~"), ("``` `a`", ""), ("~~~ `x`", "~~~"), ("text", ""), (" ```", "")]) +def test_a_fence_opens_at_three_marks_up_to_three_spaces_in_and_a_backtick_fence_has_no_backtick_in_its_info(line: str, opener: str) -> None: + assert fence_opener(line) == opener + + +@pytest.mark.parametrize("line, fence, closes", [ + ("```", "```", True), ("````", "```", True), ("``", "```", False), ("~~~", "```", False), ("``` x", "```", False), ("```", "````", False), +]) +def test_a_fence_closes_on_the_same_mark_as_long_with_nothing_after_it(line: str, fence: str, closes: bool) -> None: + assert closes_fence(line, fence) is closes + + +@pytest.mark.parametrize("line, span, end", [("a``b``c", "``", 3), ("a`b", "``", -1), ("x ` y", "`", 3), ("a``b", "`", -1)]) +def test_a_span_ends_after_the_first_run_of_its_own_length(line: str, span: str, end: int) -> None: + assert span_end(line, span) == end + + +def _hidden(lines: list[str]) -> list[bool]: + in_list = code = False + out = [] + for i in range(len(lines)): + in_list, code, hidden = indented_code(lines, i, in_list, code) + out.append(hidden) + return out + + +@pytest.mark.parametrize("lines, hidden", [ + ([" x"], [True]), + ([" c", " d"], [True, True]), + (["a", " b"], [False, False]), + (["a", "", " code"], [False, False, True]), + (["- a", " b"], [False, False]), + (["- a", "", " b"], [False, False, False]), + (["- a", "# h", "", " c"], [False, False, False, True]), + (["- a", "b", "", " c"], [False, False, False, False]), + (["- a", "", "b", "", " c"], [False, False, False, False, True]), + (["", " - a"], [False, True]), + (["x", " - a"], [False, False]), + ([" c", "", " d"], [True, False, True]), +]) +def test_an_indented_line_outside_a_list_item_after_a_blank_line_or_code_is_code(lines: list[str], hidden: list[bool]) -> None: + assert _hidden(lines) == hidden + + +def test_a_blank_line_changes_neither_the_list_nor_the_code_state() -> None: + assert indented_code([""], 0, True, True) == (True, True, False) + assert indented_code([" "], 0, False, False) == (False, False, False) + + +@pytest.mark.parametrize("line, breaks", [ + ("", True), (" ", True), ("```", True), ("- a", True), ("1. a", True), ("# h", True), ("> q", True), + ("text", False), (" # x", False), ("a - b", False), +]) +def test_a_paragraph_ends_at_a_blank_line_a_fence_a_list_item_a_heading_or_a_quote(line: str, breaks: bool) -> None: + assert paragraph_break(line) is breaks + + +@pytest.mark.parametrize("lines, ahead", [ + ([""], [True, False]), + ([""], [False, True, False]), # the blank line itself is followed by a close, the line above it is cut off + (["", "d"], [True, True, False, False]), + (["-->", "- x"], [False, False]), + (["a", "- b -->"], [False, False]), + (["a", "b"], [False, False]), +]) +def test_a_close_ahead_is_a_close_later_in_the_same_paragraph(lines: list[str], ahead: list[bool]) -> None: + assert close_ahead(lines) == ahead + + +@pytest.mark.parametrize("lines, closes", [ + (["`a", "b`"], True), + (["`a", "", "b`"], False), + (["`a", "b``"], False), + (["`a", "- b`"], False), + (["`a", "b"], False), + (["`a"], False), +]) +def test_a_span_closes_ahead_on_a_run_of_its_length_within_its_paragraph(lines: list[str], closes: bool) -> None: + assert span_closes_ahead(lines, 0, "`") is closes + + +@pytest.mark.parametrize("line, comment, opener, expected", [ + ("", "inline", "", ("", "", "")), + ("```", "inline", "```", ("```", "", "```")), + ("", "block", "", (None, "block", "")), + ("text", "inline", "", (None, "inline", "")), + ("a --> b", "inline", "", (" b", "", "")), + ("a --> b", "block", "```", (" b", "", "")), +]) +def test_a_comment_resumes_on_a_line_until_its_close_and_an_inline_one_ends_at_a_paragraph_break( + line: str, comment: str, opener: str, expected: tuple[str | None, str, str] +) -> None: + assert resume_comment(line, comment, opener) == expected