Skip to content

Regex: test concurrent matching and JIT stack exhaustion - #13683

Merged
bryancall merged 31 commits into
apache:masterfrom
bryancall:regex-inherit-shared-match-context
Nov 12, 2026
Merged

bryancall merged 31 commits into
apache:masterfrom
bryancall:regex-inherit-shared-match-context

Conversation

@bryancall

@bryancall bryancall commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Adds test coverage on top of #13748, the fix for #13660. #13748 replaced RegexMatchContext with Regex::Options, so every thread now owns its match contexts and its JIT stack and nothing is shared across threads. That made the pthread key and the inherited match context this PR started with unnecessary, and they are gone: Regex.h and Regex.cc are identical to master. What is left are the tests for that fix and one new traffic_layout info feature.

Regex matches concurrently on one instance

Eight threads share one compiled Regex and run 2,000 rounds each, starting every round at a barrier so the matches overlap. Four threads pass default Regex::Options and two pass a match limit that is never reached. Each of their rounds checks a hit, 64 times, that must return the same three captures, a miss that must stay a miss, and a deep subject of 5,000 to 5,700 bytes that overruns PCRE2's 32KiB fallback stack, so it only matches when the 1MiB JIT stack is in use. The other two threads pass a limit of 1, which must stop each of their 64 hits with PCRE2_ERROR_MATCHLIMIT. That covers both the thread's default match context and its Options copy, and a limit that leaks from one thread's match to another's fails the case.

Mutating Regex.cc so every thread shares one JIT stack fails this case in 289 of 300 runs on a Fedora build, 286 of 300 on Ubuntu 20.04 and 245 of 300 on the CentOS 7 Release build. Dropping the JIT stack from either match context fails it in 20 of 20 on Ubuntu and CentOS. Making the last non-default match limit process-wide, or sharing one options match context across threads, fails it in every run on all three. Unmutated, it passed 300 of 300 on each.

Regex reports resource exhaustion rather than crashing

This replaces master's version of the case. The #5762 pattern against a 256KiB subject must return exactly PCRE2_ERROR_JIT_STACKLIMIT, and a 10,000 byte subject must still match. The second check is the one that tells the 1MiB stack from PCRE2's 32KiB fallback.

The case runs only when pcre2_jit_compile() produces JIT code for the pattern. Master gates it on PCRE2_CONFIG_JIT, which reads 1 on a host that refuses executable memory even though every JIT compile then fails and the interpreter matches the subject, so master's version fails there. This one skips.

TS_HAS_PCRE2_JIT in traffic_layout info

Reports whether PCRE2 can actually run JIT code. On PCRE2 10.45 and later it uses PCRE2_JIT_TEST_ALLOC, which also checks that executable memory can be allocated. Older versions, such as the 10.32 that Rocky 8 ships, JIT compile a trivial pattern and report the result.

Uranium: regex_remap JIT stack exhaustion

test_regex_remap.py sends a 64,000 character query to the ^/alpha/bravo/ redirect rule. When TS_HAS_PCRE2_JIT is set, the rule must fail with exactly -46 in diags.log, the request must fall through to the origin rather than redirect, and ATS must keep serving. Without a JIT the interpreter matches the query and the request must redirect, so a TS_HAS_PCRE2_JIT that is missing or wrong fails the test instead of skipping the check. request_header_max_size is raised to fit the request. The allowed errors are narrowed to that -46 and the existing -47 match limit case.

