Repository navigation
Conversation
|
Tagging subscribers to this area: @dotnet/area-system-text-regularexpressions |
There was a problem hiding this comment.
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.ConcatinSymbolicRegexNode.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.NonBacktrackingreturns 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) |
|
|
||
| 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; |
|
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
}
]
} |
There was a problem hiding this comment.
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.csCreateConcatre-association (lines 469–474): Correct and terminating — the recursion strictly reduces the left spine depth, and it composes properly with the precedingEffect-push case sincerightis asserted non-Effect. Matches the existing re-association pattern used inPruneLowerPriorityThanNullability.CountSingletonsAlternatedoubling (lines 2319–2326): A conservative over-estimate. SinceSafeThresholdTestsassertsnfaStateCount <= expectedSafeSize, over-estimating preserves the invariant. The refactor ofContainsNestedUnboundedLoopinto the sharedContainsLoop(node, predicate)helper withstaticlambdas 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). TheSafeThresholdTestsexpectation 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
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
[2,3)=",",[3,4)=",", two matches.[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 ".*?keepsskipping ahead for a later match" branch must never outrank it.
PruneLowerPriorityThanNullabilityenforces that, but here it saw the twobranches 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.CreateConcatdoesn't enforce right-associative normal form. An optimization elsewhere
folds an optional leading space into the
.*?prefix, and once that fold'swrapper collapses away,
CreateConcatis called with aleftthat is itselfa
Concat, instead of the bare.*?node. That buries the.*?a leveldeeper than callers (specifically the priority-ordering check in
CreateDerivative) expect, so the priority order comes out backwards.Fix
Enforce the right-associative shape in
CreateConcatitself: ifleftisitself a
Concat, re-associate before building the new node.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 theworst case up to 2x. This broke the safety-threshold check in
SafeThresholdTests, sinceCountSingletons/EstimateNfaSizedidn'taccount for it. Extended
CountSingletons'sAlternatecase to cover thiscase and updated the four affected
SafeThresholdTestsexpectations.Unrelated patterns are unaffected.
Testing
Added a regression case to
Regex.MultipleMatches.Tests.cscovering therepro above; fails without the fix, passes with it.