Skip to content

Match common MATCHES patterns without a regex engine (FFE optimization) - #13564

Merged
leoromanovsky merged 6 commits into
leo.romanovsky/ffe-regex-linear-timefrom
dougqh/ffe-regex-engine-free
Dec 1, 2026
Merged

leoromanovsky merged 6 commits into
leo.romanovsky/ffe-regex-linear-timefrom
dougqh/ffe-regex-engine-free

Conversation

@dougqh

@dougqh dougqh commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

What Does This Do

Stacked on #13487 (review only the commit after it). Most MATCHES/NOT_MATCHES patterns that #13487's RegexMatcher would send to RE2/J are now matched without a regex engine, with the same results in the Rust dialect. RegexMatcher.compile tries two engine-free tiers before falling back to RE2/J:

  • Segment matcher. Literal pieces, where . 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 with indexOf. With only unbounded gaps, leftmost placement is exact, so it never backtracks.
  • Bit-parallel (shift-and) matcher. Runs of literals and character classes with ?, *, + 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 with startsWith/endsWith first, 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. compileWithoutPrototype keeps the RE2/J path as it is, for the differential test, the benchmark baseline, and RegexMatcherTest's white-box prefilter checks.

Motivation

The fixtures suggest patterns of these shapes are common in targeting rules (a census of every MATCHES pattern):

Source Already fast in #13487 Multi-segment glob Literal + class runs Other
canonical ufc-config.json 62% 15% 8% 15%
regex suite 54% 15% 17% 15%
scale (generated) 2% 0% 98% 0%

The 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, fixtures 08e8699). 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):

Shape Hit Short miss 2,000-char miss
@mycompany.com (unescaped domain) 775 → 28.3 ns 50.3 → 23.9 ns 344 → 62.2 ns
^api-.*-prod$ 1,310 → 29.0 ns 14.4 → 5.4 ns 6.9 → 5.5 ns
checkout.*v2 1,470 → 54.8 ns 1,440 → 45.9 ns 1,680 → 86.6 ns
(?i)^admin.*panel 1,390 → 60.2 ns 79.4 → 7.9 ns 119 → 9.9 ns
^[a-zA-Z0-9._%+-]+@site\.test$ 1,340 → 40.7 ns 6.5 → 4.8 ns 6.6 → 4.9 ns
^org-0000-[a-z]+-[0-9]{2,6}$ 1,090 → 67.1 ns 753 → 45.8 ns 4.3 → 4.8 ns (noise)
^\d+$ 663 → 23.1 ns 354 → 16.2 ns 81.8 → 4.7 ns
^v[0-9]+\.[0-9]+\.[0-9]+$ 545 → 20.0 ns 375 → 1.7 ns 5.7 → 5.6 ns
  • The new tiers allocate 0 B per match on every shape. RE2/J allocates 48–144 B.
  • Bits also saw the two literal shapes Evaluate feature flag regex conditions in linear time #13487 already handles get slower (@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.compile hands 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 through RegexMatcher.compile, as a configuration does.

ScaleSuiteBenchmark (2 forks, base and PR alternating):

Case Time per evaluation Bytes per evaluation
scale/regex 28.03 → 2.73 µs (−90%) 468.5 → 380.0 (−19%)
scale/regex-many 12.75 → 12.84 µs (noise) 517.7 → 476.9 (−7.9%)
regex/literals 240 → 198 ns (−17%) 304.0 → 301.1
regex/backtracking 69.19 → 2.83 µs (−96%) 304.9 → 290.7 (−4.7%)

scale/regex-many was −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):

Base PR
Scale configuration, parsed 25,981,320 B / 843,332 objects 24,695,136 B / 796,937 objects (−1.29 MB, −5.0% B, −5.5% objects)
Scale, after every flag evaluated once 26,009,264 B / 843,504 objects 24,717,072 B / 796,998 objects (−1.29 MB)
regex suite (without backtracking.json) 51,984 B / 1,736 objects 46,056 B / 1,530 objects (−11.4% B, −11.9% objects)
Canonical configuration 172,592 B / 5,722 objects 170,080 B / 5,634 objects (−1.5%)
Allocated per parse, scale 97,985,867 B 104,049,072 B (+6.06 MB, +6.2%)
Allocated per parse, canonical 891,284 B 900,952 B (+1.1%)
  • The configuration holds 1.29 MB less: lazily compiled fallbacks and class-indexed masks instead of RE2/J programs. The class lookup costs about 1–3 ns per hit, intentionally traded for the footprint.
  • Parsing the scale configuration allocates 6 MB more, presumably while building the matchers and masks. It's a one-off per configuration load, and young garbage.