Verification

  • test_tsutil on Fedora 45 x86_64 (GCC 16.2.1, PCRE2 10.49) and macOS arm64 (Apple clang 21, PCRE2 10.47), dev and dev-asan presets: all 67 cases pass, [Regex] is 34 cases and 588 assertions. Repeated [Regex] runs: 100 on the Fedora dev build and 20 on each of the other three, no failures.
  • Built with the ci-centos and ci-ubuntu presets in the CentOS 7 (GCC 10.2.1, PCRE2 10.23) and Ubuntu 20.04 (clang 12, PCRE2 10.34) CI images: both full builds pass, test_tsutil passes all 67 cases, and 20 repeated [Regex] runs pass on each.
  • With executable mappings refused through an LD_PRELOAD shim, [Regex] passes 33 cases and skips the exhaustion case, and traffic_layout info reports TS_HAS_PCRE2_JIT 0 (1 without the shim). Master's [Regex] under the same shim fails the exhaustion case with rc := 2.
  • Uranium -k regex, built with the ci-fedora-urtest preset in the CI image, normal and ASAN: 16 passed each. The regex_remap run logs the -46 from ^/alpha/bravo/ and the -47 from ^/match_limit/, with no sanitizer reports. With executable mappings refused for the whole run, regex_remap passes through the redirect branch.
  • The redirect rule's JIT stack threshold is 43,672 characters after action=newsfed; on both x86_64 PCRE2 10.49 and arm64 PCRE2 10.47.

…ch context

Two problems with the same root: a caller-supplied RegexMatchContext was built
blank, and the JIT stack was held in a thread_local.

pcre2_match_context_create(nullptr) produces a context that configures nothing,
so a caller who wanted only to set a match limit silently gave up everything the
shared context provides, including its 1 MiB JIT stack. PCRE2 then fell back to
its own 32 KiB machine-stack block, which resolves about 1,362 bytes of a subject
that backtracks once per character. A production regex_remap rule hit that bound
at 1,377 bytes of query string. Copy the shared context instead, so a caller
overrides only what it means to override.

A shared context needs a per thread JIT stack, and a thread_local holding one
registers its destructor through __cxa_thread_atexit, which takes the dynamic
loader lock. Doing that from a match inverts lock order against a dlopen caller
running a plugin's static initialization; Diags::tag_activated documents that
exact deadlock. Take the stack from a callback backed by a pthread key instead,
whose destructor is registered once at key creation and never from the matching
path.

pthread_key_create can fail, and jit_stack_key is zero initialized, so key 0
could belong to another subsystem and hand its value to PCRE2 as a JIT stack.
Record whether the key was created and return null when it was not, which
pcre2jit documents as falling back to its own stack. If pthread_setspecific
fails, free the stack rather than leaking one per match.

Record why the maximum is one mebibyte, measured rather than assumed: the
maximum costs nothing per match at any size, and one mebibyte already resolves a
longer subject than request_header_max_size lets a client send.
Copilot AI lite review requested due to automatic review settings September 15, 2026 04:43
@bryancall bryancall added Core Backport Marked for backport for an LTS patch release Bug labels Sep 15, 2026
@bryancall bryancall self-assigned this Sep 15, 2026
@bryancall bryancall added this to the 11.0.0 milestone Sep 15, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Multithreaded coverage and JIT-capability gating remain unresolved.

Get a fresh assessment by requesting another Copilot review.

Pull request overview

Fixes regex matching by preserving the shared PCRE2 context and providing per-thread JIT stacks.

Changes:

  • Adds pthread-key-backed JIT stack handling.
  • Copies shared settings into caller-supplied contexts.
  • Updates unit and regex_remap regression tests.
File summaries
File Description
tests/gold_tests/pluginTest/regex_remap/regex_remap.test.py Updates long-query expectations and crash-guard coverage.
src/tsutil/unit_tests/test_Regex.cc Adds JIT inheritance and resource-exhaustion tests.
src/tsutil/Regex.cc Implements shared-context copying and per-thread JIT stack handling.
Review details

Suppressed comments (1)

src/tsutil/unit_tests/test_Regex.cc:1088

  • The key correctness property of this change is that one copied RegexMatchContext can be used concurrently without sharing a JIT stack, but both new tests execute matches on a single thread. A regression that returned one stack for every thread would therefore still pass; please add a multithreaded test that shares a context and drives JIT matching (the repository already uses std::thread in test_thread_safety.cc).
