Skip to content

fix: RegexOptions.NonBacktracking returns consistent matches with Backtracking - #130176

Open
ieviev wants to merge 2 commits into
dotnet:mainfrom
ieviev:main
Open

ieviev wants to merge 2 commits into
dotnet:mainfrom
ieviev:main

Conversation

@ieviev

@ieviev ieviev commented Jul 3, 2026

Copy link
Copy Markdown
Contributor

I found a long standing RegexOptions.NonBacktracking bug while testing multiple engines:

RegexOptions.NonBacktracking returns incorrect matches (drops a match) for patterns with an optional element next to the implicit search prefix

var re = new Regex(" ?, ?", RegexOptions.NonBacktracking);
re.Matches(" a,,").Select(m => m.Value).ToArray()
  • Default engine: [2,3)=",", [3,4)=",", two matches.
  • NonBacktracking engine: only [3,4)=",". The first match is silently dropped.

Reproduces on .NET 7, 8, 9, 10, and
the .NET 11 preview.

Root cause

NonBacktracking finds matches with an automaton for .*?<pattern>, where the
.*? searches for a start position. Once a match is found, the ".*? keeps
skipping ahead for a later match" branch must never outrank it.
PruneLowerPriorityThanNullability enforces that, but here it saw the two
branches in the wrong order, kept the wrong one alive, and let the "skip
ahead" branch overwrite the correct match end with a later one.

The branches end up in the wrong order because SymbolicRegexNode.CreateConcat
doesn't enforce right-associative normal form. An optimization elsewhere
folds an optional leading space into the .*? prefix, and once that fold's
wrapper collapses away, CreateConcat is called with a left that is itself
a Concat, instead of the bare .*? node. That buries the .*? a level
deeper than callers (specifically the priority-ordering check in
CreateDerivative) expect, so the priority order comes out backwards.

Fix

Enforce the right-associative shape in CreateConcat itself: if left is
itself a Concat, re-associate before building the new node.

if (left._kind == SymbolicRegexNodeKind.Concat)
{
    Debug.Assert(left._left is not null && left._right is not null);
    return CreateConcat(builder, left._left, CreateConcat(builder, left._right, right));
}

In SymbolicRegexNode.CreateConcat
(src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexNode.cs).

For patterns like .*?A|B, this fix can also increase memory use, in the
worst case up to 2x. This broke the safety-threshold check in
SafeThresholdTests, since CountSingletons/EstimateNfaSize didn't
account for it. Extended CountSingletons's Alternate case to cover this
case and updated the four affected SafeThresholdTests expectations.
Unrelated patterns are unaffected.

Testing

Added a regression case to Regex.MultipleMatches.Tests.cs covering the
repro above; fails without the fix, passes with it.

Copilot AI review requested due to automatic review settings July 3, 2026 11:41
@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label Jul 3, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @dotnet/area-system-text-regularexpressions
See info in area-owners.md if you want to be subscribed.

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.

Pull request overview

This PR fixes a correctness issue in the symbolic (NonBacktracking) regex engine where match selection could become inconsistent with the backtracking engine due to unexpected Concat tree shape, and updates the related safety-size estimation/tests accordingly.

Changes:

  • Enforce right-associative normal form for SymbolicRegexNodeKind.Concat in SymbolicRegexNode.CreateConcat.
  • Adjust NFA size estimation heuristics (CountSingletons) to account for cases where the normalization can increase node counts (impacting safe-threshold expectations).
  • Add a regression test ensuring RegexOptions.NonBacktracking returns the same set of adjacent matches as the default engine for the reported pattern.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.

File Description
src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexNode.cs Normalize Concat shape; update singleton counting / loop detection used by size estimates.
src/libraries/System.Text.RegularExpressions/tests/UnitTests/SymbolicRegexTests.cs Update safe-size expected values for .*?-prefixed patterns that are alternations.
src/libraries/System.Text.RegularExpressions/tests/FunctionalTests/Regex.MultipleMatches.Tests.cs Add regression coverage for dropped match in NonBacktracking engine.


case SymbolicRegexNodeKind.Alternate:
Debug.Assert(_left is not null && _right is not null);
// #(this) = #(_left) + #(_right)
Copilot AI review requested due to automatic review settings July 11, 2026 21:33

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.

Pull request overview

Copilot reviewed 3 out of 3 changed files in this pull request and generated 2 comments.