Additional Notes

  • Correctness. PrototypeRegexTest checks both tiers and the wired-in compile against compileWithoutPrototype.
    • Patterns: every pattern of the canonical fixture, the regex suite and the scale suite, plus about 45 hand-picked ones.
    • Generated inputs per pattern: strings built to match it, one- and two-character mutations, padded variants, random ASCII, every ASCII code point 0–127 inserted and substituted, and line feeds, non-ASCII characters, surrogate pairs and case-folding probes (ſ, the Kelvin sign) injected.
    • Result: 983,367 inputs, no disagreements. Planting bugs in either matcher makes it fail.
    • Hand-picked edge cases: (?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 \s handles \v like Rust on ASCII.
  • Conformance. The regex suite's cases pass through the evaluator (ScaleSuiteTest, CanonicalFixtureTest).
  • It's a prototype. The naming (PrototypeRegex, compileWithoutPrototype) and the single-file layout are meant for discussion, not final. If this direction is wanted, it could move into RegexMatcher's own tiers once Evaluate feature flag regex conditions in linear time #13487 lands.
  • Fixtures path. This branch still has the fixtures under dd-smoke-tests. The differential test accepts either location, so it keeps working after Evaluate feature flag regex conditions in linear time #13487 moves to master's layout.
  • A product question surfaced by the census. The canonical fixture contains *@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

Jira ticket: [PROJ-IDENT]

Review follow-ups

  • Fixed (P1 from Bits' review): repetition counts were read with Integer.parseInt, which accepts a sign, leading zeros and negative numbers. RE2/J reads a zero-padded count like {0002147483647} as literal text, and RegexMatcher.Limits skips 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: OutOfMemoryError on the old parser). Counts are now read only as both RE2/J and Limits read 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 through RegexMatcher.compile, but it's rejected too.
  • Fixed (P2s):
    • The segment matcher placed segments by counting chars, so a surrogate pair was miscounted in a counted gap or an end-anchored segment with . (^a.b$ missed a😀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] indexed set['\0' - 32].
    • A negative count can no longer be read, and max < min is rejected.
  • 18 new hand-picked differential patterns and new non-BMP probes. The differential test now checks 1,036,656 inputs.
  • (?i) classes are case-folded before negation, as the Rust crate and RE2/J do: (?i)[^a-z] excludes A-Z too. New hand-picked differential cases cover it.
  • The optional-run closure in BitParallelMatcher stops as soon as the state stops changing.

🤖 Generated with Claude Code

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>
@dougqh dougqh added type: feature Enhancements and improvements tag: performance Performance related changes tag: ai generated Largely based on code generated by an AI or LLM comp: openfeature OpenFeature labels Nov 19, 2026
@datadog-datadog-prod-us1-2

datadog-datadog-prod-us1-2 Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

🎯 Code Coverage (details)
• Patch Coverage: 96.52%
• Overall Coverage: 60.73% (+0.22%)

This comment will be updated automatically if new data arrives.
🔗 Commit SHA: 0982ad7 | Docs | Give us feedback!

@dd-octo-sts

dd-octo-sts Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

🟢 Java Benchmark SLOs — All performance SLOs passed

Suite Status
Startup 🟢 pass

SLO thresholds are defined here based on automatically generated metrics. A warning is raised when results are within 5% of the threshold.

PR vs. master results
Scenario Candidate master Δ (95% CI of mean)
startup:insecure-bank:iast:Agent 14.84 s 14.72 s [-0.1%; +1.6%] (no difference)
startup:insecure-bank:tracing:Agent 13.67 s 13.75 s [-1.3%; +0.2%] (no difference)
startup:petclinic:appsec:Agent 17.88 s 17.66 s [+0.3%; +2.2%] (maybe worse)
startup:petclinic:iast:Agent 17.60 s 17.83 s [-2.2%; -0.4%] (maybe better)
startup:petclinic:profiling:Agent 17.35 s 16.72 s [-0.8%; +8.3%] (no difference)
startup:petclinic:sca:Agent 17.93 s 17.74 s [+0.1%; +2.1%] (maybe worse)
startup:petclinic:tracing:Agent 16.68 s 16.92 s [-2.6%; -0.3%] (maybe better)

Commit: 0982ad70 · CI Pipeline · Benchmarking Platform UI


Load and DaCapo benchmarks can be triggered manually in the GitLab pipeline. Results will appear in the Benchmarking Platform UI after completion.

dougqh and others added 5 commits November 19, 2026 17:01
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
leoromanovsky merged commit e31d585 into leo.romanovsky/ffe-regex-linear-time Dec 1, 2026
679 of 683 checks passed
@leoromanovsky
leoromanovsky deleted the dougqh/ffe-regex-engine-free branch December 1, 2026 03:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp: openfeature OpenFeature tag: ai generated Largely based on code generated by an AI or LLM tag: performance Performance related changes type: feature Enhancements and improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants