Skip to content

fix(memory): find the opener of every index link in one pass (#1262) - #1434

Merged
napetrov merged 2 commits into
intel:mainfrom
antonwolfy:fix/memory-index-opener
Nov 30, 2026
Merged

napetrov merged 2 commits into
intel:mainfrom
antonwolfy:fix/memory-index-opener

Conversation

@antonwolfy

@antonwolfy antonwolfy commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

MemoryStore.index_targets took quadratic time on an index of many links, in two places. It asked _has_opener(text, m.start()) for each link: that scan goes back from the ] until it finds an unmatched [ or the paragraph begins, so for a link with no opener (a](b), an escaped \[a](b)) it runs to the start of the paragraph. And _used_labels tested each [label] of a line against every link span of that line with any(...), so a line of n links did n times n tests, which is the time the issue measured on its own shape. On main, index_targets() CPU time:

index text n = 500 n = 1000 n = 2000
"[a](b) " * n (the issue's shape), on main 0.011 s 0.040 s 0.151 s
"[a](b) " * n, with this change 0.001 s 0.003 s 0.005 s
"[ " + "a](b) " * n, on main 0.042 s 0.168 s 0.673 s
"[ " + "a](b) " * n, with this change 0.001 s 0.001 s 0.002 s
"\\[a](b) " * n, on main 0.087 s 0.310 s 1.233 s
"\\[a](b) " * n, with this change 0.010 s 0.039 s 0.152 s
"[a](b)\n" * n (one paragraph), on main and with this change 0.029 s 0.116 s 0.427 s

The last row is not changed: its time is in prose_lines and _blank_blocks (a profile at n = 2000 puts 1.59 of 1.62 s there), which is #1261, and a long run of definitions is #1263. The "\\[a](b) " row after the change is the backslash reads of _escaped plus the rest of the lint, not the opener pass.

The fix for the opener is the issue's first option: a left-to-right walk with a count of open brackets, instead of a stack or a per-offset cache (a count is all _has_opener reads: whether an unmatched [ stands before the ]). The per-link test of a link against every definition title and the per-label test against every link span (any(...) over a list) are lookups by bisection over the sorted spans now.

Closes #1262

Changes

  • dokimi/dokimi/memory/store.py: _closing_openers(text, closes) makes one pass over the joined index and returns the ] offsets in closes that close an opener: an unescaped [ adds one to the count, an unescaped ] removes one when the count is above 0 (and is a hit, when asked about, before it removes), a blank line resets it. index_targets calls it once, not _has_opener per link. _has_opener stays: _LinkCache.end still calls it per ]( of a paragraph.
  • _merged(spans) sorts spans and joins overlapping ones; index_targets finds the title that holds a link by bisect_right, and _used_labels finds the link span that holds a label the same way, with the starts built once per line, and the current and next line it passes to _inline_link_at are joined once per line, not once per label.
  • dokimi/tests/test_blank_inline.py: a differential test (a table of shapes and 400 seeded random strings over [ ] ( ) \ \n a: the pass gives _has_opener's answer at every ], so index_targets gives the same links as before), a table of index_targets results (a](b), [[a]](b), escaped brackets, an opener before a blank line, a leading newline, a link inside a definition title), a test that no _has_opener call is made per link, a test of _merged, growth tests of the opener pass on three shapes, a table of _used_labels results with a label inside a link destination or a title, and an end-to-end growth test of index_targets() on "[a](b) " * n, all under tests/growth_timing.py.
  • Changelog fragments (Fixed): one for the opener walk and the title lookup, one for the label lookup.

Risk

None: the links index_targets returns and the labels _used_labels counts as used are unchanged for every input the tests cover (the differential test compares the new pass with _has_opener at every ] of 400 random strings and the shapes above; the link spans are disjoint, so the bisect gives the answer of the any(...) test). A hit is answered before the bracket is removed, as _has_opener does. Backslash runs are still read per bracket (_escaped), as before; a line of many backslashes is not made worse. The open #1430 also changes memory/store.py (many reference definitions); git merge-tree of its head with this branch is clean.

Testing

On Linux, at 29abcd36 (on main e260503):

  • make ci-local: 37 passed, 1 failed, 16 skipped (steps that need a tool the host lacks, another job's matrix, or a PR-only condition). 31502 tests passed, 1 failed, 27 skipped. The one failure is tests/test_repo_typecheck_grader.py::test_a_stub_in_the_workspace_that_hides_a_module_fails_the_grade hitting the 60 s timeout under load, in a file this change does not touch; that file alone passes (116 passed). An earlier run at the same code failed four other tests of untouched files on the same timeout, and those four pass alone (246 passed).
  • On main's code (the test file copied in): the end-to-end growth test fails on the ratio (248.8 against a limit of 64); the opener-pass growth tests, the no-call test and the _merged test of the first commit fail on main too (5 failed, 172 passed there, with _closing_openers and _merged given _has_opener's per-close answer and a plain sort).
  • Mutants, each failing the test it pins: no reset at a blank line, \[ not escaped, a hit asked after the removal, no join of overlapping title spans, titles ignored, _has_opener per link in index_targets, _has_opener per close in the pass (growth test), inside = False in _used_labels (both table rows with a label inside a destination or a title), the any(...) over spans in _used_labels (end-to-end growth test, ratio 236).
  • Not run: Python 3.11, 3.12 and 3.14 (only 3.13 here), CI's merge commit.

Open questions

None.

Revert

A plain revert restores the per-link backward scan, the linear title test and the linear label test. Nothing is stored.

Checklist

  • Tests added/updated and pytest passes [the full run had one 60 s timeout under host load in an untouched file, which passes alone]
  • 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)

)

