[SPARK-60632][SQL] Fix the LIKE/RLIKE expensive heuristic to look at the pattern #59879
1. [Medium] Evaluating the pattern here can fail the optimizer
PushPredicateThroughNonJoin calls expensive (Optimizer.scala:2628), and before this change it never evaluated anything. L92 now evaluates any foldable pattern. That includes a pattern which ConstantFolding deliberately leaves unfolded because it throws inside a conditional branch (expressions.scala:67-72, FAILED_TO_EVALUATE). For example, with ANSI on:
SELECT * FROM (
SELECT IF(s IS NULL, NULL, s RLIKE CAST(1/0 AS STRING)) AS f FROM t
) WHERE f
If.expensive goes through hasExpensiveChild to RLike.expensive, and L92 throws DIVIDE_BY_ZERO inside the optimizer. PushDownPredicates also runs before ConstantFolding in each iteration (Optimizer.scala:108, 139), so the first iteration sees unfolded patterns even outside conditional branches.
The codegen paths at L204 and L548 evaluate the pattern too, so with whole-stage codegen on, this query already fails at execution. What changes:
EXPLAIN and queryExecution.optimizedPlan now fail.spark.sql.codegen.wholeStage=false, the expression codegen error falls back to the interpreter (CodeGeneratorWithInterpretedFallback.scala:52-54). The query used to succeed when the branch was not taken, and now it fails.Separately, L92 evaluates the plan's own instance. ConstantFolding.tryFold evaluates freshCopyIfContainsStatefulExpression() instead (expressions.scala:65), because a stateful foldable pattern such as regexp_replace('a+b', 'x', 'y') (RegExpReplace, L756) mutates its caches when evaluated.
Could L91-96 evaluate a fresh copy and treat a pattern that fails to evaluate as expensive?
private lazy val _expensivePattern = !right.foldable || {
try {
val str = right.freshCopyIfContainsStatefulExpression().eval()
str != null && isExpensivePattern(str.toString)
} catch {
case NonFatal(_) => true
}
}
2. [Medium] Every constant LIKE pattern is classed cheap, including the slow ones
% and _ do not nest, but consecutive % wildcards still backtrack polynomially. StringUtils.escapeLikeRegex turns '%a%a%a%b' into (?s).\Qa\E.\Qa\E.\Qa\E.\Qb\E, and Like.matches uses matches(). On JDK 25, matching one value of n as with no b took:
| n | time for one value |
|---|---|
| 200 | 0.13 s |
| 400 | 2.0 s |
| 800 | 31 s |
LikeSimplification already rewrites the single-% shapes (x%, %x, x%y, %x%) into cheap string functions. So the LIKE expressions that are still Like here are mostly the multi-wildcard ones this heuristic should catch. With this change, a filter on such an alias is pushed below the Project and the LIKE runs twice per row. The new test even asserts that %a%b% is cheap (RegexpExpressionsSuite.scala:750).
Could a LIKE pattern with several % (say three or more) be classed expensive? Or could the escaped regex go through the same check as RLIKE?
3. [Low] A leading ^ or \b does not bound the backtracking
An anchor only removes the scan over start positions. The backtracking inside the match is unchanged. ^.a.a.a.b is classed cheap here, but on JDK 25 it took 2.5 s on one 400-character value, about the same as without the anchor. \b is not a start anchor at all: with find(), the match is still tried at every word boundary.
By contrast, the nested-group pattern in the new test, (a+)+b, took 0 ms on the same JDK, which avoids that exponential case. Could the anchor exemption apply only when the rest of the pattern has at most one quantifier, or be dropped?
*4. [Low] The [+{] check also matches characters that are not quantifiers*
find() on [+{] also matches:
a\+b[+]\p{...} and \x{...}, e.g. \p{Lu}None of these can backtrack, but all are classed expensive. An inline flag also hides the anchor: (?i)^abc. is expensive while ^abc.* is cheap.
For these patterns, a filter on the alias is still not pushed. So the partition pruning and data filter pushdown that this PR restores are still lost for them. If the heuristic stays text-based, could it skip escaped characters and character classes, and allow leading inline flags before ^?
5. [Low] The new abstract member breaks subclasses outside Spark
StringRegexExpression is a public, non-sealed abstract class. A subclass compiled against 4.2.0 does not implement isExpensivePattern. It would fail with AbstractMethodError the first time the optimizer reaches L93 for it, and it no longer compiles against this branch.
Catalyst is not a public API, but this would also reach 4.2.x if it is backported. Could this have a default instead, e.g. = true (what 4.2.0 answers for a column LIKE/RLIKE) or the regex check, with Like and RLike overriding it?
6. [Low] The partition test reads part back as an INT, and its asserts are weak
part is written as a string, but partition type inference reads 0 to 3 back as IntegerType. So the RLIKE case runs as CAST(part AS STRING) RLIKE '^1'.
Every value has one digit, so part LIKE '1_' matches no partition and only part = '1' returns rows. The LIKE leg's result is never checked.
partitionFilters.nonEmpty here, and dataFilters.nonEmpty at L628, would also pass if only an isnotnull(part) reached the scan, or if the pushed predicate pruned nothing.
Could the test do the following?
spark.sql.sources.partitionColumnTypeInference.enabled.7. [Low] Partition pruning still depends on this per-row cost heuristic
This narrows the regression but does not remove it. With the defaults, SELECT FROM (SELECT name, part RLIKE '2024-.' AS p FROM t) WHERE p still gets PartitionFilters: [], because .* is a quantifier. Yet this is where double evaluation costs least: a predicate on partition columns alone is evaluated once per partition during listing, not once per row.
As far as I can tell, ScanOperation cannot inline the alias either:
InferFiltersFromConstraints adds isnotnull(p) (QueryPlanConstraints.scala:174), so p is referenced twice.patterns.scala:78, Optimizer.scala:1885).This is not a blocker for this PR. Would a separate JIRA be worth it, to let partition pruning see through the alias for partition-only predicates regardless of expensive?
8. [Nit] No test checks that an expensive child still wins over a cheap pattern
Suppose hasExpensiveChild || were dropped from L87. Then an RLIKE with a cheap constant pattern over an expensive subject, e.g. RLike(scalaUdf(col), Literal("^1")), would become cheap. A filter on it would be pushed and the UDF evaluated twice, and none of the new tests would fail.
Could this test cover that case? FilterPushdownSuite could also cover two more cases:
^a.*bLike(Lower(left), Lower(right))9. [Nit] A precompiled Pattern and a companion method are more than this needs
isExpensiveRegex has one caller, and the check is a search for three characters. Could RLike.isExpensivePattern hold it directly, with no Pattern?
override protected def isExpensivePattern(str: String): Boolean =
!str.startsWith("^") && !str.startsWith("\\b") &&
str.exists(c => c == '+' || c == '*' || c == '{')
Also, Like always answers false, so L92 evaluates every foldable LIKE pattern only to discard the result.
10. [Nit] This helper splits the test relation definitions
It sits between testStringRelation and testArrayStringRelation. AGENTS.md asks that a new member go with the code it belongs to, without splitting an existing section. Could it go after the block of relation and predicate vals?
Thank you for fixing this, @viirya. Looking at the pattern instead of the subject is the right fix, and the FileSourceStrategySuite test shows the lost pruning well. I left 10 inline comments. Items 1 and 2 matter most:
% patterns that LikeSimplification cannot rewrite. Each evaluation of such a pattern can take seconds on one row.Summary:
1. [Medium] Evaluating the pattern here can fail the optimizer (regexpExpressions.scala:92)
A foldable pattern that ConstantFolding left unfolded inside a conditional branch throws here. EXPLAIN then fails, and so does the query with whole-stage codegen off. The same line also evaluates stateful patterns in place.
2. [Medium] Every constant LIKE pattern is classed cheap, including the slow ones (regexpExpressions.scala:185)
'%a%a%a%b' took 31 s on one 800-character value, and a filter on its alias is now pushed and evaluated twice.
3. [Low] A leading ^ or \b does not bound the backtracking (regexpExpressions.scala:111)
4. *[Low] The [+{] check also matches characters that are not quantifiers (regexpExpressions.scala:104)
5. [Low] The new abstract member breaks subclasses outside Spark (regexpExpressions.scala:99)
6. [Low] The partition test reads part back as an INT, and its asserts are weak (FileSourceStrategySuite.scala:622)
7. [Low] Partition pruning still depends on this per-row cost heuristic (regexpExpressions.scala:87)
This is not a blocker for this PR; it could be a separate JIRA.
8. [Nit] No test checks that an expensive child still wins over a cheap pattern (RegexpExpressionsSuite.scala:739)
9. [Nit] A precompiled Pattern and a companion method are more than this needs (regexpExpressions.scala:110)
10. [Nit] This helper splits the test relation definitions** (FilterPushdownSuite.scala:66)
The timings come from java.util.regex on JDK 25, one value per measurement.
Done in 0048df0. _expensivePattern now evaluates right.freshCopyIfContainsStatefulExpression() and treats a pattern that fails to evaluate as expensive. RegexpExpressionsSuite covers CAST(1/0 AS STRING) as the pattern under ANSI. Before this change, PushPredicateThroughNonJoin threw DIVIDE_BY_ZERO on your IF(...) example.
Agreed. A LIKE with three or more % is now expensive. On JDK 17, one 400-character value took 0.1 ms with two %, 18 ms with three and 1.7 s with four, so two stay cheap. %a%b% is now in the expensive cases of the test.
Agreed, the anchor exemption is gone. I see the same on JDK 17: ^.a.a.a.b and .a.a.*b both take 2.1 s on 400 characters. RLIKE now counts repeating quantifiers and treats two or more as expensive, anchored or not. Two quantifiers took 22 ms there, three took 2.1 s.
The check is now a small scanner that counts , + and {n,m}. It skips escaped characters, \Q...\E, character classes and the braces of \p{..}, \x{..} and \N{..}, and does not count again the + or ? that makes a quantifier possessive or lazy. Because it no longer looks for an anchor, inline flags do not matter: (?i)^abc. has one quantifier and is cheap, like ^abc.. The test covers a\+b\, [+{]x+, \p{Lu}+, \x{41}. and \Q.+\E..
Done: isExpensivePattern now defaults to true, which is what 4.2.0 answers for a column LIKE/RLIKE, and Like and RLike override it.
Fixed. The partition values are now v0 to v3, so they stay strings, and the cases are:
part RLIKE '^v1' (1 partition)part RLIKE 'v[12].*' (2)part LIKE '_1' OR part = 'v2' (2)Each asserts that the LIKE/RLIKE reaches partitionFilters and checks selectedPartitions.partitionCount. The data filter case asserts that the RLIKE reaches dataFilters.
Agreed that the remaining case is real and is a separate issue, so I'd keep it out of this PR. With the quantifier count, your part RLIKE '2024-.' example has one quantifier and is now cheap, so it gets pruned; the part RLIKE 'v[12].' case in FileSourceStrategySuite covers that shape. A partition-only predicate that is still expensive, e.g. a UDF over a partition column, still loses pruning.
Added: an RLIKE or LIKE over a ScalaUDF subject with a cheap pattern is expensive. FilterPushdownSuite now also pushes ^a.b and an ILIKE in the form the optimizer sees it, Like(Lower(e), Lower('%Magic%')), and does not push .a.*b or %a%b%c.
The Pattern is gone. The counting has to skip escapes and character classes, so it is a loop rather than a one-liner; it sits in the companion object next to the LIKE counterpart. Like now uses the evaluated pattern too.
Moved after the relation and predicate definitions.
1. [Medium] A fixed {n} on a group that holds a quantifier is not counted
Skipping a {n} without a comma is right for \d{4}. But on a group, {n} repeats everything inside it, so (.a){3} backtracks like .a.a.a and still counts as one quantifier. The textbook catastrophic-backtracking pattern is classed cheap:
| Pattern | Count | Input (no match) | JDK 25 | JDK 17 |
|---|---|---|---|---|
| ^(.?,){11}P | 1 | one line of 30 comma-separated numbers, 82 chars | 1.9 s | 2.1 s |
| ^(.?,){13}P | 1 | the same line | 6.1 s | 6.3 s |
| (.a){3}x | 1 | 400 as | 14.4 s | 7.4 s |
| .a.a.ax | 3 | 400 as | 10.2 s | 4.3 s |
So a filter on col RLIKE '^(.?,){11}P' AS p is pushed below the projection and evaluated twice. Meanwhile the faster .a.a.ax stays above it.
Could a quantifier that follows ) be counted even when it is a fixed {n}? That gives 2 for both patterns above, and \d{4} is still not counted.
2. [Low] A [ that does not open a class hides every later quantifier
The scanner treats every [ it does not skip as the start of a class, and it counts nothing while classDepth > 0. Java does not read two kinds of [ as a class:
\c[ is a control-character escape (ESC). The '\\' case consumes only the c, so the [ opens a class here.(?x) pattern, # starts a comment, and the comment may contain a [.Both "\\c[.a.b" and "(?x)a # [\n.a.b" compile in Java. Both count 0 here, although each has the two .s that make .a.*b expensive (4.3 s on 2000 chars on JDK 25).
These patterns are rare. A cheap guard would be to treat a pattern whose classDepth is still positive at the end as expensive, since the stray [ is never closed. Skipping the character after \c would also fix the first case.
3. [Low] An anchored RLIKE gets a lower threshold than the LIKE with the same cost
This reopens part of my round-1 comment 3. As I wrote there, an anchor does not bound the backtracking inside a match. But it does remove the extra factor that the comment above uses to justify 2 instead of 3. With ^, find() fails at once at every start position after the first.
So a ^-anchored RLIKE costs about the same as the LIKE with the same number of .s, yet the two are classed differently:
| Pattern | Count | Classed | 2000 as, JDK 25 | JDK 17 |
|---|---|---|---|---|
| LIKE '%a%b' | 2 | cheap | 15 ms | 21 ms |
| RLIKE '^.a.b' | 2 | expensive | 9 ms | 16 ms |
| RLIKE '.a.b' | 2 | expensive | 4.3 s | 4.8 s |
With three wildcards on 400 as, LIKE '%a%a%b' took 31 ms and RLIKE '^.a.a.b' took 35 ms on JDK 25. Without the anchor, '.a.a.b' took 3.7 s.
This costs the pruning that this PR restores. For example, a filter on part RLIKE '^v[0-9]+_.' AS p still stays above the projection. Could a pattern that starts with ^ or \A use the LIKE threshold of 3, when it has no (?m) flag and no top-level |?
4. [Low] ?+ and {n}+ are counted, and so are quantifiers that cannot backtrack
skipModifier() runs only after , + and {n,m}. After ? or a fixed {n}, the possessive + reaches the case '' | '+' branch and is counted as a new quantifier:
a?+b?+ counts 2.a{3}+b counts 1.Neither pattern has a quantifier that can backtrack. The possessive + and ++ cannot backtrack either, yet each is counted once, so a+b+ is expensive. A small bounded range is counted like too. The test asserts that a{1,9}b{1,9} is expensive, although each range adds a factor of at most 9, not a factor of the input length.
All of these err on the expensive side, so nothing regresses from 4.2.0. But they lose the pushdown and pruning that this PR restores. They also disagree with the scaladoc, which counts quantifiers because they are "what make a failed match backtrack". Could the modifier after ? and {n} be skipped too, and could possessive quantifiers be left uncounted?
5. [Nit] countLikeWildcards can be countRegexQuantifiers(escape(str))
escape turns each unescaped % into .* and quotes every other character with \Q..\E, which countRegexQuantifiers skips. So countRegexQuantifiers(escape(str)) gives the same count. I checked the LIKE patterns in the new test, plus %a\\%b% (an escaped backslash, then a wildcard) and 50\%%off%%, and the counts match for all of them.
That would leave one parser of the LIKE escape rules instead of two. escapeLikeRegex walks code points and throws on a bad escape, while this loop walks chars and skips a bad escape silently. With the change, a bad escape would throw inside the existing try and count as expensive. isExpensivePattern could then live in StringRegexExpression, and Like and RLike would give only their thresholds.
6. [Nit] No case covers a quantified group or a [ that is not a class
All the new RLIKE cases are flat. Could the expensive list also have "^(.?,){11}P", "(.a){3}x" and "\\c[.a.b"? All three fail today, which is items 1 and 2. A nested or intersected class such as "[a-z&&[^b]]+x" in the cheap list would also pin down the classDepth handling.
Thank you for the quick update, @viirya. The quantifier scanner, the evaluation guard and the new tests address round 1, and I agree that round-1 item 7 can be handled separately. I left 6 more inline comments on the new code.
Item 1 matters most. A quantifier inside a group that is repeated a fixed number of times is not counted. So the textbook catastrophic pattern ^(.?,){11}P is classed cheap, although one 82-character value takes about 2 s.
Summary:
1. [Medium] A fixed {n} on a group that holds a quantifier is not counted (regexpExpressions.scala:159)
^(.?,){11}P and (.a){3}x each count 1 and are pushed. Yet (.a){3}x is slower than .a.a.*ax, which stays above the projection.
2. [Low] A [ that does not open a class hides every later quantifier (regexpExpressions.scala:154)
3. [Low] An anchored RLIKE gets a lower threshold than the LIKE with the same cost (regexpExpressions.scala:604)
This reopens part of round-1 comment 3.
4. [Low] ?+ and {n}+ are counted, and so are quantifiers that cannot backtrack (regexpExpressions.scala:137)
5. [Nit] countLikeWildcards can be countRegexQuantifiers(escape(str)) (regexpExpressions.scala:111)
6. [Nit] No case covers a quantified group or a [ that is not a class (RegexpExpressionsSuite.scala:750)
The timings come from java.util.regex on JDK 25 and JDK 17, one value per measurement.
Review summary
No defects found in this revision. A pattern that is not foldable is expensive. A foldable pattern is evaluated on a fresh copy, and an evaluation failure is classed as expensive instead of failing the optimizer. A port of the two new counters reproduces every case in the new RegexpExpressionsSuite test. The ten inline comments from the earlier review are addressed at 0048df0. As agreed in that thread, partition-only pruning for predicates that stay expensive is a separate issue. Two questions for the author follow.
Cross-cutting observations
Separation: The anchored threshold concerns the cost model for constant RLIKE patterns, while the streaming question concerns whether any classification change may move a filter across a stateful operator for an existing checkpoint, so each needs its own decision and answering one does not settle the other.
Findings
0 total: 0 P0, 0 P1, 0 P2, 0 P3.
No findings.
Decision challenges
Anchored RLIKE patterns use the unanchored two-quantifier threshold
RLike.isExpensivePattern treats two or more repeating quantifiers as expensive, one below LIKE's three %. The comment above it says the lower threshold is there because find also tries every start position. A pattern that starts with ^ or \A does not pay that factor. RLIKE compiles without MULTILINE, so the anchor can only match at the start of the input, and every other start position fails at the anchor. The threshold is the same anchored or not. So a common anchored validator with two quantifiers, such as ^\d+-\d+$, ^[A-Z]+_[0-9]+$ or ^v[0-9]+_[0-9]+$, is classed expensive. A filter on such an alias, e.g. SELECT FROM (SELECT name, part RLIKE '^v[0-9]+_[0-9]+$' AS p FROM t) WHERE p, stays above the Project, and the scan gets no partition filter. Plans and results match the merge base, where every column RLIKE was expensive. This is pushdown the PR could restore but does not.
Your JDK 17 timings in the review thread fit this. ^.a.a.a.b (four quantifiers, anchored) and .a.a.b (three, unanchored) both took 2.1 s on 400 characters. On a string of n as, the anchored pattern tries about C(n, 4) splits. The unanchored one tries C(n-i, 3) at each start position i, which sums to C(n+1, 4). By the same count, an anchored pattern with two quantifiers costs about what a LIKE with two % costs: 0.1 ms in the PR body, and classed cheap. No timing in the PR or the review measures an anchored two-quantifier pattern directly. Timing ^.a.b against .a.b on 400 as would confirm it.
Was the same threshold for anchored and unanchored patterns intended? Or should a pattern that starts with ^ or \A, outside (?m), get LIKE's threshold of three? That threshold would still class ^.a.a.a.b, the anchored pattern timed in the review, as expensive.
Streaming queries resumed from 4.2.0+ checkpoints get the new filter placement
Existing streaming checkpoints may need to keep the old filter placement. Deciding that needs your call or a committer's.
Verified in source at 0048df0:
spark.sql.optimizer.avoidDoubleFilterEval=true, because the subject-based check marks the alias expensive. That code is on branch-4.2, branch-4.3 and branch-4.x. branch-4.1 has neither the check nor the config.l_k RLIKE '^a' is pushed below the Project (Optimizer.scala:2604-2628). PushPredicateThroughJoin then moves a deterministic, non-throwable conjunct that references one side into that side of an inner join, or into the preserved side of an outer join. It has no streaming guard, and RLIKE is not throwable.OffsetSeqMetadata.relevantSQLConfs (OffsetSeq.scala:199-211) does not record avoidDoubleFilterEval, and nothing else there pins this classification. spark.sql.optimizer.pruneFiltersCanPruneStreamingSubplan, by contrast, is recorded there with a legacy default for older checkpoints (OffsetSeq.scala:205, :275).Example: a stream-stream inner join l JOIN r ON l.id = r.id, followed by withColumn("flag", col("l_k").rlike("^a")).filter("flag"). A query started on 4.2.x keeps the filter above the join, so the join state holds every left row. After a restart from that checkpoint on a build with this PR, the filter runs on the left input below the join. Left rows already in state whose l_k does not match ^a can still pair with new right rows. Nothing above the join filters those pairs, so they are emitted with flag = false until the rows are evicted from state. A Project that cannot be collapsed into a streaming Aggregate, for example one that references an aggregate result twice, has the same exposure in complete or append mode. The common streaming aggregate is unaffected: CollapseProject merges its Project into the Aggregate, and the Aggregate pushdown case already pushes such a filter at the merge base.
Not verified: an end-to-end streaming run across the upgrade.
Does Spark need to keep the old placement for checkpoints written by 4.2.0 or later? One way would be a config recorded in the offset log with a legacy default. Which release lines will this fix go to? If it is backported to branch-4.2 or branch-4.3, the change also arrives in a maintenance upgrade.
Generated by Omnigent on Databricks
<!-- SPARK_OSS_REVIEW_REQUEST 34502278653 -->
<!-- SPARK_DEV_REVIEW_CODE {"findings":[],"head_sha":"0048df06bb7beddfb6a778476b123451c4e134e8","verdict_sha256":"ad546de1a14a66351f0ed471529a63f961d25f5984f53430356aa446cf33e0a3"} -->
Good catch. Counting the {n} after ) once would not survive item 3, though: with the anchored threshold of 3, ^(.?,){11}P would count 2 and be cheap again. So a repeated group that holds a counted quantifier now makes the pattern expensive outright, whatever the anchor, since the repetition multiplies the factors inside it. This covers {n}, {n,m} with an upper bound of at least 2, and +, and also (a+)+b and ^(a+)+b. A repeated group without a quantifier inside, such as (ab){3}.*, is not affected.
Done both: the character after \c is skipped, and a [ that is still open at the end makes the pattern expensive, which covers the (?x) comment case.
You're right, and my round-1 reply misread my own numbers: ^.a.a.a.b taking as long as .a.a.b shows exactly that the anchor removes one factor. On JDK 17 I see ^.a.a.b at 42 ms and \A.a.a.b at 41 ms on 400 as, against 40 ms for LIKE '%a%a%b' and 4.2 s for .a.a.b.
A pattern that starts with ^ or \A now uses the threshold of 3, unless a leading inline flag mentions m or the pattern has a | outside any group. ^v[0-9]+_. is now cheap (0.2 ms on 2000 characters), while ^a|.b.c and (?m)^.a.*b stay expensive. LIKE goes through the same path as a regex that must match the whole input, so both use 3.
Done. ? now skips its modifier like the others, a fixed {n} is consumed together with its modifier, and a possessive quantifier is not counted, so a?+b?+, a{3}+b, a+b+ and .+a.+b are cheap (.+a.+b takes 35 ms on 2000 characters). A {n,m} is counted only when its range is unbounded or spans at least 10. On 400 characters, three .{0,9} took 2.8 ms and three .{0,50} took 120 ms, so a{1,9}b{1,9} moved to the cheap cases and .{0,50}a.{0,50}b is in the expensive ones.
Thank you for addressing all six round-2 comments, @viirya. The repeated-group rule, the anchored threshold and the shared isExpensiveRegex path read well. A port of the scanner gives the expected answer for every case in the new test. I left 9 more inline comments.
Items 1 and 2 matter most. In both, a pattern is classed cheap although one short value takes more than a second, so a filter on its alias is pushed and evaluated twice.
Summary:
1. [Medium] A repeated group that holds a small range or an alternation is not caught (regexpExpressions.scala:146)
(a{1,9}){6}b and (a|aa){20}b count 0, yet each takes about 1.5 s on one value of 400 or 100 characters.
2. [Medium] Under (?x), whitespace before a group's quantifier hides the repeat (regexpExpressions.scala:212)
(?x) ^ (.*?,) {11} P counts 1. Without the space before {11}, it is MAX.
3. [Low] Small ranges in sequence multiply, but none of them is counted (regexpExpressions.scala:198)
4. [Low] A quantifier at the end of the pattern is counted, though a failed match never backtracks into it (regexpExpressions.scala:305)
This keeps the common LIKE '%foo%bar%' expensive.
5. [Low] A ] right after [ closes the class too early (regexpExpressions.scala:177)
6. [Low] Quantifiers in different lookarounds or atomic groups are added up, though they do not multiply (regexpExpressions.scala:179)
7. [Low] bounds copies the rest of the pattern for every { (regexpExpressions.scala:225)
8. [Nit] A repeated group between distinct delimiters is always expensive (regexpExpressions.scala:184)
9. [Nit] The three quantifier cases repeat the same steps (regexpExpressions.scala:188)
I agree with the streaming-checkpoint question in the spark-test review, so I did not repeat it inline. A pattern that moves from expensive to cheap can move its filter below a stream-stream join when the query restarts from a 4.2.0 or later checkpoint, and the rows already in the join state are never filtered.
The timings come from java.util.regex on JDK 25 and JDK 17, one value per measurement.
Thanks for the review. The anchored threshold was changed in round 2: a pattern that starts with ^ or \A, outside (?m) and without a top-level |, now uses the threshold of 3.
On the streaming question, I agree that checkpoints written by 4.2.0 or later should keep the old placement. This PR adds an internal config, spark.sql.optimizer.estimateRegexPatternCost, which defaults to true. When it is false, every LIKE and RLIKE is expensive, as in 4.2.0. The config is recorded in the offset log. A checkpoint without it uses false, the same way pruneFiltersCanPruneStreamingSubplan is handled. A query resumed from a 4.2.x or 4.3.x checkpoint therefore keeps its filter above the join. One from a 4.1 checkpoint also takes the 4.2.0 placement. That moves the filter up rather than down, which does not change results. With this in place the fix is also safe to backport to branch-4.2 and branch-4.3.
Thank you for addressing round 3, @viirya. The marked groups, the small-range product, the trailing-quantifier rule and the in-place matching read well. The new estimateRegexPatternCost conf answers the streaming question for existing checkpoints. I'm fine with keeping round-3 items 6 and 8 as they are. I left 9 more inline comments.
Item 1 matters most. A repeated group that holds two ? is classed cheap, although one value of 40 characters takes more than 20 s. My round-3 comment was wrong to say that ? can stay out.
Summary:
1. [Medium] Two ? in a repeated group blow up, but ? is never counted (regexpExpressions.scala:227)
^(.?.?){20}x counts 0 and takes over 20 s on 40 as. a{0,1} is counted, but a? is not.
2. [Low] A LIKE/RLIKE inside another expression keeps the answer of the first conf value (regexpExpressions.scala:87)
hasExpensiveChild is a lazy val, so NOT (s RLIKE '^1') can stay cheap after a restart from a 4.2 checkpoint, and its filter moves below a stream-stream join.
3. [Low] The small-range product drops what is left at each reset (regexpExpressions.scala:181)
.{0,9}a.{0,9}a.{0,8}a.b counts 1 and is classed cheap, yet it is slower than .a.*b, which is classed expensive.
4. [Low] The offset log pins whether the estimate is on, not which estimate (OffsetSeq.scala:211)
5. [Low] Quantifiers in different top-level alternatives are added up (regexpExpressions.scala:223)
6. [Low] The version should be the first release that gets the conf (SQLConf.scala:681)
7. [Nit] as in 4.2.0 does not hold for a literal subject (SQLConf.scala:679)
8. [Nit] No test restarts a query from a checkpoint without the key (OffsetSeqLogSuite.scala:55)
9. [Nit] A Matcher is built at every ( (regexpExpressions.scala:212)
The timings come from java.util.regex on JDK 25 and JDK 17, one value per measurement.
Merge Summary:
Posted by merge_spark_pr.py
Thanks @dongjoon-hyun !
dongjoon-hyun
viirya
What changes were proposed in this pull request?
SPARK-47672 added an
expensiveheuristic toStringRegexExpression(LIKE/RLIKE), used byPushPredicateThroughNonJointo avoid evaluating an expensive alias twice whenspark.sql.optimizer.avoidDoubleFilterEvalis true (the default). The heuristic had these bugs:1. It matched on
left, the subject string, instead ofright, the pattern. For the usualcol LIKE/RLIKE 'literal'it fell intocase _ => true, so every LIKE/RLIKE over a column was classed expensive, including'^1', which the code's own comment says should be cheap.2. The backtracking check
Pattern.compile("\\+\\\\{").matcher(str).matches()only matches the literal string+{, so it never fired.3. The regex-specific
^/\banchor checks were also applied to LIKE patterns.4. The detection
Patternwas a per-instanceval, compiled for every Like/RLike.This PR makes the heuristic look at the pattern:
ConstantFoldingleft in a conditional branch because it throws. The pattern is evaluated on a fresh copy, asConstantFoldingdoes.,+,?and{n,m}). A failed match tries every combination of their lengths, so each one costs a factor of the input length, and an unanchored RLIKE (find) costs one more factor for trying every start position. On JDK 17, one 400-character value took about 40 ms for LIKE'%a%a%b'or RLIKE'^.a.a.b', but 4.2 s for RLIKE'.a.a.b'. So:- An RLIKE pattern is expensive with two or more quantifiers, or three or more when it starts with
^or\A(with no leading multiline flag, no quantifier on the anchor and no top-level|).- A LIKE pattern is expensive with three or more
%that are not at the end. It is checked by escaping it to its regex and scanning that the same way, as a regex that must match the whole input.- The alternatives of a top-level
|are tried one after another, so each is counted on its own and the largest count is used.- A quantifier that ends the pattern or a top-level alternative, possibly followed by the
)of groups that end there too, is not counted, since a failed match never backtracks into it. Possessive quantifiers are not counted either.?and a{n,m}range spanning fewer than 10 are not counted on their own, but their choices multiply, together with one choice of two for each group that holds a|, and they count as one quantifier each time their product reaches 32.- A backreference, which compares as many characters as its group holds, and a repetition of at least 100, which adds its length to every attempt even when it cannot backtrack, count as one quantifier each, unless they end the pattern or a top-level alternative.
- A repeated group that holds a quantifier, a small range or a
|, such as^(.?,){11}P,(a+)+bor(a|aa){20}b, is always expensive. So is a pattern that turns on COMMENTS mode ((?x)), where whitespace can separate a group from its quantifier, and one with a[that is never closed. An empty\Q\Ebetween a group and its quantifier is skipped, sincePatternremoves it.- Some patterns stay expensive on purpose, although they cost no more than their cheap relatives: alternatives inside a group, such as
(a.b|c.d), are counted together, and a top-level|turns off the anchored threshold even when every alternative is anchored, such as^a.a.b|^c.c.d. This errs on the side of keeping a filter above the projection.- Escaped characters,
\Q...\E, character classes (where a]right after[or[^is a literal) and the braces of\p{..},\x{..}and\N{..}are skipped.isExpensivePatterndefaults totrue, andLikeandRLikeoverride it.spark.sql.optimizer.regexPatternCostEstimateVersion(default1), selects the estimate. With0, every LIKE and RLIKE is expensive, as in 4.2.0 for a subject that is not a literal.PushPredicateThroughNonJoinchecks it rather thanexpensive, since a parent expression cacheshasExpensiveChild. It is recorded in the streaming offset log, and a checkpoint without it uses0. A later change that makes any pattern cheaper needs a new version. A cheap pattern can move a filter below a stateful operator such as a stream-stream join, so a query resumed from a 4.2.x or 4.3.x checkpoint keeps its old filter placement. One resumed from an older checkpoint also takes the 4.2.0 placement, which keeps the filter higher and does not change results.The SPARK-47672 and SPARK-55014 tests in
FilterPushdownSuiteused$"e".rlike("magic")as their expensive stand-in and only passed because of bug 1. They now use a helper,expensiveRLike(tag), which is an RLIKE with a non-constant pattern, so they keep testing the rule.Why are the changes needed?
With the default config, a filter on an alias of a LIKE/RLIKE expression is not pushed below the Project, which loses partition pruning and data filter pushdown. For example, over a Parquet table partitioned by
part:The scan gets
PartitionFilters: [], whereas withspark.sql.optimizer.avoidDoubleFilterEval=falseit prunes partitions. The same happens forpart LIKE '1_' OR part = '1'and for data filters such asname RLIKE '^1'.LIKE 'x%'is not affected, becauseLikeSimplificationrewrites it toStartsWithfirst.Does this PR introduce _any_ user-facing change?
Yes, compared with 4.2.0: filters on aliased LIKE/RLIKE expressions with a cheap constant pattern are pushed down again, as they were before 4.2.0, so partition pruning and data filter pushdown work for them. Query results do not change. Streaming queries resumed from an existing checkpoint keep their filter placement.
How was this patch tested?
New tests:
RegexpExpressionsSuite: the heuristic for constant (including anchored, possessive, nested and bounded quantifiers), foldable, null, failing and non-foldable patterns, and for an expensive subject.RegexpExpressionsSuitealso covers repeated groups with ranges or alternations, COMMENTS mode, sequences of small ranges and?, trailing quantifiers, top-level alternatives, a leading]in a class, groups that hold a|, quantified anchors, backreferences, long repetitions and an empty\Q\E.FilterPushdownSuite: a filter on a cheap LIKE/RLIKE/ILIKE alias is pushed; one on a backtracking LIKE/RLIKE alias is not, and neither is a cheap one, nor one underNOT, with version0of the estimate, which also splits the projection between two LIKE/RLIKE aliases.OffsetSeqLogSuite: the config is recorded as1for new checkpoints and read as0from old ones.StreamingQueryManagerSuite: a query restarted from a checkpoint without the config keeps the filter on aNOT (value RLIKE '^1')alias above the projection, where it was pushed below before the restart.FileSourceStrategySuite: partition filters and data filters on aliased LIKE/RLIKE reach the Parquet scan and prune the expected partitions.Existing tests:
catalyst/testOnly org.apache.spark.sql.catalyst.optimizer. RegexpExpressionsSuite, andsql/testOnly OffsetSeqLogSuite StreamingQueryManagerSuite FileSourceStrategySuite DataFrameSuite PruneFileSourcePartitionsSuite StringFunctionsSuite.Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Code (Claude Opus 5.5)
This pull request and its description were written by Isaac.