Skip to content

fix(memory): an index of many reference definitions is linted in linear time - #1430

Merged
antonwolfy merged 1 commit into
intel:mainfrom
antonwolfy:fix/memory-index-linear
Nov 30, 2026
Merged

antonwolfy merged 1 commit into
intel:mainfrom
antonwolfy:fix/memory-index-linear

Conversation

@antonwolfy

Copy link
Copy Markdown
Contributor

Summary

index_targets on an index of n lines [li]: fi.md took more than quadratic time (#1263). Measured on main (CPU seconds, one run each):

index n = 500 n = 1000 n = 2000
[li]: fi.md 0.156 1.012 7.723
[li]: fi.md 'a (unclosed title) 0.225 1.325 9.048

Two sites account for it; the other two the issue names (_definitions, _used_labels) were not hot. _title_spans joined lines[k:end] for every candidate end of every definition and matched the closed-title pattern on the join: a definition with no title never matches, so each one walked to the end of its paragraph (and the unclosed title fails the same way, because its first closer on the next line is followed by text). _blank_blocks walked back to the start of the paragraph and joined the blanked lines above for every line, though _blank_inline reads that text only when a link check needs it. Fix option taken from the issue: read each definition's neighbours by index instead of joining lines per definition, for the title; the paragraph start is tracked down the text for the other site. Both indexes now take 0.004, 0.008, 0.016 s (no title) and 0.005, 0.011, 0.024 s (unclosed title) at 500, 1000, 2000: about 2x per doubling. Nothing else was still quadratic on either index.

Two other inputs, not named by the issue, are still quadratic and are tracked in #1428 (definitions with closed titles, then many links) and #1429 (many links on one line).

Closes #1263

Changes

  • dokimi/dokimi/memory/store.py: _title_spans finds the closing line of a title with _title_last_line, which reads each line once with the body of _TITLE_CLOSED for the title's opener. The first closer on a line decides: only blanks may follow it, else (text after it, a ( in a parenthesised title, a backslash that ends the line) there is no span. A line that reaches its end goes on to the next, up to a blank line or the end of the text. The spans are the ones the join scan returned.
  • dokimi/dokimi/memory/store.py: _blank_blocks tracks the paragraph start (_paragraph_start: a line starts one when the line above is blank or a fence, else the previous start) and passes _blank_inline a memoised call that joins the lines above, _paragraph_above(out, start, i). _blank_inline, _BlankedLine and _unpaired_run take before as a string or such a call and read it only when a code span or comment is blanked or a backtick run is left; a string still works, so tests/test_blank_inline.py is unchanged.
  • dokimi/tests/test_memory_index_definitions_linear.py (new): the new title scan against a copy of the old function on 32 awkward paragraphs (with the definitions _definitions keeps, and with every definition the pattern matches) and on 3000 seeded random paragraphs; the work counted for both repros (reads of _TITLE_CLOSED, reads of _FENCE, calls that join the paragraph above).
  • Changelog fragment (Fixed).

Risk

None expected: index_targets() returns what it returned for every input, which the title comparison and the existing memory lint, catalog link, code span and _blank_inline tests pin. _paragraph_above changed its signature and has no other caller. Open PR #1406 changes dokimi/dokimi/records.py only, so a merge with it meets none of these lines. Open issue #1261 (_blank_blocks joins the paragraph above every line) is fixed here for lines with no code span or comment; a line that has one still builds the paragraph above, so #1261 stays open for that part.

Testing

On Linux, at 4b5bbec7 (on main e260503):

  • make ci-local: 38 passed, 0 failed, 16 skipped (external catalog smoke needs Docker and network; the pre-commit ruff, zizmor and secrets hooks; semgrep; micromamba; the fuzz job; the matrix, deploy and report jobs that only run elsewhere). 31557 tests passed, 27 skipped; changed-line coverage 100%.
  • The new test file on main's code: 7 failed, 68 passed. The first failure is the paragraph walk-back, assert 278.8 < 24 (work at 16n over n for _FENCE); the title tests fail on assert 2350360310 <= 15140.
  • Mutants, each failing the new tests: the join per candidate end in _title_spans restored (2 failed), the walk back to the paragraph start restored (2 failed), the paragraph above joined for every line (3 failed), the join not memoised (1 failed), a closer followed by text accepted (11 failed), the blank-line stop of the title scan dropped (3 failed), the column of a title on the next line not corrected (5 failed).
  • Not run: the matrix legs on Python 3.11, 3.12 and 3.14.

Open questions

None.

Revert

A plain revert restores the quadratic scans. Nothing is stored.

Checklist

  • Tests added/updated and pytest passes
  • ruff, mypy, and schema checks pass
  • Docs updated (or N/A) — see the docs-drift checklist in CONTRIBUTING.md
  • Self-reviewed per "Before opening a PR" in AGENTS.md
  • Each new raise/exit and test names the doc, contract or issue it traces to
  • No ad-hoc run artifacts committed
  • New files carry the SPDX license header (or are exempt in .github/.licenserc.yaml)

…ar time (intel#1263)

Two sites made the time of `index_targets` grow faster than the square of the lines in an index of definitions. `_title_spans` joined `lines[k:end]` for every candidate end of every definition and matched the closed-title pattern on the join, so a definition with no title walked to the end of its paragraph. `_blank_blocks` walked back to the start of the paragraph and joined the lines above for every line, though `_blank_inline` reads that text only when a link check needs it.

`_title_spans` now reads a title line by line with the body of the closed-title pattern for its opener: the first closer on a line decides, and only blanks may follow it. The paragraph start is tracked down the text (`_paragraph_start`), and the text above a line is passed to `_blank_inline` as a call that builds it once, when read. The spans and the blanked lines are unchanged.

Signed-off-by: Anton Volkov <antonwolfy@gmail.com>
@exai-bot

exai-bot commented Nov 30, 2026 •

Copy link
Copy Markdown

✅ OpenCodeReview: Review complete: 0 finding(s) across 3 selected item(s).

CI at 4b5bbec: 21 passing, 4 skipped.

Review details
  • Commit reviewed: 4b5bbec against merge base e260503
  • Coverage: 3 files in 3 groups
  • Engine: OpenCodeReview v1.13.5-exai.4.8f73eada, us.openai.gpt-6.1-sol
  • Usage: 210k tokens (128k from cache), 20s
  • Tool calls: 9 (4 file_read, 2 ci_status, 2 file_read_diff, 1 code_search)
  • dokimi/changelog.d/20261130_120000_memory-index-definitions-linear.md: 1 file
  • dokimi/dokimi/memory/store.py: 1 file
  • dokimi/tests/test_memory_index_definitions_linear.py: 1 file

@codecov-commenter

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 96.28%. Comparing base (e260503) to head (4b5bbec).
❗ Your organization needs to install the Codecov GitHub app to enable full functionality.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1430      +/-   ##
==========================================
- Coverage   96.28%   96.28%   -0.01%     
==========================================
  Files         513      513              
  Lines       68470    68499      +29     
  Branches    11884    11886       +2     
==========================================
+ Hits        65924    65951      +27     
  Misses       1566     1566              
- Partials      980      982       +2     
Files with missing lines Coverage Δ
dokimi/dokimi/memory/store.py 97.25% <100.00%> (+0.85%) ⬆️

... and 5 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@github-actions

Copy link
Copy Markdown

Mutation of changed lines

80 mutants of the lines this PR changes, at 4b5bbec: 69 killed, 11 survived, 0 waived, 0 inconclusive, 0 timed out, 0 errors, 0 not run.

The mutant cap left out 29 more mutants of covered changed lines.

A survivor is a change to that line that the tests covering it do not notice: add an assertion that fails on it or, if the change cannot alter behaviour, put # mutation-ok[<operator>]: <reason> at the end of the line or alone on the line above.

Line Operator Was Became Tests run
dokimi/dokimi/memory/store.py:166 bump-int 0 1 10
dokimi/dokimi/memory/store.py:314 return-none i if i and (not lines[i - 1].strip() or _FENCE.match(lines[i - 1])) else start None 10
dokimi/dokimi/memory/store.py:319 return-none "\n".join(out[start:i]) None 1
dokimi/dokimi/memory/store.py:413 delete-statement self._prefix_text = "" pass 174
dokimi/dokimi/memory/store.py:414 delete-statement self._head = 0 pass 174
dokimi/dokimi/memory/store.py:314 take-branch i if i and (not lines[i - 1].strip() or _FENCE.match(lines[i - 1])) else start (i) 10
dokimi/dokimi/memory/store.py:414 bump-int 0 1 174
dokimi/dokimi/memory/store.py:314 take-branch i if i and (not lines[i - 1].strip() or _FENCE.match(lines[i - 1])) else start (start) 10
dokimi/dokimi/memory/store.py:426 take-branch before + "\n" if before else "" (before + "\n") 156
dokimi/dokimi/memory/store.py:314 drop-clause i and (not lines[i - 1].strip() or _FENCE.match(lines[i - 1])) (i) 10
dokimi/dokimi/memory/store.py:314 drop-clause i and (not lines[i - 1].strip() or _FENCE.match(lines[i - 1])) (not lines[i - 1].strip() or _FENCE.match(lines[i - 1])) 10

Warn-only: a survivor does not fail the job yet. Updated on every push; the full report is in the ci run summary.

@napetrov napetrov left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Change class: CONTRACT (head 4b5bbec)

  • Contract: candidate (count signal only, no file:line)
  • Responsibility: none
  • Dependency: none
  • Review depth: check the changed surface: callers, docs, tests pin new behaviour
  • Coverage gaps: none

The title scan consumes each candidate line without repeatedly rebuilding the prefix. I checked joined destinations, escaping, closing delimiters and paragraph boundaries against the old implementation and reviewed the equivalence tests. CI passed. I did not rerun timings locally.

@antonwolfy
antonwolfy merged commit cd992fb into intel:main Nov 30, 2026
25 checks passed
@antonwolfy
antonwolfy deleted the fix/memory-index-linear branch November 30, 2026 17:20
antonwolfy added a commit to antonwolfy/dokimi that referenced this pull request Nov 30, 2026
dokimi/dokimi/memory/store.py conflicted with intel#1430, which also stopped joining the paragraph above every line, by tracking the paragraph start (`_paragraph_start`) and passing a lazy join (`_paragraph_above`, `cache(partial(...))`) to `_blank_inline`.

Resolution: this branch's `_Above` (the shared rows, the paragraph start, the row offsets and the last `](`) replaces both, since it also removes the join for a line with a code span; `_paragraph_start`, `_paragraph_above`, the callable `before` of `_blank_inline`, `_unpaired_run` and `_BlankedLine`, and the `cache`/`partial` import are dropped. intel#1430's `_title_last_line`, `_title_spans` and the title patterns are kept as main has them.

dokimi/tests/test_memory_index_definitions_linear.py (from main) counted calls of `_paragraph_above`, which is gone: the two tests that did now count the reads of the paragraph above (`_Text.tail`) and assert none for the same inputs.

Signed-off-by: Anton Volkov <antonwolfy@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

memory lint: an index of many reference definitions takes more than quadratic time

4 participants