Skip to content

fix: avoid quadratic re_newline_whitespace scan in process_text - #296

Open
Chandan3456 wants to merge 1 commit into
matthewwithanm:developfrom
Chandan3456:newline-whitespace-quadratic
Open

Chandan3456 wants to merge 1 commit into
matthewwithanm:developfrom
Chandan3456:newline-whitespace-quadratic

Conversation

@Chandan3456

Copy link
Copy Markdown

process_text collapses newline whitespace in every text node with re_newline_whitespace, [\t \r\n]*[\r\n][\t \r\n]*. on a run of spaces or tabs that contains no newline, re.sub retries the match at each position of the run and every attempt scans to the end of the run before failing, so conversion time grows with the square of the run length. this is the default path (wrap=False, any text outside <pre>), so a single small document like '<p>' + ' ' * 65536 + 'x</p>' takes about ten seconds to convert, and each doubling of the run quadruples that. it is the same kind of regex backtracking (CWE-1333) as the <pre> strip in #286 / #287, but on ordinary text, which that change does not touch.

the original pattern can only ever match starting at the first character of a whitespace run, so a (?<![\t \r\n]) lookbehind leaves the matches unchanged and makes every other start position fail in one step. compared against the old pattern on all 488,281 strings of length 0 to 8 over space, tab, \r, \n and x, plus 20,000 random strings that include nbsp, \v and \f: no differences.

markdownify() on python 3.8, same process, identical output:

input before after
16 KiB of spaces in <p> 0.59 s 0.0007 s
32 KiB of spaces in <p> 2.42 s 0.0014 s
64 KiB of spaces in <p> 9.60 s 0.0024 s
64 KiB of ordinary words 0.0020 s 0.0021 s

the new test in tests/test_basic.py fails on develop (about 18 s) and passes in milliseconds with the fix. pytest (84 passed), flake8, restructuredtext-lint, mypy and the wheel/sdist build are clean.

On a run of spaces or tabs with no newline, re.sub retried the pattern
at every position of the run and each attempt scanned to the end of it,
so text conversion was quadratic in the run length (64 KiB of spaces
took about 10 s). A match can only start at the beginning of a
whitespace run, so anchor it there with a lookbehind: matches are
unchanged and the scan is linear.
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.

1 participant