Repository navigation
fix(text): find code spans in linear time on mixed backtick runs (#1073) - #1118
Conversation
…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>
|
✅ OpenCodeReview: Review complete: 0 finding(s) across 2 selected item(s). CI at Test notes (1)
Review details
|
|
Codecov Report✅ All modified and coverable lines are covered by tests. 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
🚀 New features to boost your workflow:
|
…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>
|
Review points answered at Follow-up issues opened:
|
napetrov
left a comment
There was a problem hiding this comment.
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.
vchamarthi
left a comment
There was a problem hiding this comment.
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.
…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>
@napetrov (#1118 (review)): The question is answered in fd22dc6 (see the reply on |
@vchamarthi (#1118 (review)): Approval with two optional nits; both are the threads on |
#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>
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, andonline_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. Onmain, for the text"".join("" * i + "a" for i in range(1, m + 1))`:degrade._INLINE_FENCEskill_markdown.CODE_SPAN_REmemory.store._CODE_SPANonline_checks._URL_CODE_SPAN_REWith 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.findper 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 forCODE_SPAN_RE), and a stop pattern that ends the body (a line break for_INLINE_FENCEand_CODE_SPAN,online_checks._BLOCK_STARTfor the URL regex).Closes #1073
Changes
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_spansandreplace_code_spanswith the arguments above, andCodeSpan, which answersstart(),end(),span()andgroup(0|1|2)like there.Matchthe callers read (groupindexes a tuple of the three, sogroup(3)andgroup(-1)raise the tuple'sIndexError, asre.Match.groupdoes). It is a new module, not part oftext_spans.py, which another open PR edits;tests/test_import_architecture.pylists it in the foundation layer.eval/degrade.py:_replace_code_blocksreplaces inline fences withreplace_code_spans(line, ..., min_run=3, stop=LINE_BREAK);_INLINE_FENCEis gone.external/skill_markdown.py:CODE_SPAN_REis replaced bycode_spans(text)(a run after a backslash opens no span);link_piecesandexternal/command_checks.pyuse it. Only the definition and its direct uses changed.memory/store.py:_blank_inlinebuilds oneCodeSpanScanner(line, pos, stop=LINE_BREAK)per line and_code_spansearches 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 + "ab" 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_urlsfinds the code spans that hide a URL withiter_code_spans(body, stop=_BLOCK_START_RE);_URL_CODE_SPAN_REis gone.tests/test_code_spans.py(alsotest_sequential_spans_are_found_without_a_binary_search, which counts thebisect_leftcalls of 600 sequential spans, andtest_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_regexcompares_blank_inlinewith the old regex on random lines, andtest_blanking_a_line_reads_each_run_oncecounts run reads through_blank_inline.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-localpasses the existing tests of the four sites unchanged.CODE_SPAN_RE,_INLINE_FENCE,_CODE_SPANand_URL_CODE_SPAN_REno longer exist; the only users were in the files above.CODE_SPAN_RE's function replacement returns an iterator ofCodeSpan, 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=TrueonCodeSpan, the initial value of the stop-position cache (it only has to exceed any position it is asked about), the default head0of 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 bound0of 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.pyon 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 (keepcode_spans(para)here and #1046'sBLOCK_ENDthere). #849 editscommand_checks.pyfar from these lines (command_findings), #1092 edits the link code ofexternal/skill_markdown.py(link_piecesand new helpers) and usesCODE_SPAN_REinlink_pieces, which this change replaces withcode_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 totests/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(onmain06341ca4):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).test_sequential_spans_are_found_without_a_binary_searchsees 0bisect_leftcalls for 600 spans. Three mutants offd22dc6cfailtests/test_code_spans.py: the closer head reset to 0 with a bisect per span fails that test, the seek that goes back dropped fromfindfailstest_a_search_that_goes_back_finds_the_same_span_again, andgroupindexing the tuple with a negative index as given failstest_a_span_has_three_groupsonpytest.raises(IndexError)._blank_inlineon"".join("" * i + "ab" for i in range(2, k + 2)): run reads 3876, 15251, 60501 at k=50, 100, 200 atf65ef04; 202, 402, 802 at18e39c8. Two mutants of18e39c8failtests/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 pastposfailstest_random_texts_read_as_the_old_regex_did`.main's code, with the names the test imports given the old regexes' values,tests/test_code_spans.pyfails 10 of its 35 tests, the growth ones, onassert 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, pinsCodeSpan, whichmaindoes not have.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), theafterskip 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=3ofdegrade,stopofstoreandonline_checks,not_afterofcode_spans), and a fourth entry in the groups tuple ofCodeSpan.group, whichtest_a_span_has_three_groupsfails onpytest.raises(IndexError)(15 mutants in all); thenot_afterof the masking inlink_piecesis caught bytests/test_catalog_links.py::test_an_escaped_backtick_does_not_open_a_code_span.Open questions
None.
Revert
A plain revert restores the four regexes and their quadratic scan on mixed backtick runs. Nothing is stored.
Checklist
pytestpassesruff,mypy, and schema checks passAGENTS.mdraise/exit and test names the doc, contract or issue it traces to (no new explicitraise; theIndexErrorofCodeSpan.group(3)andgroup(-1)comes from the tuple andtest_a_span_has_three_groupspins it).github/.licenserc.yaml)