← Back to Pull requests

Match CPython for `$` and `\Z` in `re` patterns #1038

Open
Likheet opened this pull request with 514 lines diff across 4 files
View on GitHub
Likheet Likheet commented on Oct 14, 2026 08:24 UTC
Author

fancy-regex reads $ and \Z differently from Python's re.
Python's $ outside MULTILINE also matches before a newline that ends the string, where fancy-regex's $ is only the very end.
Python's \Z is only the very end, where fancy-regex's \Z also allows trailing newlines.
So a check on a line that still has its newline fails, and \Z accepts trailing newlines:

| | Monty main | CPython 3.14 |
| --- | --- | --- |
| re.match(r'^\d+$', '123\n') | None | match '123' |
| re.findall(r'\w+$', 'line1\nline2\n') | [] | ['line2'] |
| re.sub(r'$', '!', 'a\n') | 'a\n!' | 'a!\n!' |
| re.search(r'ab\Z', 'ab\n') | match 'ab' | None |
| re.findall(r'(?-m:\w+$)', 'ab\ncd\n', re.M) | [] | ['cd'] |

Neither is in limitations/re.md.

Patterns are now rewritten before compiling (translate_end_anchors): \Z becomes \z, and $ outside MULTILINE becomes (?=\n?\z) at the end of the pattern, \n?\z where it ends an alternative of a lookahead, and (?:\z|(?=\n\z)) anywhere else.
The rewrite reads the pattern as Python does: escapes, classes, (?#...) comments and # comments under (?x) are copied, and MULTILINE and VERBOSE are followed through re.M, inline (?m) and scoped (?m:...) / (?-m:...) groups.
Pattern.pattern keeps the original text.

The $ rewrite needs a lookaround, and it only changes a result when the subject ends in \n.
fancy-regex runs a lookahead on its linear engine only when the lookahead ends the pattern; anywhere else the pattern moves to its backtracking VM, which is slower and raises PatternError after 1,000,000 backtracking steps in one search.
So RePattern holds two CompiledSets: its current regexes for every other subject, and the rewritten ones, built on first use by a subject ending in \n. Each method picks one through for_subject.
A $ at the end of the pattern stays a trailing lookahead, which keeps re.search(r'end$', text) on a 400 kB string ending in \n at about 0.1 ms.
match() moves a final $ that applies to the whole pattern after its \A(?:...) wrapper, and fullmatch() drops it before \z, so re.match(r'^\d+$', line) stays linear too.
A $ that ends an alternative of a lookahead can consume the \n, since the lookahead is zero-width already, which keeps \w+(?=,|$) linear.
Anywhere else the $ is an alternation, since fancy-regex won't repeat a bare lookahead, as in (?:$)*.
Those placements, like \w+(?:,|$), now raise PatternError on long subjects ending in \n, so limitations/re.md now lists them with the backtrack limit.

Testing

  • New asserts in re__basic.py fail on main and pass on Monty and CPython 3.14. They cover match, search, fullmatch, findall, sub and split with a trailing newline, \Z, scoped and inline MULTILINE, $ in a class, escaped, after an escaped backslash and in a comment, and $ in a repeated group.

  • The second commit adds asserts for a final $ with and without a top-level |, $ in lookaheads, a 250 kB subject and (?x) comments that hold a ). The 250 kB one and cubic's (?x) one fail on the first commit, and the other (?x) one fails when the # handling is removed.

  • 32,000 generated search, match, fullmatch, finditer, sub and split calls against CPython 3.14.7 and a main build. The patterns mix $, \Z, \z, ^, \A and \b with scoped and inline flags, classes, escapes and comments, and the subjects end with and without newlines.

  • - The 12,053 calls whose pattern has no $ or \Z give byte-identical results to main, including the error messages.
    - 1,029 calls that differed from CPython on main now match it, and none that matched stopped matching.
    - The 1,546 that still differ come from two limits that exist on main too: an empty match right after the previous match is skipped (all 1,470 such calls come out the same when CPython's own engine is run with fancy-regex's iteration rule), and a group holding only a (?#...) comment can't be repeated.
  • The second commit gives the same output as the first on 157,275 further calls: 4,500 generated patterns with $ at the end, in the middle, after a top-level |, in lookaheads and capture groups, under re.M, inline and scoped MULTILINE and (?x) comments holding ) and |, on subjects with and without a trailing \n.

  • In a debug build, 20,000 re.match(r'^\d+$', line) calls take 235 ms for lines without \n and 265 ms for the same lines ending in \n (best of 5 runs).

  • cargo test -p monty passes, and the datatest suite passes on the Monty side. The CPython-side cases that fail for me also fail on main in my environment; none of them is an re case.
  • #1036 adds split_with_groups, which reads self.compiled directly.
    Whichever of the two is merged second should use self.for_subject(text)?.compiled there, like the other methods; with that change the three open branches (#1033, #1036 and this one) pass the suite together.

    <!-- This is an auto-generated description by cubic. -->
    ---

    Summary by cubic


    Fixes re pattern anchors $ and \Z to match CPython: $ outside MULTILINE now also matches before a trailing newline, and \Z matches only at the very end.

    Patterns are rewritten before compiling (\Z becomes \z, $ becomes a lookahead), but a faster base regex is kept for subjects that don't end in \n; the rewritten variant compiles lazily only for subjects ending in \n, and Pattern.pattern keeps the original text. A final $ is kept outside the match()/fullmatch() anchors and a $ ending a lookahead alternative becomes \n?\z, so both run on fancy-regex's linear engine. A lazily compiled form over the cache's size cap recompiles at the default limit for that call only. Under (?x), rewriting skips whitespace and # comments, so a $ followed by a comment still ends the pattern or a lookahead alternative.

    Testing

  • New assertions in re__basic.py cover match, search, fullmatch, findall, sub, and split with trailing newlines, plus $ in classes, escapes, comments, repeated groups, lookahead alternatives, and scoped/inline MULTILINE.

  • Generated comparisons against CPython 3.14.7 show no regressions on patterns without $/\Z; remaining differences are pre-existing iteration limits.

  • limitations/re.md documents the backtracking limit, the $ placements that still need the VM, and that the backtracking stack counts toward max_memory.
  • split_with_groups on #1036 reads self.compiled directly; whichever branch merges second should switch it to self.for_subject(text)?.compiled.

    <sup>Written for commit 3cc16ab4a1844962740a6a6b6d5d8b6113452c98. Summary will update on new commits.</sup>

    <a href="https://cubic.dev/pr/pydantic/monty/pull/1038?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="View guided diff" src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>

    <!-- End of auto-generated description by cubic. -->

    Diff: 514 lines (+444 / -70) across 4 files Reviewer: samuelcolvin Review duration: 7511m
    All Vouch review confidence checks passed
    Residual risk 0.03 = Change Risk (0.45) × (1 − Review Confidence (0.94)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.45 · 514 lines diff across 4 files
    0.45
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.98 · 5 substantive comment(s)
    0.98
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    94%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.374
    Real PR Conversation Timeline
    18 items
    github-actions[bot] github-actions[bot] commented on Oct 14, 2026 08:24 UTC
    Bot

    <!-- branch-diff -->

    Branch diff: fix/re-end-anchors

    | Commit | Message | Production | Test | Docs | Other |
    | --- | --- | --: | --: | --: | --: |
    | 684e5be37 | Match CPython for $ and \Z in… | +199 -23 | +33 -1 | +0 -0 | +0 -0 |
    | c29052c6a | Keep $ off fancy-regex's ba… | +228 -128 | +28 -0 | +11 -0 | +0 -0 |
    | 3cc16ab4a | Keep lazily compiled regexes … | +78 -55 | +3 -0 | +2 -1 | +0 -0 |
    | | TOTAL | +368 -69 | +64 -1 | +12 -0 | +0 -0 |

    cubic-dev-ai[bot] cubic-dev-ai[bot] commented on Oct 14, 2026 08:30 UTC
    Reviewer

    <!-- cubic:review-summary:start -->
    All reported issues were addressed across 2 files
    <!-- cubic:review-summary:end -->

    <sub>Reply with feedback, questions, or to request a fix.<br /><br />View guided diff | Re-trigger cubic</sub>

    <!-- cubic:review-post:ai_pr_review_github_delivery_9f27a37a31d11c75b7c79dc0d001e2da758231cee8d7972cf17faf96162884c8:684e5be37cd00596ee70e89920677fbebf3769d2:8cf5d602-5260-596e-b4dc-376e0565b6d7 -->

    cubic-dev-ai[bot] cubic-dev-ai[bot] commented on code on Oct 14, 2026 08:30 UTC
    Code Review
    crates/monty/src/types/re_pattern.rs:1
    @@ -688,6 +744,126 @@ fn compile_regex_limited(pattern: &str, flags: u16, delegate_size_limit: Option<
         builder.build()
     }
     
    +/// Rewrites a Python pattern's `$` and `\Z` for `fancy_regex`, and reports whether it has a
    +/// `$` outside MULTILINE.
    +///
    +/// Python's `\Z` is the very end, which is `fancy_regex`'s `\z` (its own `\Z` also allows
    +/// trailing newlines). Python's `$` outside MULTILINE also matches before a `\n` that ends the
    +/// string, where `fancy_regex`'s is only the very end; with `dollar_before_newline` it becomes
    +/// `(?=\n?\z)` at the end of the pattern, which `fancy_regex` turns into a plain suffix match,
    +/// and `(?:\z|(?=\n\z))` elsewhere, since it won't repeat a bare lookahead as in `(?:$)*`.
    +/// Escapes, classes and `(?#...)` comments are copied as they are, and MULTILINE is tracked
    +/// through inline and scoped flags.
    +fn translate_end_anchors(pattern: &str, multiline: bool, dollar_before_newline: bool) -> (Cow<'_, str>, bool) {
    +    if !pattern.contains('$') && !pattern.contains("\\Z") {
    +        return (Cow::Borrowed(pattern), false);
    +    }
    +    let mut out = String::with_capacity(pattern.len() + 16);
    +    let mut multiline = multiline;
    +    let mut has_dollar = false;
    +    // MULTILINE as it was outside each open group, restored at its `)`
    +    let mut outer = Vec::new();
    +    let mut chars = pattern.chars().peekable();
    +    while let Some(c) = chars.next() {
    +        match c {
    +            '\\' => match chars.next() {
    +                Some('Z') => out.push_str("\\z"),
    +                Some(escaped) => {
    +                    out.push('\\');
    +                    out.push(escaped);
    +                }
    +                None => out.push('\\'),
    +            },
    +            '[' => copy_class(&mut chars, &mut out),
    +            '(' => {
    +                out.push('(');
    +                if chars.next_if_eq(&'?').is_some() {
    +                    out.push('?');
    +                    if chars.next_if_eq(&'#').is_some() {
    +                        // a comment runs to the next `)`
    +                        out.push('#');
    +                        for c in chars.by_ref() {
    +                            out.push(c);
    +                            if c == ')' {
    +                                break;
    +                            }
    +                        }
    +                        continue;
    +                    }
    +                    if let Some((text, scoped, sets_multiline)) = inline_flags(&chars) {
    +                        chars.nth(text.chars().count() - 1);
    +                        out.push_str(&text);
    +                        if scoped {
    +                            outer.push(multiline);
    +                        }
    +                        multiline = sets_multiline.unwrap_or(multiline);
    +                        continue;
    +                    }
    +                }
    +                outer.push(multiline);
    +            }
    +            ')' => {
    +                out.push(')');
    +                multiline = outer.pop().unwrap_or(multiline);
    +            }
    +            '$' if !multiline => {

    <!-- cubic:v=6e10d3da-8827-41d2-92c5-38fd27126d55 -->
    <!-- cubic:review-run=8cf5d602-5260-596e-b4dc-376e0565b6d7 -->
    <!-- metadata:{"confidence":9} -->
    P2: Verbose (?x) comments can contain ) and currently corrupt the MULTILINE scope before this anchor is classified. Scan # comments through the next unescaped newline while verbose mode is active, so (?xm)(?-m:a # )\n$) preserves CPython’s scoped (?-m:...) behavior.

    <details>
    <summary>Prompt for AI agents</summary>

    Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty/src/types/re_pattern.rs, line 809:
    
    <comment>Verbose `(?x)` comments can contain `)` and currently corrupt the MULTILINE scope before this anchor is classified. Scan `#` comments through the next unescaped newline while verbose mode is active, so `(?xm)(?-m:a # )\n$)` preserves CPython’s scoped `(?-m:...)` behavior.</comment>
    
    <file context>
    @@ -688,6 +744,126 @@ fn compile_regex_limited(pattern: &str, flags: u16, delegate_size_limit: Option<
    +                out.push(')');
    +                multiline = outer.pop().unwrap_or(multiline);
    +            }
    +            '$' if !multiline => {
    +                has_dollar = true;
    +                out.push_str(match (dollar_before_newline, chars.peek()) {
    </file context>
    

    </details>

    ✅ Addressed in c29052c

    cubic-dev-ai[bot] cubic-dev-ai[bot] commented on code on Oct 14, 2026 08:30 UTC
    Code Review
    crates/monty/src/types/re_pattern.rs:1
    @@ -70,6 +72,13 @@ pub(crate) struct RePattern {
         /// unanchored still fits anchored). `None` = the engine's default limit. Not
         /// serialized — restored patterns recompile at the default limit.
         delegate_size_limit: Option<usize>,
    +    /// Whether these regexes read a `$` outside MULTILINE as Python does, also matching before
    +    /// a `\n` that ends the subject. Only a `newline_variant` does, since it costs speed.
    +    dollar_before_newline: bool,
    +    /// The pattern compiled with `dollar_before_newline`, built on first use by a subject that
    +    /// ends in `\n` (see [`RePattern::for_subject`]). `None` when the pattern has no `$`
    +    /// outside MULTILINE, so its regexes already match like Python for every subject.
    +    newline_variant: Option<OnceCell<Box<Self>>>,

    <!-- cubic:v=51f4d433-b86d-4964-8712-83becc49bcdc -->
    <!-- cubic:review-run=8cf5d602-5260-596e-b4dc-376e0565b6d7 -->
    <!-- metadata:{"confidence":9} -->
    P2: A cached $ pattern that sees a trailing-newline subject retains a second full Regex beside the original, so the cache's documented compiled-memory bound no longer holds. Account for both variants in the cache budget or avoid retaining the second one.

    <details>
    <summary>Prompt for AI agents</summary>

    Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty/src/types/re_pattern.rs, line 81:
    
    <comment>A cached `$` pattern that sees a trailing-newline subject retains a second full `Regex` beside the original, so the cache's documented compiled-memory bound no longer holds. Account for both variants in the cache budget or avoid retaining the second one.</comment>
    
    <file context>
    @@ -70,6 +72,13 @@ pub(crate) struct RePattern {
    +    /// The pattern compiled with `dollar_before_newline`, built on first use by a subject that
    +    /// ends in `\n` (see [`RePattern::for_subject`]). `None` when the pattern has no `$`
    +    /// outside MULTILINE, so its regexes already match like Python for every subject.
    +    newline_variant: Option<OnceCell<Box<Self>>>,
     }
     
    </file context>
    

    </details>

    ✅ Addressed in 3cc16ab

    codecov[bot] codecov[bot] commented on Oct 14, 2026 08:36 UTC
    Bot

    Codecov Report


    :x: Patch coverage is 88.23529% with 24 lines in your changes missing coverage. Please review.
    | Files with missing lines | Patch % | Lines |
    |---|---|---|
    | crates/monty/src/types/re\_pattern.rs | 88.23% | 8 Missing and 16 partials :warning: |

    :loudspeaker: Thoughts on this report? Let us know!

    codspeed[bot] codspeed[bot] commented on Oct 14, 2026 08:41 UTC
    Bot

    <!-- __CODSPEED_PERFORMANCE_REPORT_COMMENT__ -->

    Merging this PR will degrade performance by 4.08%

    <details>
    <summary>:warning: <b>10 benchmarks spent significant time in system calls</b></summary>

    System calls cannot be consistently instrumented, so they are not included in the measure, which understates the real cost. Please switch to the Walltime instrument to accurately measure system calls.

    > Measurement and system calls

    > - ` walk_files__monty

    - add_two__monty

    - glob_wildcard_overlay__monty

    - glob_wildcard__monty

    - ext_calls_1000

    - pool_create_session_run

    - glob_recursive__monty

    - glob_recursive_overlay__monty

    - session_checkout_run

    - ext_call_rows

    </details>
    <details>
    <summary>:warning: <b>Different runtime environments detected</b></summary>

    Some benchmarks with significant performance changes were compared across different runtime environments,

    which may affect the accuracy of the results.

    > Open the report in CodSpeed to investigate

    </details>

    ❌ 1 regressed benchmark
    ✅ 49 untouched benchmarks
    ⏩ 16 skipped benchmarks[^skipped]

    [!WARNING]

    Please fix the performance issues or acknowledge them on CodSpeed.

    Performance Changes

    | | Benchmark | BASE | HEAD | Efficiency |
    | --- | --------- | ------ | ------ | ---------- |
    | ❌ :warning: |
    walk_files__monty | 53.8 ms | 56.1 ms | -4.08% |

    [!TIP]

    Investigate this regression by commenting @codspeedbot fix this regression` on this PR, or directly use the CodSpeed MCP with your agent.

    ---

    <sub>Comparing <code>Likheet:fix/re-end-anchors</code> (3cc16ab) with <code>main</code> (4246aa7)</sub>

    <a href="https://app.codspeed.io/pydantic/monty/branches/Likheet%3Afix%2Fre-end-anchors?utm_source=github&utm_medium=comment-v2&utm_content=button">
    <picture>
    <source media="(prefers-color-scheme: dark)" srcset="https://codspeed.io/pr-report/open-in-codspeed-dark.svg">
    <source media="(prefers-color-scheme: light)" srcset="https://codspeed.io/pr-report/open-in-codspeed-light.svg">
    <img alt="Open in CodSpeed" src="https://codspeed.io/pr-report/open-in-codspeed-light.svg" width="169" height="32">
    </picture>
    </a>

    [^skipped]: 16 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.

    samuelcolvin samuelcolvin commented on Oct 14, 2026 09:48 UTC
    Reviewer

    Review from Claude

    The fix is correct for every case I tried (lookbehind with $, group counting after fancy-regex's explicit group 0, named groups, sub references, re.I, \Z in a class, conditionals, cache reuse across newline and non-newline subjects), and the new test cases pass on both sides. But the rewrite introduces a regression class that I think needs addressing before merge.

    1. A mid-pattern $ moves onto the backtracking VM and hits the backtrack limit on ordinary input

    A $ at the very end of the pattern becomes (?=\n?\z), which fancy-regex's optimizer turns into (X)\n?\z and delegates to the linear engine. Everywhere else it becomes (?:\z|(?=\n\z)), which is "hard" and runs on the backtracking VM. That VM counts backtracks per run call, and an unanchored search is a single run looping over every start position (compile.rs emits the .*? split), so the 1,000,000 limit accumulates across the whole subject.

    On a subject of repeated word ending in end\n (debug build):

    | pattern | 100 kB | 150 kB | 200 kB | main (400 kB) | CPython |
    | --- | --- | --- | --- | --- | --- |
    | \w+$\|zz | ok | ok | PatternError | [] in 6 ms | ['end'] |
    | \w+(?=,\|$) | ok | PatternError | PatternError | [] in 9 ms | ['end'] |
    | \w+(?:,\|$) | ok | PatternError | PatternError | [] | ['end'] |
    | (\w+)$\|zz | ok | ok | PatternError | [] | ['end'] |

    The error is re.PatternError: Error executing regex: Max limit for backtracking count exceeded. (?=,|$) and (?:\s|$) are about the most common idioms people (and LLMs) write, and the failure is input-dependent: it works on text.strip() and raises on the contents of a file. main gave the wrong answer here, but linearly and silently, and the backtrack limit isn't mentioned in limitations/re.md at all today.

    The same mechanism hits match/fullmatch for the common ^...$ shape: the \A(?:…) wrapper puts a ) after the $, so it takes the alternation form and the VM. re.match(r'^\d+$', '123\n') x20k went from 43 ms on main to 115 ms in a debug build, matching the 2x in the PR description. Mid-pattern searches that don't error are much slower: re.split(r',|$', big) went from 0.5 ms to 79 ms.

    Suggestions, in order of value:

  • Hoist a trailing top-level $ out of the wrappers: match → \A(?:X)(?=\n?\z) (trailing lookahead, so delegated), fullmatch → \A(?:X)\z (the $ is redundant before \z). translate_end_anchors already tracks depth, so "last char, depth 0, no top-level |" is cheap to detect.

  • Inside a lookahead, a $ that ends an alternative can be \n?\z rather than a nested lookahead, since the context is already zero-width. That keeps \w+(?=,|$) on the linear engine.

  • Whatever stays on the VM must be documented in limitations/re.md: which $ placements, that the backtrack limit raises PatternError, and that the VM's backtrack stack isn't tracked by the resource limits.
  • 2. cubic's memory comment: directionally right, but the documented bound was already loose

    A cached entry already retains up to three regexes (plain, match, fullmatch), and fancy-regex documents delegate_size_limit as a per-delegated-sub-regex cap. The variant doubles that to six regexes plus a second copy of the source text, so the theoretical worst case goes from ~49 MB to ~98 MB. I'd fix the comments on delegate_size_limit and CACHE_CAPACITY rather than add accounting.

    Separately, newline_variant: Option<OnceCell<Box<Self>>> duplicates pattern, flags, delegate_size_limit and an always-None nested variant. A small CompiledSet { compiled, compiled_match, compiled_fullmatch } held twice would be cleaner and drop the pattern.clone().

    3. cubic's verbose-comment comment: correct, but not a regression

    Monty passes inline (?x) through to fancy-regex, so # comments are live, and for cubic's exact pattern the branch returns [] where CPython returns ['a']. main also returns [], so nothing got worse, and it takes (?x), a # comment containing a paren, and a scoped (?-m:…) group together. Because the translator copies text verbatim and only touches $/\Z, a misparse can only mis-track MULTILINE, never corrupt the pattern. inline_flags already sees the x flag, so skipping # to end of line while it's on is a few lines. Low priority either way.

    Smaller notes

  • translate_end_anchors runs twice per compile (once inside compile_regex_limited, once just for has_dollar). Return the flag from the first call.

  • If the variant's compile exceeds CACHED_SIZE_LIMIT when the base didn't, the user gets a PatternError from search() rather than a result. I couldn't construct a case, but the path exists.

  • [[:alpha:]$]: the translator reads classes like Python but the regex crate reads nested sets, so the rewritten $ lands inside a class. main, this branch and CPython all give different answers; a pre-existing divergence, just a different wrong answer now.
  • Likheet Likheet commented on Oct 15, 2026 02:49 UTC
    Author

    Thanks for the review, all three points were right. I pushed c29052c with these changes.

    1. The backtracking VM

  • match() now puts a final $ that applies to the whole pattern after its wrapper, \A(?:X)$, so it stays a trailing lookahead. fullmatch() drops it: \A(?:X)\z.

  • translate_end_anchors decides this: the $ must be the last character, outside every group, with no top-level | and no re.MULTILINE. With a top-level |, only fullmatch() drops it.
  • A $ that ends an alternative of a lookahead becomes \n?\z, so \w+(?=,|$) stays on the linear engine.

  • limitations/re.md now has the backtrack limit, that the steps add up over start positions, that the VM's backtrack stack isn't tracked, and the $ placements that still need the VM.

  • I didn't find a linear form for a $ inside a group that isn't a lookahead, like \w+(?:,|$), since it has to stay zero-width there.

    Your table, in a debug build on Windows (subjects of repeated word ending in end\n; 20k calls, best of 5 for the last two rows):

    | | previous commit | this commit |
    | --- | --- | --- |
    | re.findall(r'\w+(?=,\|$)', s), 150 kB to 400 kB | PatternError | ['end'] in 6 to 17 ms |
    | \w+(?:,\|$), \w+$\|zz, (\w+)$\|zz | PatternError from 150 to 200 kB | unchanged, now in limitations/re.md |
    | re.match(r'^\d+$', '123\n') | 388 ms | 265 ms (235 ms for '123') |
    | re.fullmatch(r'^\d+$', '123\n') | 318 ms | 136 ms |

    2. Memory

    RePattern now holds two CompiledSet { compiled, compiled_match, compiled_fullmatch }, so there is no Box<Self> and no pattern.clone().
    The comments on delegate_size_limit, CACHE_CAPACITY and CACHED_SIZE_LIMIT now say that an entry can hold six regexes and that the limit applies per delegated sub-regex.

    3. Verbose comments

    # now runs to the end of the line while x is on, followed through inline and scoped flags like MULTILINE.
    This mattered more after the lookahead change: in (?x)a(?=(b # )\n|$)), the ) in the comment closed the capture group early, so the $ looked like it ended the lookahead and group 1 captured the \n.
    That pattern and cubic's are both tests now.

    Smaller notes

  • translate_end_anchors runs once per compile: compile_regex_limited returns what it found.

  • A lazily compiled regex that goes over CACHED_SIZE_LIMIT is now compiled at the default limit instead of raising PatternError (compile_lazily), and the comments say it can be retained slightly over the cap.

  • I left [[:alpha:]$] as it is, since it's a separate divergence.
  • Testing

  • New asserts in re__basic.py. The 250 kB lookahead one and cubic's verbose one fail on the previous commit, and the other verbose one fails when the # handling is removed.

  • 4,500 generated patterns with $ in all of the placements above, re.M, inline and scoped MULTILINE, and (?x) comments holding ) and |, on subjects with and without a trailing \n.

  • All 157,275 search, match, fullmatch, findall, sub and split calls give the same output as the previous commit.
    Against CPython 3.14.0 the only differences are in findall, sub and split, from the empty-match iteration rule, and they are the same set as on the previous commit.
  • cargo test -p monty passes, and the datatest suite passes on the Monty side.

  • The 11 CPython-side cases that fail on this machine (CPython 3.14.0) don't run Monty code, and none of them is an re case.
  • clippy on monty with --tests --all-features -D warnings, scripts/check_imports.py, rustfmt, and ruff on the test file pass.
  • Likheet Likheet commented on code on Oct 15, 2026 02:49 UTC
    Code Review
    crates/monty/src/types/re_pattern.rs:1
    @@ -70,6 +72,13 @@ pub(crate) struct RePattern {
         /// unanchored still fits anchored). `None` = the engine's default limit. Not
         /// serialized — restored patterns recompile at the default limit.
         delegate_size_limit: Option<usize>,
    +    /// Whether these regexes read a `$` outside MULTILINE as Python does, also matching before
    +    /// a `\n` that ends the subject. Only a `newline_variant` does, since it costs speed.
    +    dollar_before_newline: bool,
    +    /// The pattern compiled with `dollar_before_newline`, built on first use by a subject that
    +    /// ends in `\n` (see [`RePattern::for_subject`]). `None` when the pattern has no `$`
    +    /// outside MULTILINE, so its regexes already match like Python for every subject.
    +    newline_variant: Option<OnceCell<Box<Self>>>,

    Changed in c29052c as Samuel suggested in his review: the regexes for subjects ending in \n are now a second CompiledSet without their own copy of the pattern, and instead of adding accounting, the comments on CACHE_CAPACITY, CACHED_SIZE_LIMIT and delegate_size_limit now give the real bound: an entry can hold six regexes, and the limit applies per delegated sub-regex.

    cubic-dev-ai[bot] cubic-dev-ai[bot] commented on code on Oct 15, 2026 02:55 UTC
    Code Review
    crates/monty/src/types/re_pattern.rs:1
    @@ -131,57 +159,102 @@ impl RePattern {
         }
     
         /// Shared constructor for [`RePattern::compile`] / [`RePattern::compile_bounded`].
    +    ///
    +    /// Only the regex for subjects that don't end in `\n` is compiled here: the
    +    /// others wait for a call that needs them.
         fn compile_inner(pattern: String, flags: u16, delegate_size_limit: Option<usize>) -> Result<Self, RegexError> {
    -        let compiled = compile_regex_limited(&pattern, flags, delegate_size_limit)?;
    +        let (compiled, anchors) = compile_regex_limited(&pattern, flags, delegate_size_limit, false)?;
             Ok(Self {
                 pattern,
                 flags,
    -            compiled,
    -            compiled_match: OnceCell::new(),
    -            compiled_fullmatch: OnceCell::new(),
                 delegate_size_limit,
    +            trailing_dollar: anchors.trailing_dollar,
    +            regexes: CompiledSet::new(compiled, false),
    +            newline_regexes: anchors.has_dollar.then(OnceCell::new),
             })
         }
     
    -    /// Returns the `\A(?:pattern)` regex for `match()`, compiling it on first use.
    +    /// The regexes to match `text` with: the `newline_regexes` when it ends in `\n` and the
    +    /// pattern has a `$` outside MULTILINE, compiling them on first use, else `regexes`.
         ///
    -    /// Wrapping a pattern that already compiled essentially never fails, so any
    -    /// error surfaces (as `re.PatternError`) at `match()` rather than `re.compile()`.
    -    fn match_regex(&self) -> RunResult<&Regex> {
    -        if let Some(regex) = self.compiled_match.get() {
    +    /// Only then do Python's `$` and `fancy_regex`'s differ, and the newline regexes are slower.
    +    fn for_subject(&self, text: &str) -> RunResult<&CompiledSet> {
    +        match &self.newline_regexes {
    +            Some(cell) if text.ends_with('\n') => {
    +                if let Some(regexes) = cell.get() {
    +                    return Ok(regexes);
    +                }
    +                let compiled = self.compile_lazily(&self.pattern, true)?;
    +                // `set` only fails on a concurrent init, impossible on the single-threaded VM.
    +                let _ = cell.set(CompiledSet::new(compiled, true));
    +                Ok(cell.get().expect("cell was just initialised"))
    +            }
    +            _ => Ok(&self.regexes),
    +        }
    +    }
    +
    +    /// Returns the `\A(?:pattern)` regex of `regexes` for `match()`, compiling it on first use.
    +    ///
    +    /// A final `$` that applies to the whole pattern goes after the group instead, so it stays a
    +    /// trailing lookahead, which `fancy_regex` runs on its linear engine (see [`TrailingDollar`]).
    +    fn match_regex<'a>(&self, regexes: &'a CompiledSet) -> RunResult<&'a Regex> {
    +        if let Some(regex) = regexes.compiled_match.get() {
                 return Ok(regex);
             }
    -        let compiled = compile_regex_limited(
    -            &format!("\\A(?:{})", self.pattern),
    -            self.flags,
    -            self.delegate_size_limit,
    -        )
    -        .map_err(ExcType::re_pattern_error)?;
    +        let source = match self.trailing_dollar {
    +            TrailingDollar::WholePattern => format!("\\A(?:{})$", self.without_trailing_dollar()),
    +            TrailingDollar::None | TrailingDollar::LastAlternative => format!("\\A(?:{})", self.pattern),
    +        };
    +        let compiled = self.compile_lazily(&source, regexes.dollar_before_newline)?;
             // `set` only fails on a concurrent init, impossible on the single-threaded VM.
    -        let _ = self.compiled_match.set(compiled);
    -        Ok(self.compiled_match.get().expect("cell was just initialised"))
    +        let _ = regexes.compiled_match.set(compiled);
    +        Ok(regexes.compiled_match.get().expect("cell was just initialised"))
         }
     
    -    /// Returns the `\A(?:pattern)\z` regex for `fullmatch()`, compiling on first use.
    -    fn fullmatch_regex(&self) -> RunResult<&Regex> {
    -        if let Some(regex) = self.compiled_fullmatch.get() {
    +    /// Returns the `\A(?:pattern)\z` regex of `regexes` for `fullmatch()`, compiling on first use.
    +    ///
    +    /// A final `$` outside every group is dropped: just before `\z` it always holds, and kept
    +    /// it would put the regex on `fancy_regex`'s backtracking VM.
    +    fn fullmatch_regex<'a>(&self, regexes: &'a CompiledSet) -> RunResult<&'a Regex> {
    +        if let Some(regex) = regexes.compiled_fullmatch.get() {
                 return Ok(regex);
             }
    -        let compiled = compile_regex_limited(
    -            &format!("\\A(?:{})\\z", self.pattern),
    -            self.flags,
    -            self.delegate_size_limit,
    -        )
    -        .map_err(ExcType::re_pattern_error)?;
    -        let _ = self.compiled_fullmatch.set(compiled);
    -        Ok(self.compiled_fullmatch.get().expect("cell was just initialised"))
    +        let body = match self.trailing_dollar {
    +            TrailingDollar::None => self.pattern.as_str(),
    +            TrailingDollar::WholePattern | TrailingDollar::LastAlternative => self.without_trailing_dollar(),
    +        };
    +        let compiled = self.compile_lazily(&format!("\\A(?:{body})\\z"), regexes.dollar_before_newline)?;
    +        let _ = regexes.compiled_fullmatch.set(compiled);
    +        Ok(regexes.compiled_fullmatch.get().expect("cell was just initialised"))
    +    }
    +
    +    /// The pattern without the final `$` that `trailing_dollar` records.
    +    fn without_trailing_dollar(&self) -> &str {
    +        &self.pattern[..self.pattern.len() - 1]
    +    }
    +
    +    /// Compiles `source`, the pattern or an anchored form of it, for a regex built on first use.
    +    ///
    +    /// These forms can be a little bigger than the regex [`RePattern::compile_bounded`] checked,
    +    /// so one over the cache's size cap is compiled at the default limit, not failed as invalid.
    +    fn compile_lazily(&self, source: &str, dollar_before_newline: bool) -> RunResult<Regex> {
    +        let compiled = match compile_regex_limited(source, self.flags, self.delegate_size_limit, dollar_before_newline)
    +        {
    +            Err(err) if self.delegate_size_limit.is_some() && is_size_limit_error(&err) => {
    +                compile_regex_limited(source, self.flags, None, dollar_before_newline)

    <!-- cubic:v=fd84cdcd-24f9-4d4e-98b1-e230ca067c5f -->
    <!-- cubic:review-run=bf87909e-2ee9-5e03-8a73-922a86a2052f -->
    <!-- metadata:{"confidence":9} -->
    P1: This fallback bypasses the cache's compiled-size bound and the resulting regex is retained in newline_regexes. A pattern can fit the bounded unanchored compile but expand past the limit when $ is rewritten, letting repeated cached patterns retain substantially oversized regexes and undermine the cache's memory protection. Keep over-limit lazy variants out of the retained cache, or use a bounded/evictable representation for them.

    <details>
    <summary>Prompt for AI agents</summary>

    Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty/src/types/re_pattern.rs, line 244:
    
    <comment>This fallback bypasses the cache's compiled-size bound and the resulting regex is retained in `newline_regexes`. A pattern can fit the bounded unanchored compile but expand past the limit when `$` is rewritten, letting repeated cached patterns retain substantially oversized regexes and undermine the cache's memory protection. Keep over-limit lazy variants out of the retained cache, or use a bounded/evictable representation for them.</comment>
    
    <file context>
    @@ -139,89 +158,103 @@ impl RePattern {
    +        let compiled = match compile_regex_limited(source, self.flags, self.delegate_size_limit, dollar_before_newline)
    +        {
    +            Err(err) if self.delegate_size_limit.is_some() && is_size_limit_error(&err) => {
    +                compile_regex_limited(source, self.flags, None, dollar_before_newline)
    +            }
    +            result => result,
    </file context>
    

    </details>

    ✅ Addressed in 3cc16ab

    cubic-dev-ai[bot] cubic-dev-ai[bot] commented on code on Oct 15, 2026 02:55 UTC
    Code Review
    crates/monty/src/types/re_pattern.rs:1
    @@ -685,7 +772,195 @@ fn compile_regex_limited(pattern: &str, flags: u16, delegate_size_limit: Option<
         if let Some(limit) = delegate_size_limit {
             builder.delegate_size_limit(limit);
         }
    -    builder.build()
    +    builder.build().map(|regex| (regex, anchors))
    +}
    +
    +/// What [`translate_end_anchors`] found out about a pattern's `$`s outside MULTILINE.
    +#[derive(Debug, Clone, Copy, Default)]
    +struct EndAnchors {
    +    /// Whether it has one, which `fancy_regex` reads differently for a subject ending in `\n`.
    +    has_dollar: bool,
    +    /// Whether and how one ends the pattern.
    +    trailing_dollar: TrailingDollar,
    +}
    +
    +/// Whether and how a `$` outside MULTILINE ends a pattern, outside every group.
    +///
    +/// Wrapped in `\A(?:...)`, such a `$` no longer ends the pattern, and `fancy_regex` runs a
    +/// lookahead on its linear engine only there, so `match()` moves one that applies to the whole
    +/// pattern after the wrapper, and `fullmatch()` drops it.
    +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
    +enum TrailingDollar {
    +    /// The pattern doesn't end in one.
    +    #[default]
    +    None,
    +    /// It does, and the `$` applies to the whole pattern.
    +    WholePattern,
    +    /// It does after a top-level `|`, so the `$` applies to the last alternative only.
    +    LastAlternative,
    +}
    +
    +/// Rewrites a Python pattern's `$` and `\Z` for `fancy_regex`, and reports what it found out
    +/// about the `$`s outside MULTILINE.
    +///
    +/// Python's `\Z` is the very end, which is `fancy_regex`'s `\z` (its own `\Z` also allows
    +/// trailing newlines). Python's `$` outside MULTILINE also matches before a `\n` that ends the
    +/// string, where `fancy_regex`'s is only the very end; with `dollar_before_newline` it becomes
    +/// `(?=\n?\z)` at the end of the pattern, which `fancy_regex` turns into a plain suffix match,
    +/// `\n?\z` where it ends an alternative of a lookahead, which is zero-width already, and
    +/// `(?:\z|(?=\n\z))` elsewhere, since it won't repeat a bare lookahead as in `(?:$)*`.
    +/// Escapes, classes and comments are copied as they are, and MULTILINE and VERBOSE are
    +/// tracked through inline and scoped flags.
    +fn translate_end_anchors(pattern: &str, multiline: bool, dollar_before_newline: bool) -> (Cow<'_, str>, EndAnchors) {
    +    if !pattern.contains('$') && !pattern.contains("\\Z") {
    +        return (Cow::Borrowed(pattern), EndAnchors::default());
    +    }
    +    let mut out = String::with_capacity(pattern.len() + 16);
    +    let mut anchors = EndAnchors::default();
    +    let mut scope = Scope {
    +        multiline,
    +        verbose: false,
    +    };
    +    // the flags outside each open group, restored at its `)`, and whether it is a lookahead
    +    let mut open: Vec<(Scope, bool)> = Vec::new();
    +    let mut top_level_alternation = false;
    +    let mut chars = pattern.chars().peekable();
    +    while let Some(c) = chars.next() {
    +        match c {
    +            '\\' => match chars.next() {
    +                Some('Z') => out.push_str("\\z"),
    +                Some(escaped) => {
    +                    out.push('\\');
    +                    out.push(escaped);
    +                }
    +                None => out.push('\\'),
    +            },
    +            '[' => copy_class(&mut chars, &mut out),
    +            '#' if scope.verbose => {
    +                // a verbose comment runs to the end of the line
    +                out.push('#');
    +                for c in chars.by_ref() {
    +                    out.push(c);
    +                    if c == '\n' {
    +                        break;
    +                    }
    +                }
    +            }
    +            '(' => {
    +                out.push('(');
    +                let mut lookahead = false;
    +                if chars.next_if_eq(&'?').is_some() {
    +                    out.push('?');
    +                    if chars.next_if_eq(&'#').is_some() {
    +                        // a comment runs to the next `)`
    +                        out.push('#');
    +                        for c in chars.by_ref() {
    +                            out.push(c);
    +                            if c == ')' {
    +                                break;
    +                            }
    +                        }
    +                        continue;
    +                    }
    +                    if let Some((text, scoped, inner)) = inline_flags(&chars, scope) {
    +                        chars.nth(text.chars().count() - 1);
    +                        out.push_str(&text);
    +                        if scoped {
    +                            open.push((scope, false));
    +                        }
    +                        scope = inner;
    +                        continue;
    +                    }
    +                    lookahead = matches!(chars.peek(), Some('=' | '!'));
    +                }
    +                open.push((scope, lookahead));
    +            }
    +            ')' => {
    +                out.push(')');
    +                scope = open.pop().map_or(scope, |(outer, _)| outer);
    +            }
    +            '|' => {
    +                top_level_alternation |= open.is_empty();
    +                out.push('|');
    +            }
    +            '$' if !scope.multiline => {
    +                anchors.has_dollar = true;
    +                let next = chars.peek().copied();
    +                // moved out of a `match()` wrapper, the `$` must still be outside MULTILINE
    +                if next.is_none() && open.is_empty() && !multiline {

    <!-- cubic:v=6e639902-c852-4165-bac6-2461bef3aaa4 -->
    <!-- cubic:review-run=bf87909e-2ee9-5e03-8a73-922a86a2052f -->
    <!-- metadata:{"confidence":8} -->
    P2: A $ followed only by ignored verbose whitespace or a comment is still the pattern's trailing anchor, but this check leaves it unclassified and rewrites it into an internal lookahead on newline subjects. Long matches can consequently hit the backtracking limit; classify trailing anchors after skipping verbose trivia.

    <details>
    <summary>Prompt for AI agents</summary>

    Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty/src/types/re_pattern.rs, line 890:
    
    <comment>A `$` followed only by ignored verbose whitespace or a comment is still the pattern's trailing anchor, but this check leaves it unclassified and rewrites it into an internal lookahead on newline subjects. Long matches can consequently hit the backtracking limit; classify trailing anchors after skipping verbose trivia.</comment>
    
    <file context>
    @@ -790,34 +862,60 @@ fn translate_end_anchors(pattern: &str, multiline: bool, dollar_before_newline:
    +                anchors.has_dollar = true;
    +                let next = chars.peek().copied();
    +                // moved out of a `match()` wrapper, the `$` must still be outside MULTILINE
    +                if next.is_none() && open.is_empty() && !multiline {
    +                    anchors.trailing_dollar = if top_level_alternation {
    +                        TrailingDollar::LastAlternative
    </file context>
    

    </details>

    ✅ Addressed in 3cc16ab

    cubic-dev-ai[bot] cubic-dev-ai[bot] commented on code on Oct 15, 2026 02:55 UTC
    Code Review
    docs/limitations/re.md:1
    @@ -88,3 +88,14 @@ representation does not carry them.
     - Patterns whose *compiled* form is very large, e.g. huge counted repeats
         like `a{5000000}`, raise `re.PatternError` (`fancy-regex`/`regex` enforce a
         compiled-size limit), whereas CPython compiles them.
    +- A pattern with a backreference or a lookaround runs on `fancy-regex`'s backtracking VM.
    +    The exception is a positive lookahead that ends a pattern with no other lookaround or backreference, which
    +    `search()`, `findall()`, `finditer()`, `sub()` and `split()` run on the linear engine.
    +    A search on the VM raises `re.PatternError: Error executing regex: Max limit for backtracking count exceeded` once
    +    it has taken 1,000,000 backtracking steps, where CPython continues.
    +    The steps add up over every start position the search tries, so a pattern can work on a short subject and raise on a
    +    long one whose next match is far from where the search starts.
    +    The VM's backtracking stack is not tracked by the resource limits.

    <!-- cubic:v=965492b9-4690-476b-95d7-b88acb3116bf -->
    <!-- cubic:review-run=bf87909e-2ee9-5e03-8a73-922a86a2052f -->
    <!-- metadata:{"confidence":8} -->
    P2: The backtracking stack's allocator-backed allocations still count toward max_memory. Clarify that matching does not poll resource limits during backtracking instead of saying its memory is untracked.

    <details>
    <summary>Prompt for AI agents</summary>

    Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/limitations/re.md, line 98:
    
    <comment>The backtracking stack's allocator-backed allocations still count toward `max_memory`. Clarify that matching does not poll resource limits during backtracking instead of saying its memory is untracked.</comment>
    
    <file context>
    @@ -88,3 +88,14 @@ representation does not carry them.
    +    it has taken 1,000,000 backtracking steps, where CPython continues.
    +    The steps add up over every start position the search tries, so a pattern can work on a short subject and raise on a
    +    long one whose next match is far from where the search starts.
    +    The VM's backtracking stack is not tracked by the resource limits.
    +- For a subject ending in `\n`, a `$` outside MULTILINE also puts the pattern on that VM, unless the `$` ends the
    +    pattern or ends an alternative of a lookahead that ends the pattern.
    </file context>
    

    </details>

        Matching does not poll resource limits while backtracking, though its stack allocations still count toward `max_memory` and the allocator hard limit.
    

    ✅ Addressed in 3cc16ab

    cubic-dev-ai[bot] cubic-dev-ai[bot] commented on Oct 15, 2026 02:55 UTC
    Reviewer

    <!-- cubic:review-summary:start -->
    All reported issues were addressed across 4 files (changes from recent commits).
    <!-- cubic:review-summary:end -->

    <sub>Reply with feedback, questions, or to request a fix.<br /><br />View guided diff | Re-trigger cubic</sub>

    <!-- cubic:review-post:ai_pr_review_github_delivery_664736311eb68fff0b7eb0a4e1e8b91771248a29d93829d06022b28915bce144:c29052c6abd6152283e099faf9c307190c0e9267:bf87909e-2ee9-5e03-8a73-922a86a2052f -->

    Likheet Likheet commented on code on Oct 15, 2026 04:02 UTC
    Code Review
    crates/monty/src/types/re_pattern.rs:1
    @@ -131,57 +159,102 @@ impl RePattern {
         }
     
         /// Shared constructor for [`RePattern::compile`] / [`RePattern::compile_bounded`].
    +    ///
    +    /// Only the regex for subjects that don't end in `\n` is compiled here: the
    +    /// others wait for a call that needs them.
         fn compile_inner(pattern: String, flags: u16, delegate_size_limit: Option<usize>) -> Result<Self, RegexError> {
    -        let compiled = compile_regex_limited(&pattern, flags, delegate_size_limit)?;
    +        let (compiled, anchors) = compile_regex_limited(&pattern, flags, delegate_size_limit, false)?;
             Ok(Self {
                 pattern,
                 flags,
    -            compiled,
    -            compiled_match: OnceCell::new(),
    -            compiled_fullmatch: OnceCell::new(),
                 delegate_size_limit,
    +            trailing_dollar: anchors.trailing_dollar,
    +            regexes: CompiledSet::new(compiled, false),
    +            newline_regexes: anchors.has_dollar.then(OnceCell::new),
             })
         }
     
    -    /// Returns the `\A(?:pattern)` regex for `match()`, compiling it on first use.
    +    /// The regexes to match `text` with: the `newline_regexes` when it ends in `\n` and the
    +    /// pattern has a `$` outside MULTILINE, compiling them on first use, else `regexes`.
         ///
    -    /// Wrapping a pattern that already compiled essentially never fails, so any
    -    /// error surfaces (as `re.PatternError`) at `match()` rather than `re.compile()`.
    -    fn match_regex(&self) -> RunResult<&Regex> {
    -        if let Some(regex) = self.compiled_match.get() {
    +    /// Only then do Python's `$` and `fancy_regex`'s differ, and the newline regexes are slower.
    +    fn for_subject(&self, text: &str) -> RunResult<&CompiledSet> {
    +        match &self.newline_regexes {
    +            Some(cell) if text.ends_with('\n') => {
    +                if let Some(regexes) = cell.get() {
    +                    return Ok(regexes);
    +                }
    +                let compiled = self.compile_lazily(&self.pattern, true)?;
    +                // `set` only fails on a concurrent init, impossible on the single-threaded VM.
    +                let _ = cell.set(CompiledSet::new(compiled, true));
    +                Ok(cell.get().expect("cell was just initialised"))
    +            }
    +            _ => Ok(&self.regexes),
    +        }
    +    }
    +
    +    /// Returns the `\A(?:pattern)` regex of `regexes` for `match()`, compiling it on first use.
    +    ///
    +    /// A final `$` that applies to the whole pattern goes after the group instead, so it stays a
    +    /// trailing lookahead, which `fancy_regex` runs on its linear engine (see [`TrailingDollar`]).
    +    fn match_regex<'a>(&self, regexes: &'a CompiledSet) -> RunResult<&'a Regex> {
    +        if let Some(regex) = regexes.compiled_match.get() {
                 return Ok(regex);
             }
    -        let compiled = compile_regex_limited(
    -            &format!("\\A(?:{})", self.pattern),
    -            self.flags,
    -            self.delegate_size_limit,
    -        )
    -        .map_err(ExcType::re_pattern_error)?;
    +        let source = match self.trailing_dollar {
    +            TrailingDollar::WholePattern => format!("\\A(?:{})$", self.without_trailing_dollar()),
    +            TrailingDollar::None | TrailingDollar::LastAlternative => format!("\\A(?:{})", self.pattern),
    +        };
    +        let compiled = self.compile_lazily(&source, regexes.dollar_before_newline)?;
             // `set` only fails on a concurrent init, impossible on the single-threaded VM.
    -        let _ = self.compiled_match.set(compiled);
    -        Ok(self.compiled_match.get().expect("cell was just initialised"))
    +        let _ = regexes.compiled_match.set(compiled);
    +        Ok(regexes.compiled_match.get().expect("cell was just initialised"))
         }
     
    -    /// Returns the `\A(?:pattern)\z` regex for `fullmatch()`, compiling on first use.
    -    fn fullmatch_regex(&self) -> RunResult<&Regex> {
    -        if let Some(regex) = self.compiled_fullmatch.get() {
    +    /// Returns the `\A(?:pattern)\z` regex of `regexes` for `fullmatch()`, compiling on first use.
    +    ///
    +    /// A final `$` outside every group is dropped: just before `\z` it always holds, and kept
    +    /// it would put the regex on `fancy_regex`'s backtracking VM.
    +    fn fullmatch_regex<'a>(&self, regexes: &'a CompiledSet) -> RunResult<&'a Regex> {
    +        if let Some(regex) = regexes.compiled_fullmatch.get() {
                 return Ok(regex);
             }
    -        let compiled = compile_regex_limited(
    -            &format!("\\A(?:{})\\z", self.pattern),
    -            self.flags,
    -            self.delegate_size_limit,
    -        )
    -        .map_err(ExcType::re_pattern_error)?;
    -        let _ = self.compiled_fullmatch.set(compiled);
    -        Ok(self.compiled_fullmatch.get().expect("cell was just initialised"))
    +        let body = match self.trailing_dollar {
    +            TrailingDollar::None => self.pattern.as_str(),
    +            TrailingDollar::WholePattern | TrailingDollar::LastAlternative => self.without_trailing_dollar(),
    +        };
    +        let compiled = self.compile_lazily(&format!("\\A(?:{body})\\z"), regexes.dollar_before_newline)?;
    +        let _ = regexes.compiled_fullmatch.set(compiled);
    +        Ok(regexes.compiled_fullmatch.get().expect("cell was just initialised"))
    +    }
    +
    +    /// The pattern without the final `$` that `trailing_dollar` records.
    +    fn without_trailing_dollar(&self) -> &str {
    +        &self.pattern[..self.pattern.len() - 1]
    +    }
    +
    +    /// Compiles `source`, the pattern or an anchored form of it, for a regex built on first use.
    +    ///
    +    /// These forms can be a little bigger than the regex [`RePattern::compile_bounded`] checked,
    +    /// so one over the cache's size cap is compiled at the default limit, not failed as invalid.
    +    fn compile_lazily(&self, source: &str, dollar_before_newline: bool) -> RunResult<Regex> {
    +        let compiled = match compile_regex_limited(source, self.flags, self.delegate_size_limit, dollar_before_newline)
    +        {
    +            Err(err) if self.delegate_size_limit.is_some() && is_size_limit_error(&err) => {
    +                compile_regex_limited(source, self.flags, None, dollar_before_newline)

    Fixed in 3cc16ab: a lazily compiled form over the size cap is now compiled at the default limit for that call only and not kept in the entry, as the cache does with a pattern over its cap. For example, at the smallest limit a{100}$ compiles at (3,440), its newline form does not fit, and it is now returned per call without being stored.

    Likheet Likheet commented on code on Oct 15, 2026 04:02 UTC
    Code Review
    crates/monty/src/types/re_pattern.rs:1
    @@ -685,7 +772,195 @@ fn compile_regex_limited(pattern: &str, flags: u16, delegate_size_limit: Option<
         if let Some(limit) = delegate_size_limit {
             builder.delegate_size_limit(limit);
         }
    -    builder.build()
    +    builder.build().map(|regex| (regex, anchors))
    +}
    +
    +/// What [`translate_end_anchors`] found out about a pattern's `$`s outside MULTILINE.
    +#[derive(Debug, Clone, Copy, Default)]
    +struct EndAnchors {
    +    /// Whether it has one, which `fancy_regex` reads differently for a subject ending in `\n`.
    +    has_dollar: bool,
    +    /// Whether and how one ends the pattern.
    +    trailing_dollar: TrailingDollar,
    +}
    +
    +/// Whether and how a `$` outside MULTILINE ends a pattern, outside every group.
    +///
    +/// Wrapped in `\A(?:...)`, such a `$` no longer ends the pattern, and `fancy_regex` runs a
    +/// lookahead on its linear engine only there, so `match()` moves one that applies to the whole
    +/// pattern after the wrapper, and `fullmatch()` drops it.
    +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
    +enum TrailingDollar {
    +    /// The pattern doesn't end in one.
    +    #[default]
    +    None,
    +    /// It does, and the `$` applies to the whole pattern.
    +    WholePattern,
    +    /// It does after a top-level `|`, so the `$` applies to the last alternative only.
    +    LastAlternative,
    +}
    +
    +/// Rewrites a Python pattern's `$` and `\Z` for `fancy_regex`, and reports what it found out
    +/// about the `$`s outside MULTILINE.
    +///
    +/// Python's `\Z` is the very end, which is `fancy_regex`'s `\z` (its own `\Z` also allows
    +/// trailing newlines). Python's `$` outside MULTILINE also matches before a `\n` that ends the
    +/// string, where `fancy_regex`'s is only the very end; with `dollar_before_newline` it becomes
    +/// `(?=\n?\z)` at the end of the pattern, which `fancy_regex` turns into a plain suffix match,
    +/// `\n?\z` where it ends an alternative of a lookahead, which is zero-width already, and
    +/// `(?:\z|(?=\n\z))` elsewhere, since it won't repeat a bare lookahead as in `(?:$)*`.
    +/// Escapes, classes and comments are copied as they are, and MULTILINE and VERBOSE are
    +/// tracked through inline and scoped flags.
    +fn translate_end_anchors(pattern: &str, multiline: bool, dollar_before_newline: bool) -> (Cow<'_, str>, EndAnchors) {
    +    if !pattern.contains('$') && !pattern.contains("\\Z") {
    +        return (Cow::Borrowed(pattern), EndAnchors::default());
    +    }
    +    let mut out = String::with_capacity(pattern.len() + 16);
    +    let mut anchors = EndAnchors::default();
    +    let mut scope = Scope {
    +        multiline,
    +        verbose: false,
    +    };
    +    // the flags outside each open group, restored at its `)`, and whether it is a lookahead
    +    let mut open: Vec<(Scope, bool)> = Vec::new();
    +    let mut top_level_alternation = false;
    +    let mut chars = pattern.chars().peekable();
    +    while let Some(c) = chars.next() {
    +        match c {
    +            '\\' => match chars.next() {
    +                Some('Z') => out.push_str("\\z"),
    +                Some(escaped) => {
    +                    out.push('\\');
    +                    out.push(escaped);
    +                }
    +                None => out.push('\\'),
    +            },
    +            '[' => copy_class(&mut chars, &mut out),
    +            '#' if scope.verbose => {
    +                // a verbose comment runs to the end of the line
    +                out.push('#');
    +                for c in chars.by_ref() {
    +                    out.push(c);
    +                    if c == '\n' {
    +                        break;
    +                    }
    +                }
    +            }
    +            '(' => {
    +                out.push('(');
    +                let mut lookahead = false;
    +                if chars.next_if_eq(&'?').is_some() {
    +                    out.push('?');
    +                    if chars.next_if_eq(&'#').is_some() {
    +                        // a comment runs to the next `)`
    +                        out.push('#');
    +                        for c in chars.by_ref() {
    +                            out.push(c);
    +                            if c == ')' {
    +                                break;
    +                            }
    +                        }
    +                        continue;
    +                    }
    +                    if let Some((text, scoped, inner)) = inline_flags(&chars, scope) {
    +                        chars.nth(text.chars().count() - 1);
    +                        out.push_str(&text);
    +                        if scoped {
    +                            open.push((scope, false));
    +                        }
    +                        scope = inner;
    +                        continue;
    +                    }
    +                    lookahead = matches!(chars.peek(), Some('=' | '!'));
    +                }
    +                open.push((scope, lookahead));
    +            }
    +            ')' => {
    +                out.push(')');
    +                scope = open.pop().map_or(scope, |(outer, _)| outer);
    +            }
    +            '|' => {
    +                top_level_alternation |= open.is_empty();
    +                out.push('|');
    +            }
    +            '$' if !scope.multiline => {
    +                anchors.has_dollar = true;
    +                let next = chars.peek().copied();
    +                // moved out of a `match()` wrapper, the `$` must still be outside MULTILINE
    +                if next.is_none() && open.is_empty() && !multiline {

    Fixed in 3cc16ab: under (?x) the rewrite now takes the next character past whitespace and # comments, so (?x)\w+$ # comment and (?x)\w+ (?= , | $ ) stay linear; both are tests on a 250 kB subject. match() still only moves a $ that is the last character, since it cuts that character off the pattern text.

    Likheet Likheet commented on code on Oct 15, 2026 04:02 UTC
    Code Review
    docs/limitations/re.md:1
    @@ -88,3 +88,14 @@ representation does not carry them.
     - Patterns whose *compiled* form is very large, e.g. huge counted repeats
         like `a{5000000}`, raise `re.PatternError` (`fancy-regex`/`regex` enforce a
         compiled-size limit), whereas CPython compiles them.
    +- A pattern with a backreference or a lookaround runs on `fancy-regex`'s backtracking VM.
    +    The exception is a positive lookahead that ends a pattern with no other lookaround or backreference, which
    +    `search()`, `findall()`, `finditer()`, `sub()` and `split()` run on the linear engine.
    +    A search on the VM raises `re.PatternError: Error executing regex: Max limit for backtracking count exceeded` once
    +    it has taken 1,000,000 backtracking steps, where CPython continues.
    +    The steps add up over every start position the search tries, so a pattern can work on a short subject and raise on a
    +    long one whose next match is far from where the search starts.
    +    The VM's backtracking stack is not tracked by the resource limits.

    Fixed in 3cc16ab: the sentence now says that the stack counts toward max_memory, but no checkpoint runs during a search, so only the hard ceiling applies to it, with a link to resource_limits.md.

    Likheet Likheet commented on Oct 15, 2026 04:02 UTC
    Author

    Follow-up in 3cc16ab, for cubic's review of c29052c:

  • A lazily compiled regex over CACHED_SIZE_LIMIT is no longer kept: it is compiled at the default limit for the call only, like a pattern over the cache's cap. So the part of my reply above about retaining it slightly over the cap no longer applies.

  • Under (?x), a $ followed only by whitespace or a comment now gets the same rewrite as one with nothing after it.

  • limitations/re.md now says that the backtracking stack counts toward max_memory, but only the hard ceiling applies to it during a search.
  • Reviewers
    Assignees
    Likheet Likheet
    Labels
    risk: low confidence: 94.2% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 44.7% (MEDIUM) · Higher = larger blast radius
    44.7%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 94.2% · Lower = rushed or shallow review
    94.2%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 2.6% · Safe to merge
    2.6%
    Repository