Skip to content

Evaluate feature flag regex conditions in linear time - #13487

Draft
leoromanovsky wants to merge 24 commits into
masterfrom
leo.romanovsky/ffe-regex-linear-time
Draft

leoromanovsky wants to merge 24 commits into
masterfrom
leo.romanovsky/ffe-regex-linear-time

Conversation

@leoromanovsky

@leoromanovsky leoromanovsky commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

What Does This Do

The FFE provider now evaluates MATCHES and NOT_MATCHES in linear time, with the dialect of the Rust regex crate that libdatadog uses. A long attribute value can no longer make one evaluation backtrack for milliseconds.

At parse time, each distinct pattern of a configuration is compiled once into the cheapest matcher that gives the same result:

Behavior changes for existing configurations:

  • A pattern that the Rust crate rejects is now a parse error: lookaround, backreferences, atomic groups and \Q. The flag is dropped with PARSE_ERROR, as libdatadog does; the unsupported-syntax cases of the shared regex suite check this. Before this change, Java evaluated these patterns.
  • Some syntax that the Rust crate accepts is a parse error here, because RE2/J rejects it or reads it differently: nested repetition such as a*+, repeat counts above 1,000, class set operations, nested classes, and the x and R flags.
  • \<, \> and \b{...} are a parse error, because RE2/J would read them as literal text.
  • A pattern that nests more than 100 groups or unrolls to more than 100,000 characters (for example ((a{1000}){1000}){1000}) is a parse error instead of exhausting the heap while the configuration is parsed. A stack overflow in the RE2/J compiler (for example x{1,1000} on a small thread stack) is a parse error too.
  • $ does not match before a final line feed, . matches \r, and \d and \s are Unicode classes.
  • The bare POSIX translation ([:alnum:] to \p{Alnum}) is removed. Bracketed POSIX classes, such as [[:alnum:]], still work.
  • com.google.re2j:re2j:1.8 (the BSD-style Go License, with no dependencies of its own) is a new runtime dependency of the published dd-openfeature artifact.

Motivation

We need to win a performance-sensitive customer. java.util.regex backtracks. On a 2 KB attribute value that does not match, a common pattern shape, .*@(site-a|site-b)\.example$, takes about 11 ms for each evaluation (RegexMatcherBenchmark below). A chain such as .*.*.*.*.*= does not finish within 5 s. Attribute values come from the application (emails, user agents), so this is a latency risk and a ReDoS risk. ReDoS is a denial of service that uses slow regular expressions.

Java also gives different results from the Rust-based SDKs (libdatadog) for some patterns. For example, $ before a final line feed matches in Java but not in Rust, and lookahead patterns match in Java but are a parse error in Rust.

Additional Notes

RE2/J, not a new engine. RE2/J is already used inside the agent (IAST), and it stays the fallback for the few patterns the engine-free tiers don't take. Doug's tiers give the speed of a DFA on the common shapes without its memory limit.

Engine-free tiers, by @dougqh. A differential test compares the tiers with RE2/J on 1,036,656 generated inputs and finds no disagreement. Doug's RegexDispatchBenchmark (#13564) shows that going from 5 to 7 matcher classes at the call site is within noise for literal patterns, and that the new tiers stay 89–99% faster even when the classes are mixed. The literal tier and RegexMatcher.compile are unchanged; compile tries the engine-free tiers before RE2/J.

Scale suite results. Head e31d585 against master 5e0370d (later master commits change only a test lockfile in this module), back to back on one machine: AWS workspace, Intel Xeon Platinum 8175M, JDK 21.0.10, JMH 1.37 AverageTime, 2 forks, 3 warm-up and 5 measurement iterations of 2 s, -prof gc. Each row is the mean over the cases of the file; allocation is per evaluation.

Case file master This PR Change
scale/regex (2 KB inputs, 300 duplicate conditions) 1.94 ms (±0.08), 12.2 KB 3.26 µs (±0.36), 368 B −99.8% time, −97% allocation
scale/regex-many (1,000 distinct patterns, 500 alternatives, counted repetition) 22.4 µs (±0.9), 42.2 KB 14.6 µs (±1.5), 477 B −35% time, −99% allocation
regex/backtracking does not finish 3.80 µs (±0.66), 291 B
regex/literals not run 283 ns (±48), 301 B
Suite load (ScaleSuiteLoadBenchmark, scale) master This PR
Parse time 114 ms (±15) 152 ms (±17)
Allocated by one parse 97.6 MB 110.5 MB

Parse is about a third slower and allocates 13 MB more, because each distinct pattern is analyzed for the tiers once per configuration. Evaluation is the hot path; parsing happens when a configuration arrives.

This PR adds the literals and backtracking case files of the regex suite to ScaleSuiteBenchmark, because the JDK engine on master does not finish the backtracking cases.

Per-shape results. Doug's RegexShapesBenchmark, same machine, 2 forks, 3 warm-up and 5 measurement iterations of 1 s, -prof gc. It compares master's Pattern.matcher(v).find(), this PR's matcher without the engine-free tiers, and this PR as a configuration compiles it. Ranges are across the shapes in each row.

Shapes Input java.util.regex Without the tiers This PR
Literal suffix, contains hit or miss 35–75 ns, 128–208 B 8–13 ns, 0 B 8–12 ns, 0 B
Domain, prefix-suffix, two inner literals, case-insensitive, email, id and digit classes, version hit 42–254 ns, 128–208 B 732–1,817 ns, 72–144 B 24–83 ns, 0 B
The same eight shapes miss 41–185 ns, 128–208 B 7–1,757 ns, 0–48 B 2–58 ns, 0 B
Contains, domain, two inner literals, email class 2 KB miss 2.3–21.0 µs 8–2,168 ns 6–276 ns, 0 B

The engine-free tiers are faster than java.util.regex in all 30 cases, and they allocate nothing per match. Without them, a short input that reaches RE2/J would be 7–21× slower than the JDK engine.

Cross-SDK check. DataDog/ffe-system-test-data#78 adds an opt-in regex suite with 63 cases. Its expected results come from libdatadog. ScaleSuiteTest now evaluates all four case files of the suite, including the PARSE_ERROR cases, and this branch gives the same result for all 63. DataDog/ffe-system-test-data#78 is merged, and the submodule pins its merge commit, the same pin as master.

Tests. :dd-openfeature:test passes locally at e31d585, with 1,877 tests. RegexMatcherTest compares each fast path with the RE2/J result on generated inputs, and PrototypeRegexTest and PrototypeRegexParserTest pin the edges of the engine-free subset.

Size. This PR adds more than 1,000 lines, and has the tag: override pr size check label.

Contributor Checklist

Jira ticket: [PROJ-IDENT]

@leoromanovsky leoromanovsky 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 17, 2026
@datadog-prod-us1-5

datadog-prod-us1-5 Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

🎯 Code Coverage (details)
• Patch Coverage: 98.01%
• Overall Coverage: 61.33% (+0.38%)

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

@dd-octo-sts

dd-octo-sts Bot commented Nov 17, 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.88 s 14.76 s [-0.1%; +1.8%] (no difference)
startup:insecure-bank:tracing:Agent 13.65 s 13.73 s [-1.3%; +0.1%] (no difference)
startup:petclinic:appsec:Agent 17.73 s 17.51 s [+0.3%; +2.1%] (maybe worse)
startup:petclinic:iast:Agent 17.45 s 17.68 s [-2.0%; -0.6%] (maybe better)
startup:petclinic:profiling:Agent 17.44 s 17.35 s [-0.8%; +1.8%] (no difference)
startup:petclinic:sca:Agent 17.78 s 17.74 s [-0.6%; +1.0%] (no difference)
startup:petclinic:tracing:Agent 16.33 s 16.76 s [-6.7%; +1.7%] (no difference)

Commit: e31d585e · 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.

leoromanovsky and others added 5 commits November 17, 2026 00:47
Add ScaleSuiteBenchmark, which evaluates each case of the opt-in scale suite of the shared FFE fixtures. The setup checks every expected value and reason first. Pin ffe-system-test-data to the scale suite PR head.
The scale benchmark sat on the JSON value change and checked JSON
integers by type, so it could not set a baseline on master. It now
compares JSON numbers by value, covers every case file of the scale and
scale-json suites, can isolate one case with the index parameter, and
prints each case's index. A load benchmark measures parsing each suite's
configuration and prints the heap it retains, so changes that move work
to load time show their cost.

The submodule points to the scale-suite fixture branch, which adds the
N x M dimensions and JSON values up to 10 MB.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Replace java.util.regex for MATCHES and NOT_MATCHES with tiers like the
Rust evaluator: literal checks for patterns that are only text, checks
that need no engine for .*, .+ and \b-literal patterns, and RE2/J with
required prefix and suffix checks for all other patterns. A long
attribute value can no longer make one evaluation backtrack for
milliseconds.

