Skip to content

grep: accelerate portable_regex default path with compile-time prefilters (#1531) - #1532

Merged
caomengxuan666 merged 1 commit into
mainfrom
fix/grep-default-engine-1531
Nov 7, 2026
Merged

caomengxuan666 merged 1 commit into
mainfrom
fix/grep-default-engine-1531

Conversation

@caomengxuan666

Copy link
Copy Markdown
Member

Summary

Fixes the root cause of #1531: the default (no-flag BRE) grep path was ~35-73x slower than -F/-E because the portable_regex local engine attempted a full interpreter parse at every position of every line, with per-attempt state/result vector allocations. -E was fast only because grep.cpp wires text-layer fast prefixes for ExtendedRegex exclusively; BRE got nothing.

The fix lives in src/utils/regex.cppm at engine level, so every local-engine consumer (grep BRE/ERE fallback, sed, expr, find, csplit, nl, less, diff, tac) benefits, and the fast path cannot diverge from the interpreter — it is derived from the same parsed node tree, mirroring GNU grep's compile-time kwset/dfa "must" analysis, not a text re-lex:

  1. anchored — pattern's first consumable element is ^, so every match starts at absolute position 0: single attempt at 0, none when start > 0.
  2. required literal prefix — bytes every match must begin with (Literal runs, single-member char classes, {m} expansions of literal bodies). find_first memchr-jumps between candidates and runs the interpreter only there; match_at/matches_entire reject up front. Candidate positions provably coincide with what legacy traversal attempts (continuation-range first bytes are rejected), so skipping non-candidates cannot change which positions get tried.
  3. first-byte bitset — 256-bit set of bytes the first consumed byte may be (classes expanded by exact per-byte replication of class_matches(); literals by the engine's own fold rule); futile attempts skipped, legacy advance rule kept.
  4. pure-literal whitelist — whole tree provably Literal-only with no captures, so a prefix candidate IS the match. Anything not provably literal keeps the interpreter.

All four are necessary conditions, never sufficient: alternations, backreferences, dot, empty-matchable roots and dense first sets keep the legacy per-position scan. -E/-F/-P paths are untouched.

Performance (interleaved A/B, same session, median of 2x5 runs, 64MiB / 999421 lines)

mode base fixed delta
BRE grep -c fox 3792 ms 278 ms 13.6x, now <= -F
BRE grep -c f[o]+x 4971 ms 277 ms 17.9x
BRE grep -c foxtrot 4287 ms 263 ms 16.3x
BRE grep -c ^alpha 4576 ms 524 ms 8.7x
BRE grep -n fox 4419 ms 945 ms 4.7x (printer-bound)
ERE -E -c fox 284 ms 279 ms -2% (unchanged)
FIX -F -c fox 284 ms 286 ms +1% (unchanged)
PERL -P -c fox 583 ms 569 ms -2% (unchanged)

-E/-F/-P within plus/minus 2% (requirement: within 10%). Raw: target/issue-suites/results/1531/perf-ab.txt.

Correctness differential vs WSL GNU grep 3.11

591 pattern x flag cases (>=300 required) over mixed text (long/short/empty lines, duplicates, digits, punctuation), Chinese UTF-8, binary bytes (NUL + high bytes), CRLF, and 100k-char-token inputs; covering literal / . / * / + / ? / [a-z] / [^] / anchors / \(\)\1 backreferences / \{m,n\} / \b / \w / \s / -i / -w / -x / -v / -c / -n / -o / -l / -h / -e multi / -f pattern file / empty pattern / invalid patterns / 5000-char patterns / BRE vs -E semantic split points / -P spot checks:

  • 583/591 byte-identical (stdout + exit code; stderr wording logged separately, not counted)
  • 0 new divergences introduced by this change
  • 8 pre-existing divergences, identical on the unmodified base binary: GNU accepts bare +/? as literals in ERE (2), [中文] class byte-vs-locale semantics under -o (1), GNU "binary file matches" counting nuance (1), 100k-char-token exit-253 work-limit cases (4). Raw artifacts: target/issue-suites/results/1531/ (case-detail.log, existing.log; regressions.log empty).

Other verification

  • Full unit suite: 3753 tests — identical failure set as the unmodified base (20 environment-bound: NUL-device-name issue1333 family, shell-root path issue1385/1364 family, nohup/nice process tests). No regressions.
  • scripts/check_i18n_drift.py --i18n-repo <fresh clone>: OK (21 recorded items, none new) — no option/help strings changed.
  • scripts/format.py --check src/utils/regex.cppm: clean.

Note on the issue report

The issue's --no-pcre 0.046s datapoint is a false alarm: --no-pcre is not a WinuxCmd grep option (nor a GNU one); it belongs to a different grep on the reporter's PATH. The default-engine slowness itself was real and is what this PR fixes.

Fixes #1531

…ters (#1531)

Root cause: the local engine (detail::Parser + NodeKind interpreter) was
the only matcher used for the default BRE path, and find_first attempted
a full parse at EVERY position of every line, each attempt allocating
result/state vectors. A literal pattern like `fox` therefore scanned
64MiB in ~3.8s while `-F` (Aho-Corasick) and `-E` (text-layer fast
prefixes wired only for ExtendedRegex) did it in ~0.28s — the 35-73x
gap reported in #1531.

Fix at engine level, derived from the same parsed node tree GNU's
prefilters are derived from (kwset / dfa "must" analysis) — no
text-layer re-lexing, so the fast path cannot diverge from the
interpreter that still validates every candidate:

- FastPath.anchored: root's first consumable element is '^', so every
  match starts at absolute position 0; find_first runs the single
  attempt at 0 (and none when start > 0).
- FastPath.prefix: bytes every match must begin with (Literal runs,
  single-member classes, {m} expansions of literal bodies, zero-width
  assertions skipped). find_first memchr-jumps between candidates and
  runs the interpreter only there; match_at / matches_entire reject up
  front. Candidates from an ASCII/lead-byte first byte sit exactly on
  positions legacy traversal attempts (start, then non-UTF-8-
  continuation positions), so skipping non-candidates cannot change
  results; a continuation-range first byte is rejected in
  build_fast_path for that reason.
- FastPath.first: 256-bit set of bytes the first consumed byte may be
  (classes expanded by exact per-byte replication of class_matches(),
  literals via the engine's own fold rule). Legacy advance rule kept;
  only the futile attempts are skipped.
- FastPath.pure_literal: whole tree provably Literal-only with no
  captures (whitelist; everything else falls back to the interpreter) —
  a prefix candidate IS the match, byte-identical to the interpreter's
  report.

All four are necessary conditions, never sufficient: anything not
modeled (alternations, backreferences, dot, empty-matchable roots,
dense first sets) keeps the legacy per-position scan. `-E`, `-F` and
`-P` paths are untouched.

Interleaved A/B on 64MiB/999421 lines (median of 5, base vs fixed):
- BRE  grep -c fox        3792ms -> 278ms  (13.6x; now <= -F)
- BRE  grep -c f[o]+x     4971ms -> 277ms  (17.9x)
- BRE  grep -c foxtrot    4287ms -> 263ms  (16.3x)
- BRE  grep -c ^alpha     4576ms -> 524ms  (8.7x)
- ERE -E -c fox            284ms -> 279ms   (-2%)
- FIX -F -c fox            284ms -> 286ms   (+1%)
- PERL -P -c fox           583ms -> 569ms   (-2%)

Verification:
- Differential vs WSL GNU grep 3.11, 591 pattern x flag cases over
  mixed/UTF-8/binary/CRLF/huge-token inputs: 583 byte-identical
  (stdout + exit code), 0 new divergences, 8 pre-existing ones
  (identical on base; raw artifacts under
  target/issue-suites/results/1531/).
- Full unit suite: 3753 tests, same 20 failures as unmodified base
  (NUL-device-name, shell-root path, nohup/nice environment issues).
- scripts/check_i18n_drift.py: OK (no user-visible strings changed).
@caomengxuan666

Copy link
Copy Markdown
Member Author

Captain review verdict: CAN MERGE

Reviewed the full diff (src/utils/regex.cppm, +425/−0, single file) and the CI state. This fixes the reported defect.

What it does. Engine-level compile-time prefilters on the local regex engine, mirroring GNU's kwset/dfa "must" analysis: anchored (single attempt at 0), required literal prefix (memchr-jump + interpreter per candidate), first-byte bitset (skip futile attempts, legacy advance kept), and a pure-literal whitelist (a prefix candidate is the match). All four are necessary conditions, never sufficient — every candidate still goes through the unmodified interpreter, except the provably literal-only whitelist. PCRE2/-E/-F paths return before the fast checks, untouched.

Soundness read. The analysis is conservative throughout, which is the load-bearing property: analyze_first falls back on Dot / BackReference / empty-matchable roots; extract_required_prefix stops (keeping the valid prefix so far) at Alternation / Dot / BackReference and at min_repeat == 0; the continuation-byte guard rejects prefix-first-bytes in [0x80, 0xC0) so candidates only land where the legacy traversal attempts; pure_literal requires a Literal-only tree, zero captures, and length == prefix size. I found no unsound arm.

Evidence.

  • CI run 42257327899 is fully green: builds (x64/arm64, default/full), baseline, baseline-growth, compare, and oracle all success. The oracle leg's first failure was infrastructure only (savannah gnulib fetch HTTP 500 while building GNU master — same signature as feat(wpm): bundle packages via installs: [...] index field (+3 latent include fixes) #1529's differential run); re-run green.
  • Author's differential vs WSL GNU grep 3.11: 583/591 byte-identical, 0 new divergences (8 pre-existing, identical on the base binary). Author's A/B on the reported 64 MiB corpus: BRE grep -c fox 3792 ms → 278 ms (13.6×, now ≤ -F); -E/-F/-P within ±2%.
  • Note for the record: the issue's --no-pcre datapoint is correctly identified as a false alarm (not a WinuxCmd option); the default-path slowness itself was real and is what this fixes.

Two non-blocking notes.

  1. No new regression tests ship with the PR — the four prefilter arms have no dedicated pins (the existing suite + differentials carry the coverage). A follow-up pin set for the arms (anchored / prefix with backrefs + intervals / first-set / pure-literal, incl. -i and UTF-8 boundary cases) would be worth adding.
  2. This does not implement the GNU engine split (fast DFA default, PCRE opt-in) — but it achieves the reported goal (default path now ≤ -F) with a less invasive change, so the split is not needed for grep's default engine is ~73x slower than --no-pcre, and that flag is undocumented #1531. The PCRE-default wiring stays as is.

Merging is the maintainer's call; I am not merging from here.

@caomengxuan666
caomengxuan666 merged commit 26a0e9b into main Nov 7, 2026
16 of 17 checks passed
@caomengxuan666
caomengxuan666 deleted the fix/grep-default-engine-1531 branch November 18, 2026 05:50
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.

grep's default engine is ~73x slower than --no-pcre, and that flag is undocumented

1 participant