Skip to content

fix(sed): memoize repeat exploration — nested quantifier no longer hangs (Fixes #1495, Refs rubash#2481) - #1498

Merged
caomengxuan666 merged 2 commits into
mainfrom
fix/1495-sed-nested-quantifier-backtracking
Nov 2, 2026
Merged

caomengxuan666 merged 2 commits into
mainfrom
fix/1495-sed-nested-quantifier-backtracking

Conversation

@caomengxuan666

Copy link
Copy Markdown
Member

WIP: fix(sed): memoize repeat exploration — nested quantifiers no longer backtrack catastrophically (Fixes #1495, Refs rubash#2481, Refs #1496, Refs #1497)

Draft for the 1.2.1 window (1.2.0 release is in flight on another branch). Do not merge while WIP.

Root cause

src/utils/regex.cppm — the portable_regex engine 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:

auto child_states = match_node(node.child, text, state);
for (const auto& next : child_states) {
  if (next.pos == state.pos) continue;                  // empty-match guard (already correct)
  collect_repeat(node, text, next, count + 1, out);     // no memo: 2^(n-1) paths
}
if (count >= node.min_repeat) out.push_back(state);     // out grows per PATH

For s/^\(.*\)*$/X/ the outer * splits the line into every ordered chunk
decomposition; the inner .* yields all cut points, so the recursion visits
2^(n-1) paths for an n-char line (8 chars fine, 32 chars = permanent hang).
Every path pushed a heap-allocated State (captures vector) into out —
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)

  1. Memoization. collect_repeat keeps a per-match_repeat visited set
    keyed on (completed-iteration count, full state). A repeat subproblem
    is a pure function of that key, so the second visit of a key explores
    exactly the states the first visit already emitted. When min==0 and
    max==unlimited every count-dependent branch is constant, so the count
    is dropped from the key — this is what makes \(.*\)* O(states) =
    O(n²) instead of O(states·n).
  2. Incremental output dedup. out is 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, not
    heuristic.
  3. Hard budget as last resort. A single match call is bounded by
    kStepLimit (2²⁶ match_node steps) and kVisitedLimit/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_exceeded instead of hanging. GNU sed answers
    those 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 all
compared. Matrix in D:\tmp\wc1495 (cases.txt / gnu/ / wc/):

  • s/^\(.*\)*$/X/ on 8/32/64/128-char lines and one empty line: identical
  • s/^\(.*\)*$/[\1]/ (3/8 chars), s/^\(a*\)*$/[\1]/: identical
  • s/^\(.*\)\{0,2\}$/X/, s/^\(.*\)\+$/X/, double-nested
    s/^\(\(.*\)*\)*$/X/: identical
  • ERE sed -E 's/^(.*)*$/X/': identical
  • non-anchored s/\(.*\)*e/X/: identical
  • the real bash-it composure metafor() line (helpers.bash:914) on the
    real ag.aliases.bash, TAB kept byte-exact: prints
    the silver searcher (ag) aliases in 0.126s — was permanent hang + 40GB

Known 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)
  • error wording sed: unterminated s command lacks gnu's
    file F line N: prefix (compat-wording class)

Budget trip measurement (documented worst case)

  • 4KB single line + s/^\(.*\)*$/X/: 3.34s / 13.6MB peak (gnu: instant X;
    ours: budget trips → line unchanged + flag set)
  • 64KB single line: 3.07s / 13.7MB peak (trip time flat in line length)
  • 2MB single line + s/foo/QUX/g (legit workload): 0.25s, correct, no trip

Tests

  • new gtest cases (tests/unit/sed/sed_unit_test.cpp):
    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.txt device-name handling) fails
    identically 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_issue1333
    same device-name family; less.less_file_operand_uses_shell_root_issue1385
    depends 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.

…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.
@caomengxuan666
caomengxuan666 marked this pull request as ready for review November 2, 2026 00:28
@caomengxuan666 caomengxuan666 changed the title WIP: fix(sed): memoize repeat exploration — nested quantifier no longer hang (Fixes #1495, Refs rubash#2481) fix(sed): memoize repeat exploration — nested quantifier no longer hangs (Fixes #1495, Refs rubash#2481) Nov 2, 2026
@caomengxuan666
caomengxuan666 merged commit fa65e40 into main Nov 2, 2026
13 checks passed
@caomengxuan666
caomengxuan666 deleted the fix/1495-sed-nested-quantifier-backtracking branch November 2, 2026 01:13
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.

[sed] 嵌套量词 \(.*\)* 触发指数回溯挂死+内存无界膨胀(bash-it describe 全家不可用,rubash#2481 转入)

1 participant