Use the dialect of the Rust regex crate, which libdatadog uses: $ matches
only at the end of the input, . does not match a line feed, the u flag
is accepted, and lookaround, backreferences and atomic groups are a
parse error. The parser compiles each distinct pattern once per
configuration.
- Read each multi-character escape (\p{..}, \pX, \x{..}, \xHH, octal) as
  one token, so that its characters are not a required literal suffix.
- Translate \d, \D, \s and \S to the Unicode classes of the Rust regex
  crate. Reject \Q, class set operations and nested classes, which the
  Rust crate rejects or reads differently from RE2/J.
- Remove a - that is left without a flag after the u flag is removed.
- Keep a surrogate pair together when a quantifier follows it.
- Return an unmodifiable list of required suffixes.
- Share the group and alternation helpers, remove the unused pattern
  field, and use matches() in place of an expectMatch parameter.
- Move the parser tests to UniversalFlagConfigParserTest.
- Add a JMH benchmark that compares java.util.regex with RegexMatcher.
The base scale benchmark cannot run the regex suite, because the JDK
engine does not finish its backtracking cases. With the linear-time
matcher it does, so add its literal and backtracking case files.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@leoromanovsky
leoromanovsky force-pushed the leo.romanovsky/ffe-regex-linear-time branch from ad69415 to a571f3a Compare November 17, 2026 01:00
@leoromanovsky
leoromanovsky changed the base branch from master to leo.romanovsky/ffe-scale-suite-benchmark November 17, 2026 01:00
@leoromanovsky leoromanovsky added the crucible: reviewing A Crucible review has started; this PR has reviewer attention. label Nov 17, 2026 — with ddtool CLI
@leoromanovsky leoromanovsky removed the crucible: reviewing A Crucible review has started; this PR has reviewer attention. label Nov 17, 2026
leoromanovsky and others added 4 commits November 17, 2026 04:00
The scale benchmarks failed the forbidden API check on System.out, and
nothing outside a manual JMH run checked the scale cases, so a sibling
change that resolves a large configuration wrongly would go unnoticed.

- Add ScaleSuiteTest: evaluate every case of the scale and scale-json
  suites twice, and fail when the benchmark misses a case file. The
  cases, their check and the suite reader move to the test sources and
  the benchmarks reuse them; the reader uses JsonReading.
- Allow System.out in the benchmark setups (@SuppressForbidden).
- Check every case again after the measurement, fail on an error code,
  and reject expectations the check does not handle.
- Rerun the jmh task when the fixtures change.
- Measure retained heap after a first parse, as the smallest of three
  signed samples.
- Describe a row as the unweighted mean over the cases of a file, say
  that hooks are not measured and when to run three forks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The fixture PR now checks that the committed scale files match the
generator and fixes its docs. The case and configuration files are
unchanged, so the benchmark numbers do not change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The smoke-test app adds the dd-openfeature jar as a file, so Gradle does
not resolve its dependencies. Without RE2/J, parsing a configuration
with a MATCHES condition throws NoClassDefFoundError, the provider does
not start, and every OpenFeature smoke test fails.

RE2/J is now a runtime dependency of the published dd-openfeature
artifact, so it is listed in LICENSE-3rdparty.csv.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
RE2/J unrolls counted repetitions and compiles recursively, with no
limit. ((a{1000}){1000}){1000} exhausted the heap, and x{1,1000}
overflowed a 512 KB stack. Both are errors, not parse errors, so the
whole configuration failed. Patterns that nest more than 100 groups or
unroll to more than 100,000 characters are now a parse error, and a
stack overflow in the RE2/J compiler is one too.

RE2/J reads \<, \> and \b{...} as literal text, but the Rust crate
reads them as word boundaries. They are now a parse error, as the
Javadoc says.

Also cover the remaining branches for the coverage check, test a
condition that was not parsed, and remove the reference to a private
repository.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@leoromanovsky leoromanovsky added the tag: override pr size check Override the "pull request size" check label Nov 17, 2026 — with ddtool CLI
leoromanovsky and others added 3 commits November 17, 2026 04:25
A flag dropped for a MATCHES or NOT_MATCHES pattern that the Rust
dialect rejects was reported as invalid_flag, like any malformed flag.
It is now reported as unsupported_regex. The warning names only the
flag: the pattern and the error message can contain targeting values.

