Repository navigation
Regex: test concurrent matching and JIT stack exhaustion - #13683
Conversation
…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.
There was a problem hiding this comment.
🟡 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_remapregression 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
RegexMatchContextcan 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 usesstd::threadintest_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.
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.
There was a problem hiding this comment.
🔵 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 oneRegexMatchContextacross 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
RegexMatchContextper 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
|
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 Verified on Fedora 44, gcc 16.2.1, PCRE2 10.47:
|
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.
|
@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 |
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.
|
I've rescoped this PR. #13748 landed while it was open and replaced What's left is test coverage for #13748's fix: the 8-thread concurrency case through default and non-default #13660 looks fixed by #13748. I'll leave closing it to its owner. |
|
[approve ci centos ubuntu] |
JosiahWI
left a comment
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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. | ||
| { |
There was a problem hiding this comment.
Nit: this block could be extracted to a helper function so that the print_feature section flows cleanly without this low-level interruption.
|
Sadly, it seems the |
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.
|
Thanks for catching that. 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. |
Adds test coverage on top of #13748, the fix for #13660. #13748 replaced
RegexMatchContextwithRegex::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.handRegex.ccare identical to master. What is left are the tests for that fix and one newtraffic_layout infofeature.Regex matches concurrently on one instanceEight threads share one compiled
Regexand run 2,000 rounds each, starting every round at a barrier so the matches overlap. Four threads pass defaultRegex::Optionsand 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 withPCRE2_ERROR_MATCHLIMIT. That covers both the thread's default match context and itsOptionscopy, and a limit that leaks from one thread's match to another's fails the case.Mutating
Regex.ccso 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 crashingThis 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 onPCRE2_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_JITintraffic_layout infoReports 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_remapJIT stack exhaustiontest_regex_remap.pysends a 64,000 character query to the^/alpha/bravo/redirect rule. WhenTS_HAS_PCRE2_JITis set, the rule must fail with exactly -46 indiags.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 aTS_HAS_PCRE2_JITthat is missing or wrong fails the test instead of skipping the check.request_header_max_sizeis raised to fit the request. The allowed errors are narrowed to that -46 and the existing -47 match limit case.Verification
test_tsutilon 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.ci-centosandci-ubuntupresets 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_tsutilpasses all 67 cases, and 20 repeated[Regex]runs pass on each.LD_PRELOADshim,[Regex]passes 33 cases and skips the exhaustion case, andtraffic_layout inforeportsTS_HAS_PCRE2_JIT 0(1 without the shim). Master's[Regex]under the same shim fails the exhaustion case withrc := 2.-k regex, built with theci-fedora-urtestpreset in the CI image, normal and ASAN: 16 passed each. Theregex_remaprun 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_remappasses through the redirect branch.action=newsfed;on both x86_64 PCRE2 10.49 and arm64 PCRE2 10.47.