← Back to Pull requests

[SPARK-60632][SQL] Fix the LIKE/RLIKE expensive heuristic to look at the pattern #59879

Closed
viirya closed this pull request without merging on Oct 31, 2026 18:11 UTC
View on GitHub
viirya viirya commented on Oct 28, 2026 17:26 UTC
Author

What changes were proposed in this pull request?

SPARK-47672 added an expensive heuristic to StringRegexExpression (LIKE/RLIKE), used by PushPredicateThroughNonJoin to avoid evaluating an expensive alias twice when spark.sql.optimizer.avoidDoubleFilterEval is true (the default). The heuristic had these bugs:

1. It matched on left, the subject string, instead of right, the pattern. For the usual col LIKE/RLIKE 'literal' it fell into case _ => 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 ^ / \b anchor checks were also applied to LIKE patterns.
4. The detection Pattern was a per-instance val, compiled for every Like/RLike.

This PR makes the heuristic look at the pattern:

  • A pattern that is not foldable is expensive, since it is compiled for every row. So is a foldable pattern that fails to evaluate, e.g. one that ConstantFolding left in a conditional branch because it throws. The pattern is evaluated on a fresh copy, as ConstantFolding does.

  • A foldable pattern that evaluates to null is cheap.

  • A constant pattern is classed by its repeating quantifiers that can backtrack (, +, ? 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+)+b or (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\E between a group and its quantifier is skipped, since Pattern removes 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.
  • isExpensivePattern defaults to true, and Like and RLike override it.

  • A new internal config, spark.sql.optimizer.regexPatternCostEstimateVersion (default 1), selects the estimate. With 0, every LIKE and RLIKE is expensive, as in 4.2.0 for a subject that is not a literal. PushPredicateThroughNonJoin checks it rather than expensive, since a parent expression caches hasExpensiveChild. It is recorded in the streaming offset log, and a checkpoint without it uses 0. 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 FilterPushdownSuite used $"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:

    SELECT * FROM (SELECT name, part RLIKE '^1' AS p FROM t) WHERE p
    

    The scan gets PartitionFilters: [], whereas with spark.sql.optimizer.avoidDoubleFilterEval=false it prunes partitions. The same happens for part LIKE '1_' OR part = '1' and for data filters such as name RLIKE '^1'. LIKE 'x%' is not affected, because LikeSimplification rewrites it to StartsWith first.

    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.

  • RegexpExpressionsSuite also 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 under NOT, with version 0 of the estimate, which also splits the projection between two LIKE/RLIKE aliases.

  • OffsetSeqLogSuite: the config is recorded as 1 for new checkpoints and read as 0 from old ones.

  • StreamingQueryManagerSuite: a query restarted from a checkpoint without the config keeps the filter on a NOT (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, and sql/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.

    Diff: 646 lines (+554 / -92) across 9 files Reviewer: dongjoon-hyun Review duration: 4364m
    All Vouch review confidence checks passed
    Residual risk 0.07 = Change Risk (0.53) × (1 − Review Confidence (0.87)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.53 · 646 lines diff across 9 files
    0.53
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.80 · 5 substantive comment(s)
    0.80
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    87%
    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.387
    Real PR Conversation Timeline
    39 items
    dongjoon-hyun dongjoon-hyun commented on code on Oct 28, 2026 19:20 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/regexpExpressions.scala:1
    @@ -84,33 +84,32 @@ abstract class StringRegexExpression extends BinaryExpression
         }
       }
     
    -  override def expensive: Boolean = hasExpensiveChild || _expensiveRegex
    -
    -  // Heuristic, not designed to be perfect. Look for things likely to have
    -  // back tracking.
    -  private val detectExpensiveRegexPattern = Pattern.compile("\\+\\*\\{")
    -
    -  private lazy val _expensiveRegex = {
    -    // A quick heuristic for expensive a pattern is.
    -    left match {
    -      case StringLiteral(str) =>
    -        // If we have a clear start limited back tracking required.
    -        if (str.startsWith("^") || str.startsWith("\\b")) {
    -          false
    -        } else if (detectExpensiveRegexPattern.matcher(str).matches()) {
    -          // Greedy matching can be tricky.
    -          true
    -        } else {
    -          // Default to pushdown for now.
    -          false
    -        }
    -      case _ =>
    -        true // per row regex compilation.
    -    }
    +  override def expensive: Boolean = hasExpensiveChild || _expensivePattern
    +
    +  // Heuristic, not designed to be perfect. A pattern that is not foldable is compiled for every
    +  // row; a foldable one is left to `isExpensivePattern`.
    +  private lazy val _expensivePattern = if (right.foldable) {
    +    val str = right.eval()

    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.

  • With 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
      }
    }
    

    dongjoon-hyun dongjoon-hyun commented on code on Oct 28, 2026 19:20 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/regexpExpressions.scala:1
    @@ -182,6 +181,9 @@ case class Like(left: Expression, right: Expression, escapeChar: Char)
     
       override def matches(regex: Pattern, str: String): Boolean = regex.matcher(str).matches()
     
    +  // A LIKE pattern only has the `%` and `_` wildcards, which do not nest.
    +  override protected def isExpensivePattern(str: String): Boolean = false

    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?

    dongjoon-hyun dongjoon-hyun commented on code on Oct 28, 2026 19:20 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/regexpExpressions.scala:1
    @@ -84,33 +84,32 @@ abstract class StringRegexExpression extends BinaryExpression
         }
       }
     
    -  override def expensive: Boolean = hasExpensiveChild || _expensiveRegex
    -
    -  // Heuristic, not designed to be perfect. Look for things likely to have
    -  // back tracking.
    -  private val detectExpensiveRegexPattern = Pattern.compile("\\+\\*\\{")
    -
    -  private lazy val _expensiveRegex = {
    -    // A quick heuristic for expensive a pattern is.
    -    left match {
    -      case StringLiteral(str) =>
    -        // If we have a clear start limited back tracking required.
    -        if (str.startsWith("^") || str.startsWith("\\b")) {
    -          false
    -        } else if (detectExpensiveRegexPattern.matcher(str).matches()) {
    -          // Greedy matching can be tricky.
    -          true
    -        } else {
    -          // Default to pushdown for now.
    -          false
    -        }
    -      case _ =>
    -        true // per row regex compilation.
    -    }
    +  override def expensive: Boolean = hasExpensiveChild || _expensivePattern
    +
    +  // Heuristic, not designed to be perfect. A pattern that is not foldable is compiled for every
    +  // row; a foldable one is left to `isExpensivePattern`.
    +  private lazy val _expensivePattern = if (right.foldable) {
    +    val str = right.eval()
    +    str != null && isExpensivePattern(str.toString)
    +  } else {
    +    true
       }
    +
    +  /** Whether matching against the constant pattern `str` is likely to be expensive. */
    +  protected def isExpensivePattern(str: String): Boolean
     }
     
     private[catalyst] object StringRegexExpression {
    +  // Quantifiers, which are what make a regex backtrack.
    +  private val quantifierPattern = Pattern.compile("[+*{]")
    +
    +  /**
    +   * Heuristic for whether a regex is likely to backtrack: one with a clear start limits the
    +   * backtracking, otherwise any quantifier may need it.
    +   */
    +  def isExpensiveRegex(regex: String): Boolean =
    +    !regex.startsWith("^") && !regex.startsWith("\\b") && quantifierPattern.matcher(regex).find()

    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?

    dongjoon-hyun dongjoon-hyun commented on code on Oct 28, 2026 19:20 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/regexpExpressions.scala:1
    @@ -84,33 +84,32 @@ abstract class StringRegexExpression extends BinaryExpression
         }
       }
     
    -  override def expensive: Boolean = hasExpensiveChild || _expensiveRegex
    -
    -  // Heuristic, not designed to be perfect. Look for things likely to have
    -  // back tracking.
    -  private val detectExpensiveRegexPattern = Pattern.compile("\\+\\*\\{")
    -
    -  private lazy val _expensiveRegex = {
    -    // A quick heuristic for expensive a pattern is.
    -    left match {
    -      case StringLiteral(str) =>
    -        // If we have a clear start limited back tracking required.
    -        if (str.startsWith("^") || str.startsWith("\\b")) {
    -          false
    -        } else if (detectExpensiveRegexPattern.matcher(str).matches()) {
    -          // Greedy matching can be tricky.
    -          true
    -        } else {
    -          // Default to pushdown for now.
    -          false
    -        }
    -      case _ =>
    -        true // per row regex compilation.
    -    }
    +  override def expensive: Boolean = hasExpensiveChild || _expensivePattern
    +
    +  // Heuristic, not designed to be perfect. A pattern that is not foldable is compiled for every
    +  // row; a foldable one is left to `isExpensivePattern`.
    +  private lazy val _expensivePattern = if (right.foldable) {
    +    val str = right.eval()
    +    str != null && isExpensivePattern(str.toString)
    +  } else {
    +    true
       }
    +
    +  /** Whether matching against the constant pattern `str` is likely to be expensive. */
    +  protected def isExpensivePattern(str: String): Boolean
     }
     
     private[catalyst] object StringRegexExpression {
    +  // Quantifiers, which are what make a regex backtrack.
    +  private val quantifierPattern = Pattern.compile("[+*{]")

    *4. [Low] The [+{] check also matches characters that are not quantifiers*

    find() on [+{] also matches:

  • escaped literals, e.g. a\+b

  • characters inside a class, e.g. [+]

  • the braces of \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 ^?

    dongjoon-hyun dongjoon-hyun commented on code on Oct 28, 2026 19:20 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/regexpExpressions.scala:1
    @@ -84,33 +84,32 @@ abstract class StringRegexExpression extends BinaryExpression
         }
       }
     
    -  override def expensive: Boolean = hasExpensiveChild || _expensiveRegex
    -
    -  // Heuristic, not designed to be perfect. Look for things likely to have
    -  // back tracking.
    -  private val detectExpensiveRegexPattern = Pattern.compile("\\+\\*\\{")
    -
    -  private lazy val _expensiveRegex = {
    -    // A quick heuristic for expensive a pattern is.
    -    left match {
    -      case StringLiteral(str) =>
    -        // If we have a clear start limited back tracking required.
    -        if (str.startsWith("^") || str.startsWith("\\b")) {
    -          false
    -        } else if (detectExpensiveRegexPattern.matcher(str).matches()) {
    -          // Greedy matching can be tricky.
    -          true
    -        } else {
    -          // Default to pushdown for now.
    -          false
    -        }
    -      case _ =>
    -        true // per row regex compilation.
    -    }
    +  override def expensive: Boolean = hasExpensiveChild || _expensivePattern
    +
    +  // Heuristic, not designed to be perfect. A pattern that is not foldable is compiled for every
    +  // row; a foldable one is left to `isExpensivePattern`.
    +  private lazy val _expensivePattern = if (right.foldable) {
    +    val str = right.eval()
    +    str != null && isExpensivePattern(str.toString)
    +  } else {
    +    true
       }
    +
    +  /** Whether matching against the constant pattern `str` is likely to be expensive. */
    +  protected def isExpensivePattern(str: String): Boolean

    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?

    dongjoon-hyun dongjoon-hyun commented on code on Oct 28, 2026 19:20 UTC
    Code Review
    sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/FileSourceStrategySuite.scala:1
    @@ -606,6 +606,30 @@ class FileSourceStrategySuite extends SharedSparkSession {
         checkDataFilters(Set.empty)
       }
     
    +  test("SPARK-60632: Filters on an aliased LIKE/RLIKE column are pushed into the file scan") {
    +    withTempPath { path =>
    +      spark.range(20)
    +        .selectExpr("CAST(id AS STRING) AS name", "CAST(id % 4 AS STRING) AS part")
    +        .write.partitionBy("part").parquet(path.getCanonicalPath)
    +      val table = spark.read.parquet(path.getCanonicalPath)
    +
    +      def scanOf(df: DataFrame): FileSourceScanExec =
    +        df.queryExecution.sparkPlan.collectFirst { case s: FileSourceScanExec => s }.get
    +
    +      Seq("part RLIKE '^1'", "part LIKE '1_' OR part = '1'").foreach { pred =>
    +        withClue(pred) {
    +          val df = table.selectExpr("name", s"$pred AS p").where("p")
    +          assert(scanOf(df).partitionFilters.nonEmpty)

    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?

  • Use non-numeric partition values, or turn off spark.sql.sources.partitionColumnTypeInference.enabled.

  • Make the LIKE match a partition.

  • Assert on the pushed predicate or on the number of selected partitions.
  • dongjoon-hyun dongjoon-hyun commented on code on Oct 28, 2026 19:20 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/regexpExpressions.scala:1
    @@ -84,33 +84,32 @@ abstract class StringRegexExpression extends BinaryExpression
         }
       }
     
    -  override def expensive: Boolean = hasExpensiveChild || _expensiveRegex
    -
    -  // Heuristic, not designed to be perfect. Look for things likely to have
    -  // back tracking.
    -  private val detectExpensiveRegexPattern = Pattern.compile("\\+\\*\\{")
    -
    -  private lazy val _expensiveRegex = {
    -    // A quick heuristic for expensive a pattern is.
    -    left match {
    -      case StringLiteral(str) =>
    -        // If we have a clear start limited back tracking required.
    -        if (str.startsWith("^") || str.startsWith("\\b")) {
    -          false
    -        } else if (detectExpensiveRegexPattern.matcher(str).matches()) {
    -          // Greedy matching can be tricky.
    -          true
    -        } else {
    -          // Default to pushdown for now.
    -          false
    -        }
    -      case _ =>
    -        true // per row regex compilation.
    -    }
    +  override def expensive: Boolean = hasExpensiveChild || _expensivePattern

    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.

  • The non-cheap producer is therefore kept (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?

    dongjoon-hyun dongjoon-hyun commented on code on Oct 28, 2026 19:20 UTC
    Code Review
    sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/RegexpExpressionsSuite.scala:1
    @@ -735,4 +735,28 @@ class RegexpExpressionsSuite extends SparkFunSuite with ExpressionEvalHelper {
         assert(extractAllCopy ne extractAll,
           "freshCopyIfContainsStatefulExpression should return a new instance for RegExpExtractAll")
       }
    +
    +  test("SPARK-60632: LIKE and RLIKE expensive heuristic looks at the pattern") {

    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:

  • an anchored pattern with a quantifier being pushed, e.g. ^a.*b

  • an ILIKE alias, which reaches this code as Like(Lower(left), Lower(right))
  • dongjoon-hyun dongjoon-hyun commented on code on Oct 28, 2026 19:20 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/regexpExpressions.scala:1
    @@ -84,33 +84,32 @@ abstract class StringRegexExpression extends BinaryExpression
         }
       }
     
    -  override def expensive: Boolean = hasExpensiveChild || _expensiveRegex
    -
    -  // Heuristic, not designed to be perfect. Look for things likely to have
    -  // back tracking.
    -  private val detectExpensiveRegexPattern = Pattern.compile("\\+\\*\\{")
    -
    -  private lazy val _expensiveRegex = {
    -    // A quick heuristic for expensive a pattern is.
    -    left match {
    -      case StringLiteral(str) =>
    -        // If we have a clear start limited back tracking required.
    -        if (str.startsWith("^") || str.startsWith("\\b")) {
    -          false
    -        } else if (detectExpensiveRegexPattern.matcher(str).matches()) {
    -          // Greedy matching can be tricky.
    -          true
    -        } else {
    -          // Default to pushdown for now.
    -          false
    -        }
    -      case _ =>
    -        true // per row regex compilation.
    -    }
    +  override def expensive: Boolean = hasExpensiveChild || _expensivePattern
    +
    +  // Heuristic, not designed to be perfect. A pattern that is not foldable is compiled for every
    +  // row; a foldable one is left to `isExpensivePattern`.
    +  private lazy val _expensivePattern = if (right.foldable) {
    +    val str = right.eval()
    +    str != null && isExpensivePattern(str.toString)
    +  } else {
    +    true
       }
    +
    +  /** Whether matching against the constant pattern `str` is likely to be expensive. */
    +  protected def isExpensivePattern(str: String): Boolean
     }
     
     private[catalyst] object StringRegexExpression {
    +  // Quantifiers, which are what make a regex backtrack.
    +  private val quantifierPattern = Pattern.compile("[+*{]")
    +
    +  /**
    +   * Heuristic for whether a regex is likely to backtrack: one with a clear start limits the
    +   * backtracking, otherwise any quantifier may need it.
    +   */
    +  def isExpensiveRegex(regex: String): Boolean =

    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.

    dongjoon-hyun dongjoon-hyun commented on code on Oct 28, 2026 19:20 UTC
    Code Review
    sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/FilterPushdownSuite.scala:1
    @@ -61,6 +61,10 @@ class FilterPushdownSuite extends PlanTest {
     
       val testStringRelation = LocalRelation(attrA, attrB, attrE)
     
    +  // Stands in for an expensive expression: a regex whose pattern is not a constant is compiled
    +  // for every row.
    +  private def expensiveRLike(tag: String): Expression = $"e".rlike(Concat(Seq($"e", Literal(tag))))

    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?

    dongjoon-hyun dongjoon-hyun commented on Oct 28, 2026 19:20 UTC
    Reviewer

    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:

  • Evaluating the pattern in the optimizer can now make planning fail.

  • Treating every constant LIKE as cheap brings back double evaluation for the multi-% 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.

    viirya viirya commented on code on Oct 28, 2026 19:54 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/regexpExpressions.scala:1
    @@ -84,33 +84,32 @@ abstract class StringRegexExpression extends BinaryExpression
         }
       }
     
    -  override def expensive: Boolean = hasExpensiveChild || _expensiveRegex
    -
    -  // Heuristic, not designed to be perfect. Look for things likely to have
    -  // back tracking.
    -  private val detectExpensiveRegexPattern = Pattern.compile("\\+\\*\\{")
    -
    -  private lazy val _expensiveRegex = {
    -    // A quick heuristic for expensive a pattern is.
    -    left match {
    -      case StringLiteral(str) =>
    -        // If we have a clear start limited back tracking required.
    -        if (str.startsWith("^") || str.startsWith("\\b")) {
    -          false
    -        } else if (detectExpensiveRegexPattern.matcher(str).matches()) {
    -          // Greedy matching can be tricky.
    -          true
    -        } else {
    -          // Default to pushdown for now.
    -          false
    -        }
    -      case _ =>
    -        true // per row regex compilation.
    -    }
    +  override def expensive: Boolean = hasExpensiveChild || _expensivePattern
    +
    +  // Heuristic, not designed to be perfect. A pattern that is not foldable is compiled for every
    +  // row; a foldable one is left to `isExpensivePattern`.
    +  private lazy val _expensivePattern = if (right.foldable) {
    +    val str = right.eval()

    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.

    viirya viirya commented on code on Oct 28, 2026 19:54 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/regexpExpressions.scala:1
    @@ -182,6 +181,9 @@ case class Like(left: Expression, right: Expression, escapeChar: Char)
     
       override def matches(regex: Pattern, str: String): Boolean = regex.matcher(str).matches()
     
    +  // A LIKE pattern only has the `%` and `_` wildcards, which do not nest.
    +  override protected def isExpensivePattern(str: String): Boolean = false

    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.

    viirya viirya commented on code on Oct 28, 2026 19:54 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/regexpExpressions.scala:1
    @@ -84,33 +84,32 @@ abstract class StringRegexExpression extends BinaryExpression
         }
       }
     
    -  override def expensive: Boolean = hasExpensiveChild || _expensiveRegex
    -
    -  // Heuristic, not designed to be perfect. Look for things likely to have
    -  // back tracking.
    -  private val detectExpensiveRegexPattern = Pattern.compile("\\+\\*\\{")
    -
    -  private lazy val _expensiveRegex = {
    -    // A quick heuristic for expensive a pattern is.
    -    left match {
    -      case StringLiteral(str) =>
    -        // If we have a clear start limited back tracking required.
    -        if (str.startsWith("^") || str.startsWith("\\b")) {
    -          false
    -        } else if (detectExpensiveRegexPattern.matcher(str).matches()) {
    -          // Greedy matching can be tricky.
    -          true
    -        } else {
    -          // Default to pushdown for now.
    -          false
    -        }
    -      case _ =>
    -        true // per row regex compilation.
    -    }
    +  override def expensive: Boolean = hasExpensiveChild || _expensivePattern
    +
    +  // Heuristic, not designed to be perfect. A pattern that is not foldable is compiled for every
    +  // row; a foldable one is left to `isExpensivePattern`.
    +  private lazy val _expensivePattern = if (right.foldable) {
    +    val str = right.eval()
    +    str != null && isExpensivePattern(str.toString)
    +  } else {
    +    true
       }
    +
    +  /** Whether matching against the constant pattern `str` is likely to be expensive. */
    +  protected def isExpensivePattern(str: String): Boolean
     }
     
     private[catalyst] object StringRegexExpression {
    +  // Quantifiers, which are what make a regex backtrack.
    +  private val quantifierPattern = Pattern.compile("[+*{]")
    +
    +  /**
    +   * Heuristic for whether a regex is likely to backtrack: one with a clear start limits the
    +   * backtracking, otherwise any quantifier may need it.
    +   */
    +  def isExpensiveRegex(regex: String): Boolean =
    +    !regex.startsWith("^") && !regex.startsWith("\\b") && quantifierPattern.matcher(regex).find()

    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.

    viirya viirya commented on code on Oct 28, 2026 19:54 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/regexpExpressions.scala:1
    @@ -84,33 +84,32 @@ abstract class StringRegexExpression extends BinaryExpression
         }
       }
     
    -  override def expensive: Boolean = hasExpensiveChild || _expensiveRegex
    -
    -  // Heuristic, not designed to be perfect. Look for things likely to have
    -  // back tracking.
    -  private val detectExpensiveRegexPattern = Pattern.compile("\\+\\*\\{")
    -
    -  private lazy val _expensiveRegex = {
    -    // A quick heuristic for expensive a pattern is.
    -    left match {
    -      case StringLiteral(str) =>
    -        // If we have a clear start limited back tracking required.
    -        if (str.startsWith("^") || str.startsWith("\\b")) {
    -          false
    -        } else if (detectExpensiveRegexPattern.matcher(str).matches()) {
    -          // Greedy matching can be tricky.
    -          true
    -        } else {
    -          // Default to pushdown for now.
    -          false
    -        }
    -      case _ =>
    -        true // per row regex compilation.
    -    }
    +  override def expensive: Boolean = hasExpensiveChild || _expensivePattern
    +
    +  // Heuristic, not designed to be perfect. A pattern that is not foldable is compiled for every
    +  // row; a foldable one is left to `isExpensivePattern`.
    +  private lazy val _expensivePattern = if (right.foldable) {
    +    val str = right.eval()
    +    str != null && isExpensivePattern(str.toString)
    +  } else {
    +    true
       }
    +
    +  /** Whether matching against the constant pattern `str` is likely to be expensive. */
    +  protected def isExpensivePattern(str: String): Boolean
     }
     
     private[catalyst] object StringRegexExpression {
    +  // Quantifiers, which are what make a regex backtrack.
    +  private val quantifierPattern = Pattern.compile("[+*{]")

    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..

    viirya viirya commented on code on Oct 28, 2026 19:54 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/regexpExpressions.scala:1
    @@ -84,33 +84,32 @@ abstract class StringRegexExpression extends BinaryExpression
         }
       }
     
    -  override def expensive: Boolean = hasExpensiveChild || _expensiveRegex
    -
    -  // Heuristic, not designed to be perfect. Look for things likely to have
    -  // back tracking.
    -  private val detectExpensiveRegexPattern = Pattern.compile("\\+\\*\\{")
    -
    -  private lazy val _expensiveRegex = {
    -    // A quick heuristic for expensive a pattern is.
    -    left match {
    -      case StringLiteral(str) =>
    -        // If we have a clear start limited back tracking required.
    -        if (str.startsWith("^") || str.startsWith("\\b")) {
    -          false
    -        } else if (detectExpensiveRegexPattern.matcher(str).matches()) {
    -          // Greedy matching can be tricky.
    -          true
    -        } else {
    -          // Default to pushdown for now.
    -          false
    -        }
    -      case _ =>
    -        true // per row regex compilation.
    -    }
    +  override def expensive: Boolean = hasExpensiveChild || _expensivePattern
    +
    +  // Heuristic, not designed to be perfect. A pattern that is not foldable is compiled for every
    +  // row; a foldable one is left to `isExpensivePattern`.
    +  private lazy val _expensivePattern = if (right.foldable) {
    +    val str = right.eval()
    +    str != null && isExpensivePattern(str.toString)
    +  } else {
    +    true
       }
    +
    +  /** Whether matching against the constant pattern `str` is likely to be expensive. */
    +  protected def isExpensivePattern(str: String): Boolean

    Done: isExpensivePattern now defaults to true, which is what 4.2.0 answers for a column LIKE/RLIKE, and Like and RLike override it.

    viirya viirya commented on code on Oct 28, 2026 19:54 UTC
    Code Review
    sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/FileSourceStrategySuite.scala:1
    @@ -606,6 +606,30 @@ class FileSourceStrategySuite extends SharedSparkSession {
         checkDataFilters(Set.empty)
       }
     
    +  test("SPARK-60632: Filters on an aliased LIKE/RLIKE column are pushed into the file scan") {
    +    withTempPath { path =>
    +      spark.range(20)
    +        .selectExpr("CAST(id AS STRING) AS name", "CAST(id % 4 AS STRING) AS part")
    +        .write.partitionBy("part").parquet(path.getCanonicalPath)
    +      val table = spark.read.parquet(path.getCanonicalPath)
    +
    +      def scanOf(df: DataFrame): FileSourceScanExec =
    +        df.queryExecution.sparkPlan.collectFirst { case s: FileSourceScanExec => s }.get
    +
    +      Seq("part RLIKE '^1'", "part LIKE '1_' OR part = '1'").foreach { pred =>
    +        withClue(pred) {
    +          val df = table.selectExpr("name", s"$pred AS p").where("p")
    +          assert(scanOf(df).partitionFilters.nonEmpty)

    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.

    viirya viirya commented on code on Oct 28, 2026 19:54 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/regexpExpressions.scala:1
    @@ -84,33 +84,32 @@ abstract class StringRegexExpression extends BinaryExpression
         }
       }
     
    -  override def expensive: Boolean = hasExpensiveChild || _expensiveRegex
    -
    -  // Heuristic, not designed to be perfect. Look for things likely to have
    -  // back tracking.
    -  private val detectExpensiveRegexPattern = Pattern.compile("\\+\\*\\{")
    -
    -  private lazy val _expensiveRegex = {
    -    // A quick heuristic for expensive a pattern is.
    -    left match {
    -      case StringLiteral(str) =>
    -        // If we have a clear start limited back tracking required.
    -        if (str.startsWith("^") || str.startsWith("\\b")) {
    -          false
    -        } else if (detectExpensiveRegexPattern.matcher(str).matches()) {
    -          // Greedy matching can be tricky.
    -          true
    -        } else {
    -          // Default to pushdown for now.
    -          false
    -        }
    -      case _ =>
    -        true // per row regex compilation.
    -    }
    +  override def expensive: Boolean = hasExpensiveChild || _expensivePattern

    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.

    viirya viirya commented on code on Oct 28, 2026 19:54 UTC
    Code Review
    sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/RegexpExpressionsSuite.scala:1
    @@ -735,4 +735,28 @@ class RegexpExpressionsSuite extends SparkFunSuite with ExpressionEvalHelper {
         assert(extractAllCopy ne extractAll,
           "freshCopyIfContainsStatefulExpression should return a new instance for RegExpExtractAll")
       }
    +
    +  test("SPARK-60632: LIKE and RLIKE expensive heuristic looks at the pattern") {

    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.

    viirya viirya commented on code on Oct 28, 2026 19:54 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/regexpExpressions.scala:1
    @@ -84,33 +84,32 @@ abstract class StringRegexExpression extends BinaryExpression
         }
       }
     
    -  override def expensive: Boolean = hasExpensiveChild || _expensiveRegex
    -
    -  // Heuristic, not designed to be perfect. Look for things likely to have
    -  // back tracking.
    -  private val detectExpensiveRegexPattern = Pattern.compile("\\+\\*\\{")
    -
    -  private lazy val _expensiveRegex = {
    -    // A quick heuristic for expensive a pattern is.
    -    left match {
    -      case StringLiteral(str) =>
    -        // If we have a clear start limited back tracking required.
    -        if (str.startsWith("^") || str.startsWith("\\b")) {
    -          false
    -        } else if (detectExpensiveRegexPattern.matcher(str).matches()) {
    -          // Greedy matching can be tricky.
    -          true
    -        } else {
    -          // Default to pushdown for now.
    -          false
    -        }
    -      case _ =>
    -        true // per row regex compilation.
    -    }
    +  override def expensive: Boolean = hasExpensiveChild || _expensivePattern
    +
    +  // Heuristic, not designed to be perfect. A pattern that is not foldable is compiled for every
    +  // row; a foldable one is left to `isExpensivePattern`.
    +  private lazy val _expensivePattern = if (right.foldable) {
    +    val str = right.eval()
    +    str != null && isExpensivePattern(str.toString)
    +  } else {
    +    true
       }
    +
    +  /** Whether matching against the constant pattern `str` is likely to be expensive. */
    +  protected def isExpensivePattern(str: String): Boolean
     }
     
     private[catalyst] object StringRegexExpression {
    +  // Quantifiers, which are what make a regex backtrack.
    +  private val quantifierPattern = Pattern.compile("[+*{]")
    +
    +  /**
    +   * Heuristic for whether a regex is likely to backtrack: one with a clear start limits the
    +   * backtracking, otherwise any quantifier may need it.
    +   */
    +  def isExpensiveRegex(regex: String): Boolean =

    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.

    viirya viirya commented on code on Oct 28, 2026 19:54 UTC
    Code Review
    sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/FilterPushdownSuite.scala:1
    @@ -61,6 +61,10 @@ class FilterPushdownSuite extends PlanTest {
     
       val testStringRelation = LocalRelation(attrA, attrB, attrE)
     
    +  // Stands in for an expensive expression: a regex whose pattern is not a constant is compiled
    +  // for every row.
    +  private def expensiveRLike(tag: String): Expression = $"e".rlike(Concat(Seq($"e", Literal(tag))))

    Moved after the relation and predicate definitions.

    dongjoon-hyun dongjoon-hyun commented on code on Oct 28, 2026 20:25 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/regexpExpressions.scala:1
    @@ -84,33 +84,92 @@ abstract class StringRegexExpression extends BinaryExpression
         }
       }
     
    -  override def expensive: Boolean = hasExpensiveChild || _expensiveRegex
    -
    -  // Heuristic, not designed to be perfect. Look for things likely to have
    -  // back tracking.
    -  private val detectExpensiveRegexPattern = Pattern.compile("\\+\\*\\{")
    -
    -  private lazy val _expensiveRegex = {
    -    // A quick heuristic for expensive a pattern is.
    -    left match {
    -      case StringLiteral(str) =>
    -        // If we have a clear start limited back tracking required.
    -        if (str.startsWith("^") || str.startsWith("\\b")) {
    -          false
    -        } else if (detectExpensiveRegexPattern.matcher(str).matches()) {
    -          // Greedy matching can be tricky.
    -          true
    -        } else {
    -          // Default to pushdown for now.
    -          false
    -        }
    -      case _ =>
    -        true // per row regex compilation.
    +  override def expensive: Boolean = hasExpensiveChild || _expensivePattern
    +
    +  // Heuristic, not designed to be perfect. A pattern that is not foldable is compiled for every
    +  // row; a foldable one is left to `isExpensivePattern`. Like `ConstantFolding`, evaluate a fresh
    +  // copy so that a stateful pattern keeps its state.
    +  private lazy val _expensivePattern = !right.foldable || {
    +    try {
    +      val str = right.freshCopyIfContainsStatefulExpression().eval()
    +      str != null && isExpensivePattern(str.toString)
    +    } catch {
    +      // E.g. a pattern that `ConstantFolding` left in a conditional branch because it throws.
    +      case NonFatal(_) => true
         }
       }
    +
    +  /** Whether matching against the constant pattern `str` is likely to be expensive. */
    +  protected def isExpensivePattern(str: String): Boolean = true
     }
     
     private[catalyst] object StringRegexExpression {
    +  /**
    +   * Counts the `%` wildcards in a LIKE pattern, skipping escaped characters. Each one becomes a
    +   * `.*`, and a failed match tries every combination of their lengths.
    +   */
    +  def countLikeWildcards(pattern: String, escapeChar: Char): Int = {
    +    var count = 0
    +    var i = 0
    +    while (i < pattern.length) {
    +      val c = pattern.charAt(i)
    +      if (c == escapeChar) {
    +        i += 1
    +      } else if (c == '%') {
    +        count += 1
    +      }
    +      i += 1
    +    }
    +    count
    +  }
    +
    +  /**
    +   * Counts the repeating quantifiers (`*`, `+` and `{n,m}`) in a regex, which are what make a
    +   * failed match backtrack. Escaped characters, quoted text, character classes and the braces of
    +   * `\p{..}`, `\x{..}` and `\N{..}` are skipped, and the `+` or `?` that makes a quantifier
    +   * possessive or lazy is not counted again.
    +   */
    +  def countRegexQuantifiers(regex: String): Int = {
    +    var count = 0
    +    var classDepth = 0
    +    var i = 0
    +    // Moves `i` past a `+` or `?` that modifies the quantifier ending at `i`.
    +    def skipModifier(): Unit = {
    +      if (i + 1 < regex.length && (regex.charAt(i + 1) == '+' || regex.charAt(i + 1) == '?')) {
    +        i += 1
    +      }
    +    }
    +    while (i < regex.length) {
    +      regex.charAt(i) match {
    +        case '\\' if i + 1 < regex.length =>
    +          i += 1
    +          if (regex.charAt(i) == 'Q') {
    +            val end = regex.indexOf("\\E", i)
    +            i = if (end < 0) regex.length else end + 1
    +          } else if ("pPxN".indexOf(regex.charAt(i)) >= 0 &&
    +              i + 1 < regex.length && regex.charAt(i + 1) == '{') {
    +            val end = regex.indexOf('}', i)
    +            i = if (end < 0) regex.length else end
    +          }
    +        case '[' => classDepth += 1
    +        case ']' if classDepth > 0 => classDepth -= 1
    +        case '*' | '+' if classDepth == 0 =>
    +          count += 1
    +          skipModifier()
    +        case '{' if classDepth == 0 =>

    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.

    dongjoon-hyun dongjoon-hyun commented on code on Oct 28, 2026 20:25 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/regexpExpressions.scala:1
    @@ -84,33 +84,92 @@ abstract class StringRegexExpression extends BinaryExpression
         }
       }
     
    -  override def expensive: Boolean = hasExpensiveChild || _expensiveRegex
    -
    -  // Heuristic, not designed to be perfect. Look for things likely to have
    -  // back tracking.
    -  private val detectExpensiveRegexPattern = Pattern.compile("\\+\\*\\{")
    -
    -  private lazy val _expensiveRegex = {
    -    // A quick heuristic for expensive a pattern is.
    -    left match {
    -      case StringLiteral(str) =>
    -        // If we have a clear start limited back tracking required.
    -        if (str.startsWith("^") || str.startsWith("\\b")) {
    -          false
    -        } else if (detectExpensiveRegexPattern.matcher(str).matches()) {
    -          // Greedy matching can be tricky.
    -          true
    -        } else {
    -          // Default to pushdown for now.
    -          false
    -        }
    -      case _ =>
    -        true // per row regex compilation.
    +  override def expensive: Boolean = hasExpensiveChild || _expensivePattern
    +
    +  // Heuristic, not designed to be perfect. A pattern that is not foldable is compiled for every
    +  // row; a foldable one is left to `isExpensivePattern`. Like `ConstantFolding`, evaluate a fresh
    +  // copy so that a stateful pattern keeps its state.
    +  private lazy val _expensivePattern = !right.foldable || {
    +    try {
    +      val str = right.freshCopyIfContainsStatefulExpression().eval()
    +      str != null && isExpensivePattern(str.toString)
    +    } catch {
    +      // E.g. a pattern that `ConstantFolding` left in a conditional branch because it throws.
    +      case NonFatal(_) => true
         }
       }
    +
    +  /** Whether matching against the constant pattern `str` is likely to be expensive. */
    +  protected def isExpensivePattern(str: String): Boolean = true
     }
     
     private[catalyst] object StringRegexExpression {
    +  /**
    +   * Counts the `%` wildcards in a LIKE pattern, skipping escaped characters. Each one becomes a
    +   * `.*`, and a failed match tries every combination of their lengths.
    +   */
    +  def countLikeWildcards(pattern: String, escapeChar: Char): Int = {
    +    var count = 0
    +    var i = 0
    +    while (i < pattern.length) {
    +      val c = pattern.charAt(i)
    +      if (c == escapeChar) {
    +        i += 1
    +      } else if (c == '%') {
    +        count += 1
    +      }
    +      i += 1
    +    }
    +    count
    +  }
    +
    +  /**
    +   * Counts the repeating quantifiers (`*`, `+` and `{n,m}`) in a regex, which are what make a
    +   * failed match backtrack. Escaped characters, quoted text, character classes and the braces of
    +   * `\p{..}`, `\x{..}` and `\N{..}` are skipped, and the `+` or `?` that makes a quantifier
    +   * possessive or lazy is not counted again.
    +   */
    +  def countRegexQuantifiers(regex: String): Int = {
    +    var count = 0
    +    var classDepth = 0
    +    var i = 0
    +    // Moves `i` past a `+` or `?` that modifies the quantifier ending at `i`.
    +    def skipModifier(): Unit = {
    +      if (i + 1 < regex.length && (regex.charAt(i + 1) == '+' || regex.charAt(i + 1) == '?')) {
    +        i += 1
    +      }
    +    }
    +    while (i < regex.length) {
    +      regex.charAt(i) match {
    +        case '\\' if i + 1 < regex.length =>
    +          i += 1
    +          if (regex.charAt(i) == 'Q') {
    +            val end = regex.indexOf("\\E", i)
    +            i = if (end < 0) regex.length else end + 1
    +          } else if ("pPxN".indexOf(regex.charAt(i)) >= 0 &&
    +              i + 1 < regex.length && regex.charAt(i + 1) == '{') {
    +            val end = regex.indexOf('}', i)
    +            i = if (end < 0) regex.length else end
    +          }
    +        case '[' => classDepth += 1

    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.

  • In a (?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.

    dongjoon-hyun dongjoon-hyun commented on code on Oct 28, 2026 20:25 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/regexpExpressions.scala:1
    @@ -534,6 +598,10 @@ case class RLike(left: Expression, right: Expression) extends StringRegexExpress
     
       override def escape(v: String): String = v
       override def matches(regex: Pattern, str: String): Boolean = regex.matcher(str).find(0)
    +  // Like the `%` of LIKE, but `find` also tries every start position, which costs one more
    +  // factor of the input length. An anchor does not bound the backtracking within a match.
    +  override protected def isExpensivePattern(str: String): Boolean =
    +    StringRegexExpression.countRegexQuantifiers(str) >= 2

    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 |?

    dongjoon-hyun dongjoon-hyun commented on code on Oct 28, 2026 20:25 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/regexpExpressions.scala:1
    @@ -84,33 +84,92 @@ abstract class StringRegexExpression extends BinaryExpression
         }
       }
     
    -  override def expensive: Boolean = hasExpensiveChild || _expensiveRegex
    -
    -  // Heuristic, not designed to be perfect. Look for things likely to have
    -  // back tracking.
    -  private val detectExpensiveRegexPattern = Pattern.compile("\\+\\*\\{")
    -
    -  private lazy val _expensiveRegex = {
    -    // A quick heuristic for expensive a pattern is.
    -    left match {
    -      case StringLiteral(str) =>
    -        // If we have a clear start limited back tracking required.
    -        if (str.startsWith("^") || str.startsWith("\\b")) {
    -          false
    -        } else if (detectExpensiveRegexPattern.matcher(str).matches()) {
    -          // Greedy matching can be tricky.
    -          true
    -        } else {
    -          // Default to pushdown for now.
    -          false
    -        }
    -      case _ =>
    -        true // per row regex compilation.
    +  override def expensive: Boolean = hasExpensiveChild || _expensivePattern
    +
    +  // Heuristic, not designed to be perfect. A pattern that is not foldable is compiled for every
    +  // row; a foldable one is left to `isExpensivePattern`. Like `ConstantFolding`, evaluate a fresh
    +  // copy so that a stateful pattern keeps its state.
    +  private lazy val _expensivePattern = !right.foldable || {
    +    try {
    +      val str = right.freshCopyIfContainsStatefulExpression().eval()
    +      str != null && isExpensivePattern(str.toString)
    +    } catch {
    +      // E.g. a pattern that `ConstantFolding` left in a conditional branch because it throws.
    +      case NonFatal(_) => true
         }
       }
    +
    +  /** Whether matching against the constant pattern `str` is likely to be expensive. */
    +  protected def isExpensivePattern(str: String): Boolean = true
     }
     
     private[catalyst] object StringRegexExpression {
    +  /**
    +   * Counts the `%` wildcards in a LIKE pattern, skipping escaped characters. Each one becomes a
    +   * `.*`, and a failed match tries every combination of their lengths.
    +   */
    +  def countLikeWildcards(pattern: String, escapeChar: Char): Int = {
    +    var count = 0
    +    var i = 0
    +    while (i < pattern.length) {
    +      val c = pattern.charAt(i)
    +      if (c == escapeChar) {
    +        i += 1
    +      } else if (c == '%') {
    +        count += 1
    +      }
    +      i += 1
    +    }
    +    count
    +  }
    +
    +  /**
    +   * Counts the repeating quantifiers (`*`, `+` and `{n,m}`) in a regex, which are what make a
    +   * failed match backtrack. Escaped characters, quoted text, character classes and the braces of
    +   * `\p{..}`, `\x{..}` and `\N{..}` are skipped, and the `+` or `?` that makes a quantifier
    +   * possessive or lazy is not counted again.
    +   */
    +  def countRegexQuantifiers(regex: String): Int = {
    +    var count = 0
    +    var classDepth = 0
    +    var i = 0
    +    // Moves `i` past a `+` or `?` that modifies the quantifier ending at `i`.
    +    def skipModifier(): Unit = {

    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?

    dongjoon-hyun dongjoon-hyun commented on code on Oct 28, 2026 20:25 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/regexpExpressions.scala:1
    @@ -84,33 +84,92 @@ abstract class StringRegexExpression extends BinaryExpression
         }
       }
     
    -  override def expensive: Boolean = hasExpensiveChild || _expensiveRegex
    -
    -  // Heuristic, not designed to be perfect. Look for things likely to have
    -  // back tracking.
    -  private val detectExpensiveRegexPattern = Pattern.compile("\\+\\*\\{")
    -
    -  private lazy val _expensiveRegex = {
    -    // A quick heuristic for expensive a pattern is.
    -    left match {
    -      case StringLiteral(str) =>
    -        // If we have a clear start limited back tracking required.
    -        if (str.startsWith("^") || str.startsWith("\\b")) {
    -          false
    -        } else if (detectExpensiveRegexPattern.matcher(str).matches()) {
    -          // Greedy matching can be tricky.
    -          true
    -        } else {
    -          // Default to pushdown for now.
    -          false
    -        }
    -      case _ =>
    -        true // per row regex compilation.
    +  override def expensive: Boolean = hasExpensiveChild || _expensivePattern
    +
    +  // Heuristic, not designed to be perfect. A pattern that is not foldable is compiled for every
    +  // row; a foldable one is left to `isExpensivePattern`. Like `ConstantFolding`, evaluate a fresh
    +  // copy so that a stateful pattern keeps its state.
    +  private lazy val _expensivePattern = !right.foldable || {
    +    try {
    +      val str = right.freshCopyIfContainsStatefulExpression().eval()
    +      str != null && isExpensivePattern(str.toString)
    +    } catch {
    +      // E.g. a pattern that `ConstantFolding` left in a conditional branch because it throws.
    +      case NonFatal(_) => true
         }
       }
    +
    +  /** Whether matching against the constant pattern `str` is likely to be expensive. */
    +  protected def isExpensivePattern(str: String): Boolean = true
     }
     
     private[catalyst] object StringRegexExpression {
    +  /**
    +   * Counts the `%` wildcards in a LIKE pattern, skipping escaped characters. Each one becomes a
    +   * `.*`, and a failed match tries every combination of their lengths.
    +   */
    +  def countLikeWildcards(pattern: String, escapeChar: Char): Int = {

    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.

    dongjoon-hyun dongjoon-hyun commented on code on Oct 28, 2026 20:25 UTC
    Code Review
    sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/RegexpExpressionsSuite.scala:1
    @@ -735,4 +735,46 @@ class RegexpExpressionsSuite extends SparkFunSuite with ExpressionEvalHelper {
         assert(extractAllCopy ne extractAll,
           "freshCopyIfContainsStatefulExpression should return a new instance for RegExpExtractAll")
       }
    +
    +  test("SPARK-60632: LIKE and RLIKE expensive heuristic looks at the pattern") {
    +    val str = $"s".string.at(0)
    +    val pattern = $"p".string.at(1)
    +
    +    // The subject string is irrelevant; a constant pattern is checked. Two or more repeating
    +    // quantifiers make an RLIKE expensive, anchored or not.
    +    Seq("^1", "magic", "a.b", "^a.*b", "2024-.*", "\\d{2,}", "a{3}b*", "a*+b", "(?i)^abc.*",
    +      "a\\+b\\*", "[+*{]x+", "\\p{Lu}+", "\\x{41}.*", "\\Q.*+\\E.*").foreach { p =>
    +      assert(!RLike(str, Literal(p)).expensive, p)
    +    }
    +    Seq(".*a.*b", "^.*a.*a.*a.*b", "\\b.*a.*b", "(a+)+b", "a{2,}b+", "\\d+\\s*", "a+?b.*",
    +      "a{1,9}b{1,9}").foreach { p =>

    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.

    dongjoon-hyun dongjoon-hyun commented on Oct 28, 2026 20:25 UTC
    Reviewer

    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.

    spark-test spark-test commented on Oct 28, 2026 21:31 UTC
    Reviewer

    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

  • Both open questions come from the same reclassification of LIKE/RLIKE aliases, and they pull in opposite directions. Treating anchored two-quantifier patterns as cheap would push more aliased filters below their projection. Any pattern that moves from expensive to cheap can also move a filter across a stateful operator, such as a stream-stream join, in a streaming query resumed from a checkpoint written by 4.2.0 or later. If you relax the anchored threshold, the streaming answer has to cover those extra patterns too.

  • 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:

  • Since 4.2.0, a filter on any column LIKE/RLIKE alias stays above its Project under the default 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.

  • With this PR, a cheap pattern such as 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"} -->

    viirya viirya commented on code on Oct 29, 2026 03:18 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/regexpExpressions.scala:1
    @@ -84,33 +84,92 @@ abstract class StringRegexExpression extends BinaryExpression
         }
       }
     
    -  override def expensive: Boolean = hasExpensiveChild || _expensiveRegex
    -
    -  // Heuristic, not designed to be perfect. Look for things likely to have
    -  // back tracking.
    -  private val detectExpensiveRegexPattern = Pattern.compile("\\+\\*\\{")
    -
    -  private lazy val _expensiveRegex = {
    -    // A quick heuristic for expensive a pattern is.
    -    left match {
    -      case StringLiteral(str) =>
    -        // If we have a clear start limited back tracking required.
    -        if (str.startsWith("^") || str.startsWith("\\b")) {
    -          false
    -        } else if (detectExpensiveRegexPattern.matcher(str).matches()) {
    -          // Greedy matching can be tricky.
    -          true
    -        } else {
    -          // Default to pushdown for now.
    -          false
    -        }
    -      case _ =>
    -        true // per row regex compilation.
    +  override def expensive: Boolean = hasExpensiveChild || _expensivePattern
    +
    +  // Heuristic, not designed to be perfect. A pattern that is not foldable is compiled for every
    +  // row; a foldable one is left to `isExpensivePattern`. Like `ConstantFolding`, evaluate a fresh
    +  // copy so that a stateful pattern keeps its state.
    +  private lazy val _expensivePattern = !right.foldable || {
    +    try {
    +      val str = right.freshCopyIfContainsStatefulExpression().eval()
    +      str != null && isExpensivePattern(str.toString)
    +    } catch {
    +      // E.g. a pattern that `ConstantFolding` left in a conditional branch because it throws.
    +      case NonFatal(_) => true
         }
       }
    +
    +  /** Whether matching against the constant pattern `str` is likely to be expensive. */
    +  protected def isExpensivePattern(str: String): Boolean = true
     }
     
     private[catalyst] object StringRegexExpression {
    +  /**
    +   * Counts the `%` wildcards in a LIKE pattern, skipping escaped characters. Each one becomes a
    +   * `.*`, and a failed match tries every combination of their lengths.
    +   */
    +  def countLikeWildcards(pattern: String, escapeChar: Char): Int = {
    +    var count = 0
    +    var i = 0
    +    while (i < pattern.length) {
    +      val c = pattern.charAt(i)
    +      if (c == escapeChar) {
    +        i += 1
    +      } else if (c == '%') {
    +        count += 1
    +      }
    +      i += 1
    +    }
    +    count
    +  }
    +
    +  /**
    +   * Counts the repeating quantifiers (`*`, `+` and `{n,m}`) in a regex, which are what make a
    +   * failed match backtrack. Escaped characters, quoted text, character classes and the braces of
    +   * `\p{..}`, `\x{..}` and `\N{..}` are skipped, and the `+` or `?` that makes a quantifier
    +   * possessive or lazy is not counted again.
    +   */
    +  def countRegexQuantifiers(regex: String): Int = {
    +    var count = 0
    +    var classDepth = 0
    +    var i = 0
    +    // Moves `i` past a `+` or `?` that modifies the quantifier ending at `i`.
    +    def skipModifier(): Unit = {
    +      if (i + 1 < regex.length && (regex.charAt(i + 1) == '+' || regex.charAt(i + 1) == '?')) {
    +        i += 1
    +      }
    +    }
    +    while (i < regex.length) {
    +      regex.charAt(i) match {
    +        case '\\' if i + 1 < regex.length =>
    +          i += 1
    +          if (regex.charAt(i) == 'Q') {
    +            val end = regex.indexOf("\\E", i)
    +            i = if (end < 0) regex.length else end + 1
    +          } else if ("pPxN".indexOf(regex.charAt(i)) >= 0 &&
    +              i + 1 < regex.length && regex.charAt(i + 1) == '{') {
    +            val end = regex.indexOf('}', i)
    +            i = if (end < 0) regex.length else end
    +          }
    +        case '[' => classDepth += 1
    +        case ']' if classDepth > 0 => classDepth -= 1
    +        case '*' | '+' if classDepth == 0 =>
    +          count += 1
    +          skipModifier()
    +        case '{' if classDepth == 0 =>

    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.

    viirya viirya commented on code on Oct 29, 2026 03:18 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/regexpExpressions.scala:1
    @@ -84,33 +84,92 @@ abstract class StringRegexExpression extends BinaryExpression
         }
       }
     
    -  override def expensive: Boolean = hasExpensiveChild || _expensiveRegex
    -
    -  // Heuristic, not designed to be perfect. Look for things likely to have
    -  // back tracking.
    -  private val detectExpensiveRegexPattern = Pattern.compile("\\+\\*\\{")
    -
    -  private lazy val _expensiveRegex = {
    -    // A quick heuristic for expensive a pattern is.
    -    left match {
    -      case StringLiteral(str) =>
    -        // If we have a clear start limited back tracking required.
    -        if (str.startsWith("^") || str.startsWith("\\b")) {
    -          false
    -        } else if (detectExpensiveRegexPattern.matcher(str).matches()) {
    -          // Greedy matching can be tricky.
    -          true
    -        } else {
    -          // Default to pushdown for now.
    -          false
    -        }
    -      case _ =>
    -        true // per row regex compilation.
    +  override def expensive: Boolean = hasExpensiveChild || _expensivePattern
    +
    +  // Heuristic, not designed to be perfect. A pattern that is not foldable is compiled for every
    +  // row; a foldable one is left to `isExpensivePattern`. Like `ConstantFolding`, evaluate a fresh
    +  // copy so that a stateful pattern keeps its state.
    +  private lazy val _expensivePattern = !right.foldable || {
    +    try {
    +      val str = right.freshCopyIfContainsStatefulExpression().eval()
    +      str != null && isExpensivePattern(str.toString)
    +    } catch {
    +      // E.g. a pattern that `ConstantFolding` left in a conditional branch because it throws.
    +      case NonFatal(_) => true
         }
       }
    +
    +  /** Whether matching against the constant pattern `str` is likely to be expensive. */
    +  protected def isExpensivePattern(str: String): Boolean = true
     }
     
     private[catalyst] object StringRegexExpression {
    +  /**
    +   * Counts the `%` wildcards in a LIKE pattern, skipping escaped characters. Each one becomes a
    +   * `.*`, and a failed match tries every combination of their lengths.
    +   */
    +  def countLikeWildcards(pattern: String, escapeChar: Char): Int = {
    +    var count = 0
    +    var i = 0
    +    while (i < pattern.length) {
    +      val c = pattern.charAt(i)
    +      if (c == escapeChar) {
    +        i += 1
    +      } else if (c == '%') {
    +        count += 1
    +      }
    +      i += 1
    +    }
    +    count
    +  }
    +
    +  /**
    +   * Counts the repeating quantifiers (`*`, `+` and `{n,m}`) in a regex, which are what make a
    +   * failed match backtrack. Escaped characters, quoted text, character classes and the braces of
    +   * `\p{..}`, `\x{..}` and `\N{..}` are skipped, and the `+` or `?` that makes a quantifier
    +   * possessive or lazy is not counted again.
    +   */
    +  def countRegexQuantifiers(regex: String): Int = {
    +    var count = 0
    +    var classDepth = 0
    +    var i = 0
    +    // Moves `i` past a `+` or `?` that modifies the quantifier ending at `i`.
    +    def skipModifier(): Unit = {
    +      if (i + 1 < regex.length && (regex.charAt(i + 1) == '+' || regex.charAt(i + 1) == '?')) {
    +        i += 1
    +      }
    +    }
    +    while (i < regex.length) {
    +      regex.charAt(i) match {
    +        case '\\' if i + 1 < regex.length =>
    +          i += 1
    +          if (regex.charAt(i) == 'Q') {
    +            val end = regex.indexOf("\\E", i)
    +            i = if (end < 0) regex.length else end + 1
    +          } else if ("pPxN".indexOf(regex.charAt(i)) >= 0 &&
    +              i + 1 < regex.length && regex.charAt(i + 1) == '{') {
    +            val end = regex.indexOf('}', i)
    +            i = if (end < 0) regex.length else end
    +          }
    +        case '[' => classDepth += 1

    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.

    viirya viirya commented on code on Oct 29, 2026 03:18 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/regexpExpressions.scala:1
    @@ -534,6 +598,10 @@ case class RLike(left: Expression, right: Expression) extends StringRegexExpress
     
       override def escape(v: String): String = v
       override def matches(regex: Pattern, str: String): Boolean = regex.matcher(str).find(0)
    +  // Like the `%` of LIKE, but `find` also tries every start position, which costs one more
    +  // factor of the input length. An anchor does not bound the backtracking within a match.
    +  override protected def isExpensivePattern(str: String): Boolean =
    +    StringRegexExpression.countRegexQuantifiers(str) >= 2

    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.

    viirya viirya commented on code on Oct 29, 2026 03:18 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/regexpExpressions.scala:1
    @@ -84,33 +84,92 @@ abstract class StringRegexExpression extends BinaryExpression
         }
       }
     
    -  override def expensive: Boolean = hasExpensiveChild || _expensiveRegex
    -
    -  // Heuristic, not designed to be perfect. Look for things likely to have
    -  // back tracking.
    -  private val detectExpensiveRegexPattern = Pattern.compile("\\+\\*\\{")
    -
    -  private lazy val _expensiveRegex = {
    -    // A quick heuristic for expensive a pattern is.
    -    left match {
    -      case StringLiteral(str) =>
    -        // If we have a clear start limited back tracking required.
    -        if (str.startsWith("^") || str.startsWith("\\b")) {
    -          false
    -        } else if (detectExpensiveRegexPattern.matcher(str).matches()) {
    -          // Greedy matching can be tricky.
    -          true
    -        } else {
    -          // Default to pushdown for now.
    -          false
    -        }
    -      case _ =>
    -        true // per row regex compilation.
    +  override def expensive: Boolean = hasExpensiveChild || _expensivePattern
    +
    +  // Heuristic, not designed to be perfect. A pattern that is not foldable is compiled for every
    +  // row; a foldable one is left to `isExpensivePattern`. Like `ConstantFolding`, evaluate a fresh
    +  // copy so that a stateful pattern keeps its state.
    +  private lazy val _expensivePattern = !right.foldable || {
    +    try {
    +      val str = right.freshCopyIfContainsStatefulExpression().eval()
    +      str != null && isExpensivePattern(str.toString)
    +    } catch {
    +      // E.g. a pattern that `ConstantFolding` left in a conditional branch because it throws.
    +      case NonFatal(_) => true
         }
       }
    +
    +  /** Whether matching against the constant pattern `str` is likely to be expensive. */
    +  protected def isExpensivePattern(str: String): Boolean = true
     }
     
     private[catalyst] object StringRegexExpression {
    +  /**
    +   * Counts the `%` wildcards in a LIKE pattern, skipping escaped characters. Each one becomes a
    +   * `.*`, and a failed match tries every combination of their lengths.
    +   */
    +  def countLikeWildcards(pattern: String, escapeChar: Char): Int = {
    +    var count = 0
    +    var i = 0
    +    while (i < pattern.length) {
    +      val c = pattern.charAt(i)
    +      if (c == escapeChar) {
    +        i += 1
    +      } else if (c == '%') {
    +        count += 1
    +      }
    +      i += 1
    +    }
    +    count
    +  }
    +
    +  /**
    +   * Counts the repeating quantifiers (`*`, `+` and `{n,m}`) in a regex, which are what make a
    +   * failed match backtrack. Escaped characters, quoted text, character classes and the braces of
    +   * `\p{..}`, `\x{..}` and `\N{..}` are skipped, and the `+` or `?` that makes a quantifier
    +   * possessive or lazy is not counted again.
    +   */
    +  def countRegexQuantifiers(regex: String): Int = {
    +    var count = 0
    +    var classDepth = 0
    +    var i = 0
    +    // Moves `i` past a `+` or `?` that modifies the quantifier ending at `i`.
    +    def skipModifier(): Unit = {

    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.

    dongjoon-hyun dongjoon-hyun commented on Oct 29, 2026 14:06 UTC
    Reviewer

    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.

    viirya viirya commented on Oct 29, 2026 22:28 UTC
    Author

    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.

    dongjoon-hyun dongjoon-hyun commented on Oct 30, 2026 00:14 UTC
    Reviewer

    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.

    viirya viirya commented on Oct 31, 2026 18:11 UTC
    Author
    viirya viirya commented on Oct 31, 2026 18:12 UTC
    Author

    Thanks @dongjoon-hyun !

    Reviewers
    Assignees
    viirya viirya
    Labels
    risk: low confidence: 87% 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: 53.4% (MEDIUM) · Higher = larger blast radius
    53.4%
    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: 87% · Lower = rushed or shallow review
    87%
    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: 6.9% · Safe to merge
    6.9%
    Repository