The parser now shares matchers with computeIfAbsent. A pattern that
does not compile is not cached, so every flag that uses it is dropped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Brings in ScaleSuiteTest, the benchmark hardening, and the fixtures pin
f425d578. ScaleSuiteTest now also checks the four case files of the
regex suite, so the cross-SDK regex contract runs in CI. ScaleCase
accepts an expected errorCode, so the PARSE_ERROR cases of
unsupported-syntax.json are compared, not skipped. semantics and
unsupported-syntax are checked but not benchmarked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The libdatadog evaluator calls the regex crate directly and has no
matcher tiers, so the Javadoc no longer says that it follows them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Copy link
Copy Markdown
Contributor Author

Heads up: the ffe-system-test-data submodule that this stack pins comes from #13485 and points to a commit of DataDog/ffe-system-test-data#78, which is still open. #78 needs to merge, and the pin needs to move to a commit on its main branch, before this stack merges.

Copy link
Copy Markdown
Contributor Author

Heads up: the dd-gitlab/check_base failure on this PR comes from the base, #13485. Its forbiddenApisJmh check rejected System.out in ScaleSuiteBenchmark and ScaleSuiteLoadBenchmark. #13485 fixed it in a887657, and this PR now includes the fix through a merge of the #13485 tip.

leoromanovsky and others added 2 commits November 17, 2026 04:39
The fixtures add a case file with ONE_OF lists of the integers 1 to
1000 and of the powers of two up to 2^52, which an index keyed on exact
doubles must still match. Pin them and benchmark the file; its 8 cases
pass on master.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Brings in the scale/one-of-small-numbers case file and the fixtures pin
08e86993. The benchmark and ScaleSuiteTest keep both the new case file
and the regex suite.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
leoromanovsky and others added 2 commits November 17, 2026 04:46
The OpenFeature client passes the provider a new LayeredEvaluationContext
on each call, while the benchmark reused one MutableContext. A rule on
`id` when the context has no `id` reads the layered context's key set,
which it builds again on each call, so the benchmark did not show what
applications pay for it.

evaluateLayered wraps each case's context the way the client does, as
ExperimentationOptOutBenchmark.evaluateFreshLayeredContext does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Brings in the evaluateLayered benchmark, which evaluates with the fresh
layered context that the OpenFeature client builds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Base automatically changed from leo.romanovsky/ffe-scale-suite-benchmark to master November 19, 2026 03:09
dougqh added a commit that referenced this pull request Nov 19, 2026
…terns

Not for merging. Builds on #13487's RegexMatcher: patterns it sends to RE2/J are tried first as
literal segments with single-character wildcards separated by unbounded gaps (after the glob
matcher of the sampling-rules prototype), then as a shift-and matcher over up to 64 positions.
Both decide ASCII input only and fall back to RegexMatcher otherwise.

PrototypeRegexTest checks them against RegexMatcher on 388k generated inputs over every fixture
pattern; RegexShapesBenchmark compares java.util.regex, RegexMatcher and the prototype.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
dougqh added a commit that referenced this pull request Nov 19, 2026
…ompile

RegexMatcher.compile tries PrototypeRegex's segment and bit-parallel tiers before falling back
to RE2/J. compileWithoutPrototype keeps #13487's behavior alone, for the differential test, the
benchmark baseline and RegexMatcherTest's white-box prefilter checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
dougqh added a commit that referenced this pull request Nov 19, 2026
From review: the configuration grew 1.2 MB on scale, because every engine-free matcher kept its
compiled RE2/J fallback, and each bit-parallel matcher held a long[128] of masks.

- The fallback is now a LazyFallback that holds only the pattern string, which the
  configuration already holds, and compiles #13487's matcher on the first input that needs it.
- The bit-parallel matcher maps each ASCII character to a class index (byte[128]) and keeps one
  mask per distinct class.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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 and others added 3 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>
dougqh added a commit that referenced this pull request Nov 20, 2026
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>
(cherry picked from commit a0931e8)
dougqh and others added 4 commits November 20, 2026 12:07
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>
#13485, #13486 and #13488 are on master now. The conflicts were the
scale-suite files, which this branch had taken from #13485 before it
was squashed, and a parser test next to master's new one-of index test.
Both tests are kept.
Doug's segment and bit-parallel tiers match most MATCHES patterns
without RE2/J. RE2/J is now compiled only on first use, for the
patterns the tiers cannot take, so this branch needs no lazy Engine of
its own. The literal tier and RegexMatcher.compile are unchanged.

Co-authored-by: Douglas Q Hawkins <douglas.hawkins@datadoghq.com>

This branch has not been deployed

No deployments
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: override pr size check Override the "pull request size" check 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