TEST_CASE("RegexMatchContext matches the shared context", "[libts][Regex][RegexMatchContext]")
{
  // Quantified alternation of capture groups: every subject character pushes a
  // backtracking frame, so the JIT stack size is what bounds this.
  char const *const pattern = R"(^(?:(a)|(b))+$)";
  • Files reviewed: 3/3 changed files
  • Comments generated: 1
  • Review effort level: Lite

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

The crash-guard run sends a 64 KB query and asserts two things: that the rule does
not redirect, and that regex_remap logs a resource-limit error for it. Both hold
only when PCRE2 can run the pattern on the just-in-time engine, because that is the
only engine with a stack to exhaust here. The interpreter keeps its backtracking
frames on the heap, so on a build without JIT the subject simply matches, the rule
redirects, and the run fails for a reason that has nothing to do with what it tests.
The unit tests added alongside it already skip themselves on the same condition;
this run did not, so a PCRE2 built without JIT would fail the suite.

Report whether PCRE2 has a JIT as TS_HAS_PCRE2_JIT from traffic_layout, which
already includes pcre2.h and links it through tsutil, and gate the run on it the
way the QUIC and Brotli runs gate on their features. Nothing else in the file
depends on the JIT: the 3 KB redirect run gets the same answer from either engine,
and the crash property itself is still covered without a JIT by the match-limit run
and by the unit test that asserts it directly.
Copilot AI review requested due to automatic review settings September 15, 2026 15:37
The two tests added with the pthread key both match on a single thread, so an
implementation that handed the same JIT stack to every thread would pass them. That
is the one regression this change exists to prevent, and nothing covered it.

Eight threads match on one Regex, half of them through a single caller-supplied
context built before the workers start. That is the production shape: regex_remap
builds a context when it loads a rule and every net thread then matches through it,
so a context that cached a stack rather than resolving one per thread through the
callback would pass a test that gave each thread its own context and corrupt this
one. Every thread must reach the same verdict, and under ThreadSanitizer the run
must also be clean.

The start gate is a mutex and condition variable rather than std::latch, which says
it more directly but is not in libstdc++ before 11, and the CentOS build runs
devtoolset-10. It keeps the property the latch was there for, that every thread is
inside the match loop before any of them gets far, so the matching overlaps instead
of running one thread at a time.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Add concurrent-match regression coverage for a shared RegexMatchContext before approval.

Review details

Suppressed comments (2)

src/tsutil/Regex.cc:188

  • This callback is the thread-safety guarantee for a single copied RegexMatchContext, but the new test only runs the shared and caller-supplied paths serially on one thread. Please add a regression test that shares one RegexMatchContext across several concurrent matches; otherwise a shared-stack regression could pass the current tests while corrupting simultaneous JIT matches.
    pcre2_jit_stack_assign(_match_context, jit_stack_for_this_thread, nullptr);

src/tsutil/unit_tests/test_Regex.cc:1103

  • This test exercises the caller-supplied context only on the thread that constructed it. The new callback/key design is specifically required because regex_remap keeps one RegexMatchContext per remap instance and uses it from multiple ET_NET threads; an implementation that accidentally shared one thread's stack pointer would still pass this test but corrupt concurrent matches. Please add a multithreaded regression that constructs one context and runs matches concurrently from other threads.
  RegexMatchContext match_context;
  RegexMatches      own_matches;

  int const shared_rc = re.exec(subject, shared_matches);
  int const own_rc    = re.exec(subject, own_matches, 0, &match_context);
  • Files reviewed: 4/4 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

Copilot AI review requested due to automatic review settings September 15, 2026 15:46
@bryancall

Copy link
Copy Markdown
Contributor Author

Both findings from the Copilot review are addressed. The JIT gating one had a thread and is answered and resolved there; this covers the suppressed one, which had no thread to reply in.

Multithreaded coverage. You were right, and the gap was mine: I had written exactly this test and then filed it with the wrong change. It sat on the follow-up branch that makes the pcre2 contexts process-wide, because that is where it first landed. The property it guards is introduced here, by resolving the JIT stack per thread through a callback, so here is where it belongs. Moved in c4cdac1.

Eight threads match on one Regex, half of them through a single RegexMatchContext built before the workers start. That is deliberate and it is the shape your comment asked for: an implementation that cached one stack in the context, or handed the same stack to every thread, passes a test that gives each thread its own context and corrupts this one. The start gate is a mutex and condition variable rather than std::latch, which says it more directly but is not in libstdc++ before 11 and the CentOS lane runs devtoolset-10.

Verified on Fedora 44, gcc 16.2.1, PCRE2 10.47:

  • [Regex] under ThreadSanitizer: 388 assertions in 21 cases, no warnings. [threads] alone is also clean.
  • [Regex] under AddressSanitizer with UBSan: same counts, clean.
  • regex_remap autest executes 14 runs with TS_HAS_PCRE2_JIT 1; diags.log carries both -46 and -47.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Low-level PCRE2 JIT stack and threading changes warrant final human review.

Review details
  • Files reviewed: 4/4 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The concurrency-sensitive JIT stack and shared-context changes warrant final human review.

Review details
  • Files reviewed: 4/4 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

Eight lines of measurements above one call. Keep the two facts a reader needs to
judge the number, that the maximum is reserved rather than committed and that a
mebibyte already outruns what a client can send, and leave the measured table in the
pull request. The rationale for holding the stack in a pthread key stays where it is,
because that is the part someone would otherwise simplify back into a deadlock.
Copilot AI review requested due to automatic review settings September 15, 2026 19:21
@bryancall

Copy link
Copy Markdown
Contributor Author

@JosiahWI you flagged comment verbosity on #13684 and #13685, so I applied the same pass here before you had to say it a third time: the eight lines of stack-size measurements above one call are down to the two facts needed to judge the number, and the table is in the description instead.

I deliberately left the comment on the pthread key at full length. It is the one that explains why the stack is not in a thread_local, which is the change someone would otherwise make back into a loader-lock inversion. Happy to cut it too if you disagree.

The hand-rolled barrier copied notstd::barrier from benchmark_LogObject.cc,
which dates from when the tree built as C++17 and std::barrier was not
available. The tree is C++20 now, and std::barrier is reusable from one
phase to the next, which is what a round barrier needs. It compiles and
runs with GCC 11 from CI's Rocky 8 image, GCC 16 and Apple clang 21.

The concurrency case again says how often it catches threads sharing a
JIT stack, measured against this tree's design: with one stack forced on
every thread, 300 of 300 runs fail on x86_64 Linux, and 276 of 300 with
the barrier taken out. The remaining comments in that namespace become
plain ones.
The single alternation ran past the 132 column limit that ruff format
enforces. One pattern per expected error also reads more plainly.
They overrun the 32KiB fallback stack, which is what the case relies on;
they do not need the full 1MiB. The pattern_has_jit() comment no longer
says the compile fails in every no-JIT case and then names an exception,
and the measured detection rates stay in the commit that took them.
Only a JIT build sends the exhausting request, and the JIT reports that
bound as -46. Accepting the match, depth and heap limit codes as well
let a match limit hit pass for stack exhaustion.
The Uranium allow list now expects the same single -46 for the alpha/bravo
rule as the shutdown check does. In test_Regex.cc, the deep subject only
proves a larger stack ran on a JIT build, and the concurrency comment now
names what the barrier helps it catch.
Every non-default thread in the concurrency case used the same limit,
so a limit that reached another thread's match went unseen. Two
threads now use a limit too small for the hit and must get
PCRE2_ERROR_MATCHLIMIT while the others must still match.

The regex_remap exhaustion check now also runs without a JIT and
expects the redirect there, so a TS_HAS_PCRE2_JIT that is missing or
wrong fails the test instead of skipping it.

The rest restates comments as facts, names both measured PCRE2
versions for the 64,000 query, and makes has_jit a bool.
The concurrency case's round and stack comments still described every
thread doing the deep match. The pattern_has_jit comment had the
interpreter outcome backwards: without JIT code the exhaustion case
fails rather than passes. The 65,535 ceiling is an assert only in
debug builds. A local flag now names the limited threads.
The concurrency round's comment named the wrong threads, the positive
control's bounds are in KB rather than KiB, and the debug assert fires
at 65,535 bytes as well as above it.
Copilot AI lite review requested due to automatic review settings November 11, 2026 00:11

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

No active review issues remain for the regex JIT hardening and its targeted regression coverage.

No open issues 🎉

Review effort: Lite

@bryancall bryancall changed the title Regex: hold the JIT stack in a pthread key and inherit the shared match context Regex: test concurrent matching and JIT stack exhaustion Nov 11, 2026
@bryancall

Copy link
Copy Markdown
Contributor Author

I've rescoped this PR. #13748 landed while it was open and replaced RegexMatchContext with Regex::Options, so each thread now owns its match contexts and JIT stack. That fixed the 32KiB JIT stack problem this PR was opened for, and the pthread key and inherited match context here aren't needed anymore. After merging master, Regex.h and Regex.cc match master exactly.

What's left is test coverage for #13748's fix: the 8-thread concurrency case through default and non-default Options, the exhaustion case gated on real JIT code instead of PCRE2_CONFIG_JIT, TS_HAS_PCRE2_JIT in traffic_layout info, and the Uranium JIT stack exhaustion check. I updated the title and description to match and dropped the "Fixes #13660" line.

#13660 looks fixed by #13748. I'll leave closing it to its owner.

@JosiahWI

Copy link
Copy Markdown
Contributor

[approve ci centos ubuntu]

JosiahWI
JosiahWI previously approved these changes Nov 11, 2026

@JosiahWI JosiahWI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider addressing two comments, but I'm OK with merging as both comments are nitpicks. Thank you for reducing the scope - that landed this PR in the sweet spot for review size.

)
assert "HTTP/1.1 200 OK" in output and "uuid: 180" in output
wait_for_file_lines(_ats.diags_log, r"ERROR: .regex_remap. Bad regular expression result -47", 1)
run_jit_stack_exhaustion_check(_ats=_ats, _curl=_curl)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: this call is at the wrong level of abstraction, I think. It should go in the same place as the run_matching_checks call, not inside run_matching_checks. Conceptually, run_jit_stack_exhaustion_check is testing something a bit different, and the naming suggests the two functions are at the same level of abstraction, so it's weird for one to call the other.

