This is an automated email from the ASF dual-hosted git repository.

MaxGekk pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark.git


The following commit(s) were added to refs/heads/master by this push:
     new 9d6d9af05028 [SPARK-60332][SQL] Evaluate a predicate's common 
subexpressions at their first conjunct
9d6d9af05028 is described below

commit 9d6d9af05028d5732c349aa25dca3e26186458bb
Author: Max Gekk <[email protected]>
AuthorDate: Tue Nov 10 15:42:25 2026 +0100

    [SPARK-60332][SQL] Evaluate a predicate's common subexpressions at their 
first conjunct
    
    ### What changes were proposed in this pull request?
    
    With whole-stage codegen disabled, `FilterExec` evaluates its condition 
through `Predicate.create`, which under the default factory mode builds a 
`GeneratePredicate` with subexpression elimination. `GeneratePredicate` 
evaluated every common subexpression of the condition before the condition 
itself (`subexprFunctionsCode`), so a subexpression shared only by conjuncts 
after a FALSE conjunct was evaluated on a row that `And.eval` drops at that 
conjunct, and an error it raised failed the [...]
    
    This PR makes `GeneratePredicate` evaluate a common subexpression just 
before the first top-level conjunct that references it, as the CSE branch of 
`FilterExec.doConsume` does with whole-stage codegen on (SPARK-56032):
    
    - When subexpression elimination is on and the predicate has several 
top-level conjuncts, `GeneratePredicate.create` calls the new 
`CodegenContext.generateConjunctsWithSubexprCodes`, which generates each 
conjunct with the calls of the subexpressions to evaluate before it, and 
evaluates the conjuncts like `And.eval`: a FALSE conjunct returns false, a NULL 
one sets a flag and the evaluation goes on, and the condition is TRUE only if 
all conjuncts are. Otherwise, and when no subexpressio [...]
    - The common subexpressions are found in the whole predicate, as 
`generateExpressions` finds them, so that the same subexpressions are 
eliminated as before: none inside a task for a predicate that holds a plan 
expression (SPARK-38333), and only those of the first conjunct with 
`spark.sql.subexpressionElimination.skipForShortcutExpr`. The predicate is then 
split into its conjuncts, keeping an `AND` of the top-level chain that is 
itself a common subexpression, e.g. one repeated under `N [...]
    - The function of a subexpression that contains an eliminated subexpression 
reads the state of the latter, so the calls before a conjunct are ordered by 
their dependencies: a contained subexpression is called before the conjunct 
that first references the containing one, even when its own first reference is 
later. A conjunct can contain a copy of the containing subexpression without 
the contained one, e.g. `(a + c) + b` for `(a + b) + c` under the 
canonicalization of `+`.
    - The checks of the conjuncts are split into functions through 
`splitExpressions` when their code exceeds 
`spark.sql.codegen.methodSplitThreshold`, each returning false at a FALSE 
conjunct, so that `eval` stays within the JIT limits for a predicate with many 
conjuncts; the NULL-conjunct flag is a field for that, reset at the start of 
`eval`. A predicate within the threshold keeps a single inline block.
    - `CodegenContext.firstReferencingExpression` computes the first conjunct 
that references a subexpression, shared with the CSE branch of 
`FilterExec.doConsume`.
    
    The subexpression elimination itself does not change: a subexpression 
common to several conjuncts, or repeated within one, is still evaluated once. 
Only its place in the generated code moves, from before the condition to before 
the first conjunct that references it.
    
    The alternative, the internal config 
`spark.sql.subexpressionElimination.skipForShortcutExpr` (SPARK-42815), avoids 
the error by excluding everything after the first operand of an `AND`/`OR` 
chain from subexpression elimination, so a filter condition gets no elimination 
past its first conjunct. Emitting the subexpression at the first use site 
inside the generated `And` code was rejected too: a subexpression common to all 
the branches of a conditional expression would be evaluated in t [...]
    
    Not fixed here, on master as well as after this PR: a subexpression whose 
first occurrence is in a conditionally evaluated part of a conjunct, such as a 
`CASE WHEN` branch, is still evaluated before that conjunct, in both 
generators. That is tracked in SPARK-60774.
    
    Also not fixed here, the same as on master: an `AND` of the top-level chain 
that is itself a common subexpression stays one conjunct, so a subexpression 
first referenced inside it is evaluated before its first operand is checked. 
For example, `b < 0 AND y + 1 > 0`, when an `IF` condition repeats it, keeps 
evaluating `y + 1` before `b < 0`. That is tracked in SPARK-61197.
    
    ### Why are the changes needed?
    
    The same query must not fail with whole-stage codegen off and return rows 
with it on (SPARK-60332). Reproducer (ANSI mode):
    
    ```sql
    CREATE TABLE t USING parquet AS
      SELECT * FROM VALUES (NULL, 1, 2147483647, NULL), (0, 1, 0, 1) AS v(a, b, 
y, x);
    SET spark.sql.parquet.filterPushdown=false;
    
    SET spark.sql.codegen.wholeStage=false;
    SELECT a FROM t WHERE x IS NOT NULL AND NOT (a > 0 AND b > 0) AND y + 1 > 0 
AND y + 1 > -1;
    -- before: [ARITHMETIC_OVERFLOW] overflow. ... SQLSTATE: 22003
    -- after:  0
    
    SET spark.sql.codegen.wholeStage=true;
    SELECT a FROM t WHERE x IS NOT NULL AND NOT (a > 0 AND b > 0) AND y + 1 > 0 
AND y + 1 > -1;
    -- before and after: 0
    ```
    
    On the first row `isnotnull(x)` is FALSE, so `And.eval` never reaches `y + 
1`, but the common `y + 1` was evaluated up front and overflowed. The same 
happens without a NULL conjunct, e.g. with `b < 0` as the first conjunct.
    
    This is independent of SPARK-60315 (a NULL conjunct stopping the evaluation 
with codegen on) and of SPARK-60329 (an `IS NOT NULL` check generated later 
than its position with codegen on): the inconsistency here is in the opposite 
direction, codegen off raised where codegen on drops the row. The common 
subexpressions of the update expressions of an aggregate function with a 
`FILTER` clause are a separate problem, SPARK-60393.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, a bug fix. A predicate evaluated through `Predicate.create` outside of 
whole-stage codegen, that is a filter condition with whole-stage codegen 
disabled, or a join condition on the non-codegen paths of the hash, sort-merge, 
broadcast nested loop and cartesian product joins, no longer raises an error 
from a subexpression shared by conjuncts after a FALSE one on a row that the 
FALSE conjunct drops, as `And.eval` does not. For example, `SELECT a FROM t 
WHERE b < 0 AND y + 1 > 0 AND  [...]
    
    ### How was this patch tested?
    
    - New tests in `CodegenSubexpressionEliminationSuite`, where 
`ExprWithEvaluatedState` now counts its evaluations: a `GeneratePredicate` over 
`And(And(first, Not(leaf)), Not(leaf))`, with and without subexpression 
elimination, checks that `leaf` is not evaluated when `first` is FALSE, and is 
evaluated once with the elimination and twice without when `first` is TRUE or 
NULL, with the result of `And.eval`; the same for a subexpression that only the 
second conjunct repeats, `EqualTo(Not(l [...]
    - A new test in `WholeStageCodegenSuite`, next to the SPARK-60315 tests: 
the reproducer above, the `b < 0` variant and a NULL-conjunct variant, with 
whole-stage codegen on and off and the legacy config on and off; a cartesian 
product whose condition has a common `y + 1` after a FALSE conjunct, with 
whole-stage codegen on and off; the `(a + c) + b` query over inline `VALUES`, 
which the optimizer filters through this generated predicate; and a filter with 
a scalar subquery over a cached [...]
    
    ```
    build/sbt 'catalyst/testOnly *CodegenSubexpressionEliminationSuite 
*SubexpressionEliminationSuite *CodeGenerationSuite *PredicateSuite'
    build/sbt 'sql/testOnly *WholeStageCodegenSuite *SQLQuerySuite *JoinSuite 
*SubquerySuite'
    ```
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Code (Claude Fable 5.1)
    
    🤖 Generated with [Claude Code](https://claude.com/claude-code)
    
    
    
    
    Closes #59984 from MaxGekk/SPARK-60332-predicate-cse-order.
    
    Authored-by: Max Gekk <[email protected]>
    Signed-off-by: Max Gekk <[email protected]>
    
    
    skip-checks: true
---
 docs/sql-migration-guide.md                        |   3 +-
 .../expressions/codegen/CodeGenerator.scala        | 179 +++++++++++++++-----
 .../expressions/codegen/GeneratePredicate.scala    |  59 ++++++-
 .../CodegenSubexpressionEliminationSuite.scala     | 187 ++++++++++++++++++++-
 .../sql/execution/basicPhysicalOperators.scala     |   2 +-
 .../sql/execution/WholeStageCodegenSuite.scala     |  86 +++++++++-
 6 files changed, 460 insertions(+), 56 deletions(-)

diff --git a/docs/sql-migration-guide.md b/docs/sql-migration-guide.md
index 62040c06a941..5d2750011456 100644
--- a/docs/sql-migration-guide.md
+++ b/docs/sql-migration-guide.md
@@ -29,6 +29,7 @@ license: |
 
 ## Upgrading from Spark SQL 4.3 to 4.4
 
+- Since Spark 4.4, a predicate evaluated through generated code outside of 
whole-stage codegen, such as a filter condition with whole-stage codegen 
disabled or a join condition, evaluates a subexpression common to its top-level 
conjuncts, whether several of them share it or one of them repeats it, just 
before the first conjunct that references it, instead of before the whole 
condition. So a `FALSE` conjunct before them stops the evaluation, as `AND` 
does when evaluated directly, and an e [...]
 - Since Spark 4.4, `make_timestamp`, `make_timestamp_ltz` and 
`make_timestamp_ntz` return `NULL` for a seconds value above 2147.483647 or 
below -2147.483648, or raise `DATETIME_FIELD_OUT_OF_BOUNDS` when 
`spark.sql.ansi.enabled` is `true`, as they do for other out-of-range seconds 
such as 61; `try_make_timestamp`, `try_make_timestamp_ltz` and 
`try_make_timestamp_ntz` return `NULL`. Previously, such a value wrapped around 
modulo 2^32 microseconds and could return a wrong timestamp, for exa [...]
 - Since Spark 4.4, dividing an ANSI interval by a number raises 
`INTERVAL_ARITHMETIC_OVERFLOW.WITH_SUGGESTION` (SQLSTATE 22015) whenever the 
result does not fit the interval type, in every evaluation mode. Previously, 
dividing the minimum year-month or day-time interval by `-1` raised 
`ARITHMETIC_OVERFLOW` (SQLSTATE 22003) in generated code, and dividing an 
interval by a decimal or a floating-point number whose quotient, once rounded, 
does not fit the type, or is infinite, raised a `java [...]
 - Since Spark 4.4, when a file source reads a partition column with a 
user-specified `DECIMAL` type from directory names, it converts each value to 
the precision and scale of that type, rounding half up as `CAST` does. 
Previously, the vectorized Parquet and ORC readers applied the declared scale 
to the digits in the directory name without an error, for example `d=1.5` read 
as `DECIMAL(10,2)` returned `0.15`. Data derived from affected query results 
may need to be recomputed. A value that [...]
@@ -79,7 +80,7 @@ license: |
 - Since Spark 4.4, the value columns of `UNPIVOT` and `Dataset.unpivot` merge 
the nested nullability (array element, map value, and struct field nullability) 
of all unpivoted values. Previously, a value column took the nested nullability 
of the first listed value, so a `NULL` array element, map value, or struct 
field of a later value could be returned as a non-`NULL` value such as `0`, and 
`IS NULL` on it returned `false`. A view created by an earlier Spark version 
over such an `UNPIVOT` [...]
 - Since Spark 4.4, when `spark.sql.parquet.fieldId.read.enabled` is true, a 
Parquet read fails with `PARQUET_FIELD_REQUESTED_MORE_THAN_ONCE` if two or more 
requested fields of a struct (or of the top-level schema) resolve to the same 
Parquet field. This happens when one requested field is matched by field ID and 
another by name, or when two requested fields have the same field ID. In Spark 
4.3 and earlier, such a read returned wrong values without an error: with the 
vectorized reader one [...]
 - Since Spark 4.4, when `spark.sql.groupByOrdinal` is true (the default), the 
pipe `AGGREGATE` operator rejects an aliased integer literal in its `GROUP BY` 
clause, such as `TABLE t |> AGGREGATE sum(x) AS s GROUP BY 2 AS grp`, with 
`UNSUPPORTED_FEATURE.PIPE_OPERATOR_AGGREGATE_UNSUPPORTED_CASE`, because a bare 
integer literal in the same position is an ordinal. Previously the aliased 
literal was grouped as a constant. Bare ordinals and aliases on other grouping 
expressions are not affecte [...]
-- Since Spark 4.4, with whole-stage codegen enabled, a filter condition, 
including the `FILTER` clause of an aggregate function, evaluates the remaining 
top-level conjuncts of the condition on a row after one of them evaluates to 
`NULL`, as the SQL standard requires, and does so in the order they appear in 
the condition, as Spark already did with whole-stage codegen disabled, which 
also evaluates a subexpression shared by several conjuncts before the 
condition. Only a `FALSE` conjunct st [...]
+- Since Spark 4.4, with whole-stage codegen enabled, a filter condition, 
including the `FILTER` clause of an aggregate function, evaluates the remaining 
top-level conjuncts of the condition on a row after one of them evaluates to 
`NULL`, as the SQL standard requires, and does so in the order they appear in 
the condition, as Spark already did with whole-stage codegen disabled. Only a 
`FALSE` conjunct stops the evaluation. One exception: an `IS NOT NULL` check on 
a column, or on an express [...]
 - Since Spark 4.4, the optimizer no longer infers a filter from data 
constraints when evaluating the filter can fail, such as, in ANSI mode, 
integral or decimal arithmetic, a division or a narrowing cast, or when it 
calls a user-defined function. The check is conservative, so a few filters that 
cannot fail are not inferred either, such as `upper(s) = 'A'`. For example, 
with ANSI mode on, `SELECT * FROM t WHERE x = y AND 10 / y > 0` no longer adds 
the filter `10 / x > 0`, which failed wit [...]
 - Since Spark 4.4, when a format is specified, `to_timestamp`, 
`try_to_timestamp`, and `to_timestamp_ltz` cast a numeric first argument to a 
string and parse it with the format, for example `to_timestamp(20201231, 
'yyyyMMdd')` returns `2020-12-31 00:00:00`. This matches the existing behavior 
when `spark.sql.timestampType` is `TIMESTAMP_NTZ`. Previously, with the default 
`TIMESTAMP_LTZ` timestamp type, such calls failed with `INTERNAL_ERROR`. Note 
that the string form of the number is par [...]
 - Since Spark 4.4, the Spark Thrift Server logs a warning at startup when 
`hive.server2.enable.doAs` is `true` and `hive.server2.authentication` verifies 
user identities (any recognized type other than `NONE`/`NOSASL`), because 
executor-side data access still runs as the server's own service identity 
rather than the connecting user (SPARK-5159). Set 
`spark.sql.hive.thriftServer.allowIneffectiveDoAs` to `true` to acknowledge the 
limitation and silence the warning. Spark 5.0 is expected to [...]
diff --git 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/codegen/CodeGenerator.scala
 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/codegen/CodeGenerator.scala
