Skip to content

fix(text): seven regexes read a run of spaces in linear time (#1074) - #1121

Merged
xaleryb merged 1 commit into
intel:mainfrom
antonwolfy:fix/linear-whitespace-runs
Nov 23, 2026
Merged

xaleryb merged 1 commit into
intel:mainfrom
antonwolfy:fix/linear-whitespace-runs

Conversation

@antonwolfy

Copy link
Copy Markdown
Contributor

Summary

Seven regexes had whitespace matched on both sides of an optional token (\s*\|?\s*, \s*,?\s*=, \s*(?:<>)?\s*, [{\[]?\s*, )?\s*p, \s*:?\s*$, \S*\s*\d), so a run of spaces that ended in a failure was split between the two runs at every position and the time grew with the square of the run. #1074 names the first two; the same search over dokimi/dokimi/ found five more of the same shape that go through the same reproduction. On main, CPU time for 1500 and for 6000 spaces:

Regex Input 1500 6000 Ratio
prefilter._TABLE_DELIMITER (fullmatch) " " * n + "|" 0.0108 s 0.1737 s 16.1
prefilter._TABLE_DELIMITER (fullmatch) "|--" + " " * n + "x" 0.0035 s 0.0591 s 16.9
prefilter._TABLE_DELIMITER (fullmatch) "-" + " " * n + "x" 0.0035 s 0.0583 s 16.5
l0/adapters assignment scan (finditer, re.M) "a" + " " * n + "x" 0.0009 s 0.0146 s 15.4
memory/store._EMPTY_LINK (match) "](" + " " * n + "x" 0.0010 s 0.0146 s 15.4
frontmatter_shape.YAML_KEY_RE (match) " " * n + "x" 0.0113 s 0.1807 s 16.0
shell_sed._PRINT_ONLY (fullmatch) " " * n + "x" 0.0010 s 0.0146 s 15.3
inspect_ai._DOC_SECTION (match) "Args" + " " * n + "x" 0.0034 s 0.0552 s 16.5
spans version_gate (search) "requires" + " " * n + "!" 0.0045 s 0.0710 s 15.9

A ratio near 16 for 4x the input is quadratic; linear work gives about 4. With this change every row above is 3.7 to 4.3. The issue's suggested form (\s*(?:\|\s*)? for the leading pipe alone) leaves the table delimiter quadratic where :?-+:?\s* is followed by the final \|?\s* ("-" + " " * n + "x", the third row), so the table pattern is written once for the leading pipe, the runs between cells and the final pipe: \s*(?:\|\s*)?:?-+:?(?:\s*\|\s*:?-+:?)*\s*(?:\|\s*)?. The issue's other repro, many short cells ("|--" + " |--" * n + " x"), is already linear on main (ratio 4.1) and stays so.

Two other regexes of the same cause need a different rewrite or sit in a file other work touches, and are tracked in #1119 (harnesses/tbench_v1._SIZE_RE) and #1120 (the [^\n]*\)?\]?\s*= check in l0/adapters._bzl_public).

Closes #1074

Changes

  • context/prefilter.py: _TABLE_DELIMITER writes each whitespace run once.
  • repos/l0/adapters.py: the assignment pattern is \s*(?:,\s*)?=(?!=) and moves from an inline literal to the module constant _BZL_BINDING, so a test can read it. _bzl_public uses it unchanged otherwise.
  • memory/store.py _EMPTY_LINK is \]\(\s*(?:<>\s*)?\); external/frontmatter_shape.py YAML_KEY_RE takes (?:[{\[]\s*)?; repos/shell_sed.py _PRINT_ONLY takes the address and its \s* as one optional group before p; task_formats/imports/inspect_ai.py _DOC_SECTION takes \s*(?::\s*)?$; novelty/spans.py version_gate takes \s+(?:\S+\s*)?\d.
  • tests/test_whitespace_run_regexes.py: for each regex, a copy of the old one is compared with the new one on a hand table and on 1500 seeded random strings (a 3000-string table-delimiter corpus, and the assignment pattern's group 1, group 2 and match end), and a growth test with tests/growth_timing.py for each repro above.
  • Changelog fragment (Fixed).

Risk

None for output: each new regex accepts the same strings, with the same groups and match ends, as the one it replaces (the equivalence tests above). Only the time on a long run of whitespace changes. Open PR #1045 edits novelty/spans.py two lines below the version_gate line this change edits (the ordering rule), and #1099 edits only the docstring of repos/shell_sed.py, far from _PRINT_ONLY: neither touches a line this change touches, so a merge with either is clean.

Testing

On Linux, at 6597fde9 (on main 06341ca):

  • make ci-local: 38 passed, 0 failed, 14 skipped (the matrix legs on other Pythons, semgrep, micromamba, the atheris fuzz run, and jobs that only run on a push). 26001 tests passed, 19 skipped; changed-line coverage 100%.
  • On main's code the new test file gives 13 failed, 7 passed: the 13 growth tests fail, the first on CPU time grew 160x for 16x the whitespace; the 7 equivalence tests pass there, as they should (the old and the new regex agree). On this branch all 20 pass.
  • Mutants: each of the seven equivalence tests fails when its new regex drops the whitespace after its optional token, and its growth tests fail when the old form is put back (14 mutants, all fail).
  • Merged together with fix/linear-citation-and-swebench, fix/linear-code-spans on main 06341ca: pytest -n auto 26169 passed, 19 skipped, mypy clean, ruff check clean.
  • Not run: the other Python versions (3.11, 3.12, 3.14) of the CI matrix.

Open questions

None.

Revert

A plain revert restores the old regexes and their quadratic time on a long run of spaces. 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)

)

The prefilter table delimiter, the `.bzl` assignment scan, the memory empty-link check, the front matter key check, the sed print-only script check, the Inspect AI docstring heading and the novelty version_gate tag each had `\s*` on both sides of an optional token (`\s*\|?\s*`, `\s*,?\s*=`, `\s*(?:<>)?\s*`, `[{\[]?\s*`, `)?\s*p`, `\s*:?\s*$`, `\S*\s*\d`). A run of whitespace that ended in a failure was split between the two runs at every position, so 6000 spaces took 16 times as long as 1500 (0.17 s for `" " * 6000 + "|"` against the table delimiter).

Each run is now written once, as `\s*(?:\|\s*)?`, `\s*(?:,\s*)?=` and the like, so a run has one way to be read. The table delimiter is written `\s*(?:\|\s*)?:?-+:?(?:\s*\|\s*:?-+:?)*\s*(?:\|\s*)?`: the issue's form for the leading pipe alone leaves `:?-+:?\s*` followed by the final `\|?\s*` quadratic (`"-" + " " * n + "x"`). The strings matched, the groups and the match ends are unchanged: the new test keeps each old regex and compares it with the new one on hand tables and on seeded random strings. The assignment pattern moves to a module constant (`_BZL_BINDING`) so the test can read it.

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

exai-bot commented Nov 22, 2026 •

Copy link
Copy Markdown

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

CI at `6597fde`: 1 cancelled, 24 passing, 3 skipped

27 of 28 checks passed or were skipped; the Python 3.11 package-install smoke test was cancelled. After reviewing the diff, source, workflow, and available CI evidence, there is no demonstrated change-caused failure or justified code fix. Rerun the cancelled check to complete validation.

Check Status Assessment
Package install smoke test (py3.11) cancelled Cause unclear. The check was cancelled, but no job log or cancellation reason is available. The diff changes regexes and their tests, not the package-install workflow; the available evidence cannot establish whether the job started or why it was cancelled.
Review details
  • Commit reviewed: 6597fde against merge base 06341ca
  • Coverage: 9 files in 1 groups
  • Engine: OpenCodeReview v1.13.5-exai.4.8f73eada, us.openai.gpt-6.1-sol
  • Usage: 68k tokens (22k from cache), 19s
  • Tool calls: 4 (1 ci_status, 1 code_search, 1 file_read, 1 local_check_results)
  • Linear-time whitespace regex updates, regression tests, and changelog: 9 files

@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.07%. Comparing base (06341ca) to head (6597fde).
❗ Your organization needs to install the Codecov GitHub app to enable full functionality.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1121      +/-   ##
==========================================
- Coverage   96.08%   96.07%   -0.02%     
==========================================
  Files         461      461              
  Lines       60836    60837       +1     
  Branches    10517    10517              
==========================================
- Hits        58457    58449       -8     
- Misses       1473     1478       +5     
- Partials      906      910       +4     
Files with missing lines Coverage Δ
dokimi/dokimi/context/prefilter.py 98.58% <100.00%> (ø)
dokimi/dokimi/external/frontmatter_shape.py 90.90% <100.00%> (ø)
dokimi/dokimi/memory/store.py 95.48% <100.00%> (ø)
dokimi/dokimi/novelty/spans.py 96.52% <ø> (ø)
dokimi/dokimi/repos/l0/adapters.py 94.31% <100.00%> (+0.01%) ⬆️
dokimi/dokimi/repos/shell_sed.py 100.00% <100.00%> (ø)
dokimi/dokimi/task_formats/imports/inspect_ai.py 87.36% <ø> (-1.08%) ⬇️

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

@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 6597fde)

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

All seven regex rewrites preserve the matches used by their callers. I checked the table delimiter, Starlark binding groups, empty links, YAML keys, sed print commands, Inspect section headings and novelty version gates. All seven differential tests passed, including the captured groups and match endpoints used by the scanners. The focused integration runs with #1118 and #1099 passed 117 and 37 tests, respectively.

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

Approved on 6597fde. Ran the head merged with current main: 280000 random inputs over the seven patterns give identical spans and groups for the old and the new pattern, runs of spaces at 10x and 100x are linear on the head and quadratic on main, the new test file passes (14 of its tests fail on main's code, the equivalence tests pass on both), and the full suite, ruff, mypy, bandit, growth and comment-block gates are clean. CI is green and no thread is open.

@xaleryb
xaleryb merged commit c09caa3 into intel:main Nov 23, 2026
35 of 36 checks passed
@antonwolfy
antonwolfy deleted the fix/linear-whitespace-runs branch November 23, 2026 09:58
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.

Two adjacent \s* around an optional token make the table delimiter check and the assignment scan quadratic on a whitespace run

5 participants