Repository navigation
fix(sed): memoize repeat exploration — nested quantifier no longer hangs (Fixes #1495, Refs rubash#2481) - #1498
Merged
Conversation
…ger hang (Fixes #1495, Refs rubash#2481, Refs #1496) collect_repeat() enumerated every chunk decomposition of a Repeat body with no memoization and deduplicated only the final output vector, so a group-quantifier over an unbounded body (`^\(.*\)*$`) enumerated 2^(n-1) paths for an n-char line: 8 chars fine, 32 chars = permanent hang with ~115MB/s unbounded memory growth (bash-it describe family, 40GB+ in the field). The POSIX empty-iteration guard was already correct; the bug is purely the missing subproblem memoization. utils/regex.cppm Pattern::collect_repeat now: - memoizes per (completed-iteration count, full match state); a repeat subproblem is a pure function of that key, so a revisit explores exactly the states the first visit already emitted. When min==0 and max==unlimited the count is dropped from the key (every count-dependent branch is constant), collapsing `\(.*\)*` to one visit per distinct state: exponential -> polynomial (O(n^(2c)) states for c captures). - deduplicates `out` incrementally (push_unique). unique_states() kept first occurrences in push order, so skipping repeats yields the identical sequence: match results stay byte-identical to the unbounded exploration, including tie-breaking among equal-length parses. - bounds each match call with a work budget (2^26 match_node steps, 300k-entry memo/output caps, ~160MB worst case) so residual polynomial blowup on pathological inputs (nested quantifier x multi-KB single line) degrades to a conservative no-match flagged via the new exported per-thread portable_regex::work_limit_exceeded instead of hanging. Legit workloads stay far below (2MB single line, s/foo/QUX/g: 0.25s). Verification (WSL GNU sed 4.8 oracle, script files, stdout+stderr+rc): - s/^\(.*\)*$/X/ on 8/32/64/128-char lines and empty line: identical - capture forms s/^\(.*\)*$/[\1]/, s/^\(a*\)*$/[\1]/: identical (\(\(x\)*\)* and \(.*\)\{2,\} capture picks still differ from glibc - pre-existing, unchanged, tracked as #1496) - \{0,2\}, \+, double-nested \(\(.*\)*\)*, ERE -E, non-anchored: identical - bash-it composure metafor() line (helpers.bash:914) on the real ag.aliases.bash, byte-exact TAB: prints "the silver searcher (ag) aliases" in 0.126s (was: hang + 40GB) - budget trip: 4KB/64KB single-line pathological = 3.3s / 13.7MB peak (was unbounded); glibc answers those instantly - known bounded divergence, flagged not silent - gtest sed.*: 137/138 (1 env-bound NUL.txt device-name failure, fails identically on the pre-fix control build); grep/expr/csplit/diff/ find/less/nl/tac: 394/396 (both env-bound, no regex involvement) - new regression tests: nested_quantifier_issue1495_* (32/128-char no -hang, capture stability, bash-it metafor line) Note: main @ ff5aa89 does not build on MSVC 14.51 without extra includes (#1497); verification used one-line local unblock patches in 8 unrelated files, none committed here.
This was referenced Nov 1, 2026
caomengxuan666
marked this pull request as ready for review
November 2, 2026 00:28
This was referenced Nov 2, 2026
caomengxuan666
deleted the
fix/1495-sed-nested-quantifier-backtracking
branch
November 2, 2026 01:13
This was referenced Nov 2, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
WIP: fix(sed): memoize repeat exploration — nested quantifiers no longer backtrack catastrophically (Fixes #1495, Refs rubash#2481, Refs #1496, Refs #1497)
Root cause
src/utils/regex.cppm— theportable_regexengine sed uses for BRE/ERE —is not a backtracker but an exhaustive parse enumerator:
match_node()returns the set of ALL states reachable by every parse of a node, and
leftmost-longest selection happens afterwards.
Pattern::collect_repeat()enumerated the loop recursively with no memoization, while
unique_states()deduplicated only the FINAL output vector:For
s/^\(.*\)*$/X/the outer*splits the line into every ordered chunkdecomposition; the inner
.*yields all cut points, so the recursion visits2^(n-1) paths for an n-char line (8 chars fine, 32 chars = permanent hang).
Every path pushed a heap-allocated
State(captures vector) intoout—that is the unbounded memory growth (~115MB/s observed; 40GB+ in the field).
The POSIX empty-iteration guard was already present; the bug is purely the
missing memoization, not a missing empty-match guard.
Fix (
src/utils/regex.cppm)collect_repeatkeeps a per-match_repeatvisited setkeyed on
(completed-iteration count, full state). A repeat subproblemis a pure function of that key, so the second visit of a key explores
exactly the states the first visit already emitted. When
min==0andmax==unlimitedevery count-dependent branch is constant, so the countis dropped from the key — this is what makes
\(.*\)*O(states) =O(n²) instead of O(states·n).
outis deduplicated on push(
push_unique).unique_states()kept first occurrences in push order,and skipping an already-seen state yields the identical
first-occurrence sequence, so match results are byte-identical to the
unbounded exploration — including the engine's tie-breaking among
equal-length parses. A memoized replay contributes nothing new (all its
states are already in
out), which is why skipping it is exact, notheuristic.
kStepLimit(2²⁶match_nodesteps) andkVisitedLimit/kOutLimit(300k entries each, ~160MB worst case), so residual polynomial blowup
(nested quantifier × multi-KB single line) degrades to a conservative
no-match flagged via the new exported per-thread
portable_regex::work_limit_exceededinstead of hanging. GNU sed answersthose inputs instantly (glibc regexec is DFA-based), so a trip is still
a rare pathological-input divergence — bounded and observable instead of
a 40GB hang.
Complexity: for c capture groups, distinct states are O(n^(2c)), each
expanded once → polynomial (was exponential). The 32-char repro goes from
2³¹ paths to ~33k states: 0.19s wall, 11MB peak working set.
Differential verification (WSL GNU sed 4.8 oracle, byte-for-byte)
Script files only (
sed -f, no quoting drift); stdout + stderr + rc allcompared. Matrix in
D:\tmp\wc1495(cases.txt / gnu/ / wc/):s/^\(.*\)*$/X/on 8/32/64/128-char lines and one empty line: identicals/^\(.*\)*$/[\1]/(3/8 chars),s/^\(a*\)*$/[\1]/: identicals/^\(.*\)\{0,2\}$/X/,s/^\(.*\)\+$/X/, double-nesteds/^\(\(.*\)*\)*$/X/: identicalsed -E 's/^(.*)*$/X/': identicals/\(.*\)*e/X/: identicalmetafor()line (helpers.bash:914) on thereal
ag.aliases.bash, TAB kept byte-exact: printsthe silver searcher (ag) aliasesin 0.126s — was permanent hang + 40GBKnown remaining divergences (PRE-EXISTING, unchanged by this PR, now
visible because the shapes terminate — filed as #1496):
\(\(x\)*\)*capture pick: engine[x|[xxxx]]vs gnu[xxxx|[x]]\(.*\)\{2,\}capture pick: engine[c]/[5]vs gnu whole-line(glibc counts a trailing empty iteration toward min and prefers the
single longest iteration; the engine skips empty iterations entirely)
sed: unterminated s commandlacks gnu'sfile F line N:prefix (compat-wording class)Budget trip measurement (documented worst case)
s/^\(.*\)*$/X/: 3.34s / 13.6MB peak (gnu: instantX;ours: budget trips → line unchanged + flag set)
s/foo/QUX/g(legit workload): 0.25s, correct, no tripTests
nested_quantifier_issue1495_no_catastrophic_backtracking(32/128-char),..._capture_selection_is_stable,..._bashit_metafor_line— all pass--gtest_filter=sed.*: 137/138; the 1 failure(
sed.nul_txt_reads_file_issue1333,NUL.txtdevice-name handling) failsidentically on the pre-fix control build — environment-bound on this
Win10 19045 machine, no regex involvement
grep.*:expr.*:csplit.*:diff.*:find.*:less.*:nl.*:tac.*:394/396; both failures env-bound (
grep.nul_txt_reads_file_issue1333same device-name family;
less.less_file_operand_uses_shell_root_issue1385depends on a winuxsh root env this machine does not provide)
Build note
main @ ff5aa89 does not build on MSVC 14.51 (VS18 Community) without
one-line include unblocks in 8 unrelated files (
<time.h>,<string_view>)— filed as #1497. Verification here used those local unblocks; none are
committed in this PR.