case SymbolicRegexNodeKind.Alternate:
Debug.Assert(_left is not null && _right is not null);
// #(this) = #(_left) + #(_right)
RegexNode tree = RegexParser.Parse(".*?" + Pattern, options | RegexOptions.ExplicitCapture, CultureInfo.CurrentCulture).Root;
SymbolicRegexNode<BDD> rootNode = converter.ConvertToSymbolicRegexNode(tree);
yield return new object[] { bddBuilder, rootNode, 1 + ExpectedSafeSize };
int expected = tree.Child(0).Kind == RegexNodeKind.Alternate ? 1 + (2 * ExpectedSafeSize) : 1 + ExpectedSafeSize;
@github-actions

github-actions Bot commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow state for the Holistic Review Orchestrator.

{
  "version": 5,
  "last_dispatched_commit": "21c0c6f17dfab7972829560b585c40127e710821",
  "last_dispatched_base_ref": "main",
  "last_dispatched_base_sha": "a7ed27ba3f7a0a32634be47079ac659909797806",
  "last_reviewed_commit": "21c0c6f17dfab7972829560b585c40127e710821",
  "last_reviewed_base_ref": "main",
  "last_reviewed_base_sha": "a7ed27ba3f7a0a32634be47079ac659909797806",
  "last_recorded_worker_run_id": "29681933302",
  "review_attempt_commit": "",
  "review_attempt_base_ref": "",
  "review_attempt_count": 0,
  "max_review_attempts": 5,
  "review_history_format": "holistic-review-disclosure-v1",
  "review_history": [
    {
      "commit": "21c0c6f17dfab7972829560b585c40127e710821",
      "review_id": 4730546156
    }
  ]
}

@github-actions github-actions Bot 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.

Holistic Review

Motivation: The PR fixes a real, long-standing NonBacktracking correctness bug where a match adjacent to an optional element next to the implicit .*? search prefix is silently dropped (e.g. " ?, ?" over " a,," yields one match instead of two). The repro is credible and the default engine's behavior is the correct oracle.

Approach: The fix enforces right-associative normal form for Concat directly in CreateConcat, re-associating when left is itself a Concat. This is the right layer: the codebase already assumes this invariant in several places (e.g. the Concat re-association in PruneLowerPriorityThanNullability, and comments at lines 529 and 714 stating alternations/concats are kept in right-associative normal form). Enforcing it at construction closes the gap that let a folded optional-prefix bury the .*? node a level deeper than CreateDerivative's priority-ordering check expected. The accompanying CountSingletons adjustment (doubling the estimate when an alternation branch contains a high-priority nullable unbounded lazy loop) keeps the EstimateNfaSize safety bound a valid upper bound after the fix can up to double NFA size for .*?A|B-shaped patterns, and the static lambda avoids per-call delegate allocation.

Summary: ✅ LGTM. The fix is minimal, targets the correct invariant, and is consistent with existing normal-form assumptions in the symbolic engine. The regression test is added to the shared Matches_TestData so it runs across all engines and asserts parity with the backtracking oracle. One tradeoff worth a human's awareness (not a blocker): the CountSingletons over-estimate for .*?A|B shapes could push a pattern that was previously just under the 10,000 safe-size threshold over it, causing construction to throw NotSupportedException; this is inherent to the up-to-2x size increase and is the documented cost of correctness.


Detailed Findings

No blocking issues found.

  • SymbolicRegexNode.cs CreateConcat re-association (lines 469–474): Correct and terminating — the recursion strictly reduces the left spine depth, and it composes properly with the preceding Effect-push case since right is asserted non-Effect. Matches the existing re-association pattern used in PruneLowerPriorityThanNullability.
  • CountSingletons Alternate doubling (lines 2319–2326): A conservative over-estimate. Since SafeThresholdTests asserts nfaStateCount <= expectedSafeSize, over-estimating preserves the invariant. The refactor of ContainsNestedUnboundedLoop into the shared ContainsLoop(node, predicate) helper with static lambdas is clean and allocation-free.
  • Tests: The functional regression case is well-placed in Matches_TestData (runs on every engine, so it also guards the backtracking engines against regression). The SafeThresholdTests expectation update (tree.Child(0).Kind == RegexNodeKind.Alternate ? 1 + 2*ExpectedSafeSize : ...) correctly scopes the doubling to alternation-rooted .*?-prefixed patterns.

Note

This review was generated by this repository's Holistic Review agentic workflow to complement the built-in Copilot review.

Generated by Holistic Review · 88.3 AIC · ⌖ 10.8 AIC · ⊞ 10K

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-System.Text.RegularExpressions community-contribution Indicates that the PR has been added by a community member

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants