Skip to content

fix(text): find code spans in linear time on mixed backtick runs (#1073) - #1118

Merged
antonwolfy merged 4 commits into
intel:mainfrom
antonwolfy:fix/linear-code-spans
Nov 23, 2026
Merged

antonwolfy merged 4 commits into
intel:mainfrom
antonwolfy:fix/linear-code-spans

Conversation

@antonwolfy

@antonwolfy antonwolfy commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Summary

#1073: four code-span regexes read a span as a backtick run, a lazy body and a run of the same length (degrade._INLINE_FENCE, skill_markdown.CODE_SPAN_RE, memory.store._CODE_SPAN, and online_checks._URL_CODE_SPAN_RE, which the issue does not name and which has the same shape). A run with no run of its length after it scans to the end of the text (or of the line, or up to the next block start), and so does every run of another length. On main, for the text "".join("" * i + "a" for i in range(1, m + 1))`:

Site m=100 (5150 characters) m=400 (80600 characters) Ratio for 16x the characters
degrade._INLINE_FENCE 0.0024 s 0.1486 s 62
skill_markdown.CODE_SPAN_RE 0.0026 s 0.1556 s 60
memory.store._CODE_SPAN 0.0026 s 0.1547 s 60
online_checks._URL_CODE_SPAN_RE 0.0059 s 0.4194 s 71

With this change all four read the same text in 0.1 ms and 0.3 ms (ratio 3), and return the same spans as before.

The fix is the first option of the issue, in one shared helper: each run of backticks is read once, kept by length, and matched with the next run of the same length, so a run with no closer costs no scan and neither does a later run of its length (the second option, str.find per length, still scans the rest of the text once per distinct length). The sites differ only in arguments: the shortest opening run (3 for _INLINE_FENCE), the characters a run may not follow (a backslash for CODE_SPAN_RE), and a stop pattern that ends the body (a line break for _INLINE_FENCE and _CODE_SPAN, online_checks._BLOCK_START for the URL regex).

Closes #1073

Changes

  • New dokimi/code_spans.py (foundation layer): CodeSpanScanner (keeps the runs read, finds the next span from any later position; it keeps the index of the next opener and, per run length, the head of the closer list, so sequential searches take no binary search and only a search that goes back seeks with one), iter_code_spans and replace_code_spans with the arguments above, and CodeSpan, which answers start(), end(), span() and group(0|1|2) like the re.Match the callers read (group indexes a tuple of the three, so group(3) and group(-1) raise the tuple's IndexError, as re.Match.group does). It is a new module, not part of text_spans.py, which another open PR edits; tests/test_import_architecture.py lists it in the foundation layer.
  • eval/degrade.py: _replace_code_blocks replaces inline fences with replace_code_spans(line, ..., min_run=3, stop=LINE_BREAK); _INLINE_FENCE is gone.
  • external/skill_markdown.py: CODE_SPAN_RE is replaced by code_spans(text) (a run after a backslash opens no span); link_pieces and external/command_checks.py use it. Only the definition and its direct uses changed.
  • memory/store.py: _blank_inline builds one CodeSpanScanner(line, pos, stop=LINE_BREAK) per line and _code_span searches with it, so the runs read for one span are not read again for the next (a fresh index per span read 3876 runs at 50 spans of "".join("" * i + "a b " for i in range(2, k + 2))and 60501 at 200; it reads 202 and 802 now);_CODE_SPAN` is gone.
  • external/online_checks.py: _distinct_urls finds the code spans that hide a URL with iter_code_spans(body, stop=_BLOCK_START_RE); _URL_CODE_SPAN_RE is gone.
  • tests/test_code_spans.py (also test_sequential_spans_are_found_without_a_binary_search, which counts the bisect_left calls of 600 sequential spans, and test_a_search_that_goes_back_finds_the_same_span_again): a copy of each old regex is the reference; the helper is compared with it on every text of a five-character alphabet up to six characters, on 1500 seeded random texts per site, on a table of shapes (runs of 1 to 5, adjacent runs, a backslash, a newline in the body, unclosed runs, longer and shorter closers, an empty body), and through the production functions of each site; growth tests time each site on the issue's text and on three more shapes (the last one puts unmatched runs between valid spans); test_blanking_a_line_blanks_the_spans_of_the_old_regex compares _blank_inline with the old regex on random lines, and test_blanking_a_line_reads_each_run_once counts run reads through _blank_inline.
  • Changelog fragment (Fixed).

Risk

None for the spans: the helper and the old regexes return the same spans, groups and offsets on the whole table above, and make ci-local passes the existing tests of the four sites unchanged. CODE_SPAN_RE, _INLINE_FENCE, _CODE_SPAN and _URL_CODE_SPAN_RE no longer exist; the only users were in the files above. CODE_SPAN_RE's function replacement returns an iterator of CodeSpan, not a regex match, which the two callers read the same way. Four mutants of the changed lines survive in the CI mutation step, all equivalent: frozen=True on CodeSpan, the initial value of the stop-position cache (it only has to exceed any position it is asked about), the default head 0 of a run length that has no closer search yet (a head of 1 skips only the opener, which starts before its own body), and the low bound 0 of the seek that goes back (the first run of a length starts before any body of that length).

Open PRs that change the same files: #1046 edits external/command_checks.py on the line right after the one this change edits in _code_text (return "\n".join(code + spans)), so the two will conflict there, and the second to merge takes the resolution (keep code_spans(para) here and #1046's BLOCK_END there). #849 edits command_checks.py far from these lines (command_findings), #1092 edits the link code of external/skill_markdown.py (link_pieces and new helpers) and uses CODE_SPAN_RE in link_pieces, which this change replaces with code_spans, so that merge also needs a hand resolution of the one line that masks the spans. #1113, #1082 and #986 each add a line to tests/test_import_architecture.py, next to the line this change adds, and conflict only when they add it at the same place.

Testing

On a Linux review host, at fd22dc6c (on main 06341ca4):

  • make ci-local: 38 passed, 0 failed, 14 skipped (the docker and network catalog smoke, the pinned Claude Code install, the other Python versions' matrix legs, the conda-forge, fuzz, semgrep and deploy jobs, which need tools or a PR this host does not have). 26027 tests passed, 19 skipped; changed-line coverage 100% (122 changed lines).
  • The scanner's sequential search: test_sequential_spans_are_found_without_a_binary_search sees 0 bisect_left calls for 600 spans. Three mutants of fd22dc6c fail tests/test_code_spans.py: the closer head reset to 0 with a bisect per span fails that test, the seek that goes back dropped from find fails test_a_search_that_goes_back_finds_the_same_span_again, and group indexing the tuple with a negative index as given fails test_a_span_has_three_groups on pytest.raises(IndexError).
  • _blank_inline on "".join("" * i + "a b " for i in range(2, k + 2)): run reads 3876, 15251, 60501 at k=50, 100, 200 at f65ef04; 202, 402, 802 at 18e39c8. Two mutants of 18e39c8failtests/test_code_spans.py: _blank_inlinesearching without its scanner failstest_blanking_a_line_reads_each_run_once, and the scanner's start index moved one past posfailstest_random_texts_read_as_the_old_regex_did`.
  • On main's code, with the names the test imports given the old regexes' values, tests/test_code_spans.py fails 10 of its 35 tests, the growth ones, on assert ratio < GROWTH_LIMIT (ratios of 1500 to 3600 against a limit of 64); the 25 equivalence tests pass there, as they should. The 36th test, test_a_span_has_three_groups, pins CodeSpan, which main does not have.
  • Mutants of the helper and of the call sites, each in its own run of tests/test_code_spans.py, all fail it: the cut-run skip dropped, the not-after check dropped, the minimum run ignored, the stop ignored, the stale stop cache, the per-length head dropped (growth tests), the after skip dropped, the group-2 slice one character long, the closer taken as the last run of its length, and the same arguments dropped at the four call sites (min_run=3 of degrade, stop of store and online_checks, not_after of code_spans), and a fourth entry in the groups tuple of CodeSpan.group, which test_a_span_has_three_groups fails on pytest.raises(IndexError) (15 mutants in all); the not_after of the masking in link_pieces is caught by tests/test_catalog_links.py::test_an_escaped_backtick_does_not_open_a_code_span.
  • Not run: the other Python versions (3.11, 3.12, 3.14) and CI's merge commit.

Open questions

None.

Revert

A plain revert restores the four regexes and their quadratic scan on mixed backtick runs. 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 new explicit raise; the IndexError of CodeSpan.group(3) and group(-1) comes from the tuple and test_a_span_has_three_groups pins it)
  • No ad-hoc run artifacts committed
  • New files carry the SPDX license header (or are exempt in .github/.licenserc.yaml)

…el#1073)

Four regexes read a code span as a backtick run, a lazy body and a run of the same length (`degrade._INLINE_FENCE`, `skill_markdown.CODE_SPAN_RE`, `memory.store._CODE_SPAN` and `online_checks._URL_CODE_SPAN_RE`, which has the same shape with a body that stops at a block start). A run with no run of its length after it scanned to the end of the text, and so did every run of another length: a text of runs of 1, 2, 3, ... 400 backticks each followed by `a` (80600 characters) took 0.15 s, 60 times what 100 runs (5150 characters) took, and 0.42 s, 71 times, for the URL regex.

`dokimi/code_spans.py` reads each run once, keeps the runs read so far by length, and takes the next run of the opener's length as its closer, so a run with no closer costs no scan and none for a later run of the same length. It takes the differences of the sites as arguments: the shortest opening run, the characters a run may not follow (a backslash for `CODE_SPAN_RE`) and a stop pattern that ends the body (a line break for `_INLINE_FENCE` and `_CODE_SPAN`, a block start for the URL regex). The spans read are unchanged, group 1 the run and group 2 the body.

`tests/test_code_spans.py` compares the helper with a copy of each old regex on every text of a small alphabet up to six characters, on 1500 seeded random texts and on a table of shapes, and times each site on the issue's text and two more shapes.

Signed-off-by: Anton Volkov <antonwolfy@gmail.com>
…fourth raises IndexError (intel#1073)

CodeSpan.group raised IndexError by an explicit branch no test reached. It now indexes a tuple of the whole match, the run and the body, so an out-of-range group fails with the tuple's own IndexError, and a test pins group(0), group(1), group(2) and the IndexError of group(3).

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

exai-bot commented Nov 22, 2026 •

Copy link
Copy Markdown

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

CI at fd22dc6: 21 passing, 3 skipped.

Test notes (1)
  • dokimi/dokimi/code_spans.py:88: With if h and starts[same[h - 1]] >= body: changed to if h and starts[same[h - 1]] > body:, the tests still pass: dokimi/tests/test_code_spans.py, dokimi/tests/test_import_architecture.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: fd22dc6 against merge base 18e39c8
  • Coverage: 2 files in 1 groups
  • Engine: OpenCodeReview v1.13.5-exai.4.8f73eada, us.openai.gpt-6.1-sol
  • Usage: 62k tokens (35k from cache), 27s
  • Tool calls: 8 (5 file_read, 1 ci_status, 1 code_search, 1 local_check_results)
  • small change set: 2 files

Comment thread dokimi/dokimi/memory/store.py Resolved
@codecov-commenter

codecov-commenter commented Nov 22, 2026 •

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.10%. Comparing base (06341ca) to head (fd22dc6).
⚠️ Report is 19 commits behind head on main.
❗ Your organization needs to install the Codecov GitHub app to enable full functionality.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1118      +/-   ##
==========================================
+ Coverage   96.08%   96.10%   +0.01%     
==========================================
  Files         461      465       +4     
  Lines       60836    61481     +645     
  Branches    10517    10663     +146     
==========================================
+ Hits        58457    59085     +628     
- Misses       1473     1478       +5     
- Partials      906      918      +12     
Files with missing lines Coverage Δ
dokimi/dokimi/code_spans.py 100.00% <100.00%> (ø)
dokimi/dokimi/eval/degrade.py 98.20% <100.00%> (ø)
dokimi/dokimi/external/command_checks.py 96.90% <100.00%> (ø)
dokimi/dokimi/external/online_checks.py 96.38% <100.00%> (+<0.01%) ⬆️
dokimi/dokimi/external/skill_markdown.py 100.00% <100.00%> (+1.79%) ⬆️
dokimi/dokimi/memory/store.py 95.50% <100.00%> (+0.02%) ⬆️

... and 34 files with indirect coverage changes

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

…f a line (intel#1073)

Settles the review point that `_blank_inline` built a fresh run index for every span, so an unmatched run before each `b` span rescanned the rest of the line (3876 run reads at 50 spans, 60501 at 200).

`CodeSpanScanner` keeps the runs read and finds the next span from any later position; `_blank_inline` builds one per line and `_code_span` takes it. The closer lookup bisects the runs of its length, so it no longer assumes openers come in order. `iter_code_spans` and `find_code_span` are built on the scanner, and the spans read are unchanged.

Tests: a growth shape with unmatched runs between valid spans for all four sites, a count of run reads through `_blank_inline`, and `_blank_inline` against the old regex on random lines.
Signed-off-by: Anton Volkov <antonwolfy@gmail.com>
@antonwolfy

Copy link
Copy Markdown
Contributor Author

Review points answered at 18e39c8; CI is green.

Follow-up issues opened:

@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 18e39c8)

  • Contract: changed. defaults dokimi/dokimi/code_spans.py:42; defaults dokimi/dokimi/code_spans.py:108
  • Responsibility: candidate. policy dokimi/tests/test_import_architecture.py
  • Dependency: none
  • Review depth: check the changed surface: callers, docs, tests pin new behaviour
  • Coverage gaps: none

The scanner still performs a binary search per span on ordinary Markdown. I checked all four regex replacements, the retained memory scanner, stop boundaries, escapes and match offsets. All 28 selected equivalence and behavior tests passed locally. I did not rerun the timing cases. The earlier scanner-reuse finding is fixed. The new question concerns the shared scanner itself.

Comment thread dokimi/dokimi/code_spans.py Resolved

@vchamarthi vchamarthi 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.

Approving 18e39c8.
Checked: changed tests: 97 passed, fail on main; full suite with main merged in: 28009 passed, its only failures are main's too; merges onto main; 12 broken variants of the changed code, all caught by the tests; 3 mutations and 4 edge inputs tried.
Optional: 2 nits in line comments.

Comment thread dokimi/dokimi/code_spans.py Resolved
Comment thread dokimi/dokimi/code_spans.py Resolved
…isecting per span (intel#1073)

Settles the review points on code_spans.py.

The scanner keeps the index of the next opener and, per run length, the head of its closer list, so sequential searches move forward without a binary search; a search that goes back still seeks with bisect. A test counts the bisect calls of 600 sequential spans (0), and a second test searches back and forth on one scanner.

`CodeSpan.group(-1)` raises IndexError like `re.Match.group(-1)` instead of returning the body.

`find_code_span` had no caller in the package, so it is removed; its tests use `CodeSpanScanner(text, pos).find(pos)`.

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

Copy link
Copy Markdown
Contributor Author

(commented) ### Change class: CONTRACT (head 18e39c8)

@napetrov (#1118 (review)): The question is answered in fd22dc6 (see the reply on code_spans.py:87): sequential spans of ordinary Markdown no longer bisect, and a test counts the calls.

@antonwolfy

Copy link
Copy Markdown
Contributor Author

(approved) Approving 18e39c8.

@vchamarthi (#1118 (review)): Approval with two optional nits; both are the threads on code_spans.py:48 and code_spans.py:141, answered in fd22dc6.

@antonwolfy
antonwolfy requested a review from napetrov November 23, 2026 13:28
@antonwolfy
antonwolfy merged commit fa6eda2 into intel:main Nov 23, 2026
24 checks passed
@antonwolfy
antonwolfy deleted the fix/linear-code-spans branch November 23, 2026 13:45
xaleryb added a commit that referenced this pull request Nov 24, 2026
#1149)

* test(text): check the URL scan's code-span reads by count, not by time (#1118)

The online_checks cases of test_runs_with_no_closer_are_read_in_linear_time compared CPU time at two sizes. The text of those shapes grows with k squared, and _distinct_urls makes a few whole-text passes (splitlines, join, replace), so its ratio sat at 48-54 against a limit of 64 on an idle host and failed on loaded CI runners (74 and 68 on Python 3.11 and the 3.12 wheel leg of the run for #1118). The cases are now counted: test_online_checks_reads_runs_in_linear_work counts _Runs.read at two sizes for the four shapes.

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

* test(text): keep the URL scan's whole-text passes bounded by the text length

The counted reads miss a pass over the whole text per run: a mutant of
_distinct_urls with one such pass per run is green on the count and was red
on the timed check it replaced. Time the scan against the growth of its text:
a linear scan stays under half that factor, a pass per run is above it.

Signed-off-by: Alexander Rybkin <alexander.rybkin@intel.com>

* test(text): count what the URL scan hands to str and regex methods instead of timing it

The timed check added in the previous commit bounded the scan's time ratio by half the text's growth. That fails a scanner that is linear in the bytes, and a bound above the text's growth lets most whole-text passes per run through: with the text growing 116x to 230x, a count, find, upper or re.search over the whole body once per run raises the time ratio to only 0.7 to 3.7 times that growth, against 0.16 to 0.29 for the scan itself.

The test counts instead, through the profiler: the characters of every str method call and the calls of regex methods, at k=25 and k=400. The scan's own passes grow exactly with the text (1.00x on all four shapes, the same on Python 3.11 to 3.14); a pass per run grows 14.9x to 15.9x, a re call per run takes the calls from 7 to 408. The bounds are 4x the text's growth and 2x the calls. Nothing depends on the speed of the machine. Slices, loops in Python and the inside of one regex call stay unseen.

Signed-off-by: Alexander Rybkin <alexander.rybkin@intel.com>

---------

Signed-off-by: Anton Volkov <antonwolfy@gmail.com>
Signed-off-by: Alexander Rybkin <alexander.rybkin@intel.com>
Co-authored-by: Alexander Rybkin <alexander.rybkin@intel.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.

Three Markdown code-span regexes are superlinear on backtick runs of different lengths with no matching closer

5 participants