← Back to Pull requests

[SPARK-60983][SQL] Fix query errors by ConstantPropagation when a constant is substituted into an expression that can fail #60163

Closed
dongjoon-hyun closed this pull request without merging on Nov 07, 2026 02:37 UTC
View on GitHub
dongjoon-hyun dongjoon-hyun commented on Nov 06, 2026 04:53 UTC
Author

What changes were proposed in this pull request?

ConstantPropagation replaces an attribute with the literal of an equality conjunct, such as y = 0, in the other comparisons of the same AND. The literal is the value of the attribute only on the rows that pass the whole AND. However, the rewritten conjuncts also run on other rows, and a part that becomes constant is folded by ConstantFolding before any row is read. So an expression that can fail, such as a division, an ANSI cast or an array index, can raise an error that the query cannot raise in any evaluation order of its conjuncts:

  • 10 / (id - y) > 0 AND y = 0 becomes 10 / (id - 0) > 0 AND y = 0, which divides by zero on a row with id = 0 and y = 1.

  • y = 0 AND id > 10 / y becomes y = 0 AND id > 10 / 0, which fails during the optimization, even on an empty table.
  • This PR replaces an attribute only where its value cannot change whether an expression fails:

  • under operators that cannot fail on their own, such as comparisons, AND, OR, NOT, IS NULL and COALESCE. This is the allowlist of ExprUtils.canEvaluateUnconditionally, which is now also exposed as ExprUtils.isTotalOperator.

  • in a subexpression whose attributes are all replaced, when it folds to a literal without an error. For example, y = 5 AND x = y + 1 still becomes y = 5 AND x = 6.
  • Otherwise, the expression keeps its attributes. The comparisons in the pulled up condition of a correlated IN or EXISTS subquery are rewritten within the same boundary.

    A conjunct that keeps an attribute can still run on rows where the equality does not hold, while a guard over the same attribute may become a constant, such as d <> 0 in d <> 0 AND n / d > 1 AND d = 5. So when a conjunct that can fail keeps a propagated attribute, this PR also moves the equalities ahead of the other conjuncts. An equality between an attribute and a literal cannot fail, so running it first raises no error.

    Why are the changes needed?

    The queries below cannot raise an error in any order of their conjuncts, but fail with DIVIDE_BY_ZERO.

    CREATE TABLE t1(id BIGINT, y BIGINT) USING parquet;
    INSERT INTO t1 VALUES (0, 1), (6, 0);
    -- It should return (6, 0), but fails with DIVIDE_BY_ZERO.
    SELECT * FROM t1 WHERE 10 / (id - y) > 0 AND y = 0;
    
    CREATE TABLE t2(id BIGINT, y BIGINT) USING parquet;
    -- It should return no rows, but fails with DIVIDE_BY_ZERO, with or without rows in `t2`.
    SELECT * FROM t2 WHERE y = 0 AND id > 10 / y;
    

    The same happens with other expressions that can fail. For example, s = 'abc' AND CAST(s AS INT) > 0 fails with CAST_INVALID_INPUT on a table without 'abc', and arr[i] > 0 AND i = 5 fails with INVALID_ARRAY_INDEX on a row with a shorter array and i = 1. A UDF or assert_true also fails like this with ANSI mode off.

    ConstantPropagation has substituted into all comparisons since SPARK-42500 (#42038), and ANSI mode has been on by default since SPARK-44444 (#46013). Both are in v4.0.0 (2025-05-19). Before that, it only substituted into = and <=> (SPARK-20758, #17993, v2.3.0 (2018-02-22)).

    This PR should be merged after #60162 (SPARK-60985). Without it, InferFiltersFromConstraints infers the expression that this PR no longer rewrites, such as 10 / (id - 0) > 0 from 10 / (id - y) > 0 AND y = 0, and puts it ahead of the original conditions. Then a query that works today, such as SELECT * FROM t WHERE id > 5 AND y = 0 AND 10 / (id - y) > 0 on rows (0, 0) and (6, 0), would fail with DIVIDE_BY_ZERO.

    Does this PR introduce _any_ user-facing change?

    Yes. The queries above, which fail with an error, now return their results.

    Some comparisons keep an attribute instead of a literal, for example y = 5 AND x / y > 1, y = 5 AND CASE WHEN y > 0 THEN x ELSE z END > 1, and r.d + l.b > 10 in a correlated subquery with l.b = 5.0 outside. The results are the same, but some plans become less efficient. For example, the CASE above no longer pushes x > 1 down to the scan, and l.b = 5.0 AND l.a NOT IN (SELECT c FROM r WHERE r.d + l.b > 10) is planned as a broadcast nested loop join instead of a null-aware broadcast hash join. When a conjunct that can fail keeps a propagated attribute, the equalities move ahead of the other conjuncts in the plan.

    How was this patch tested?

  • Added SPARK-60983: Do not propagate a constant into an expression that can fail to ConstantPropagationSuite. It covers an expression that can fail and does not become constant, one that becomes constant but fails to fold, one that folds, a comparison whose other side can fail, a guard that becomes a constant, after which the equality goes first, and the condition of an IF, which is not rewritten. Without this change, the test fails.

  • Added SPARK-60983: Propagate a constant into a comparison with a correlated scalar subquery to SubquerySuite. It fails with NoSuchElementException if the columns in the condition of the subquery are looked up as constants.

  • The existing SPARK-32290: SingleColumn Null Aware Anti Join Optimize in SubquerySuite covers the comparisons in the condition of a correlated subquery. It fails if they are not rewritten.

  • Ran all suites in org.apache.spark.sql.catalyst.optimizer, ExprUtilsSuite, the TPC-DS and TPC-H PlanStabilitySuites with ANSI mode on and off, SQLQueryTestSuite, SQLQuerySuite, DataFrameSuite, JoinSuite, SubquerySuite, ExplainSuite, CachedTableSuite, DynamicPartitionPruningV1SuiteAEOff, ParquetV1FilterSuite, ParquetV2FilterSuite, OrcV1FilterSuite, FileSourceStrategySuite, PruneFileSourcePartitionsSuite and the DSv2 strategy and SQL suites. All pass and no golden files change, except udtf/udtf.sql in SQLQueryTestSuite, which also fails without this change in my environment because of the error message of a newer Python.

  • Ran the queries above and the variants with a cast, an array index, a UDF, assert_true, HAVING, a window, a view, <=>, a guard over the propagated column and a correlated scalar subquery before and after this change, together with the change of #60162. They no longer fail, and y = 0 AND id > 10 / y still fails on a row with y = 0.
  • Was this patch authored or co-authored using generative AI tooling?

    Generated-by: Claude Opus 5.5

    Diff: 150 lines (+136 / -14) across 4 files Reviewer: HyukjinKwon Review duration: 1304m
    All Vouch review confidence checks passed
    Residual risk 0.07 = Change Risk (0.37) × (1 − Review Confidence (0.81)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.37 · 150 lines diff across 4 files
    0.37
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.76 · 5 substantive comment(s)
    0.76
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    81%
    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.300
    Real PR Conversation Timeline
    16 items
    HyukjinKwon HyukjinKwon approved these changes on Nov 06, 2026 05:40 UTC
    Approved Reviewer

    Approved these changes.

    dongjoon-hyun dongjoon-hyun commented on Nov 06, 2026 06:23 UTC
    Author

    Thank you, @HyukjinKwon ~

    spark-test spark-test commented on code on Nov 06, 2026 08:05 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:1
    @@ -230,21 +230,51 @@ object ConstantPropagation extends Rule[LogicalPlan] {
       private def safeToReplace(ar: AttributeReference, nullIsFalse: Boolean) =
         !ar.nullable || nullIsFalse
     
    +  /**
    +   * Replaces attributes in the comparisons of `condition` with their constant values.
    +   *
    +   * The constant is the value of an attribute only on the rows that pass the whole condition.
    +   * The rewritten condition also runs on other rows, e.g. a row with `y = 1` for
    +   * `10 / (id - y) > 0 AND y = 0`, and a part of it that becomes constant is folded with no row
    +   * at all, e.g. `10 / y` for `y = 0 AND id > 10 / y`. So that this raises no error the original
    +   * condition cannot raise, an expression that can fail keeps its attributes, unless all of them
    +   * are replaced and the result evaluates without an error.
    +   */
       private def replaceConstants(
           condition: Expression,
           equalityPredicates: AttributeMap[(Literal, BinaryComparison)]): Expression = {
         val constantsMap = AttributeMap(equalityPredicates.map { case (attr, (lit, _)) => attr -> lit })
         val predicates = equalityPredicates.values.map(_._2).toSet
         def replaceInComparison(b: BinaryComparison): Expression = {
           lazy val collationSafeReplacement = isSameCollationAttrRefComparison(b)
    -      b transform {
    -        case a: AttributeReference
    -          if isBinaryStable(a.dataType) || collationSafeReplacement =>
    -          constantsMap.getOrElse(a, a)
    +      def canReplace(a: Attribute): Boolean =
    +        constantsMap.contains(a) && (isBinaryStable(a.dataType) || collationSafeReplacement)
    +      def replace(e: Expression): Expression = e match {
    +        case a: AttributeReference if canReplace(a) => constantsMap(a)
    +        case _ if ExprUtils.isTotalOperator(e) => e.mapChildren(replace)
    +        case _ if e.references.nonEmpty && e.references.forall(canReplace) =>
    +          val replaced = e.transform { case a: AttributeReference => constantsMap(a) }

    Blocking (P1): e.references.forall(canReplace) checks only the columns in references, but this transform looks up every AttributeReference it visits with constantsMap(a), outside canFold's try/catch. For a correlated subquery, references covers only the outer columns, while its children also include the join condition that PullupCorrelatedPredicates pulled up, over the subquery's own columns. AttributeMap does not override apply, so the inherited Map.apply throws for those. As a result, SELECT * FROM t1 WHERE t1.a = 1 AND t1.b = (SELECT max(t2.b) FROM t2 WHERE t2.a = t1.a), the common latest-row-for-a-key pattern, now fails during optimization with java.util.NoSuchElementException: key not found, where the base branch ran it. The same applies under COALESCE, under other operators whose remaining columns are also equated to literals, and to EXISTS or IN nested in a comparison. No test puts a subquery operand in a rewritten comparison.

    Verification:

  • Regression: A rule-level case whose comparison operand is a correlated scalar subquery, with its outer attribute propagated and an inner attribute in its join condition, optimizes without error and keeps the subquery unchanged.

  • Behavior: An end-to-end query of the form t1.a = 1 AND t1.b = (SELECT max(t2.b) FROM t2 WHERE t2.a = t1.a) returns the expected rows.
  • spark-test spark-test commented on code on Nov 06, 2026 08:05 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:1
    @@ -230,21 +230,51 @@ object ConstantPropagation extends Rule[LogicalPlan] {
       private def safeToReplace(ar: AttributeReference, nullIsFalse: Boolean) =
         !ar.nullable || nullIsFalse
     
    +  /**
    +   * Replaces attributes in the comparisons of `condition` with their constant values.
    +   *
    +   * The constant is the value of an attribute only on the rows that pass the whole condition.
    +   * The rewritten condition also runs on other rows, e.g. a row with `y = 1` for
    +   * `10 / (id - y) > 0 AND y = 0`, and a part of it that becomes constant is folded with no row
    +   * at all, e.g. `10 / y` for `y = 0 AND id > 10 / y`. So that this raises no error the original
    +   * condition cannot raise, an expression that can fail keeps its attributes, unless all of them
    +   * are replaced and the result evaluates without an error.
    +   */
       private def replaceConstants(
           condition: Expression,
           equalityPredicates: AttributeMap[(Literal, BinaryComparison)]): Expression = {
         val constantsMap = AttributeMap(equalityPredicates.map { case (attr, (lit, _)) => attr -> lit })
         val predicates = equalityPredicates.values.map(_._2).toSet
         def replaceInComparison(b: BinaryComparison): Expression = {
           lazy val collationSafeReplacement = isSameCollationAttrRefComparison(b)
    -      b transform {
    -        case a: AttributeReference
    -          if isBinaryStable(a.dataType) || collationSafeReplacement =>
    -          constantsMap.getOrElse(a, a)
    +      def canReplace(a: Attribute): Boolean =
    +        constantsMap.contains(a) && (isBinaryStable(a.dataType) || collationSafeReplacement)
    +      def replace(e: Expression): Expression = e match {
    +        case a: AttributeReference if canReplace(a) => constantsMap(a)
    +        case _ if ExprUtils.isTotalOperator(e) => e.mapChildren(replace)
    +        case _ if e.references.nonEmpty && e.references.forall(canReplace) =>
    +          val replaced = e.transform { case a: AttributeReference => constantsMap(a) }
    +          if (canFold(replaced)) replaced else e
    +        case _ => e

    Blocking (P1): Keeping the attribute here means the expression now runs with the row's own value on rows that fail the equality, while guards written over the same column are still substituted and folded away. Under ANSI, SELECT * FROM t WHERE d <> 0 AND n / d > 1 AND d = 5 on rows (10, 0) and (10, 5) becomes n / d > 1 AND d = 5 and fails with DIVIDE_BY_ZERO on (10, 0), where the base branch produced n / 5.0 > 1.0 AND d = 5 and returned (10, 5). The PR's own 10 / (id - y) > 0 AND y = 0 fails the same way on a row (5, 5), where the base branch returned no rows. Any conjunct that keeps a propagated column and comes before the equality, as written or after CombineFilters puts a view's filter first, is affected: casts, array indexes, overflow, Scala UDFs, assert_true, and CASE branches that can fail. Python UDF conjuncts are not, because the equality is pushed below the node that evaluates them. So the description's statement that these comparisons give the same results does not hold for such data.

    See Shared repair plan 1 in the review body.

    spark-test spark-test commented on code on Nov 06, 2026 08:05 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:1
    @@ -230,21 +230,51 @@ object ConstantPropagation extends Rule[LogicalPlan] {
       private def safeToReplace(ar: AttributeReference, nullIsFalse: Boolean) =
         !ar.nullable || nullIsFalse
     
    +  /**
    +   * Replaces attributes in the comparisons of `condition` with their constant values.
    +   *
    +   * The constant is the value of an attribute only on the rows that pass the whole condition.
    +   * The rewritten condition also runs on other rows, e.g. a row with `y = 1` for
    +   * `10 / (id - y) > 0 AND y = 0`, and a part of it that becomes constant is folded with no row
    +   * at all, e.g. `10 / y` for `y = 0 AND id > 10 / y`. So that this raises no error the original
    +   * condition cannot raise, an expression that can fail keeps its attributes, unless all of them
    +   * are replaced and the result evaluates without an error.
    +   */
       private def replaceConstants(
           condition: Expression,
           equalityPredicates: AttributeMap[(Literal, BinaryComparison)]): Expression = {
         val constantsMap = AttributeMap(equalityPredicates.map { case (attr, (lit, _)) => attr -> lit })
         val predicates = equalityPredicates.values.map(_._2).toSet
         def replaceInComparison(b: BinaryComparison): Expression = {
           lazy val collationSafeReplacement = isSameCollationAttrRefComparison(b)
    -      b transform {
    -        case a: AttributeReference
    -          if isBinaryStable(a.dataType) || collationSafeReplacement =>
    -          constantsMap.getOrElse(a, a)
    +      def canReplace(a: Attribute): Boolean =
    +        constantsMap.contains(a) && (isBinaryStable(a.dataType) || collationSafeReplacement)
    +      def replace(e: Expression): Expression = e match {
    +        case a: AttributeReference if canReplace(a) => constantsMap(a)
    +        case _ if ExprUtils.isTotalOperator(e) => e.mapChildren(replace)
    +        case _ if e.references.nonEmpty && e.references.forall(canReplace) =>
    +          val replaced = e.transform { case a: AttributeReference => constantsMap(a) }
    +          if (canFold(replaced)) replaced else e
    +        case _ => e
           }
    +      b.mapChildren(replace)
    +    }
    +    def replaceInCondition(e: Expression): Expression = e match {
    +      case b: BinaryComparison if predicates.contains(b) => b
    +      case b: BinaryComparison => replaceInComparison(b)
    +      case _ if ExprUtils.isTotalOperator(e) => e.mapChildren(replaceInCondition)

    Non-blocking (P2): This recursion rewrites each operand of OR, AND, COALESCE and IN on its own, but those operators short-circuit, so a rewritten operand decides whether its siblings run. Under ANSI, SELECT * FROM t WHERE (y < 3 OR 10 / x > 1) AND y = 5 on a row with y = 1 and x = 0 cannot raise in either conjunct order, yet y < 3 becomes 5 < 3, folds away, and leaves 10 / x > 1 to fail with DIVIDE_BY_ZERO, as it already did on the base branch. coalesce(m[k], 10 / x) > 0 AND k = 'a' and an IN value or list item inside a comparison behave the same way. Once the rewrite drops the last reference to the propagated column, pushdown can also move the conjunct below an Aggregate or Window: SELECT g, sum(x) AS s FROM t GROUP BY g HAVING s = 5 AND (s < 3 OR 10 / g > 1) fails on a table whose only group has g = 0 and s = 1. So the new doc comment's guarantee, no error the original condition cannot raise, does not hold for these inputs.

    See Shared repair plan 1 in the review body.

    spark-test spark-test commented on code on Nov 06, 2026 08:05 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:1
    @@ -230,21 +230,51 @@ object ConstantPropagation extends Rule[LogicalPlan] {
       private def safeToReplace(ar: AttributeReference, nullIsFalse: Boolean) =
         !ar.nullable || nullIsFalse
     
    +  /**
    +   * Replaces attributes in the comparisons of `condition` with their constant values.
    +   *
    +   * The constant is the value of an attribute only on the rows that pass the whole condition.
    +   * The rewritten condition also runs on other rows, e.g. a row with `y = 1` for
    +   * `10 / (id - y) > 0 AND y = 0`, and a part of it that becomes constant is folded with no row
    +   * at all, e.g. `10 / y` for `y = 0 AND id > 10 / y`. So that this raises no error the original
    +   * condition cannot raise, an expression that can fail keeps its attributes, unless all of them
    +   * are replaced and the result evaluates without an error.
    +   */
       private def replaceConstants(
           condition: Expression,
           equalityPredicates: AttributeMap[(Literal, BinaryComparison)]): Expression = {
         val constantsMap = AttributeMap(equalityPredicates.map { case (attr, (lit, _)) => attr -> lit })
         val predicates = equalityPredicates.values.map(_._2).toSet
         def replaceInComparison(b: BinaryComparison): Expression = {
           lazy val collationSafeReplacement = isSameCollationAttrRefComparison(b)
    -      b transform {
    -        case a: AttributeReference
    -          if isBinaryStable(a.dataType) || collationSafeReplacement =>
    -          constantsMap.getOrElse(a, a)
    +      def canReplace(a: Attribute): Boolean =
    +        constantsMap.contains(a) && (isBinaryStable(a.dataType) || collationSafeReplacement)
    +      def replace(e: Expression): Expression = e match {
    +        case a: AttributeReference if canReplace(a) => constantsMap(a)
    +        case _ if ExprUtils.isTotalOperator(e) => e.mapChildren(replace)
    +        case _ if e.references.nonEmpty && e.references.forall(canReplace) =>
    +          val replaced = e.transform { case a: AttributeReference => constantsMap(a) }
    +          if (canFold(replaced)) replaced else e
    +        case _ => e
           }
    +      b.mapChildren(replace)
    +    }
    +    def replaceInCondition(e: Expression): Expression = e match {
    +      case b: BinaryComparison if predicates.contains(b) => b
    +      case b: BinaryComparison => replaceInComparison(b)
    +      case _ if ExprUtils.isTotalOperator(e) => e.mapChildren(replaceInCondition)
    +      // The children of these include the comparisons of a pulled up correlated condition.
    +      case _: InSubquery | _: ListQuery | _: Exists => e.mapChildren(replaceInCondition)
    +      case _ => e

    Nit (P3): Returning other containers unchanged is what keeps a substituted branch condition, as in IF(c > b, true, 10 / c > 1) AND b = 0, from sending a row with b = -1 and c = 0 into the failing branch under ANSI. No test exercises it: every new SPARK-60983 case puts the division directly under the rewritten comparison, and ConstantPropagationSuite has no IF or CASE WHEN case. If this went back to descending into every comparison, the failure would return with every assertion still passing.

    Verification:

  • Regression: Under ANSI mode, IF(c > b, true, 10.0 / CAST(c AS DOUBLE) > 0.0) AND b = 0 keeps its IF predicate and raises no error on a row with b = -1 and c = 0, and the case fails against the base branch's rewriting.
  • spark-test spark-test commented on code on Nov 06, 2026 08:05 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:1
    @@ -230,21 +230,51 @@ object ConstantPropagation extends Rule[LogicalPlan] {
       private def safeToReplace(ar: AttributeReference, nullIsFalse: Boolean) =
         !ar.nullable || nullIsFalse
     
    +  /**
    +   * Replaces attributes in the comparisons of `condition` with their constant values.
    +   *
    +   * The constant is the value of an attribute only on the rows that pass the whole condition.
    +   * The rewritten condition also runs on other rows, e.g. a row with `y = 1` for
    +   * `10 / (id - y) > 0 AND y = 0`, and a part of it that becomes constant is folded with no row
    +   * at all, e.g. `10 / y` for `y = 0 AND id > 10 / y`. So that this raises no error the original
    +   * condition cannot raise, an expression that can fail keeps its attributes, unless all of them
    +   * are replaced and the result evaluates without an error.
    +   */
       private def replaceConstants(
           condition: Expression,
           equalityPredicates: AttributeMap[(Literal, BinaryComparison)]): Expression = {
         val constantsMap = AttributeMap(equalityPredicates.map { case (attr, (lit, _)) => attr -> lit })
         val predicates = equalityPredicates.values.map(_._2).toSet
         def replaceInComparison(b: BinaryComparison): Expression = {
           lazy val collationSafeReplacement = isSameCollationAttrRefComparison(b)
    -      b transform {
    -        case a: AttributeReference
    -          if isBinaryStable(a.dataType) || collationSafeReplacement =>
    -          constantsMap.getOrElse(a, a)
    +      def canReplace(a: Attribute): Boolean =
    +        constantsMap.contains(a) && (isBinaryStable(a.dataType) || collationSafeReplacement)
    +      def replace(e: Expression): Expression = e match {
    +        case a: AttributeReference if canReplace(a) => constantsMap(a)
    +        case _ if ExprUtils.isTotalOperator(e) => e.mapChildren(replace)
    +        case _ if e.references.nonEmpty && e.references.forall(canReplace) =>
    +          val replaced = e.transform { case a: AttributeReference => constantsMap(a) }
    +          if (canFold(replaced)) replaced else e

    Nit (P3): canFold already computes the folded literal and then discards it, so the unfolded replaced reaches ConstantFolding, which evaluates the same constant again a few rules later in the same rule set. For y = 5 AND x = y + 1 that is 5 + 1 twice instead of once. Plans and results are unchanged, but an expensive constant, such as size(sequence(1, y)) with a large propagated y, is built twice during planning.

    Verification:

  • Regression: Running ConstantPropagation alone on y = 5 AND x = y + 1 yields y = 5 AND x = 6, so no unfolded constant is left for ConstantFolding to evaluate again.

  • Compatibility: The existing ConstantPropagation cases that fold a fully substituted subexpression, such as b = 2 AND a > 10.0 / CAST(b AS DOUBLE) becoming b = 2 AND a > 5.0, keep their optimized plans.
  • spark-test spark-test commented on Nov 06, 2026 08:05 UTC
    Reviewer

    Review summary

    The new rule-level test covers the shapes it targets, but tracing the full optimizer shows several remaining problems in the rewrite. A correlated scalar subquery compared with another column, with its outer column equated to a literal, now fails during optimization with java.util.NoSuchElementException, because the all-constants case looks up the subquery's inner join-condition columns. At the current base, constraint inference still re-creates the substituted copy of each conjunct this rule now keeps and runs it ahead of the condition, so the PR's own examples still fail end to end and some queries that work today start failing; the PR defers this to #60162, which the base does not contain. Kept conjuncts also run on rows that fail the equality while their guards are folded away, so d <> 0 AND n / d > 1 AND d = 5 now raises DIVIDE_BY_ZERO where the base branch returned rows. Rewritten operands of OR, AND, COALESCE and IN can still unmask a failing sibling, as on the base branch, including after pushdown moves the rewritten conjunct below an Aggregate. Two smaller items: the condition-level IF/CASE boundary has no test, and the fold check evaluates each fully constant subexpression twice. Three questions for the author follow. These conclusions come from tracing the reviewed source; no JVM was available to run them.

    Review-level concerns

  • Shared problem: The failures that remain after this PR come from one gap: the PR limits which operands ConstantPropagation rewrites, but not where the rewritten and kept conjuncts run, and not what constraint inference re-creates from the same equality. Neither repair at this boundary is enough alone. Constraint inference placing a failing copy first undoes the reordering, and fixing inference alone still leaves kept expressions and rewritten short-circuit operands running on rows the equality rejects. Land them together, with the inference part on the base branch before or with this PR, whether it arrives through #60162 or here.
  • Cross-cutting observations

  • Once the propagated equalities run first, an ordinary filter conjunct that still refers to a propagated column only runs on rows where substituting the constant preserves its value, so the conservative operator allowlist is no longer what keeps it safe. The allowlist still matters for constants folded during planning, for guards whose rewrite would let pushdown separate them from the equality, and for pulled-up correlated subquery conditions, which run in a join without the outer equality.
  • The two propagation trade-off questions can wait until the ordering fix lands: for ordinary filters they then become mostly a performance choice, while correlated subquery conditions still need an error analysis.

    Findings

    6 total: 0 P0, 3 P1, 1 P2, 2 P3.

    Blocking (P1)

  • Constraint inference re-creates the kept conjuncts and runs them first — sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:257

  • At the current base, QueryPlanConstraints.inferConstraintsFromLiteralBindings substitutes y = 0 into every conjunct that ConstantPropagation now keeps, and InferFiltersFromConstraints prepends the result ahead of the original condition. So 10 / (id - y) > 0 comes back as 10 / (id - 0) > 0 and runs before any of the user's conjuncts. Under ANSI, SELECT FROM t WHERE id > 5 AND y = 0 AND 10 / (id - y) > 0 on rows (0, 0) and (6, 0) now fails with DIVIDE_BY_ZERO, where the base branch returned (6, 0). The PR's own examples still fail end to end as well: 10 / (id - y) > 0 AND y = 0 on a row (0, 1), and y = 0 AND id > 10 / y, whose inferred id > 10 / 0 throws in ConstantFolding during planning. The PR body defers this to #60162, which the base does not contain, and the new test runs only a rule-level batch without constraint inference, so nothing here catches it.

    Recommended change: Make literal-binding constraint inference apply the same substitution boundary as ConstantPropagation, through one substitution helper shared by both, so that inference never re-creates a substituted expression the rule keeps. Land this on the base branch before, or together with, this PR: either as the InferFiltersFromConstraints change planned in #60162, or as the same edit made here. Add full-optimizer tests for the PR's example queries.

    Why this works: With the shared boundary, substituting y = 0 into 10 / (id - y) > 0 leaves the conjunct unchanged, so inference finds nothing new and adds no division ahead of the condition. id > 10 / y is not turned into id > 10 / 0, so constant folding has nothing to fail on during planning. Conjuncts the boundary does substitute keep their inferred copies as today.

    Scope: Constraint inference and ConstantPropagation share one constant-substitution rule, with full-optimizer tests for the PR's example queries.

    Compatibility: Constraint inference keeps producing literal-substituted constraints for conjuncts where the substitution cannot raise an error.

    Risks: Inferred copies that relied on substituting through operators outside the boundary disappear, such as the x > 1 copy that currently survives for y = 5 AND CASE WHEN y > 0 THEN x ELSE z END > 1, or an x / 5 > 1 copy propagated across a join on x. Scans that relied on them for pushdown or partition pruning may read more data, and PruneFilters may drop fewer redundant conjuncts. This is the trade-off in the open question about #60162's end state, and the change can be reverted on its own.

    Constraints: Keep literal-binding inference for every conjunct the shared boundary does substitute, such as b >= a with a = 5 giving b >= 5, so existing inference results stay the same.

    Exclusions:
    - Widening the shared boundary to operators that cannot fail for their types or evaluation modes is left to the open propagation trade-off questions.

    Success: Under ANSI mode, SELECT FROM t WHERE id > 5 AND y = 0 AND 10 / (id - y) > 0 on rows (0, 0) and (6, 0) returns (6, 0), as on the base branch. Through the full optimizer, 10 / (id - y) > 0 AND y = 0 on rows (0, 1) and (6, 0) returns (6, 0), and y = 0 AND id > 10 / y returns no rows without an error on a table without y = 0.

    Verification:
    - Regression: Full-optimizer or end-to-end coverage, under ANSI mode, of the three queries in the postconditions: assert their results, and assert that no inferred conjunct contains a substituted division.
    - Compatibility: Literal-binding inference into conjuncts the boundary substitutes, such as plain comparisons and fully folding arithmetic, produces the same inferred filters as before.

  • A correlated scalar subquery operand crashes the optimizer — sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:256 — see inline.

  • Kept attributes make working queries fail on rows the equality rejects — sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:258 — see inline.
  • Non-blocking (P2)

  • Rewritten short-circuit operands can still unmask a failing sibling — sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:265 — see inline.
  • Nit (P3)

  • No test pins the condition-level IF/CASE boundary — sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:268 — see inline.

  • The fold check evaluates each substituted constant twice — sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:257 — see inline.
  • Shared repair plans

    Shared repair plan 1

    Covered findings:

  • Kept attributes make working queries fail on rows the equality rejects — sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:258

  • Rewritten short-circuit operands can still unmask a failing sibling — sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:265
  • Recommended change: When the rule propagates constants from an AND, move the propagating equalities ahead of every conjunct that still refers to a propagated column after the rewrite, keeping all other conjuncts in their original relative order, so that such a conjunct only runs on rows that pass the equalities. Inside a conjunct, rewrite an operand of a nested AND, OR, COALESCE or IN only when every operand after it, as rewritten, passes ExprUtils.canEvaluateUnconditionally. Ordering alone does not cover those operands: once a rewrite removes every reference to the propagated column, predicate pushdown can move the conjunct below an Aggregate or Window that the equality stays above. Extend the ConstantPropagation optimizer tests with the safe-division guard, short-circuit and kept-attribute shapes, and add end-to-end SQL coverage for them, including a HAVING query.

    Why this works: Filter evaluation goes left to right and drops a row at the first FALSE conjunct. With the equalities ahead, a conjunct that still refers to a propagated column only runs on rows where each equality holds, apart from rows where that column is NULL, on which the original AND evaluates it too. On rows that pass, a kept expression evaluates exactly what the base branch's substituted form did, and a folded-away guard is no longer needed. An equality between a column and a literal cannot fail, so moving it earlier introduces no error. A short-circuit operand is rewritten only when nothing it can expose can fail, so changing its value can neither unmask a sibling nor leave a guard that pushdown separates from the equality.

    Scope: ConstantPropagation moves the propagated equalities ahead of the conjuncts that still refer to their columns and stops rewriting a short-circuit operand that guards an operand that can fail, with rule-level and end-to-end tests for the regressed and still-failing shapes.

    Compatibility: The PR's own fixes stay in place. A constant subexpression that fails to fold keeps its attributes, and the PR's example queries return their results.

    Risks: Conjunct order changes for filters in which another conjunct still refers to a propagated column after the rewrite. That shows up in EXPLAIN output and can change plan-stability golden files, and the fix relies on later rules keeping a filter's relative conjunct order. InferFiltersFromConstraints currently breaks that order for inferred copies, which the constraint-inference repair addresses. Guards inside AND, OR, COALESCE or IN whose later operand can fail are no longer simplified, so such a conjunct keeps a column reference and a comparison that the base branch folded away. The change can be reverted on its own.

    Constraints: Preserve the relative order of all other conjuncts, so that guards written by the user keep protecting the expressions after them, and move the equalities only when another conjunct still refers to a propagated column after the rewrite.

    Exclusions:

  • Pulled-up correlated IN/EXISTS conditions are evaluated in a join, not in the filter's conjunct order, so the reordering does not apply to them.
  • Success: Under ANSI mode, SELECT FROM t WHERE d <> 0 AND n / d > 1 AND d = 5 on rows (10, 0) and (10, 5) returns (10, 5), as on the base branch, and 10 / (id - y) > 0 AND y = 0 on a table containing (5, 5) returns no rows without an error. (y < 3 OR 10 / x > 1) AND y = 5 on a row with y = 1 and x = 0, and coalesce(m[k], 10 / x) > 0 AND k = 'a' on a row with k = 'b', m = map('b', 1.0) and x = 0, raise no error. Under ANSI mode, SELECT g, sum(x) AS s FROM t GROUP BY g HAVING s = 5 AND (s < 3 OR 10 / g > 1) raises no error on a table whose only group has g = 0 and s = 1.

    Verification:

  • Regression: Under ANSI mode, the safe-division guard query and the PR's headline query on the data in the postconditions return the base branch's results instead of DIVIDE_BY_ZERO.

  • Regression: Under ANSI mode, the Or, Coalesce and HAVING short-circuit queries in the postconditions raise no error on rows or groups that fail the equality, and the rule leaves a short-circuit guard unrewritten when an operand after it can fail.

  • Compatibility: Filters in which no other conjunct still refers to a propagated column after the rewrite keep their conjunct order, and the existing propagation cases, such as a = 1 AND b > a + 2 becoming a = 1 AND b > 3, still hold.
  • Decision challenges

    Keep propagating into CASE/IF whose conditional parts cannot fail?

    replace now stops at any operator outside the allowlist, so a CASE WHEN or IF over plain columns keeps its attributes even though nothing in it can fail. For SELECT x FROM t WHERE y = 5 AND CASE WHEN y > 0 THEN x ELSE z END > 1, the base branch rewrote the filter to x > 1 AND y = 5, pushed x > 1 to Parquet, and pruned z from the scan. With this change the CASE stays, so the scan also reads z and every row evaluates the CASE. Constraint inference still adds a substituted copy that simplifies to x > 1, so that pushdown survives at the current base, but it would be lost without the copy, for example with constraint propagation disabled or if #60162 stops inferring through such operators. For a CASE whose other branch can fail, the change does remove real failures. A cheaper implementation with the same results would also descend through CaseWhen and If when every part the conditional evaluates only for some rows, meaning each value branch and every WHEN condition after the first, passes ExprUtils.canEvaluateUnconditionally. A different branch choice then cannot unmask an error, and these rewrites come back, at the cost of more policy in the rule. Would you adopt that, or keep the current boundary and accept this cost for such filters?

    Which end state does #60162 give filters with kept conjuncts?

    Verified in the reviewed source at the current base: every conjunct this rule now keeps also gets a literal-substituted copy from inferConstraintsFromLiteralBindings, which InferFiltersFromConstraints prepends, and both are evaluated. With a deterministic Python UDF, y = 5 AND py_udf(x, y) > 0 ends up with py_udf(x, 5) > 0 and py_udf(x, y) > 0, so the Python evaluation node computes two calls for each row with y = 5, where the base branch computed one. A Scala UDF or other expensive kept expression also runs twice on rows that pass the first copy. Those same copies currently provide the simplified, pushable forms, such as x > 1 from CASE WHEN 5 > 0 THEN x ELSE z END > 1, or x / 5 > 1 propagated across a join on x. Not verifiable here is what #60162 does to them, because it is not in the base. If it stops substituting through operators that can fail, the double evaluation goes away along with those simplified forms; if it only reorders or filters the copies, the double evaluation stays. Could you confirm which end state #60162 produces, and land the two together, or fold its change in, with a full-optimizer plan test that pins the outcome you choose?

    Not verified by this review (environment unavailable). Repro sketch:

    With ANSI on, run on this PR's head, then on the head with #60162 applied. Write spark.range(1000).selectExpr("id AS x", "id % 10 AS y", "id AS z") to Parquet and register it as view t, and register a deterministic Python UDF py_udf(x, y) that returns x + y. (1) EXPLAIN EXTENDED SELECT FROM t WHERE y = 5 AND py_udf(x, y) > 0: count the UDF calls in the BatchEvalPython or ArrowEvalPython node (two at this base, one on the base branch). (2) EXPLAIN SELECT x FROM t WHERE y = 5 AND CASE WHEN y > 0 THEN x ELSE z END > 1: check whether x > 1 is among the Parquet PushedFilters and whether z is read. A full-optimizer plan test asserting both outcomes pins the chosen end state.

    Keep substituting into correlated arithmetic that cannot fail?

    Pulled-up correlated IN/EXISTS conditions now go through the same restricted replace, so a comparison that mixes an inner column with a constant-bound outer column keeps the outer column even when the arithmetic cannot fail. For SELECT FROM l WHERE l.b = 5.0 AND l.a NOT IN (SELECT c FROM r WHERE r.d + l.b > 10) with DOUBLE columns, the base branch rewrote the condition to r.d + 5.0 > 10, pushed it into r, and planned a null-aware BroadcastHashJoin. With this change r.d + l.b > 10 stays in the anti-join condition, the null-aware pattern no longer matches, and the plan becomes a BroadcastNestedLoopJoin over all of r, O(NM) instead of O(N + M); EXISTS and IN keep an unfiltered subquery side in the same way. The change does remove real failures here, such as a pushed r.d / 0 or a BIGINT overflow evaluated on r rows when no outer row qualifies. A cheaper implementation with the same results would treat arithmetic that cannot fail for its type and eval mode as substitutable, such as Add, Subtract and Multiply on floating-point types or any non-ANSI mode, at the cost of type- and mode-aware policy in the rule. The SPARK-32290 test uses d = b + 10, which still folds, so it does not cover this. Would you adopt that policy, or accept the cost and adjust the description's statement that these conditions are still rewritten as before?

    Generated by Omnigent on Databricks
    <!-- SPARK_OSS_REVIEW_REQUEST 35318168142 -->

    <!-- SPARK_DEV_REVIEW_CODE {"findings":[{"delivery":"summary","fingerprint":"cbb1742c3bf6ee8e589c","id":"finding:5f9c32811605e48fb013"},{"delivery":"inline","fingerprint":"c0902b5b6fa4bb4b047d","id":"pass-a:A1-subquery-joincond-crash"},{"delivery":"inline","fingerprint":"7fa5e26b7bbd59c1574e","id":"pass-a:A4-kept-attributes-reexpose-errors"},{"delivery":"inline","fingerprint":"d24ae9e0c97776b8d626","id":"pass-a:A5-short-circuit-incomplete-fix"},{"delivery":"inline","fingerprint":"547466570a0a0ef5268e","id":"pass-b:B3-condition-container-test-gap"},{"delivery":"inline","fingerprint":"c9d2ebe5bcc4125f1da5","id":"pass-b:B4-canfold-discards-folded-literal"}],"head_sha":"aac28a56fc39b6093b7ed9b1b870852dc6242850","verdict_sha256":"8df67edf746edcb4fee72ce5a018aa0b7bf1f4bae9b507a3c9fb507ed8220524"} -->

    dongjoon-hyun dongjoon-hyun commented on code on Nov 06, 2026 16:34 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:1
    @@ -230,21 +230,51 @@ object ConstantPropagation extends Rule[LogicalPlan] {
       private def safeToReplace(ar: AttributeReference, nullIsFalse: Boolean) =
         !ar.nullable || nullIsFalse
     
    +  /**
    +   * Replaces attributes in the comparisons of `condition` with their constant values.
    +   *
    +   * The constant is the value of an attribute only on the rows that pass the whole condition.
    +   * The rewritten condition also runs on other rows, e.g. a row with `y = 1` for
    +   * `10 / (id - y) > 0 AND y = 0`, and a part of it that becomes constant is folded with no row
    +   * at all, e.g. `10 / y` for `y = 0 AND id > 10 / y`. So that this raises no error the original
    +   * condition cannot raise, an expression that can fail keeps its attributes, unless all of them
    +   * are replaced and the result evaluates without an error.
    +   */
       private def replaceConstants(
           condition: Expression,
           equalityPredicates: AttributeMap[(Literal, BinaryComparison)]): Expression = {
         val constantsMap = AttributeMap(equalityPredicates.map { case (attr, (lit, _)) => attr -> lit })
         val predicates = equalityPredicates.values.map(_._2).toSet
         def replaceInComparison(b: BinaryComparison): Expression = {
           lazy val collationSafeReplacement = isSameCollationAttrRefComparison(b)
    -      b transform {
    -        case a: AttributeReference
    -          if isBinaryStable(a.dataType) || collationSafeReplacement =>
    -          constantsMap.getOrElse(a, a)
    +      def canReplace(a: Attribute): Boolean =
    +        constantsMap.contains(a) && (isBinaryStable(a.dataType) || collationSafeReplacement)
    +      def replace(e: Expression): Expression = e match {
    +        case a: AttributeReference if canReplace(a) => constantsMap(a)
    +        case _ if ExprUtils.isTotalOperator(e) => e.mapChildren(replace)
    +        case _ if e.references.nonEmpty && e.references.forall(canReplace) =>
    +          val replaced = e.transform { case a: AttributeReference => constantsMap(a) }

    Thank you. Confirmed: with INT columns, t1.a = 1 AND t1.b = (SELECT max(t2.b) FROM t2 WHERE t2.a = t1.a) fails with java.util.NoSuchElementException: key not found during the optimization. With BIGINT columns, t1.a = 1 is still t1.a = CAST(1 AS BIGINT) in the first iteration, and the subquery becomes a join before the rule sees a literal. Fixed in the latest commit by replacing only the attributes that canReplace accepts, so the subquery keeps its condition and is not folded. Added SPARK-60983: Propagate a constant into a comparison with a correlated scalar subquery to SubquerySuite.

    dongjoon-hyun dongjoon-hyun commented on code on Nov 06, 2026 16:34 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:1
    @@ -230,21 +230,51 @@ object ConstantPropagation extends Rule[LogicalPlan] {
       private def safeToReplace(ar: AttributeReference, nullIsFalse: Boolean) =
         !ar.nullable || nullIsFalse
     
    +  /**
    +   * Replaces attributes in the comparisons of `condition` with their constant values.
    +   *
    +   * The constant is the value of an attribute only on the rows that pass the whole condition.
    +   * The rewritten condition also runs on other rows, e.g. a row with `y = 1` for
    +   * `10 / (id - y) > 0 AND y = 0`, and a part of it that becomes constant is folded with no row
    +   * at all, e.g. `10 / y` for `y = 0 AND id > 10 / y`. So that this raises no error the original
    +   * condition cannot raise, an expression that can fail keeps its attributes, unless all of them
    +   * are replaced and the result evaluates without an error.
    +   */
       private def replaceConstants(
           condition: Expression,
           equalityPredicates: AttributeMap[(Literal, BinaryComparison)]): Expression = {
         val constantsMap = AttributeMap(equalityPredicates.map { case (attr, (lit, _)) => attr -> lit })
         val predicates = equalityPredicates.values.map(_._2).toSet
         def replaceInComparison(b: BinaryComparison): Expression = {
           lazy val collationSafeReplacement = isSameCollationAttrRefComparison(b)
    -      b transform {
    -        case a: AttributeReference
    -          if isBinaryStable(a.dataType) || collationSafeReplacement =>
    -          constantsMap.getOrElse(a, a)
    +      def canReplace(a: Attribute): Boolean =
    +        constantsMap.contains(a) && (isBinaryStable(a.dataType) || collationSafeReplacement)
    +      def replace(e: Expression): Expression = e match {
    +        case a: AttributeReference if canReplace(a) => constantsMap(a)
    +        case _ if ExprUtils.isTotalOperator(e) => e.mapChildren(replace)
    +        case _ if e.references.nonEmpty && e.references.forall(canReplace) =>
    +          val replaced = e.transform { case a: AttributeReference => constantsMap(a) }
    +          if (canFold(replaced)) replaced else e
    +        case _ => e

    Thank you. Confirmed: d <> 0 AND n / d > 1 AND d = 5 returns (10, 5) without this PR, and fails with DIVIDE_BY_ZERO with it. In the latest commit, when a conjunct that can fail still refers to a propagated attribute, the rule moves the equalities ahead of the other conjuncts, so the query returns (10, 5) again. An equality between an attribute and a literal cannot fail, so this raises no new error. Conjuncts that cannot fail, such as isnotnull(d), do not trigger it, and no PlanStabilitySuite golden file changes. 10 / (id - y) > 0 AND y = 0 on (5, 5) also returns no rows again, as without this PR.

    dongjoon-hyun dongjoon-hyun commented on code on Nov 06, 2026 16:34 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:1
    @@ -230,21 +230,51 @@ object ConstantPropagation extends Rule[LogicalPlan] {
       private def safeToReplace(ar: AttributeReference, nullIsFalse: Boolean) =
         !ar.nullable || nullIsFalse
     
    +  /**
    +   * Replaces attributes in the comparisons of `condition` with their constant values.
    +   *
    +   * The constant is the value of an attribute only on the rows that pass the whole condition.
    +   * The rewritten condition also runs on other rows, e.g. a row with `y = 1` for
    +   * `10 / (id - y) > 0 AND y = 0`, and a part of it that becomes constant is folded with no row
    +   * at all, e.g. `10 / y` for `y = 0 AND id > 10 / y`. So that this raises no error the original
    +   * condition cannot raise, an expression that can fail keeps its attributes, unless all of them
    +   * are replaced and the result evaluates without an error.
    +   */
       private def replaceConstants(
           condition: Expression,
           equalityPredicates: AttributeMap[(Literal, BinaryComparison)]): Expression = {
         val constantsMap = AttributeMap(equalityPredicates.map { case (attr, (lit, _)) => attr -> lit })
         val predicates = equalityPredicates.values.map(_._2).toSet
         def replaceInComparison(b: BinaryComparison): Expression = {
           lazy val collationSafeReplacement = isSameCollationAttrRefComparison(b)
    -      b transform {
    -        case a: AttributeReference
    -          if isBinaryStable(a.dataType) || collationSafeReplacement =>
    -          constantsMap.getOrElse(a, a)
    +      def canReplace(a: Attribute): Boolean =
    +        constantsMap.contains(a) && (isBinaryStable(a.dataType) || collationSafeReplacement)
    +      def replace(e: Expression): Expression = e match {
    +        case a: AttributeReference if canReplace(a) => constantsMap(a)
    +        case _ if ExprUtils.isTotalOperator(e) => e.mapChildren(replace)
    +        case _ if e.references.nonEmpty && e.references.forall(canReplace) =>
    +          val replaced = e.transform { case a: AttributeReference => constantsMap(a) }
    +          if (canFold(replaced)) replaced else e
    +        case _ => e
           }
    +      b.mapChildren(replace)
    +    }
    +    def replaceInCondition(e: Expression): Expression = e match {
    +      case b: BinaryComparison if predicates.contains(b) => b
    +      case b: BinaryComparison => replaceInComparison(b)
    +      case _ if ExprUtils.isTotalOperator(e) => e.mapChildren(replaceInCondition)

    Thank you. As you mentioned, this is not introduced by this PR: (y < 3 OR 10 / x > 1) AND y = 5 and the HAVING query fail the same way without it. The reordering above does not change them either, because the rewritten operand no longer refers to y. Since this needs its own policy for the operands of OR, AND, COALESCE and IN, I'd like to handle it in a separate JIRA issue.

    dongjoon-hyun dongjoon-hyun commented on code on Nov 06, 2026 16:34 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:1
    @@ -230,21 +230,51 @@ object ConstantPropagation extends Rule[LogicalPlan] {
       private def safeToReplace(ar: AttributeReference, nullIsFalse: Boolean) =
         !ar.nullable || nullIsFalse
     
    +  /**
    +   * Replaces attributes in the comparisons of `condition` with their constant values.
    +   *
    +   * The constant is the value of an attribute only on the rows that pass the whole condition.
    +   * The rewritten condition also runs on other rows, e.g. a row with `y = 1` for
    +   * `10 / (id - y) > 0 AND y = 0`, and a part of it that becomes constant is folded with no row
    +   * at all, e.g. `10 / y` for `y = 0 AND id > 10 / y`. So that this raises no error the original
    +   * condition cannot raise, an expression that can fail keeps its attributes, unless all of them
    +   * are replaced and the result evaluates without an error.
    +   */
       private def replaceConstants(
           condition: Expression,
           equalityPredicates: AttributeMap[(Literal, BinaryComparison)]): Expression = {
         val constantsMap = AttributeMap(equalityPredicates.map { case (attr, (lit, _)) => attr -> lit })
         val predicates = equalityPredicates.values.map(_._2).toSet
         def replaceInComparison(b: BinaryComparison): Expression = {
           lazy val collationSafeReplacement = isSameCollationAttrRefComparison(b)
    -      b transform {
    -        case a: AttributeReference
    -          if isBinaryStable(a.dataType) || collationSafeReplacement =>
    -          constantsMap.getOrElse(a, a)
    +      def canReplace(a: Attribute): Boolean =
    +        constantsMap.contains(a) && (isBinaryStable(a.dataType) || collationSafeReplacement)
    +      def replace(e: Expression): Expression = e match {
    +        case a: AttributeReference if canReplace(a) => constantsMap(a)
    +        case _ if ExprUtils.isTotalOperator(e) => e.mapChildren(replace)
    +        case _ if e.references.nonEmpty && e.references.forall(canReplace) =>
    +          val replaced = e.transform { case a: AttributeReference => constantsMap(a) }
    +          if (canFold(replaced)) replaced else e
    +        case _ => e
           }
    +      b.mapChildren(replace)
    +    }
    +    def replaceInCondition(e: Expression): Expression = e match {
    +      case b: BinaryComparison if predicates.contains(b) => b
    +      case b: BinaryComparison => replaceInComparison(b)
    +      case _ if ExprUtils.isTotalOperator(e) => e.mapChildren(replaceInCondition)
    +      // The children of these include the comparisons of a pulled up correlated condition.
    +      case _: InSubquery | _: ListQuery | _: Exists => e.mapChildren(replaceInCondition)
    +      case _ => e

    Thank you. Added an IF case to the test in the latest commit. It fails if the rule rewrites the comparison in the condition of the IF.

    dongjoon-hyun dongjoon-hyun commented on code on Nov 06, 2026 16:35 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:1
    @@ -230,21 +230,51 @@ object ConstantPropagation extends Rule[LogicalPlan] {
       private def safeToReplace(ar: AttributeReference, nullIsFalse: Boolean) =
         !ar.nullable || nullIsFalse
     
    +  /**
    +   * Replaces attributes in the comparisons of `condition` with their constant values.
    +   *
    +   * The constant is the value of an attribute only on the rows that pass the whole condition.
    +   * The rewritten condition also runs on other rows, e.g. a row with `y = 1` for
    +   * `10 / (id - y) > 0 AND y = 0`, and a part of it that becomes constant is folded with no row
    +   * at all, e.g. `10 / y` for `y = 0 AND id > 10 / y`. So that this raises no error the original
    +   * condition cannot raise, an expression that can fail keeps its attributes, unless all of them
    +   * are replaced and the result evaluates without an error.
    +   */
       private def replaceConstants(
           condition: Expression,
           equalityPredicates: AttributeMap[(Literal, BinaryComparison)]): Expression = {
         val constantsMap = AttributeMap(equalityPredicates.map { case (attr, (lit, _)) => attr -> lit })
         val predicates = equalityPredicates.values.map(_._2).toSet
         def replaceInComparison(b: BinaryComparison): Expression = {
           lazy val collationSafeReplacement = isSameCollationAttrRefComparison(b)
    -      b transform {
    -        case a: AttributeReference
    -          if isBinaryStable(a.dataType) || collationSafeReplacement =>
    -          constantsMap.getOrElse(a, a)
    +      def canReplace(a: Attribute): Boolean =
    +        constantsMap.contains(a) && (isBinaryStable(a.dataType) || collationSafeReplacement)
    +      def replace(e: Expression): Expression = e match {
    +        case a: AttributeReference if canReplace(a) => constantsMap(a)
    +        case _ if ExprUtils.isTotalOperator(e) => e.mapChildren(replace)
    +        case _ if e.references.nonEmpty && e.references.forall(canReplace) =>
    +          val replaced = e.transform { case a: AttributeReference => constantsMap(a) }
    +          if (canFold(replaced)) replaced else e

    Thank you. In the latest commit, canFold became fold, which returns the folded literal, so the constant is evaluated once.

    dongjoon-hyun dongjoon-hyun commented on Nov 06, 2026 16:35 UTC
    Author

    Thank you for the review, @spark-test. I ran the queries in the review on this PR with and without #60162.

  • Constraint inference: Yes. As the description says, this PR should be merged after #60162. With it, the queries in the description, including id > 5 AND y = 0 AND 10 / (id - y) > 0, return their results.

  • CASE/IF: Confirmed. With #60162, y = 5 AND CASE WHEN y > 0 THEN x ELSE z END > 1 no longer pushes x > 1 down and reads z. I'd keep the current boundary in this PR. Rewriting through a CASE WHEN or IF whose conditional parts cannot fail can be a separate improvement.

  • #60162 end state: #60162 does not infer a filter that can fail, so the copies are gone. The UDF in y = 5 AND f(x, y) > 0 runs once per row (10 calls for 10 rows), and x > 1 is not inferred from the CASE above.

  • Correlated arithmetic: Confirmed. l.b = 5.0 AND l.a NOT IN (SELECT c FROM r WHERE r.d + l.b > 10) becomes a broadcast nested loop join instead of a null-aware broadcast hash join. I'd accept this cost for now, since it needs arithmetic over an outer column that is bound to a literal. I updated the description, which said that these conditions were rewritten as before.
  • dongjoon-hyun dongjoon-hyun commented on Nov 07, 2026 02:38 UTC
    Author
    Reviewers
    Assignees
    dongjoon-hyun dongjoon-hyun
    Labels
    risk: low confidence: 81.1% 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: 37.4% (MEDIUM) · Higher = larger blast radius
    37.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: 81.1% · Lower = rushed or shallow review
    81.1%
    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: 7.1% · Safe to merge
    7.1%
    Repository