index 7f71196c3111..81555ba6860d 100644
--- 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/codegen/CodeGenerator.scala
+++ 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/codegen/CodeGenerator.scala
@@ -2325,53 +2325,65 @@ class CodegenContext extends Logging {
   /**
    * Checks and sets up the state and codegen for subexpression elimination. 
This finds the
    * common subexpressions, generates the functions that evaluate those 
expressions and populates
-   * the mapping of common subexpressions to the generated functions.
+   * the mapping of common subexpressions to the generated functions. Returns 
the calls of the
+   * functions, in an order that evaluates a subexpression before the 
subexpressions that
+   * reference it.
    */
-  private def subexpressionElimination(expressions: Seq[Expression]): Unit = {
+  private def subexpressionElimination(expressions: Seq[Expression]): 
Seq[String] = {
     // Add each expression tree and compute the common subexpressions.
     expressions.foreach(equivalentExpressions.addExprTree(_))
 
     // Get all the expressions that appear at least twice and set up the state 
for subexpression
     // elimination.
     val commonExprs = equivalentExpressions.getCommonSubexpressions
-    commonExprs.foreach { expr =>
-      val fnName = freshName("subExpr")
-      val isNull = addMutableState(JAVA_BOOLEAN, "subExprIsNull")
-      val value = addMutableState(javaType(expr.dataType), "subExprValue")
-
-      // Generate the code for this expression tree and wrap it in a function.
-      val eval = expr.genCode(this)
-      val fn =
-        s"""
-           |private void $fnName(InternalRow $INPUT_ROW) {
-           |  ${eval.code}
-           |  $isNull = ${eval.isNull};
-           |  $value = ${eval.value};
-           |}
-           """.stripMargin
+    commonExprs.map(generateSubexprFunction)
+  }
 
-      // Add a state and a mapping of the common subexpressions that are 
associate with this
-      // state. Adding this expression to subExprEliminationExprMap means it 
will call `fn`
-      // when it is code generated. This decision should be a cost based one.
-      //
-      // The cost of doing subexpression elimination is:
-      //   1. Extra function call, although this is probably *good* as the JIT 
can decide to
-      //      inline or not.
-      // The benefit doing subexpression elimination is:
-      //   1. Running the expression logic. Even for a simple expression, it 
is likely more than 3
-      //      above.
-      //   2. Less code.
-      // Currently, we will do this for all non-leaf only expression trees 
(i.e. expr trees with
-      // at least two nodes) as the cost of doing it is expected to be low.
+  /**
+   * Generates the function that evaluates the common subexpression `expr` 
into a state, registers
+   * the state so that the code generated for an expression equal to `expr` 
reads it, and returns
+   * the call of the function. The subexpressions must be generated in an 
order that evaluates a
+   * subexpression before the subexpressions that contain it, so that the 
function of the latter
+   * reads the state of the former.
+   */
+  private def generateSubexprFunction(expr: Expression): String = {
+    val fnName = freshName("subExpr")
+    val isNull = addMutableState(JAVA_BOOLEAN, "subExprIsNull")
+    val value = addMutableState(javaType(expr.dataType), "subExprValue")
 
-      val subExprCode = s"${addNewFunction(fnName, fn)}($INPUT_ROW);"
-      subexprFunctions += subExprCode
-      val state = SubExprEliminationState(
-        ExprCode(code"$subExprCode",
-          JavaCode.isNullGlobal(isNull),
-          JavaCode.global(value, expr.dataType)))
-      subExprEliminationExprs += ExpressionEquals(expr) -> state
-    }
+    // Generate the code for this expression tree and wrap it in a function.
+    val eval = expr.genCode(this)
+    val fn =
+      s"""
+         |private void $fnName(InternalRow $INPUT_ROW) {
+         |  ${eval.code}
+         |  $isNull = ${eval.isNull};
+         |  $value = ${eval.value};
+         |}
+         """.stripMargin
+
+    // Add a state and a mapping of the common subexpressions that are 
associate with this
+    // state. Registering the state in `subExprEliminationExprs` makes the 
code generated for an
+    // expression equal to this one read the state instead of evaluating it; 
the caller places the
+    // returned call of `fn` before that code. This decision should be a cost 
based one.
+    //
+    // The cost of doing subexpression elimination is:
+    //   1. Extra function call, although this is probably *good* as the JIT 
can decide to
+    //      inline or not.
+    // The benefit doing subexpression elimination is:
+    //   1. Running the expression logic. Even for a simple expression, it is 
likely more than 3
+    //      above.
+    //   2. Less code.
+    // Currently, we will do this for all non-leaf only expression trees (i.e. 
expr trees with
+    // at least two nodes) as the cost of doing it is expected to be low.
+
+    val subExprCode = s"${addNewFunction(fnName, fn)}($INPUT_ROW);"
+    val state = SubExprEliminationState(
+      ExprCode(code"$subExprCode",
+        JavaCode.isNullGlobal(isNull),
+        JavaCode.global(value, expr.dataType)))
+    subExprEliminationExprs += ExpressionEquals(expr) -> state
+    subExprCode
   }
 
   /**
@@ -2385,10 +2397,99 @@ class CodegenContext extends Logging {
     // We need to make sure that we do not reuse stateful expressions. This is 
needed for codegen
     // as well because some expressions may implement `CodegenFallback`.
     val cleanedExpressions = 
expressions.map(_.freshCopyIfContainsStatefulExpression())
-    if (doSubexpressionElimination) 
subexpressionElimination(cleanedExpressions)
+    if (doSubexpressionElimination) {
+      subexprFunctions ++= subexpressionElimination(cleanedExpressions)
+    }
     cleanedExpressions.map(e => e.genCode(this))
   }
 
+  /**
+   * Returns the index of the first of `expressions` that references the 
common subexpression
+   * `subexpr`, or -1. When the expressions are evaluated in order and one of 
them can stop the
+   * evaluation, such as a FALSE conjunct of a predicate, the subexpression is 
evaluated right
+   * before that expression instead of before all of them (SPARK-56032, 
SPARK-60332). An
+   * occurrence in a conditionally evaluated part of an expression, such as a 
branch of CASE WHEN,
+   * counts as a reference, so the subexpression is still evaluated before 
such an expression.
+   */
+  def firstReferencingExpression(expressions: Seq[Expression], subexpr: 
ExpressionEquals): Int = {
+    expressions.indexWhere(_.exists(e => ExpressionEquals(e) == subexpr))
+  }
+
+  /**
+   * Generates the code of the top-level conjuncts of `predicate` with 
subexpression elimination,
+   * for a predicate whose conjuncts are evaluated in order and whose 
evaluation stops at a FALSE
+   * conjunct, as `And.eval` does.
+   *
+   * The common subexpressions are found in the whole predicate, as 
`generateExpressions` finds
+   * them, so that the same subexpressions are eliminated: none inside a task 
for a predicate that
+   * holds a plan expression, and only those of the first conjunct with
+   * `spark.sql.subexpressionElimination.skipForShortcutExpr`. The predicate 
is then split into
+   * its conjuncts, keeping an AND of the top-level chain that is itself a 
common subexpression as
+   * one conjunct, which reads the state of the subexpression. The common 
subexpressions that a
+   * conjunct contains are evaluated by functions called just before the first 
conjunct that
+   * references them, instead of before the whole predicate (SPARK-60332). The 
other ANDs of the
+   * chain are not generated themselves; only the conjuncts they join are, one 
by one. Returns,
+   * per conjunct, the code of the calls to put before it and the code of the 
conjunct, or None,
+   * generating nothing, when no subexpression is eliminated: the caller then 
generates the
+   * predicate as a whole.
+   *
+   * The function of a subexpression that contains an eliminated subexpression 
reads the state
+   * of the latter, so the calls are ordered by their dependencies: a 
contained subexpression is
+   * called before the conjunct that first references the containing one, even 
when its own first
+   * reference is later. A conjunct can contain a copy of the containing 
subexpression that lacks
+   * the contained one, e.g. `(a + c) + b` for `(a + b) + c` under the 
canonicalization of a
+   * commutative operator.
+   *
+   * This must be the only subexpression elimination on this context.
+   */
+  def generateConjunctsWithSubexprCodes(predicate: Expression): 
Option[Seq[(String, ExprCode)]] = {
+    val cleanedPredicate = predicate.freshCopyIfContainsStatefulExpression()
+    equivalentExpressions.addExprTree(cleanedPredicate)
+    val allCommonExprs = equivalentExpressions.getCommonSubexpressions
+    val commonEqs = allCommonExprs.map(ExpressionEquals(_)).toSet
+    def split(e: Expression): Seq[Expression] = e match {
+      case And(left, right) if !commonEqs.contains(ExpressionEquals(e)) =>
+        split(left) ++ split(right)
+      case _ => Seq(e)
+    }
+    if (allCommonExprs.isEmpty) {
+      None
+    } else {
+      // Every common subexpression is a conjunct or lies inside one, since 
only the ANDs that are
+      // not common are split. A contained one comes before the ones that 
contain it.
+      val conjuncts = split(cleanedPredicate)
+      val calls =
+        allCommonExprs.map(expr => ExpressionEquals(expr) -> 
generateSubexprFunction(expr))
+      val codes = conjuncts.map(e => e.genCode(this))
+      val callOf = calls.toMap
+      val eliminated = calls.map(_._1)
+      // The eliminated subexpressions that `expr` contains, other than itself.
+      def dependencies(expr: Expression): Seq[ExpressionEquals] = 
eliminated.filter { dep =>
+        expr.children.exists(_.exists(e => ExpressionEquals(e) == dep))
+      }
+      // The eliminated subexpressions by the conjunct that first references 
them, found once.
+      val byFirstReference = eliminated.groupBy(e => 
firstReferencingExpression(conjuncts, e))
+      val emitted = mutable.HashSet.empty[ExpressionEquals]
+      Some(codes.zipWithIndex.map { case (code, k) =>
+        val callsBefore = mutable.ArrayBuffer.empty[String]
+        def emit(subexpr: ExpressionEquals): Unit = {
+          if (!emitted.contains(subexpr)) {
+            dependencies(subexpr.e).foreach(emit)
+            emitted += subexpr
+            callsBefore += callOf(subexpr)
+          }
+        }
+        byFirstReference.getOrElse(k, Nil).foreach(emit)
+        val subexprs = if (callsBefore.isEmpty) {
+          ""
+        } else {
+          splitExpressions(callsBefore.toSeq, "subexprFunc_split", 
Seq("InternalRow" -> INPUT_ROW))
+        }
+        (subexprs, code)
+      })
+    }
+  }
+
   /**
    * get a map of the pair of a place holder and a corresponding comment
    */
diff --git 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/codegen/GeneratePredicate.scala
 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/codegen/GeneratePredicate.scala
index c246d07f189b..5b9bcae47309 100644
--- 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/codegen/GeneratePredicate.scala
+++ 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/codegen/GeneratePredicate.scala
@@ -38,8 +38,59 @@ object GeneratePredicate extends CodeGenerator[Expression, 
BasePredicate] {
     val ctx = newCodeGenContext()
 
     // Do sub-expression elimination for predicates.
-    val eval = ctx.generateExpressions(Seq(predicate), 
useSubexprElimination).head
-    val evalSubexpr = ctx.subexprFunctionsCode
+    // With a subexpression common to the top-level conjuncts, whether several 
of them share it or
+    // one of them repeats it, the conjuncts are generated one by one, and the 
subexpression is
+    // evaluated just before the first conjunct that references it, not before 
the whole
+    // condition, so that a FALSE conjunct before them stops the evaluation, 
as `And.eval` and the
+    // whole-stage codegen of a filter do (SPARK-60332). The conjuncts are 
evaluated like
+    // `And.eval`: a FALSE one stops the evaluation, a NULL one does not, and 
the condition is TRUE
+    // only if all of them are. Otherwise the condition is generated as a 
whole, as before.
+    val severalConjuncts = predicate.isInstanceOf[And]
+    val conjunctCodes = if (useSubexprElimination && severalConjuncts) {
+      ctx.generateConjunctsWithSubexprCodes(predicate)
+    } else {
+      None
+    }
+    val evalCode = conjunctCodes match {
+      case Some(codes) =>
+        // A field rather than a local variable, since the checks of the 
conjuncts are split into
+        // functions when their code is long, see `splitExpressions`, with a 
FALSE conjunct
+        // returning false from its function and from `eval`.
+        val nullConjunct = ctx.addMutableState(CodeGenerator.JAVA_BOOLEAN, 
"nullConjunct")
+        val checks = codes.map { case (subexprs, ev) =>
+          s"""
+             |$subexprs
+             |${ev.code}
+             |if (${ev.isNull}) {
+             |  $nullConjunct = true;
+             |} else if (!${ev.value}) {
+             |  return false;
+             |}
+           """.stripMargin
+        }
+        val checksCode = ctx.splitExpressions(
+          checks,
+          "evalConjuncts",
+          Seq("InternalRow" -> ctx.INPUT_ROW),
+          returnType = "boolean",
+          makeSplitFunction = body => s"$body\nreturn true;",
+          foldFunctions = calls => calls.map(call => s"if (!$call) return 
false;").mkString("\n"))
+        s"""
+           |$nullConjunct = false;
+           |$checksCode
+           |return !$nullConjunct;
+         """.stripMargin
+      case None =>
+        // With more than one conjunct, no subexpression is eliminated when 
they were looked at, so
+        // the elimination is not run again on them.
+        val eliminate = useSubexprElimination && !severalConjuncts
+        val eval = ctx.generateExpressions(Seq(predicate), eliminate).head
+        s"""
+           |${ctx.subexprFunctionsCode}
+           |${eval.code}
+           |return !${eval.isNull} && ${eval.value};
+         """.stripMargin
+    }
 
     val codeBody = s"""
       public SpecificPredicate generate(Object[] references) {
@@ -60,9 +111,7 @@ object GeneratePredicate extends CodeGenerator[Expression, 
BasePredicate] {
         }
 
         public boolean eval(InternalRow ${ctx.INPUT_ROW}) {
-          $evalSubexpr
-          ${eval.code}
-          return !${eval.isNull} && ${eval.value};
+          $evalCode
         }
 
         ${ctx.declareAddedFunctions()}
diff --git 
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/codegen/CodegenSubexpressionEliminationSuite.scala
 
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/codegen/CodegenSubexpressionEliminationSuite.scala
index 471f25356887..a1df4c114638 100644
--- 
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/codegen/CodegenSubexpressionEliminationSuite.scala
+++ 
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/codegen/CodegenSubexpressionEliminationSuite.scala
@@ -20,12 +20,14 @@ package org.apache.spark.sql.catalyst.expressions.codegen
 import org.apache.spark.SparkFunSuite
 import org.apache.spark.sql.catalyst.InternalRow
 import org.apache.spark.sql.catalyst.expressions._
-import org.apache.spark.sql.types.{BooleanType, DataType}
+import org.apache.spark.sql.catalyst.plans.SQLHelper
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{BooleanType, DataType, IntegerType}
 
 /**
  * A test suite that makes sure code generation handles sub-expression 
elimination correctly.
  */
-class CodegenSubexpressionEliminationSuite extends SparkFunSuite {
+class CodegenSubexpressionEliminationSuite extends SparkFunSuite with 
SQLHelper {
 
   test("SPARK-32903: GeneratePredicate should eliminate sub-expressions") {
     Seq(true, false).foreach { useSubexprElimination =>
@@ -56,18 +58,189 @@ class CodegenSubexpressionEliminationSuite extends 
SparkFunSuite {
     }
   }
 
+  test("SPARK-60332: GeneratePredicate evaluates a common subexpression of 
later conjuncts " +
+      "after the conjuncts before it") {
+    // `Not(leaf)` is common to the last two conjuncts, and evaluated just 
before the first of
+    // them, so the first conjunct decides whether `leaf` is evaluated at all: 
a FALSE one stops
+    // the evaluation, while a TRUE or a NULL one does not, as `And.eval` 
does. With the
+    // elimination, `leaf` is evaluated once for both conjuncts, otherwise 
once per conjunct.
+    Seq(true, false).foreach { useSubexprElimination =>
+      Seq((false, 0, false), (true, 1, true), (null, 1, false)).foreach {
+        case (first, leafEvaluations, result) =>
+          // Distinct `id`s, so that the first conjunct and the leaf are not 
the same expression.
+          val leaf = ExprWithEvaluatedState(id = 1)
+          val cond = And(And(ExprWithEvaluatedState(first, isNullable = first 
== null),
+            Not(leaf)), Not(leaf))
+          val instance = GeneratePredicate.generate(cond, 
useSubexprElimination)
+          instance.initialize(0)
+          withClue(s"useSubexprElimination = $useSubexprElimination, first = 
$first: ") {
+            assert(instance.eval(null) === result)
+            val expected = if (useSubexprElimination) leafEvaluations else 2 * 
leafEvaluations
+            assert(leaf.evaluations === expected)
+          }
+      }
+    }
+  }
+
+  test("SPARK-60332: GeneratePredicate evaluates a common subexpression that 
one conjunct " +
+      "repeats after the conjuncts before it") {
+    // `Not(leaf)` is repeated only by the second conjunct, and evaluated just 
before it, so a
+    // FALSE first conjunct stops the evaluation of `leaf`, as `And.eval` does.
+    Seq(true, false).foreach { useSubexprElimination =>
+      Seq((false, 0, false), (true, 1, true), (null, 1, false)).foreach {
+        case (first, leafEvaluations, result) =>
+          val leaf = ExprWithEvaluatedState(id = 1)
+          val cond = And(ExprWithEvaluatedState(first, isNullable = first == 
null),
+            EqualTo(Not(leaf), Not(leaf)))
+          val instance = GeneratePredicate.generate(cond, 
useSubexprElimination)
+          instance.initialize(0)
+          withClue(s"useSubexprElimination = $useSubexprElimination, first = 
$first: ") {
+            assert(instance.eval(null) === result)
+            val expected = if (useSubexprElimination) leafEvaluations else 2 * 
leafEvaluations
+            assert(leaf.evaluations === expected)
+          }
+      }
+    }
+  }
+
+  test("SPARK-60332: GeneratePredicate evaluates nested common subexpressions 
in the order of " +
+      "the conjuncts that first reference them") {
+    // The nested ANDs flatten into the conjuncts `first, inner, inner, outer, 
outer`, so
+    // `inner = Not(leaf)` is first referenced by the second conjunct and 
`outer`, which contains
+    // it, by the fourth. Each is evaluated once, just before its conjunct, 
the inner one first, so
+    // the outer one reads the evaluated inner one, not its default. A FALSE 
first conjunct
+    // evaluates neither.
+    Seq((false, 0, false), (true, 1, true)).foreach { case (first, 
leafEvaluations, result) =>
+      val leaf = ExprWithEvaluatedState(id = 1)
+      val leaf2 = ExprWithEvaluatedState(id = 2)
+      val inner = Not(leaf)
+      val outer = Or(inner, leaf2)
+      val cond = And(And(And(ExprWithEvaluatedState(first), inner), And(inner, 
outer)), outer)
+      val instance = GeneratePredicate.generate(cond, useSubexprElimination = 
true)
+      instance.initialize(0)
+      withClue(s"first = $first: ") {
+        assert(instance.eval(null) === result)
+        assert(leaf.evaluations === leafEvaluations)
+        // `Or(TRUE, leaf2)` never evaluates `leaf2`.
+        assert(leaf2.evaluations === 0)
+      }
+    }
+  }
+
+  test("SPARK-60332: GeneratePredicate evaluates a contained common 
subexpression before the " +
+      "conjunct that first references the containing one") {
+    // `(a + b) + c` is common to the second and the third conjuncts, and the 
IF branch of the
+    // first one holds `(a + c) + b`, equal to it under the canonicalization 
of `+`, but without
+    // `a + b`, which is common to the last three conjuncts. The function of 
`(a + b) + c` reads the
+    // state of `a + b`, so `a + b` is evaluated before the first conjunct, 
which references the
+    // containing subexpression, not before the second, which is the first to 
reference `a + b`:
+    // otherwise `(a + b) + c` would read the default or the previous row's `a 
+ b`.
+    val Seq(a, b, c, d, x) = (0 to 4).map(i => BoundReference(i, IntegerType, 
nullable = true))
+    val cond = And(And(And(
+      GreaterThan(If(GreaterThan(x, Literal(0)), Add(Add(a, c), b), d), 
Literal(0)),
+      GreaterThan(Add(Add(a, b), c), Literal(1))),
+      LessThan(Add(Add(a, b), c), Literal(10))),
+      GreaterThan(Add(a, b), Literal(5)))
+    val instance = GeneratePredicate.generate(cond, useSubexprElimination = 
true)
+    instance.initialize(0)
+    // Rows with different values, in both orders, so that a stale state 
shows. The last one
+    // takes the IF branch and passes every conjunct, so a stale `(a + b) + c` 
or `a + b` from the
+    // row before it, -4 or -5, would drop it.
+    val rows = Seq(InternalRow(3, 3, 1, 1, 0), InternalRow(1, 1, 1, 1, 1),
+      InternalRow(3, 3, 1, 1, 0), InternalRow(-5, 0, 1, 1, 0), InternalRow(3, 
3, 1, 1, 1))
+    rows.foreach { row =>
+      assert(instance.eval(row) === cond.eval(row), row)
+    }
+  }
+
+  test("SPARK-60332: GeneratePredicate eliminates the subexpressions of the 
whole predicate") {
+    // The common subexpressions are found in the whole predicate, so that the 
same ones are
+    // eliminated as before: with `skipForShortcutExpr`, only those of the 
first conjunct. Here
+    // `Not(leaf)` is common to the last two conjuncts only, so it is not 
eliminated, and a FALSE
+    // first conjunct still evaluates neither.
+    withSQLConf(SQLConf.SUBEXPRESSION_ELIMINATION_SKIP_FOR_SHORTCUT_EXPR.key 
-> "true") {
+      Seq((false, 0, false), (true, 2, true)).foreach { case (first, 
leafEvaluations, result) =>
+        val leaf = ExprWithEvaluatedState(id = 1)
+        val cond = And(And(ExprWithEvaluatedState(first), Not(leaf)), 
Not(leaf))
+        val instance = GeneratePredicate.generate(cond, useSubexprElimination 
= true)
+        instance.initialize(0)
+        withClue(s"first = $first: ") {
+          assert(instance.eval(null) === result)
+          assert(leaf.evaluations === leafEvaluations)
+        }
+      }
+    }
+  }
+
+  test("SPARK-60332: GeneratePredicate splits the checks of many conjuncts 
into functions") {
+    // Several hundred conjuncts, with a common `a + 1` in two of them, whose 
checks exceed the
+    // length at which they are split into functions, each returning false at 
a FALSE conjunct.
+    val a = BoundReference(0, IntegerType, nullable = true)
+    val conjuncts = (0 until 400).map(k => GreaterThan(Add(a, Literal(k)), 
Literal(0))) :+
+      GreaterThan(Add(a, Literal(1)), Literal(-1))
+    val cond = conjuncts.reduce[Expression](And)
+    withSQLConf(SQLConf.CODEGEN_METHOD_SPLIT_THRESHOLD.key -> "1000") {
+      val instance = GeneratePredicate.generate(cond, useSubexprElimination = 
true)
+      instance.initialize(0)
+      // All TRUE, a FALSE one, and NULL ones, then all TRUE again, which the 
NULL conjuncts of
+      // the row before it must not affect.
+      Seq(InternalRow(1), InternalRow(-1000), InternalRow(null), 
InternalRow(1)).foreach { row =>
+        val expected = cond.eval(row)
+        assert(instance.eval(row) === (expected != null && 
expected.asInstanceOf[Boolean]), row)
+      }
+    }
+  }
+
+  test("SPARK-60332: GeneratePredicate splits the evaluation of many common 
subexpressions " +
+      "into functions") {
+    // The second conjunct, an OR of the 100 `Not(leaf)`, is the first to 
reference each of them,
+    // and the 100 conjuncts after it, the ANDs of the same `Not(leaf)` 
flattened, reference them
+    // again. The calls of the functions of all of them, before the second 
conjunct, exceed the
+    // length at which they are split into functions of their own. Each leaf 
is evaluated once.
+    Seq((false, 0, false), (true, 1, true)).foreach { case (first, 
leafEvaluations, result) =>
+      val leaves = (1 to 100).map(i => ExprWithEvaluatedState(id = i))
+      val nots = leaves.map(leaf => Not(leaf): Expression)
+      val cond = And(And(ExprWithEvaluatedState(first), nots.reduce(Or)), 
nots.reduce(And))
+      val instance = GeneratePredicate.generate(cond, useSubexprElimination = 
true)
+      instance.initialize(0)
+      withClue(s"first = $first: ") {
+        assert(instance.eval(null) === result)
+        assert(leaves.forall(_.evaluations == leafEvaluations))
+      }
+    }
+  }
+
+  test("SPARK-60332: GeneratePredicate keeps an AND of the top-level chain 
that is a common " +
+      "subexpression as one conjunct") {
+    // `common`, an AND of 3 `Not(leaf)`, is repeated under NOT in the second 
conjunct, so it is
+    // eliminated as a whole, as before, and its own occurrence in the chain 
stays one conjunct
+    // that reads the state instead of being split into conjuncts that 
recompute the `Not(leaf)`.
+    Seq((false, 0, false), (true, 1, true)).foreach { case (first, 
leafEvaluations, result) =>
+      val leaves = (1 to 3).map(i => ExprWithEvaluatedState(id = i))
+      val common = leaves.map(leaf => Not(leaf): Expression).reduce(And)
+      val cond = And(And(ExprWithEvaluatedState(first), Not(Not(common))), 
common)
+      val instance = GeneratePredicate.generate(cond, useSubexprElimination = 
true)
+      instance.initialize(0)
+      withClue(s"first = $first: ") {
+        assert(instance.eval(null) === result)
+        assert(leaves.forall(_.evaluations == leafEvaluations))
+      }
+    }
+  }
 }
 
 /**
  * An expression with evaluated state so we can know whether it is evaluated.
  */
-case class ExprWithEvaluatedState() extends LeafExpression with 
CodegenFallback {
-  var evaluated: Boolean = false
+case class ExprWithEvaluatedState(value: Any = false, isNullable: Boolean = 
false, id: Int = 0)
+  extends LeafExpression with CodegenFallback {
+  var evaluations: Int = 0
+  def evaluated: Boolean = evaluations > 0
   override def eval(input: InternalRow): Any = {
-    evaluated = true
-    false
+    evaluations += 1
+    value
   }
 
-  override def nullable: Boolean = false
+  override def nullable: Boolean = isNullable
   override def dataType: DataType = BooleanType
 }
diff --git 
a/sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala
 
b/sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala
index 010b351b2d95..eea4bf963cb6 100644
--- 
a/sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala
+++ 
b/sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala
@@ -535,7 +535,7 @@ case class FilterExec(condition: Expression, child: 
SparkPlan)
         // for the already-emitted dependencies.
         val statesByFirstUse: Map[Int, Seq[SubExprEliminationState]] =
           subExprs.states.toSeq.groupBy { case (exprEq, _) =>
-            boundOtherPreds.indexWhere(_.exists(e => ExpressionEquals(e) == 
exprEq))
+            ctx.firstReferencingExpression(boundOtherPreds, exprEq)
           }.map { case (idx, kvs) => idx -> kvs.map(_._2) }
 
         // Emit an IsNotNull check, binding against child.output so the inner 
expression
diff --git 
a/sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala
 
b/sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala
index 6dd2810b6812..c4a81d60a59a 100644
--- 
a/sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala
+++ 
b/sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala
@@ -41,7 +41,7 @@ import 
org.apache.spark.sql.execution.adaptive.DisableAdaptiveExecutionSuite
 import org.apache.spark.sql.execution.aggregate.{HashAggregateExec, 
SortAggregateExec}
 import org.apache.spark.sql.execution.columnar.InMemoryTableScanExec
 import org.apache.spark.sql.execution.debug.{codegenString, codegenStringSeq}
-import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec, 
BroadcastNestedLoopJoinExec, ShuffledHashJoinExec, SortMergeJoinExec}
+import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec, 
BroadcastNestedLoopJoinExec, CartesianProductExec, ShuffledHashJoinExec, 
SortMergeJoinExec}
 import org.apache.spark.sql.functions._
 import org.apache.spark.sql.internal.SQLConf
 import org.apache.spark.sql.test.SharedSparkSession
@@ -3081,8 +3081,8 @@ class WholeStageCodegenSuite extends SharedSparkSession
       // generated just before the first conjunct that references `x`, or 
after all of them, so
       // after a NULL conjunct it has to be generated before the conjuncts it 
precedes.
       //
-      // The common `b * 2` takes the CSE path of FilterExec. The overflowing 
`y + 1` is not
-      // common because `GeneratePredicate` (codegen off) evaluates common 
subexpressions first.
+      // The common `b * 2` takes the CSE path of FilterExec, while the 
overflowing `y + 1` is
+      // not common, so it is evaluated at its conjunct in both modes.
       val cseQuery = "SELECT a FROM t WHERE x IS NOT NULL AND NOT (a > 0 AND b 
> 0) AND " +
         "y + 1 > 0 AND b * 2 > 0 AND b * 2 > -1"
       def multiplyExactCount(filterExecCSE: Boolean): Int = {
@@ -3208,6 +3208,86 @@ class WholeStageCodegenSuite extends SharedSparkSession
     }
   }
 
+  test("SPARK-60332: a filter evaluates a common subexpression after the 
conjuncts before it") {
+    withNullConjunctTable(Int.MaxValue) {
+      // With codegen off, the condition is evaluated by a generated predicate 
with subexpression
+      // elimination, where `y + 1`, common to the last two conjuncts, 
overflows on the first row.
+      // The predicate evaluates it just before the first conjunct that 
references it, as the CSE
+      // branch of FilterExec does with codegen on, so the FALSE 
`isnotnull(x)`, or `b < 0`, drops
+      // the row first in every combination, as `And.eval` does.
+      withNullConjunctConfs(SQLConf.ANSI_ENABLED.key -> "true") { skipsAtNull 
=>
+        checkAnswer(
+          sql("SELECT a FROM t WHERE x IS NOT NULL AND NOT (a > 0 AND b > 0) 
AND y + 1 > 0 AND " +
+            "y + 1 > -1"),
+          Row(0))
+        checkAnswer(sql("SELECT a FROM t WHERE b < 0 AND y + 1 > 0 AND y + 1 > 
-1"), Seq.empty)
+        // A NULL conjunct does not stop the evaluation, so the common `y + 1` 
is evaluated,
+        // unless the legacy behavior skips the row at the NULL conjunct.
+        val nullConjunct =
+          "SELECT a FROM t WHERE NOT (a > 0 AND b > 0) AND y + 1 > 0 AND y + 1 
> -1"
+        if (skipsAtNull) {
+          checkAnswer(sql(nullConjunct), Row(0))
+        } else {
+          checkArithmeticOverflow(nullConjunct)
+        }
+      }
+      // A join condition is evaluated by the same generated predicate on the 
join paths without
+      // whole-stage codegen, here a cartesian product. Every conjunct 
references both sides, so
+      // none is pushed down into a filter, and the FALSE `b < k` stops the 
evaluation before
+      // the common `y + 1` overflows, whatever the whole-stage codegen config.
+      withTempView("u") {
+        Seq(0).toDF("k").createOrReplaceTempView("u")
+        val join = "SELECT a FROM t JOIN u ON b < k AND y + 1 > k AND y + 1 > 
k - 1"
+        Seq(true, false).foreach { codegen =>
+          withSQLConf(
+              SQLConf.ANSI_ENABLED.key -> "true",
+              SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
+              SQLConf.PARQUET_FILTER_PUSHDOWN_ENABLED.key -> "false",
+              SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> codegen.toString) {
+            val df = sql(join)
+            
assert(df.queryExecution.executedPlan.exists(_.isInstanceOf[CartesianProductExec]))
+            checkAnswer(df, Seq.empty)
+          }
+        }
+      }
+    }
+    // `(a + c) + b` in the IF branch of the first conjunct is `(a + b) + c`, 
common to the next
+    // two conjuncts, under the canonicalization of `+`, but holds no `a + b`, 
common to the last
+    // three. `a + b` is evaluated before the first conjunct, which the 
function of `(a + b) + c`
+    // reads, not before the second, or `(a + b) + c` would read the previous 
row's `a + b`, -5,
+    // and drop the last row. The filter runs through the generated predicate 
both when the
+    // optimizer filters the local data, with `ConvertToLocalRelation`, which 
the shared session
+    // excludes, and in `FilterExec` without whole-stage codegen.
+    val localData = "SELECT a FROM VALUES (3, 3, 1, 1, 0), (-5, 0, 1, 1, 0), 
(3, 3, 1, 1, 1) " +
+      "AS t(a, b, c, d, x) WHERE IF(x > 0, a + c + b, d) > 0 AND a + b + c > 1 
AND " +
+      "a + b + c < 10 AND a + b > 5"
+    Seq(
+      SQLConf.OPTIMIZER_EXCLUDED_RULES.key -> "",
+      SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> "false").foreach { conf =>
+      withSQLConf(
+          conf,
+          SQLConf.CODEGEN_FACTORY_MODE.key -> 
CodegenObjectFactoryMode.CODEGEN_ONLY.toString) {
+        checkAnswer(sql(localData), Seq(Row(3), Row(3)))
+      }
+    }
+    // The common subexpressions are found in the whole predicate, as before, 
so that a predicate
+    // with a subquery gets no elimination inside a task (SPARK-38333), and 
the conjuncts are not
+    // compared with a subquery plan on an executor.
+    withSQLConf(
+        SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> "false",
+        SQLConf.CODEGEN_FACTORY_MODE.key -> 
CodegenObjectFactoryMode.CODEGEN_ONLY.toString) {
+      withTempView("u") {
+        spark.range(10).toDF("k").cache().createOrReplaceTempView("u")
+        spark.table("u").collect()
+        checkAnswer(
+          spark.range(10).selectExpr("id AS x", "id AS y")
+            .where("x > (SELECT max(k) - 20 FROM u) AND y + 1 > 0 AND y + 1 < 
100")
+            .selectExpr("count(*)"),
+          Row(10))
+      }
+    }
+  }
+
   test("SPARK-60403: full outer joins compile with their functions spilled to 
nested classes") {
     // A full outer join outputs its rows through a function of its own, and 
generates the code of
     // the operators above it, for the body of that function, before adding 
the function: here a


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to