Repository navigation
grep: accelerate portable_regex default path with compile-time prefilters (#1531) - #1532
Conversation
…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).
Captain review verdict: CAN MERGEReviewed the full diff ( What it does. Engine-level compile-time prefilters on the local regex engine, mirroring GNU's kwset/dfa "must" analysis: Soundness read. The analysis is conservative throughout, which is the load-bearing property: Evidence.
Two non-blocking notes.
Merging is the maintainer's call; I am not merging from here. |
Summary
Fixes the root cause of #1531: the default (no-flag BRE) grep path was ~35-73x slower than
-F/-Ebecause the portable_regex local engine attempted a full interpreter parse at every position of every line, with per-attempt state/result vector allocations.-Ewas fast only because grep.cpp wires text-layer fast prefixes forExtendedRegexexclusively; BRE got nothing.The fix lives in
src/utils/regex.cppmat 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:^, so every match starts at absolute position 0: single attempt at 0, none whenstart > 0.{m}expansions of literal bodies).find_firstmemchr-jumps between candidates and runs the interpreter only there;match_at/matches_entirereject 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.class_matches(); literals by the engine's own fold rule); futile attempts skipped, legacy advance rule kept.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/-Ppaths are untouched.Performance (interleaved A/B, same session, median of 2x5 runs, 64MiB / 999421 lines)
grep -c fox-Fgrep -c f[o]+xgrep -c foxtrotgrep -c ^alphagrep -n fox-E -c fox-F -c fox-P -c fox-E/-F/-Pwithin 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 /\(\)\1backreferences /\{m,n\}/\b/\w/\s/-i/-w/-x/-v/-c/-n/-o/-l/-h/-emulti /-fpattern file / empty pattern / invalid patterns / 5000-char patterns / BRE vs-Esemantic split points /-Pspot checks:+/?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.logempty).Other verification
issue1333family, shell-root pathissue1385/1364family, 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-pcre0.046s datapoint is a false alarm:--no-pcreis 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