spark-test commented on code in PR #60516:
URL: https://github.com/apache/spark/pull/60516#discussion_r4581795950


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -289,12 +367,15 @@ object ConstantPropagation extends Rule[LogicalPlan] with 
PredicateHelper {
    * Rewrites the operands of `e`, which short-circuits, with `f`. An operand 
decides whether the
    * ones after it run, so it is rewritten only if none of those, as 
rewritten, can fail.
    */
-  private def replaceOperands(e: Expression, f: Expression => Expression): 
Expression = {
+  private def replaceOperands(
+      e: Expression,
+      f: Expression => Expression,
+      columns: FailableColumns): Expression = {
     val (newChildren, _) = e.children.foldRight((List.empty[Expression], 
false)) {
       case (child, (laterChildren, laterCanFail)) =>
         val newChild = if (laterCanFail) child else f(child)
         (newChild :: laterChildren,
-          laterCanFail || !ExprUtils.canEvaluateUnconditionally(newChild))
+          laterCanFail || !columns.canEvaluateUnconditionally(newChild))

Review Comment:
   **Blocking (P1):** Counting a later operand that reads a column 
FailableColumns collects as one that can fail keeps the earlier operand 
unrewritten even when its rewritten value would end the operator. In `(id > 0 
OR i > 0) AND id = 7`, `id > 0` would become `7 > 0`, which makes the OR TRUE; 
the base branch does that and ends up with just `id = 7`, which never reads 
`i`. Here `id > 0` stays, `id = 7` moves first, and the OR remains. Under 
whole-stage codegen `genPredicate` loads every input column a conjunct 
references before the conjunct's own code, so the short-circuit inside the OR 
does not stop `i` from being computed: by this review's reading of the code, in 
ANSI mode with the filter kept above the projection, a row ('x', 7) raises 
CAST_INVALID_INPUT where the base branch returns it. `coalesce(id, i) > 0 AND 
id = 7` hits the same case, since `coalesce(7, i)` would reduce to 7. An 
operand whose rewritten value ends the operator (TRUE for OR, FALSE for AND, a 
non-NULL value for
  COALESCE) can be rewritten safely, because the operands after it never run; 
the tests only cover the other direction, `(id < 3 OR i > 0) AND id = 5`.
   
   **Verification:**
   - **Regression:** Plan tests show `(id > 0 OR i > 0) AND id = 7` and 
`coalesce(id, i) > 0 AND id = 7`, with `i` an ANSI-cast alias, optimize to `id 
= 7`.
   - **Regression:** An end-to-end ANSI-mode query over one Parquet file with 
rows ('1', 7), ('x', 7), with the filter kept above the projection by a read 
non-deterministic column and whole-stage codegen on, returns both rows for `(id 
> 0 OR i > 0) AND id = 7`.
   - **Behavior:** An OR operand that the constant makes FALSE before an 
operand over a marked column still stays unrewritten, so `(id < 3 OR i > 0) AND 
id = 5` keeps its plan.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -236,6 +246,71 @@ object ConstantPropagation extends Rule[LogicalPlan] with 
PredicateHelper {
   private def safeToReplace(ar: AttributeReference, nullIsFalse: Boolean) =
     !ar.nullable || nullIsFalse
 
+  /**
+   * The equalities of `condition` whose constants can be propagated. An 
equality over a column
+   * that can fail (see [[FailableColumns]]), e.g. `i = 1` with `i` the alias 
`CAST(s AS INT)` of
+   * the projection below, can not go first, as it would compute that column 
on rows the conjuncts
+   * before it filter out. So it stays where it is written. A conjunct after 
it can take its
+   * constant, as after any other equality (for the rows where the equality is 
NULL, see
+   * SPARK-61438). A conjunct before it that is rewritten with its constant 
can pass a row that it
+   * would not, but only one where it would fail as well, or one where the 
column does not fail,
+   * so the equality itself raises no new error there (but for a row where the 
column is NULL,
+   * which goes on past the equality, see SPARK-61438). A conjunct that can 
fail between them
+   * could, though, e.g. `10 / x > 0` for `i > 0 AND 10 / x > 0 AND i = 1`, so 
such an equality
+   * is not propagated then, unless a conjunct before that one is FALSE, so 
that no row reaches
+   * it, or NULL where a NULL counts as FALSE, which the caller then makes 
FALSE. For simplicity,
+   * this counts from the first conjunct that is rewritten at all, with any 
constant; the next run
+   * of the rule sees that conjunct as rewritten already. Such an equality is 
not moved even where
+   * moving it would keep a conjunct before it from failing as written, e.g. 
`10 / (id - i) > 0`
+   * in `10 / (id - i) > 0 AND i = 1`.
+   */
+  private def usableEqualities(
+      condition: Expression,
+      equalityPredicates: AttributeMap[(Literal, BinaryComparison)],
+      nullIsFalse: Boolean,
+      columns: FailableColumns): AttributeMap[(Literal, BinaryComparison)] = {
+    val conjuncts = splitConjunctivePredicates(condition).toIndexedSeq
+    @tailrec
+    def usable(
+        equalities: AttributeMap[(Literal, BinaryComparison)])
+      : AttributeMap[(Literal, BinaryComparison)] = {
+      lazy val rewritten =
+        splitConjunctivePredicates(replaceConstants(condition, equalities, 
columns)).toIndexedSeq
+      lazy val first = firstRewritten(conjuncts, rewritten)
+      lazy val stop = rewritten.indexWhere { c =>
+        fold(c).exists(l => l.value == false || (l.value == null && 
nullIsFalse))
+      }
+      val unsafe = equalities.filter { case (attr, (_, equality)) =>
+        !columns.canEvaluateUnconditionally(attr) && {
+          val at = conjuncts.indexWhere(_ eq equality)
+          val end = if (stop >= 0) math.min(stop, at) else at

Review Comment:
   **Blocking (P1):** This bound lets a conjunct that folds to FALSE (or to 
NULL where NULL counts as FALSE) excuse the conjuncts that can fail only when 
it comes before them. In `i > 0 AND 10 / (id - 3) > 0 AND i + 1 > 3 AND i = 1`, 
`i = 1` turns `i + 1 > 3` into `2 > 3`, but the division lies between `i > 0`, 
the first rewritten conjunct, and the equality, so `i = 1` is withheld and the 
filter is left as written. On the base branch the constant is propagated, the 
AND folds to FALSE, and PruneFilters replaces the filter, projection and scan 
with an empty relation, so nothing is read. Here, with the filter kept above 
the projection as the new DataFrameSuite test does, the query scans and filters 
every row, and in ANSI mode, by this review's reading of the code, it raises 
CAST_INVALID_INPUT on the fixture row ('x', 0). A FALSE top-level conjunct 
makes the whole AND FALSE wherever it sits, and the optimizer folds it before 
any row is evaluated, so its position relative to the conjuncts
  that can fail does not matter. The new tests only write the contradiction 
before the conjunct that can fail.
   
   **Verification:**
   - **Regression:** Plan tests show that a condition whose FALSE conjunct 
after propagation is written after a conjunct that can fail optimizes to an 
empty relation, including `qty > 0 AND price > 5 AND qty > 10 AND qty = 1` over 
two ANSI-cast aliases and `u > 0 AND w > 5 AND v < 0 AND u = 1 AND v = 2`.
   - **Regression:** An end-to-end ANSI-mode query over one Parquet file, with 
the filter kept above the projection by a read non-deterministic column, 
returns no rows for `i > 0 AND 10 / (id - 3) > 0 AND i + 1 > 3 AND i = 1` over 
('1', 7), ('x', 0).
   - **Behavior:** Plan cases without a conjunct that folds to FALSE or NULL 
optimize as they do without this change.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -236,6 +246,71 @@ object ConstantPropagation extends Rule[LogicalPlan] with 
PredicateHelper {
   private def safeToReplace(ar: AttributeReference, nullIsFalse: Boolean) =
     !ar.nullable || nullIsFalse
 
+  /**
+   * The equalities of `condition` whose constants can be propagated. An 
equality over a column
+   * that can fail (see [[FailableColumns]]), e.g. `i = 1` with `i` the alias 
`CAST(s AS INT)` of
+   * the projection below, can not go first, as it would compute that column 
on rows the conjuncts
+   * before it filter out. So it stays where it is written. A conjunct after 
it can take its
+   * constant, as after any other equality (for the rows where the equality is 
NULL, see
+   * SPARK-61438). A conjunct before it that is rewritten with its constant 
can pass a row that it
+   * would not, but only one where it would fail as well, or one where the 
column does not fail,
+   * so the equality itself raises no new error there (but for a row where the 
column is NULL,
+   * which goes on past the equality, see SPARK-61438). A conjunct that can 
fail between them
+   * could, though, e.g. `10 / x > 0` for `i > 0 AND 10 / x > 0 AND i = 1`, so 
such an equality
+   * is not propagated then, unless a conjunct before that one is FALSE, so 
that no row reaches
+   * it, or NULL where a NULL counts as FALSE, which the caller then makes 
FALSE. For simplicity,
+   * this counts from the first conjunct that is rewritten at all, with any 
constant; the next run
+   * of the rule sees that conjunct as rewritten already. Such an equality is 
not moved even where
+   * moving it would keep a conjunct before it from failing as written, e.g. 
`10 / (id - i) > 0`
+   * in `10 / (id - i) > 0 AND i = 1`.
+   */
+  private def usableEqualities(
+      condition: Expression,
+      equalityPredicates: AttributeMap[(Literal, BinaryComparison)],
+      nullIsFalse: Boolean,
+      columns: FailableColumns): AttributeMap[(Literal, BinaryComparison)] = {
+    val conjuncts = splitConjunctivePredicates(condition).toIndexedSeq
+    @tailrec
+    def usable(
+        equalities: AttributeMap[(Literal, BinaryComparison)])
+      : AttributeMap[(Literal, BinaryComparison)] = {
+      lazy val rewritten =
+        splitConjunctivePredicates(replaceConstants(condition, equalities, 
columns)).toIndexedSeq
+      lazy val first = firstRewritten(conjuncts, rewritten)

Review Comment:
   **Nit (P3):** The next run only sees this conjunct as rewritten if the 
equality that rewrites it is kept. In `u > 0 AND w > 5 AND u = 1 AND v + 1 > 1 
AND v = 2`, with `u`, `v` and `w` ANSI casts, `first` comes from `u`'s rewrite 
of `u > 0`, so `u = 1` and `v = 2` both see `w > 5` after it and are dropped in 
the same pass; the condition comes back unchanged and every later run repeats 
that. Counted from `v`'s own rewrite of `v + 1 > 1`, nothing that can fail lies 
before `v = 2`, so the rule the comment describes would propagate it and fold 
`v + 1 > 1` away, as the base branch does. Either count `first` from the 
rewrites of the equalities that stay usable, or say in the comment that such an 
equality stays withheld.
   
   **Verification:**
   - **Regression:** A plan test shows that the optimized condition for `u > 0 
AND w > 5 AND u = 1 AND v + 1 > 1 AND v = 2`, over three ANSI-cast aliases of a 
projection, no longer contains `v + 1 > 1`.
   - **Inspection:** The comment of usableEqualities describes how the first 
rewritten conjunct is counted, matching the code.



##########
sql/core/src/test/scala/org/apache/spark/sql/DataFrameSuite.scala:
##########
@@ -3075,6 +3075,95 @@ class DataFrameSuite extends SharedSparkSession
     }
   }
 
+  test("SPARK-61437: ConstantPropagation judges a filter condition by what the 
aliases of the " +
+    "projection below stand for") {
+    withTempPath { dir =>
+      // `i` fails on the row ("x", 0), which `id > 0` and `id > 5` filter 
out. One file, so that
+      // the scan does not skip that row by the statistics of a file of its 
own.
+      Seq(("1", 7L), ("x", 0L)).toDF("s", 
"id").coalesce(1).write.parquet(dir.getCanonicalPath)
+      withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+        def projected: DataFrame = spark.read.parquet(dir.getCanonicalPath)
+          .select($"s", $"id", $"s".cast("int").as("i"))
+        // Whether the filter is above the projection that computes `i`.
+        def filtersAboveI(df: DataFrame): Boolean = 
df.queryExecution.optimizedPlan.exists {
+          case Filter(_, child) => child.exists {
+            case p: Project => p.projectList.exists(_.name == "i")
+            case _ => false
+          }
+          case _ => false
+        }
+        val conditions = Seq(
+          $"id" > 5 && $"i" * $"id" > 0 && $"i" === 1,
+          $"id" > 5 && $"i" > 0 && lit(10) / ($"id" - 3) > 0 && $"i" === 1,
+          // `id = 7` folds `id > 0`, and goes first, as `i > 0` and `i = 1` 
can fail.
+          $"id" > 0 && $"i" > 0 && $"id" === 7,
+          $"id" > 0 && $"i" === 1 && $"id" === 7)
+        withSQLConf(SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> "true") {
+          conditions.foreach { condition =>
+            // With `r` read, the filter stays above the projection, and so it 
does above a
+            // sample. The projection computes `i` only for the rows that 
reach a condition
+            // reading it.
+            Seq(
+              projected.select($"*", rand(1).as("r")).where(condition)
+                .select($"s", $"id", $"r" >= 0),
+              projected.sample(0.999, 1).where(condition).select($"s", $"id", 
lit(true))
+            ).foreach { df =>
+              assert(filtersAboveI(df))
+              checkAnswer(df, Row("1", 7L, true))
+            }
+          }
+          // As on master, `i = 1` simplifies the other conditions, so `i` is 
not computed
+          // for the row ("x", 0).
+          Seq(
+            $"i" + 1 > 3 && $"i" === 1,
+            $"i" === 1 && $"i" + 1 > 3,
+            ($"id" < 0 || $"i" + 1 > 3) && $"i" === 1,
+            nullif($"i", lit(1)) > 0 && $"i" === 1,
+            // Also with a division in between, so `i` is propagated, and no 
row computes it.
+            $"i" + 1 > 3 && lit(10) / ($"id" - 3) > 0 && $"i" === 1,
+            $"i" === 1 && lit(10) / ($"id" - 3) > 0 && $"i" === 2,
+            nullif($"i", lit(1)) > 0 && lit(10) / ($"id" - 3) > 0 && $"i" === 1
+          ).foreach { condition =>
+            checkAnswer(
+              projected.select($"*", rand(1).as("r")).where(condition)
+                .select($"s", $"id", $"r" >= 0),
+              Seq.empty)
+          }
+          // Nor the division by zero for the row ("0", 8).
+          withTempPath { zero =>
+            Seq(("1", 7L), ("0", 8L)).toDF("s", 
"id").coalesce(1).write.parquet(zero.toString)
+            val df = spark.read.parquet(zero.toString)
+              .select($"s", $"id", $"s".cast("int").as("i"), rand(1).as("r"))
+              .where(lit(10) / $"i" > 1 && $"i" === 1).select($"s", $"id", 
$"r" >= 0)
+            assert(filtersAboveI(df))
+            checkAnswer(df, Row("1", 7L, true))
+          }
+          // `id < 3` decides whether `i > 0` runs. Without the subexpression 
elimination path of
+          // `FilterExec`, which computes `i` up front for the `i > 0` that
+          // `InferFiltersFromConstraints` infers from it.
+          
withSQLConf(SQLConf.SUBEXPRESSION_ELIMINATION_FILTER_EXEC_ENABLED.key -> 
"false") {

Review Comment:
   **Nit (P3):** SPARK-61377 (fbe92075e04), which reached the base branch after 
this PR's commit, changed the path this comment describes: 
`generatePredicateCode` now loads each input column right before the first 
check or conjunct that reads it, and evaluates a shared subexpression right 
before the first conjunct that references it. Once ConstantPropagation moves 
`id = 7` ahead of the inferred `i > 0` and of the OR, the default path should 
load `i` only after `id = 7` has dropped ('x', 0); this comes from reading the 
source, not from a run. As written, a change that made the default path compute 
`i` early again would leave the suite green. Running the query under the 
default configuration too, and replacing the stale reason, would cover it; if 
the default still fails, the comment should name the path that computes `i` 
early instead.
   
   **Verification:**
   - **Behavior:** The end-to-end OR-guard case runs with FilterExec's 
subexpression elimination at its default and returns ('1', 7, true).
   - **Inspection:** The test's comment no longer attributes an up-front 
computation of `i` to FilterExec's subexpression elimination.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -318,32 +399,80 @@ object ConstantPropagation extends Rule[LogicalPlan] with 
PredicateHelper {
    * where an equality does not hold, with the value of the row, while a guard 
over the same
    * attribute may be folded away, e.g. `n / d > 1` for `d <> 0 AND n / d > 1 
AND d = 5`. The
    * same holds for a conjunct that can fail after one that is rewritten, as 
that one decides
-   * whether it runs, e.g. `10 / x > 0` for `y > 0 AND 10 / x > 0 AND y = 1`. 
An equality between
-   * an attribute and a literal cannot fail, so running it first raises no 
error.
+   * whether it runs, e.g. `10 / x > 0` for `y > 0 AND 10 / x > 0 AND y = 1`. 
A conjunct over a
+   * column of the projection below that can fail can fail too (see 
[[FailableColumns]]), e.g.
+   * `i > 0`, with `i` the alias `CAST(s AS INT)`, in ANSI mode. 
`equalityPredicates` are the
+   * equalities over a column that can not fail, which can not fail 
themselves, so running them
+   * first raises no error. The ones over a column that can fail stay where 
they are written (see
+   * [[usableEqualities]]). `keepsFailable` checks the attributes a conjunct 
reads against those
+   * of `equalityPredicates`, not those that the expressions of its columns 
read, which these
+   * equalities do not replace.
    */
   private def moveEqualitiesFirst(
       original: Expression,
       condition: Expression,
-      equalityPredicates: AttributeMap[(Literal, BinaryComparison)]): 
Expression = {
+      equalityPredicates: AttributeMap[(Literal, BinaryComparison)],
+      columns: FailableColumns): Expression = {
     val predicates = equalityPredicates.values.map(_._2).toSet[Expression]
     val propagated = AttributeSet(equalityPredicates.keys)
     val conjuncts = splitConjunctivePredicates(condition)
     val (equalities, others) = conjuncts.partition(predicates.contains)
     val reordered = equalities ++ others
     val keepsFailable = others.exists { c =>
-      c.references.intersect(propagated).nonEmpty && 
!ExprUtils.canEvaluateUnconditionally(c)
+      c.references.intersect(propagated).nonEmpty && 
!columns.canEvaluateUnconditionally(c)
     }
-    val firstRewritten = splitConjunctivePredicates(original).zip(conjuncts)
-      .indexWhere { case (before, after) => !before.fastEquals(after) }
-    val unmasksFailable = firstRewritten >= 0 &&
-      conjuncts.drop(firstRewritten + 
1).exists(!ExprUtils.canEvaluateUnconditionally(_))
+    val first = firstRewritten(splitConjunctivePredicates(original), conjuncts)
+    val unmasksFailable = first >= 0 &&
+      conjuncts.drop(first + 1).exists(!columns.canEvaluateUnconditionally(_))
     if ((keepsFailable || unmasksFailable) && reordered != conjuncts) {
       reordered.reduce(And)
     } else {
       condition
     }
   }
 
+  /**
+   * The columns of `plan` that can fail, i.e. those that a projection at its 
top, or below the
+   * filters, samples and projections there, computes with a deterministic 
expression that
+   * [[ExprUtils.canEvaluateUnconditionally]] rejects or that reads such a 
column, or passes such
+   * a column through. Under whole-stage codegen, the projection computes a 
deterministic column
+   * for a row only when a conjunct of the filter above first reads it, unless 
subexpression
+   * elimination computes it up front, and `PushPredicateThroughNonJoin` 
pushes a conjunct below
+   * the projection with the expression of the column substituted. So a 
conjunct over such a
+   * column can fail as that expression does. A non-deterministic column is 
computed on every row
+   * the projection gets, and no filter is pushed through a projection with 
one, so it does not
+   * count. Other
+   * operators are not looked through. The columns are collected once per 
filter, when needed.

Review Comment:
   **Nit (P3):** This line holds only `count. Other`; rewrapping keeps the 
paragraph continuous:
   
   ```suggestion
      * count. Other operators are not looked through. The columns are 
collected once per filter,
      * when needed.
   ```
   
   **Verification:**
   - **Inspection:** The FailableColumns Scaladoc paragraph wraps as continuous 
prose with no two-word line.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -195,14 +201,18 @@ object ConstantPropagation extends Rule[LogicalPlan] with 
PredicateHelper {
         (None, AttributeMap(Map(right -> (left, e))))
       case a: And =>
         val (newLeft, equalityPredicatesLeft) =
-          traverse(a.left, replaceChildren = false, nullIsFalse)
+          traverse(a.left, replaceChildren = false, nullIsFalse, columns)
         val (newRight, equalityPredicatesRight) =
-          traverse(a.right, replaceChildren = false, nullIsFalse)
+          traverse(a.right, replaceChildren = false, nullIsFalse, columns)
         val equalityPredicates = equalityPredicatesLeft ++ 
equalityPredicatesRight
         val newSelf = if (equalityPredicates.nonEmpty && replaceChildren) {
           val unreplaced = And(newLeft.getOrElse(a.left), 
newRight.getOrElse(a.right))
-          Some(moveEqualitiesFirst(
-            unreplaced, replaceConstants(unreplaced, equalityPredicates), 
equalityPredicates))
+          val usable = usableEqualities(unreplaced, equalityPredicates, 
nullIsFalse, columns)
+          val movable = usable.filter { case (attr, _) => 
columns.canEvaluateUnconditionally(attr) }

Review Comment:
   **Blocking (P1):** Leaving every equality over a column that FailableColumns 
collects out of `movable` means it is never moved, even when a conjunct written 
before it already reads that column. On the base branch, keepsFailable moves `i 
= 1` ahead of `10 / (id - i) > 0`, so the division only sees rows where `i = 
1`. Here the written order stays, so by this review's reading of the code, 
`spark.read.parquet(path).select($"s", $"id", $"s".cast("int").as("i"), 
rand(1).as("r")).where(lit(10) / ($"id" - $"i") > 0 && $"i" === 1).select($"s", 
$"id", $"r" >= 0)` in ANSI mode raises DIVIDE_BY_ZERO on the row ('8', 8) 
instead of returning ('1', 7), with codegen on or off; the PR description notes 
the same. When the constant is also withheld because a conjunct that can fail 
comes first, a conjunct the base branch folds runs as written: with `w` another 
ANSI cast, `i + 1 > 0 AND w > 5 AND i = 1` raises ARITHMETIC_OVERFLOW on a row 
whose `i` is 2147483647, where the base branch evaluates `w > 5
  AND i = 1` and drops the row. The cast was computed early because the 
equality went to the very front, not because it moved at all: with the filter 
above the projection, `genPredicate` loads `i` right before the first conjunct 
that reads it, so the division already computes `i` on every row it sees.
   
   **Recommended change:** When moveEqualitiesFirst moves equalities 
(keepsFailable or unmasksFailable, with conjuncts over marked columns counted 
as now, and keepsFailable also counting the conjuncts that read the column of a 
usable equality over a marked column), also move each usable equality over a 
marked column, but only to right before the first conjunct that computes its 
column on every row reaching it, found in the order the rewritten condition 
runs the conjuncts and before that equality's own constant replaces anything, 
and leave it in place when no such conjunct comes before it. Let the conjuncts 
after its new place take its constant as after any other equality, and judge 
propagation into the conjuncts before it against that place rather than its 
written position. Update the ConstantPropagation plan tests that pin the 
written order, and add plan and end-to-end cases for the conditions that now 
fail.
   
   **Why this works:** With the filter above the projection, whole-stage 
codegen loads a column right before the first conjunct that references it, on 
every row that reaches that conjunct, so an equality placed there evaluates the 
column on exactly the rows the written order does, while every conjunct after 
it sees only rows where the equality holds; that restores the base branch's 
guard for those conjuncts and keeps the PR's fix for the ones before.
   
   **Scope:** Move equalities over columns of the projection below to the first 
conjunct that computes the column, in ConstantPropagation's And case, and 
update its plan and end-to-end tests.
   
   **Compatibility:** Filters whose child computes no marked column keep the 
base branch's plan, and the PR's fix for its CAST_INVALID_INPUT target queries 
stays.
   
   **Risks:** The placement changes the optimized conjunct order of every 
filter over a marked column where a move is warranted, including the order the 
PR's plan tests now pin; no flag gates it, so rolling it back means reverting 
the change. Counting a read that skips the column on some rows, once a pushdown 
substitutes the alias, would compute the column on rows the written order 
skips, the error class the PR fixes.
   
   **Constraints:** Count a conjunct as computing the column on every row it 
receives only when it does so in every form the filter can still take: kept 
above the projection, where any reference loads it, and with the alias 
substituted after a later pushdown, where an OR, AND, COALESCE, CASE or IF 
operand can skip it, and a NULL operand of a null-intolerant operator can skip 
it unless no conjunct between the reader and the equality can drop the row. 
Only an operator the filter is not pushed through, such as a Sample, rules out 
the pushed-below form for the projections under it; a non-deterministic field 
keeps the filter above only while a column above reads it, and a later 
iteration can remove that read, after which ColumnPruning prunes the field and 
PushDownPredicates pushes the already reordered filter below. Apply the 
FALSE-conjunct fold and the per-equality counting of the two other 
usableEqualities repairs relative to the equality's placed position, not its 
written one. Keep Fai
 lableColumns' marking, the non-deterministic-column exemption and the 
operators it does not look through unchanged.
   
   **Exclusions:**
   - Operators other than Project, Filter and Sample, which the PR's comment 
leaves not looked through.
   - InferFiltersFromConstraints and the NULL rows of a moved equality, which 
the PR leaves to SPARK-61378 and SPARK-61438.
   
   **Success:** `10 / (id - i) > 0 AND i = 1` over a projection that keeps the 
filter above it, with `i` an ANSI cast of a string, returns the base branch's 
rows instead of raising DIVIDE_BY_ZERO, with whole-stage codegen on and off. 
`id > 5 AND 10 / (id - i) > 0 AND i = 1` over ('1', 7), ('8', 8), ('x', 0) 
returns ('1', 7) with whole-stage codegen on while the filter stays above the 
projection, and with codegen on or off once the filter is pushed below it. `i > 
0 AND 10 / x > 0 AND i = 1` optimizes to `i = 1 AND 10 / x > 0`, and `id > 5 
AND i * id > 0 AND i = 1` to `id > 5 AND i = 1 AND i * id > 0`. With `i` and 
`w` ANSI casts, `i + 1 > 0 AND w > 5 AND i = 1` optimizes to `i = 1 AND w > 5`, 
so no row evaluates `i + 1`. With a never-failing marked alias such as 
`upper(trim(code))`, a costly conjunct written before the equality no longer 
runs ahead of it. The PR's target queries still return ('1', 7), with the 
filter kept above and pushed below.
   
   **Verification:**
   - **Regression:** Plan tests that check conjunct order show that `10 / (id - 
i) > 0 AND i = 1`, `i > 0 AND 10 / x > 0 AND i = 1` and `n / i > 1 AND i = 5` 
over a projection with an ANSI-cast alias put the equality right before the 
conjunct that first reads its column.
   - **Regression:** End-to-end ANSI-mode queries over one Parquet file, with 
the filter kept above the projection by a read non-deterministic column, return 
the base branch's rows for `10 / (id - i) > 0 AND i = 1` over ('1', 7), ('8', 
8) with whole-stage codegen on and off, and return ('1', 7) for `id > 5 AND 10 
/ (id - i) > 0 AND i = 1` over ('1', 7), ('8', 8), ('x', 0) with codegen on, 
where the base branch raises CAST_INVALID_INPUT and the PR DIVIDE_BY_ZERO; with 
the filter pushed below the projection, that query returns ('1', 7) with 
codegen on and off.
   - **Regression:** A plan test shows that `i + 1 > 0 AND w > 5 AND i = 1`, 
with `i` and `w` ANSI-cast aliases, optimizes to `i = 1 AND w > 5`, and an 
end-to-end ANSI-mode query with the filter kept above the projection returns no 
rows, without ARITHMETIC_OVERFLOW, over a row whose `i` is 2147483647.
   - **Regression:** A plan test with a never-failing marked alias shows a 
costly conjunct written before the equality over it now runs after the equality.
   - **Behavior:** The PR's existing target queries still return ('1', 7) kept 
above and pushed below, and the plan tests that pinned the written order expect 
the new placement.
   - **Compatibility:** When the projection becomes deterministic so the filter 
is later pushed below with the alias substituted, including when a read 
non-deterministic field keeps the filter above until a later iteration removes 
that read, a condition whose first reader evaluates the column only inside an 
OR or COALESCE operand keeps the equality where it is written, and no row 
computes a cast the written order skips.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/ConstantPropagationSuite.scala:
##########
@@ -324,4 +324,184 @@ class ConstantPropagationSuite extends PlanTest {
     val lengthOfTrimmed = trimmed.where($"s" === "a" && Length($"s") === 
2).analyze
     comparePlans(Optimize.execute(lengthOfTrimmed), lengthOfTrimmed)
   }
+
+  // SPARK-61437: the columns of the projection below that can fail.
+  private val strings = LocalRelation($"s".string, $"id".long, $"x".long)
+  private def castS: Expression = $"s".cast(IntegerType)
+  private def projected: LogicalPlan = strings.select($"s", $"id", $"x", 
castS.as("i"))
+  private def divide(e: Expression): Expression = Divide(Literal(10.0), 
e.cast(DoubleType))
+
+  private def conjuncts(plan: LogicalPlan): Seq[String] = plan match {
+    case Filter(condition, _) => 
splitConjunctivePredicates(condition).map(_.sql)
+    case other => fail(s"Expected a Filter: $other")
+  }
+
+  /** Checks the optimized plan also in the order of the conjuncts, which 
`comparePlans` sorts. */
+  private def checkOrdered(child: LogicalPlan, condition: Expression, 
expected: Expression)
+    : Unit = {
+    val optimized = Optimize.execute(child.where(condition).analyze)
+    val expectedPlan = child.where(expected).analyze
+    comparePlans(optimized, expectedPlan)
+    assert(conjuncts(optimized) == conjuncts(expectedPlan))
+  }
+
+  test("SPARK-61437: Do not move an equality over a column of the projection 
below that can " +
+      "fail") {
+    withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+      // `i = 1` can fail, as the cast does, so it is not moved ahead of `id > 
5`.
+      val written = $"id" > 5L && $"i".cast(LongType) * $"id" > 0L && $"i" === 
1
+      Seq(
+        projected,
+        projected.select($"s", $"id", $"i"),
+        projected.where($"id" > 1L).select($"s", $"id", $"i"),
+        projected.sample(0.0, 0.5, withReplacement = false, 1L).select($"s", 
$"id", $"i"),
+        projected.select($"s", $"id", $"i".as("j")).select($"s", $"id", 
$"j".as("i"))
+      ).foreach(child => checkOrdered(child, written, written))
+    }
+  }
+
+  test("SPARK-61437: Propagate an equality over a column that can fail where 
it is written") {
+    withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+      // A conjunct before it that it rewrites can pass a row it would not 
only where it would fail
+      // as well or where `i` does not fail, so `i = 1` raises no new error, 
and the conjuncts
+      // after it only run where it does not fail.
+      Seq(
+        ($"id" > 5L && $"i" + 1 > 1 && $"i" === 1) -> ($"id" > 5L && $"i" === 
1),
+        (($"id" < 0L || $"i" + 1 > 3) && $"i" === 1) -> ($"id" < 0L && $"i" 
=== 1),
+        (divide($"i") > 1.0 && $"i" === 1) -> ($"i" === 1),
+        ($"id" > 5L && ($"i" <=> 1) && $"i" > 0) -> ($"id" > 5L && ($"i" <=> 
1)),
+        ($"id" > 5L && (Literal(1) <=> $"i") && $"i" > 0) -> ($"id" > 5L && 
(Literal(1) <=> $"i")),
+        // Only the conjuncts from the first rewritten one to it count.
+        (divide($"x") > 0.0 && $"i" > 0 && $"i" === 1) -> (divide($"x") > 0.0 
&& $"i" === 1),
+        ($"i" + 1 > 1 && $"i" === 1 && divide($"x") > 0.0) -> ($"i" === 1 && 
divide($"x") > 0.0),
+        // `id > 0` is rewritten by `id = 7`, which goes first. Then `i = 1` 
is propagated too.
+        ($"id" > 0L && divide($"x") > 0.0 && $"i" === 1 && $"i" + 1 > 1 && 
$"id" === 7L) ->
+          ($"id" === 7L && divide($"x") > 0.0 && $"i" === 1)
+      ).foreach { case (condition, expected) => checkOrdered(projected, 
condition, expected) }
+    }
+  }
+
+  test("SPARK-61437: Do not propagate an equality over a column that can fail 
past a " +
+      "conjunct that can fail") {
+    withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+      // The division would run on the rows that `i > 0` passes when 
rewritten, i.e. all rows.
+      val twoCasts = projected.select($"s", $"id", $"x", $"i", castS.as("j"))
+      Seq(
+        $"id" > 5L && $"i" > 0 && divide($"x") > 0.0 && $"i" === 1,
+        $"id" > 5L && $"i" > 0 && divide($"x") > 0.0 && Literal(1) === $"i",
+        $"id" > 5L && $"i" > 0 && divide($"x") > 0.0 && ($"i" <=> 1),
+        $"id" > 5L && $"i" > 0 && divide($"x") > 0.0 && (Literal(1) <=> $"i"),
+        // Without `i = 1`, `i > 0` can fail, and it comes between `j = 2` and 
`j > 0`.
+        $"j" > 0 && $"i" > 0 && $"j" === 2 && divide($"x") > 0.0 && $"i" === 1
+      ).foreach(condition => checkOrdered(twoCasts, condition, condition))
+
+      // Unless a conjunct before it becomes FALSE, or NULL, which is made 
FALSE, so no row
+      // reaches it.
+      Seq(
+        $"i" + 1 > 3 && divide($"x") > 0.0 && $"i" === 1,
+        $"i" === 1 && divide($"x") > 0.0 && $"i" === 2,
+        If($"i" === 1, Literal(null, IntegerType), $"i") > 0 && divide($"x") > 
0.0 && $"i" === 1
+      ).foreach { condition =>
+        comparePlans(Optimize.execute(projected.where(condition).analyze),
+          projected.where(false).analyze)
+      }
+      // But not NULL under a `NOT`, where the division still runs after it.
+      val upperNotNull = LocalRelation($"s".string.notNull, $"x".long.notNull)
+        .select($"x", Upper($"s").as("u"))
+      Optimize.execute(upperNotNull.where(Not(
+        If($"u" === "X", Literal(null, StringType), $"u") === "Y" && 
divide($"x") > 0.0 &&
+          $"u" === "X")).analyze) match {
+        case Filter(negated, _) => assert(negated.exists(_.isInstanceOf[If]))
+        case other => fail(s"Expected a Filter: $other")
+      }
+    }
+  }
+
+  test("SPARK-61437: A conjunct over a column that can fail can fail") {
+    withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+      // `id = 7` folds the guard `id > 0`, so it goes ahead of `i > 0`, which 
can fail.
+      checkOrdered(projected, $"id" > 0L && $"i" > 0 && $"id" === 7L, $"id" 
=== 7L && $"i" > 0)
+      checkOrdered(projected, $"id" > 0L && $"i" === 1 && $"id" === 7L,
+        $"id" === 7L && $"i" === 1)
+      // `id < 3` decides whether `i > 0` runs, so it keeps `id`, and the 
equality goes first.
+      checkOrdered(projected, ($"id" < 3L || $"i" > 0) && $"id" === 5L,
+        $"id" === 5L && ($"id" < 3L || $"i" > 0))
+
+      // Also under a `NOT`, with `s` and `id` not nullable.
+      val notNull = LocalRelation($"s".string.notNull, $"id".long.notNull)
+        .select($"s", $"id", castS.as("i"))
+      checkOrdered(notNull, Not($"id" > 0L && $"i" > 0 && $"id" === 7L),
+        Not($"id" === 7L) || $"i" <= 0)
+      // The cast is marked nullable (`Cast.forceNullable`), so `i = 1` is not 
propagated under
+      // it, as on master.
+      checkOrdered(notNull, Not($"i" + 1 > 3 && $"i" === 1), $"i" + 1 <= 3 || 
Not($"i" === 1))
+      // `upper` is not, so the condition inside becomes FALSE, as on master.
+      val upperNotNull = notNull.select($"s", Upper($"s").as("u"))
+      comparePlans(
+        Optimize.execute(upperNotNull.where(Not(Length($"u") > 3 && $"u" === 
"X")).analyze),
+        upperNotNull.where(true).analyze)
+      // But one that becomes NULL is not made FALSE, which the `NOT` would 
turn into TRUE.
+      val nullInside = Optimize.execute(upperNotNull.where(Not(
+        If($"u" === "X", Literal(null, StringType), $"u") === "Y" && $"u" === 
"X")).analyze)
+      assert(!nullInside.fastEquals(upperNotNull.where(true).analyze))
+    }
+  }
+
+  test("SPARK-61437: A condition that becomes FALSE with the constants is 
FALSE") {
+    withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+      Seq(
+        $"id" > 5L && $"i" + 1 > 3 && $"i" === 1,
+        $"i" === 1 && $"i" + 1 > 3,
+        $"i" + 1 > 3 && Literal(1) === $"i",
+        $"i" === 1 && $"id" > 5L && $"i" === 2,
+        $"i".cast(LongType) + $"id" > 3L && $"i" === 1 && $"id" === 1L
+      ).foreach { condition =>
+        comparePlans(Optimize.execute(projected.where(condition).analyze),
+          projected.where(false).analyze)
+      }
+      comparePlans(
+        Optimize.execute(
+          projected.where(($"id" < 0L || ($"i" + 1 > 3 && $"i" === 1)) && 
$"id" > 5L).analyze),
+        projected.where($"id" < 0L && $"id" > 5L).analyze)
+    }
+  }
+
+  test("SPARK-61437: Columns that can not fail") {
+    withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+      // A non-deterministic alias is computed on every row the projection 
gets, so it raises no
+      // new error here, and an equality over it is propagated and moved.
+      val random = strings.select($"id", $"x", Rand(1L).as("r"))
+      checkOrdered(random, $"r" > 0.0 && $"r" === 0.5, $"r" === 0.5)
+      checkOrdered(random, $"r" > 0.0 && divide($"x") > 0.0 && $"r" === 0.5,
+        $"r" === 0.5 && divide($"x") > 0.0)
+      // So is one over a column that reads it with an expression that can not 
fail.
+      val randomPlusOne = random.select($"id", ($"r" + 1.0).as("r1"))
+      checkOrdered(randomPlusOne, $"r1" > 0.0 && $"r1" === 1.5, $"r1" === 1.5)

Review Comment:
   **Nit (P3):** This passes whether or not `r1` is treated as able to fail: 
with nothing between `r1 > 0.0` and `r1 === 1.5`, the equality would still be 
propagated, `1.5 > 0.0` would still fold away, and the plan would still be `r1 
= 1.5`. The `r` and `k` cases each add a `divide` case that checks the equality 
moves first; adding `checkOrdered(randomPlusOne, $"r1" > 0.0 && divide($"id") > 
0.0 && $"r1" === 1.5, $"r1" === 1.5 && divide($"id") > 0.0)` would give `r1` 
the same check (the projection outputs only `id` and `r1`).
   
   **Verification:**
   - **Regression:** A plan test with a conjunct that can fail between `r1 > 
0.0` and `r1 = 1.5` checks that the equality over `r1` moves first, so marking 
such a column fails it.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


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

Reply via email to