index_targets called _has_opener once per link, and the scan back runs to the start of the paragraph whenever a link has no unmatched `[` before it (`a](b)`, an escaped `\[`), so an index of many such links took quadratic time in that step. It also tested each link against every definition title with a linear any().

The openers are now found by one left-to-right pass (_closing_openers) with a count of open brackets, reset at a blank line, with the same answers as _has_opener (a differential test pins that over a table and 400 seeded random strings). The title test is a bisect over the sorted, merged title spans. _has_opener stays for the per-span lookups of _blank_inline.

Signed-off-by: Anton Volkov <antonwolfy@gmail.com>
After the opener walk, index_targets on `"[a](b) " * n` was still quadratic: _used_labels tested every label of a line against every link span of the line with `any(...)`, and a line of n links has n spans and n labels. The spans are now sorted and merged once per line and each label is looked up with bisect_right, with the same answer as the any() test. Measured, `"[a](b) " * n` takes 0.001, 0.003, 0.005 s at n = 500, 1000, 2000. `"[a](b)\n" * n` is not changed here: its time is in prose_lines/_blank_blocks (intel#1261).

Signed-off-by: Anton Volkov <antonwolfy@gmail.com>
@antonwolfy
antonwolfy requested a review from a team as a code owner November 30, 2026 12:12
@antonwolfy antonwolfy self-assigned this Nov 30, 2026
@exai-bot

exai-bot commented Nov 30, 2026 •

Copy link
Copy Markdown

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

CI at a144aa9: 21 passing, 4 skipped.

Test notes (1)
  • dokimi/dokimi/memory/store.py:555: With if ends and lo <= ends[-1]: changed to if ends and lo < ends[-1]:, the tests still pass: dokimi/tests/test_blank_inline.py. A value exactly at the boundary gives the same result either way here, so no test says which one is meant.
Review details
  • Commit reviewed: a144aa9 against merge base e260503
  • Coverage: 4 files in 1 groups
  • Engine: OpenCodeReview v1.13.5-exai.4.8f73eada, us.openai.gpt-6.1-sol
  • Usage: 88k tokens (43k from cache), 17s
  • Tool calls: 7 (4 file_read, 1 ci_status, 1 code_search, 1 local_check_results)
  • Memory store index traversal and used-label lookup updates with tests and changelogs: 4 files

@github-actions

Copy link
Copy Markdown

Mutation of changed lines

75 mutants of the lines this PR changes, at a144aa9: 71 killed, 4 survived, 0 waived, 0 inconclusive, 0 timed out, 0 errors, 0 not run.

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:555 shift-boundary lo <= ends[-1] lo < ends[-1] 18
dokimi/dokimi/memory/store.py:124 drop-clause i >= 0 and m.start() < title_ends[i] (i >= 0) 12
dokimi/dokimi/memory/store.py:568 drop-clause i == 0 or text[i - 1] == "\n" (text[i - 1] == "\n") 16
dokimi/dokimi/memory/store.py:124 shift-boundary m.start() < title_ends[i] m.start() <= title_ends[i] 12

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

@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.26%. Comparing base (e260503) to head (a144aa9).
❗ Your organization needs to install the Codecov GitHub app to enable full functionality.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1434      +/-   ##
==========================================
- Coverage   96.28%   96.26%   -0.02%     
==========================================
  Files         513      513              
  Lines       68470    68498      +28     
  Branches    11884    11892       +8     
==========================================
+ Hits        65924    65943      +19     
- Misses       1566     1570       +4     
- Partials      980      985       +5     
Files with missing lines Coverage Δ
dokimi/dokimi/memory/store.py 97.04% <100.00%> (+0.63%) ⬆️

... and 6 files with indirect coverage changes

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

@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: LOCAL (head a144aa9)

  • Contract: none
  • Responsibility: none
  • Dependency: none
  • Review depth: skim: local change, check diff + tests
  • Coverage gaps: none

I traced opener matching, escaped brackets, the paragraph reset and membership in merged half-open spans against the old implementation. CI passed. I reviewed the growth and equivalence tests from source. I left a small follow-up for the already tracked label scanner.

Comment thread dokimi/dokimi/memory/store.py Resolved
@napetrov
napetrov merged commit 35cf584 into intel:main Nov 30, 2026
25 checks passed
@antonwolfy

Copy link
Copy Markdown
Contributor Author

(approved) ### Change class: LOCAL (head a144aa9)

@napetrov (#1434 (review)): Approval with no change asked. The follow-up it mentions is the label scanner tracked in #1429; the nit in the thread above is the only change this round.

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: index_targets looks back to the start of the paragraph for the opener of every link

4 participants