Repository navigation
Match common MATCHES patterns without a regex engine (FFE optimization) - #13564
Merged
leoromanovsky merged 6 commits intoDec 1, 2026
Merged
leoromanovsky merged 6 commits into
leoromanovsky merged 6 commits into
Conversation
RegexMatcher.compile tries two engine-free tiers before falling back to RE2/J:
- a segment matcher, after the glob matcher of the sampling-rules prototype: literal pieces with
single-character wildcards (.), separated by unbounded gaps (.*, .+), placed left to right with
indexOf. Greedy leftmost placement is exact for unbounded gaps, so it never backtracks.
- a bit-parallel (shift-and) matcher for runs of literals and character classes with ?, *, + and
{n,m}, up to 64 positions, with startsWith/endsWith prefilters.
Both decide ASCII input only, where the Rust dialect's Unicode classes and case folding agree
with ASCII. Other inputs go to a fallback that compiles #13487's matcher on first use, so no
RE2/J program is retained for patterns whose inputs stay ASCII. compileWithoutPrototype keeps
the RE2/J engine for the differential test, the benchmark baseline and white-box tests.
PrototypeRegexTest checks both tiers and the wired-in compile against compileWithoutPrototype on
983k generated inputs over every fixture pattern. RegexShapesBenchmark compares java.util.regex,
RegexMatcher alone and the new tiers on common pattern shapes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Contributor
Contributor
🟢 Java Benchmark SLOs — All performance SLOs passed
PR vs. master results
Commit: Load and DaCapo benchmarks can be triggered manually in the GitLab pipeline. Results will appear in the Benchmarking Platform UI after completion. |
Coverage verification failed on PrototypeRegex.Parser. The tests pin what the subset accepts and what it leaves to RE2/J: leading flags, end anchors, escapes, every POSIX class with a member and a non-member, class edge cases, set operations and nested classes, counted and lazy quantifiers, and nested repetition; plus Delegate keeping the wrapped matcher's kind. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review found that (?i)[^a-z] negated the class before folding, so folding added the letters
back and (?i)^[^a-z]+$ matched "abc". The Rust crate and RE2/J fold first, then negate. The
differential test now includes (?i) negated classes and agrees on 986k inputs.
Also stop the optional-position closure once nothing new is reachable, instead of always running
the longest optional run (up to 63 steps per character for patterns like [0-9]{0,40}).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The standalone compile wraps #13487's literal matchers in a delegate, which showed a few ns that a configuration never pays: compile hands those patterns to the literal tiers directly. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The prototype parsed a repetition count with Integer.parseInt, which reads
a sign, leading zeros and negative numbers. RE2/J reads a zero-padded
count such as {0002147483647} as literal text, and RegexMatcher.Limits
skips counts of more than 4 digits, so nothing had sized it: the prototype
read a count of 2^31 and exhausted the heap at configuration load. Counts
are now 1 to 4 plain digits without a leading zero, as both read them, and
anything else in braces goes to RE2/J.
Also from Bits' review:
- The segment matcher placed segments by counting chars, so a surrogate
pair under '.' or in a counted gap was miscounted (^a.b$ missed "a😀b").
Patterns that count code points now fall back on input with a surrogate.
- (?i) with a two-member class that holds no letter, like [\x00\x01],
indexed set['\0' - 32].
- max < min is rejected rather than built.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A '.' compared in place already falls back on a surrogate, so only counted gaps and an end-anchored segment with a '.' can miscount. Scanning the whole input for every pattern with a '.' cost a pass over long misses on the commonest glob, an unescaped domain like @mycompany.com. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
leoromanovsky
merged commit Dec 1, 2026
e31d585
into
leo.romanovsky/ffe-regex-linear-time
679 of 683 checks passed
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.
What Does This Do
Stacked on #13487 (review only the commit after it). Most
MATCHES/NOT_MATCHESpatterns that #13487'sRegexMatcherwould send to RE2/J are now matched without a regex engine, with the same results in the Rust dialect.RegexMatcher.compiletries two engine-free tiers before falling back to RE2/J:.is a one-character wildcard, separated by unbounded gaps (.*,.+). For example:@mycompany.com,^api-.*-prod$,checkout.*v2,(?i)^admin.*panel. It rejects on minimum length, checks an anchored suffix before the middle, and places each piece at its leftmost position withindexOf. With only unbounded gaps, leftmost placement is exact, so it never backtracks.?,*,+and{n,m}, up to 64 positions after unrolling. For example:^[a-zA-Z0-9._%+-]+@site\.test$,^org-0000-[a-z]+-[0-9]{2,6}$,^\d+$. Each input character costs one table lookup and a few mask operations, and nothing is allocated. Anchored literal prefixes and suffixes are checked withstartsWith/endsWithfirst, as the RE2/J tier's prefilter does.Both tiers decide ASCII input only, where the dialect's Unicode classes (
\d,\w,\s) and case folding agree with ASCII. Patterns with non-ASCII characters are left to RE2/J. Non-ASCII input, a line feed inside a gap, and a surrogate under.go to a fallback that compiles #13487's matcher on first use, so a configuration whose inputs stay ASCII keeps no RE2/J program.compileWithoutPrototypekeeps the RE2/J path as it is, for the differential test, the benchmark baseline, andRegexMatcherTest's white-box prefilter checks.Motivation
The fixtures suggest patterns of these shapes are common in targeting rules (a census of every
MATCHESpattern):ufc-config.jsonregexsuiteThe canonical fixture's globs are mostly unescaped dots, such as
@mycompany.com. Of the 1,053 distinct fixture patterns #13487 sends to RE2/J, 1,044 are now engine-free (1,027 bit-parallel, 17 segments).Measured on its own by Bits, at this PR's head before the benchmark fix below (
a3ec3e2d3f) against #13487's branch (f2fe79d24b, fixtures08e8699). JDK 21,-prof gc.RegexShapesBenchmark,regexMatcher(#13487) →prototype(same jar, 2 forks each with the order alternated, 3×1 s warmup and 5×1 s measurement):@mycompany.com(unescaped domain)^api-.*-prod$checkout.*v2(?i)^admin.*panel^[a-zA-Z0-9._%+-]+@site\.test$^org-0000-[a-z]+-[0-9]{2,6}$^\d+$^v[0-9]+\.[0-9]+\.[0-9]+$@datadoghq\.com$+5–18%,my-great-app+9% on a short miss and 227 → 303 ns on the 2,000-char miss). That was the benchmark, not the PR.RegexMatcher.compilehands those patterns straight to Evaluate feature flag regex conditions in linear time #13487's literal matchers. The benchmark used the standalone compile, which wrapped them in a delegate. The benchmark now goes throughRegexMatcher.compile, as a configuration does.ScaleSuiteBenchmark(2 forks, base and PR alternating):scale/regexscale/regex-manyregex/literalsregex/backtrackingscale/regex-manywas −13% on an earlier head and +0.8% now, so its time is noise. Its −41 B per evaluation is consistent across runs.Footprint (JOL, retained):
regexsuite (withoutbacktracking.json)Additional Notes
PrototypeRegexTestchecks both tiers and the wired-incompileagainstcompileWithoutPrototype.regexsuite and the scale suite, plus about 45 hand-picked ones.ſ, the Kelvin sign) injected.(?i)patterns with non-ASCII characters that fold to ASCII stay on RE2/J. Rust's\s(0x09–0x0D and the space) is matched exactly, which also confirms Evaluate feature flag regex conditions in linear time #13487's\shandles\vlike Rust on ASCII.regexsuite's cases pass through the evaluator (ScaleSuiteTest,CanonicalFixtureTest).PrototypeRegex,compileWithoutPrototype) and the single-file layout are meant for discussion, not final. If this direction is wanted, it could move intoRegexMatcher's own tiers once Evaluate feature flag regex conditions in linear time #13487 lands.dd-smoke-tests. The differential test accepts either location, so it keeps working after Evaluate feature flag regex conditions in linear time #13487 moves tomaster's layout.*@datadoghq.com, a glob typed into a regex field. It's invalid regex, so the flag is dropped. Accepting globs there would be a separate decision.Contributor Checklist
type:and (comp:orinst:) labels in addition to any other useful labelsclose,fix, or any linking keywords when referencing an issueUse
solvesinstead, and assign the PR milestone to the issueJira ticket: [PROJ-IDENT]
Review follow-ups
Integer.parseInt, which accepts a sign, leading zeros and negative numbers. RE2/J reads a zero-padded count like{0002147483647}as literal text, andRegexMatcher.Limitsskips counts of more than 4 digits, so nothing had sized it. The prototype read it as 2^31 and exhausted the heap at configuration load (reproduced:OutOfMemoryErroron the old parser). Counts are now read only as both RE2/J andLimitsread them: 1 to 4 plain digits, no leading zero. Any other braces go to RE2/J. A signed count like{+2}is a syntax error in RE2/J, so it never reached the prototype throughRegexMatcher.compile, but it's rejected too..(^a.b$misseda😀b). Those patterns now fall back on input that holds a surrogate. Others, like@mycompany.com, already compare every.in place and don't scan.(?i)[\x00\x01]indexedset['\0' - 32].max < minis rejected.(?i)classes are case-folded before negation, as the Rust crate and RE2/J do:(?i)[^a-z]excludesA-Ztoo. New hand-picked differential cases cover it.BitParallelMatcherstops as soon as the state stops changing.🤖 Generated with Claude Code