// PCRE2_JIT_TEST_ALLOC (PCRE2 10.45) also confirms the JIT can allocate executable
// memory. PCRE2_CONFIG_JIT does not, and reports 1 on a hardened runtime where every JIT
// compile then fails, which is the direction that misleads a test gate.
{

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: this block could be extracted to a helper function so that the print_feature section flows cleanly without this low-level interruption.

@JosiahWI

Copy link
Copy Markdown
Contributor

Sadly, it seems the <barrier> header does not exist on our CentOS and Ubuntu CI environments. That may be a C++20 feature that we cannot use until there is wider compiler support.

The libstdc++ of GCC 10 and earlier has no <barrier>, so the CentOS 7
and Ubuntu 20.04 CI builds could not compile test_Regex.cc. A small
mutex and condition_variable barrier gives the same per-round start.
A match limit leaking between threads shows only when one thread
changes it in the nanoseconds between another setting and using its
own. With one hit per round, a CentOS 7 Release build caught a
process-wide limit in 1 of 100 runs; with 64 it catches it every time.
Copilot AI lite review requested due to automatic review settings November 11, 2026 04:42
@bryancall

Copy link
Copy Markdown
Contributor Author

Thanks for catching that. <barrier> first shipped in libstdc++ 11, and the CentOS 7 and Ubuntu 20.04 images build against libstdc++ 10 and 9. I replaced std::barrier with a small mutex and condition_variable barrier in the test, so it only needs library features those images have. I built both CI presets in those images, and test_tsutil passes on each.

While checking that the case still catches what it's meant to on those builds, I found that on the CentOS Release build, a match limit leaking between threads was caught in only 1 of 100 runs. Each round now matches the hit 64 times instead of once, which catches it in every run with no measurable change in runtime. That's in its own commit.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

No active issues were identified in the reviewed changes, which add targeted coverage for concurrent Regex use and PCRE2 JIT-stack exhaustion.

No open issues 🎉

Review effort: Lite

@JosiahWI JosiahWI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

@bryancall
bryancall merged commit 45d9829 into apache:master Nov 12, 2026
15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants