dongjoon-hyun commented on code in PR #60516:
URL: https://github.com/apache/spark/pull/60516#discussion_r4591709797


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -195,14 +200,29 @@ 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 (movable, failable) = equalityPredicates.toSeq.partition { case 
(attr, _) =>
+            columns.canEvaluateUnconditionally(attr)
+          }
+          val substituted = if (failable.isEmpty) {
+            Some(unreplaced)
+          } else {
+            replaceConstantsInPlace(unreplaced, AttributeMap(failable))
+          }
+          Some(substituted match {
+            case Some(condition) if movable.isEmpty => condition
+            case Some(condition) => moveEqualitiesFirst(condition,
+              replaceConstants(condition, AttributeMap(movable)), 
AttributeMap(movable), columns)

Review Comment:
   **[2] With an equality of each kind, a condition that 4.3.0 folds to `FALSE` 
is kept, and a conjunct rewritten in place then fails where both master and 
4.3.0 return no row.**
   
   The constant of an equality over a column that can not fail goes through 
`replaceConstants` here, which, as on master, does not put it into an `IF` or 
`CASE WHEN` that also reads another column, while 4.3.0 put every constant into 
every comparison. So where that made the condition `FALSE` on 4.3.0, the 
condition is kept, while the conjuncts that the other constant rewrote in place 
stay rewritten, and `id = 7` goes first. With ANSI mode on, over a Parquet file 
with the row `(s, id, x) = ("2", 7, 1)`:
   
   ```scala
   val df = spark.read.parquet(path)
     .select($"s", $"id", $"x", $"s".cast("int").as("i"), rand(1).as("r"))
   df.where(lit(10) / ($"x" - $"i") > 0 && when($"id" > 10, lit(10) / 
$"x").otherwise(0) > 1 &&
     $"i" === 1 && $"id" === 7).select($"s", $"id", $"r" >= 0)
   ```
   
   - As written, `10 / (x - i)` is -10 on the row, so the condition is `FALSE` 
there.
   - 4.3.0 turns the `CASE WHEN` into `0 > 1` with `id` = 7, so the filter is 
`FALSE` and pruned.
   - Master moves `i = 1` first, which filters the row out.
   - This PR gives `id = 7 AND 10 / (x - 1) > 0 AND CASE WHEN id > 10 ... AND i 
= 1`, which fails with `DIVIDE_BY_ZERO` on the row.
   
   `when($"id" > 7, $"x" > 1).otherwise(false)` as the second conjunct does the 
same. Could the rule keep the result of 4.3.0 where the condition with all of 
the constants in place becomes `FALSE`, which here takes `SimplifyConditionals` 
as well as `ConstantFolding`? Otherwise, could the description and the tests 
cover this case?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -236,6 +256,68 @@ object ConstantPropagation extends Rule[LogicalPlan] with 
PredicateHelper {
   private def safeToReplace(ar: AttributeReference, nullIsFalse: Boolean) =
     !ar.nullable || nullIsFalse
 
+  /**
+   * Replaces the attributes of `equalityPredicates` with their constants in 
the comparisons of
+   * `condition` other than those equalities, where they are written, as 
before SPARK-60983, or
+   * returns None if `condition` would then fail to fold. These are the 
equalities over a column of
+   * the projection below that can fail (see [[FailableColumns]]), e.g. `i = 
1` with `i` the alias
+   * `CAST(s AS INT)`. Such an equality can fail, so it can not go first, as 
it would compute the
+   * column on rows that the conjuncts before it filter out. A comparison that 
it rewrites no longer
+   * reads the column, so the conditions read the column in no more places 
than written. A rewritten
+   * conjunct can fail on a row where the equality does not hold, e.g. `10 / 
(id - 1)` for
+   * `10 / (id - i) > 0 AND i = 1` on a row where `id` is 1 and `i` is 2, a 
conjunct after one that
+   * the constant folds away can run on such a row, e.g. `10 / x > 0` for
+   * `i > 0 AND 10 / x > 0 AND i = 1`, and a rewritten conjunct can pass a row 
on to another such
+   * equality that the written one stops, e.g. `j < 5` for `j < 5 AND i = 2 
AND j = 1`, as before
+   * SPARK-60983. A condition that would fail to fold, outside of a 
conditional branch, e.g. with
+   * `id > 10 / 0` for `i = 0 AND id > 10 / i`, failed the query before 
SPARK-60983, unless a rule
+   * before [[ConstantFolding]] removed the part that fails, e.g. 
[[FoldablePropagation]], so the
+   * caller then handles its equalities as since SPARK-60983. As before, an 
attribute whose type is
+   * not binary stable is replaced only in a comparison with an attribute of 
the same type (see
+   * [[isSameCollationAttrRefComparison]]), one outside of a comparison, e.g. 
in `i IN (1, 2)`, is
+   * kept, and one in the correlation of a subquery in a comparison is 
replaced.
+   */
+  private def replaceConstantsInPlace(
+      condition: Expression,
+      equalityPredicates: AttributeMap[(Literal, BinaryComparison)]): 
Option[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)

Review Comment:
   **[1] The in-place replacement also goes under a cast of a `DOUBLE` to a 
`STRING`, which tells -0.0 from 0.0, so a filter over a `DOUBLE` column that 
can fail can return wrong rows.**
   
   On master, `replaceConstants` goes into an operator only if 
`ExprUtils.isTotalOperator` accepts it or the whole operator then folds, and 
`Cast.isTotalCast` rejects a cast that can keep the sign of a zero 
(Cast.scala:637, Cast.scala:645). The transform here replaces every attribute 
of a binary stable type in the comparison, so the constant of an equality over 
a `DOUBLE` column that can fail goes under such a cast too, e.g. into `CAST(x * 
y AS STRING)`, which master keeps as it is. With ANSI mode on, over a Parquet 
file with the row `(s, y) = ("-0.0", 1.0)`:
   
   ```scala
   val df = spark.read.parquet(path)
     .select($"s", $"y", $"s".cast("double").as("x"), rand(1).as("r"))
   df.where($"x" === 0.0 && ($"x" * $"y").cast("string") === 
"-0.0").select($"s", $"r" >= 0)
   ```
   
   The row passes `x = 0.0`, as -0.0 is equal to 0.0, and `CAST(x * y AS 
STRING)` is `'-0.0'`, so master returns it. With this PR, the second conjunct 
becomes `CAST(0.0 * y AS STRING) = '-0.0'`, which is `FALSE` for the row, so 
the row is dropped. With `y` = -1.0, a row that the written condition filters 
out is returned instead, and `pow(x, y) < 0` in place of the cast drops the row 
the same way. 4.3.0 returns the same wrong rows, but the description lists only 
errors among what comes back for such a column, and the test at 
ConstantPropagationSuite.scala:315-320 does not catch this, as `x` is a column 
of the relation there, which goes through `replaceConstants`.
   
   Could the in-place replacement keep an attribute of a type with a `FLOAT` or 
`DOUBLE` in it under an operator that `ExprUtils.isTotalOperator` does not 
accept, as it already keeps a string of a non-binary collation, and could the 
suite check this case over a column that can fail?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -316,34 +401,89 @@ object ConstantPropagation extends Rule[LogicalPlan] with 
PredicateHelper {
    * Moves the equalities ahead of the other conjuncts of `condition`, the 
rewritten `original`, if
    * one that can fail still refers to a propagated attribute. Such a conjunct 
also runs on rows
    * 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.
+   * 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`. 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. The first rewritten conjunct 
counts too, not only the
+   * ones after it, if it reads such a column, as [[replaceConstants]] 
rewrites its operands as if
+   * the column could not fail, e.g. `id < 3` in `(id < 3 OR i > 0) AND id = 
7`.
+   * `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 [[replaceConstantsInPlace]]), and `original` 
has their constants
+   * already, unless the condition fails to fold with them, where 
`equalityPredicates` are all of
+   * the equalities, as since SPARK-60983. `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 unmasksFailable = firstRewritten >= 0 && 
(columns.reads(conjuncts(firstRewritten)) ||
+      conjuncts.drop(firstRewritten + 
1).exists(!columns.canEvaluateUnconditionally(_)))

Review Comment:
   **[4] In the fallback, `unmasksFailable` counts the equality over the column 
that can fail, so the equalities go first where master keeps the written 
order.**
   
   In the fallback at L223-224, `i = 0` is one of the equalities that go first, 
but it is also among the conjuncts that `unmasksFailable` checks, and 
`columns.canEvaluateUnconditionally` rejects it, as it reads `i`. So a 
rewritten conjunct before `i = 0` makes `unmasksFailable` true, while master, 
which checks with `ExprUtils.canEvaluateUnconditionally` only, does not count 
the equality. With ANSI mode on, the filter above the projection as in the 
description, and a Parquet file with the rows `(s, id, x) = ("0", 7, 1), ("x", 
0, 0)` of a string and two integers:
   
   ```scala
   $"x" > 0 && ($"id" > 5 || lit(10) / $"i" > 1).cast("int") === 1 && $"i" === 
0 && $"id" === 7
   ```
   
   With `i` = 0 in place, `10 / 0` folds outside of a conditional branch, so 
the rule falls back, and `replaceConstants` folds the second conjunct to `1 = 
1`. Master then keeps the written order, so `x > 0` filters out the row ("x", 
0, 0), and it returns ("0", 7), as does 4.3.0, which folds the second conjunct 
to `TRUE`. This PR gives `i = 0 AND id = 7 AND x > 0`, which fails with 
`CAST_INVALID_INPUT` on the row ("x", 0, 0).
   
   Could the check leave out the equalities, as below? As far as I can see, the 
tests keep their expected results with it. As the description says that the 
rule then handles the equalities as on master, checking with `ExprUtils` alone 
in the fallback, as master does, would also work.
   
   ```scala
   conjuncts.drop(firstRewritten + 1)
     .exists(c => !predicates.contains(c) && 
!columns.canEvaluateUnconditionally(c))
   ```



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -236,6 +256,68 @@ object ConstantPropagation extends Rule[LogicalPlan] with 
PredicateHelper {
   private def safeToReplace(ar: AttributeReference, nullIsFalse: Boolean) =
     !ar.nullable || nullIsFalse
 
+  /**
+   * Replaces the attributes of `equalityPredicates` with their constants in 
the comparisons of
+   * `condition` other than those equalities, where they are written, as 
before SPARK-60983, or
+   * returns None if `condition` would then fail to fold. These are the 
equalities over a column of
+   * the projection below that can fail (see [[FailableColumns]]), e.g. `i = 
1` with `i` the alias
+   * `CAST(s AS INT)`. Such an equality can fail, so it can not go first, as 
it would compute the
+   * column on rows that the conjuncts before it filter out. A comparison that 
it rewrites no longer
+   * reads the column, so the conditions read the column in no more places 
than written. A rewritten
+   * conjunct can fail on a row where the equality does not hold, e.g. `10 / 
(id - 1)` for
+   * `10 / (id - i) > 0 AND i = 1` on a row where `id` is 1 and `i` is 2, a 
conjunct after one that
+   * the constant folds away can run on such a row, e.g. `10 / x > 0` for
+   * `i > 0 AND 10 / x > 0 AND i = 1`, and a rewritten conjunct can pass a row 
on to another such
+   * equality that the written one stops, e.g. `j < 5` for `j < 5 AND i = 2 
AND j = 1`, as before
+   * SPARK-60983. A condition that would fail to fold, outside of a 
conditional branch, e.g. with
+   * `id > 10 / 0` for `i = 0 AND id > 10 / i`, failed the query before 
SPARK-60983, unless a rule
+   * before [[ConstantFolding]] removed the part that fails, e.g. 
[[FoldablePropagation]], so the
+   * caller then handles its equalities as since SPARK-60983. As before, an 
attribute whose type is
+   * not binary stable is replaced only in a comparison with an attribute of 
the same type (see
+   * [[isSameCollationAttrRefComparison]]), one outside of a comparison, e.g. 
in `i IN (1, 2)`, is
+   * kept, and one in the correlation of a subquery in a comparison is 
replaced.
+   */
+  private def replaceConstantsInPlace(
+      condition: Expression,
+      equalityPredicates: AttributeMap[(Literal, BinaryComparison)]): 
Option[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)
+      }
+    }
+    val rewritten = 
condition.transformWithPruning(_.containsPattern(BINARY_COMPARISON)) {
+      case b: BinaryComparison if !predicates.contains(b) => 
replaceInComparison(b)
+    }
+    Some(rewritten).filter(r => r.fastEquals(condition) || 
foldsWithoutError(r))

Review Comment:
   **[3] The fold check sees only the constants of the equalities over a column 
that can fail, so a condition that fails to fold once more constants are in 
does not fall back to the handling of master.**
   
   `foldsWithoutError` checks the condition as this rule runs, with only those 
constants in it, and `ConstantFolding` folds every child of a conditional 
expression that is not foldable as a branch (L92). So a part that becomes 
constant only after the other constants or `FoldablePropagation` put more in 
still fails, also outside of a conditional branch. With ANSI mode on, the 
filter above the projection as in the description, and the row `(s, id) = ("2", 
7)`:
   
   1. `coalesce(lit(10) / $"i", $"id") > 0 && $"i" === 0 && $"id" === 7`: the 
check folds `coalesce(10 / 0, id)` without an error, as `10 / 0` is a branch 
there. Then `replaceConstants` makes it `coalesce(10 / 0, 7)`, which is 
foldable, so `ConstantFolding` evaluates it and fails.
   2. `$"id" > $"total" / $"i" && $"i" === 0`, with `total` the alias 
`lit(100)`: the check sees `total / 0`, which does not fold, and 
`FoldablePropagation`, which runs after this rule (Optimizer.scala:135-136), 
then makes it `100 / 0`.
   3. `lit(10) / ($"id" - 6 - $"i") > 0 && $"i" === 1 && $"id" === 7`: the 
check passes `10 / (id - 6 - 1)`, `replaceConstants` keeps it, as it fails to 
fold with `id` = 7, and `id = 7` goes first. So every row with `id` = 7 fails 
with `DIVIDE_BY_ZERO`, also this one, on which the written condition is `FALSE`.
   
   The first two fail while the query is optimized, also over an empty table. 
Master returns no row in all three, and 4.3.0 fails while the query is 
optimized, so they do not match "such a query no longer fails while it is 
optimized" in the description. Could the check also put in the constants of the 
other equalities, as 4.3.0 would, which covers the first and the third? The 
second would also need the foldable aliases of the projection below, so it may 
be simpler to narrow that sentence of the description.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -316,34 +401,89 @@ object ConstantPropagation extends Rule[LogicalPlan] with 
PredicateHelper {
    * Moves the equalities ahead of the other conjuncts of `condition`, the 
rewritten `original`, if
    * one that can fail still refers to a propagated attribute. Such a conjunct 
also runs on rows
    * 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.
+   * 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`. 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. The first rewritten conjunct 
counts too, not only the
+   * ones after it, if it reads such a column, as [[replaceConstants]] 
rewrites its operands as if
+   * the column could not fail, e.g. `id < 3` in `(id < 3 OR i > 0) AND id = 
7`.
+   * `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 [[replaceConstantsInPlace]]), and `original` 
has their constants
+   * already, unless the condition fails to fold with them, where 
`equalityPredicates` are all of
+   * the equalities, as since SPARK-60983. `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 unmasksFailable = firstRewritten >= 0 && 
(columns.reads(conjuncts(firstRewritten)) ||
+      conjuncts.drop(firstRewritten + 
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 its 
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.
+   */
+  private class FailableColumns(plan: LogicalPlan) {

Review Comment:
   **[6] nit: The columns that can fail are a property of the plan below, so 
`FailableColumns` could be a shared helper rather than a private class of this 
rule.**
   
   `CombineFilters` has the same blind spot: it combines a conjunct written 
after a non-deterministic one with the filter below when 
`ExprUtils.canEvaluateUnconditionally` accepts it (Optimizer.scala:2489), also 
when the conjunct reads an alias that can fail. With ANSI mode on, this fails 
with `DIVIDE_BY_ZERO` on master and with this PR, although `rand(10) * 10 > 
100` is never true:
   
   ```scala
   spark.range(0, 10, 1, 1).toDF()
     .select($"id", (lit(10L) / ($"id" - 3)).as("q"))
     .where($"id" >= 0)
     .where(rand(10) * 10 > 100 && $"q" > 0)
   ```
   
   That is a separate issue from this PR, but it is a second rule that needs 
the same notion. Could `failableOutput` and a `canEvaluateUnconditionally(expr, 
plan)` live next to `canEvaluate` in `PredicateHelper`, so that the rules share 
one definition? This does not need to block this PR.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -236,6 +256,68 @@ object ConstantPropagation extends Rule[LogicalPlan] with 
PredicateHelper {
   private def safeToReplace(ar: AttributeReference, nullIsFalse: Boolean) =
     !ar.nullable || nullIsFalse
 
+  /**
+   * Replaces the attributes of `equalityPredicates` with their constants in 
the comparisons of
+   * `condition` other than those equalities, where they are written, as 
before SPARK-60983, or
+   * returns None if `condition` would then fail to fold. These are the 
equalities over a column of
+   * the projection below that can fail (see [[FailableColumns]]), e.g. `i = 
1` with `i` the alias
+   * `CAST(s AS INT)`. Such an equality can fail, so it can not go first, as 
it would compute the
+   * column on rows that the conjuncts before it filter out. A comparison that 
it rewrites no longer
+   * reads the column, so the conditions read the column in no more places 
than written. A rewritten
+   * conjunct can fail on a row where the equality does not hold, e.g. `10 / 
(id - 1)` for
+   * `10 / (id - i) > 0 AND i = 1` on a row where `id` is 1 and `i` is 2, a 
conjunct after one that
+   * the constant folds away can run on such a row, e.g. `10 / x > 0` for
+   * `i > 0 AND 10 / x > 0 AND i = 1`, and a rewritten conjunct can pass a row 
on to another such
+   * equality that the written one stops, e.g. `j < 5` for `j < 5 AND i = 2 
AND j = 1`, as before
+   * SPARK-60983. A condition that would fail to fold, outside of a 
conditional branch, e.g. with
+   * `id > 10 / 0` for `i = 0 AND id > 10 / i`, failed the query before 
SPARK-60983, unless a rule
+   * before [[ConstantFolding]] removed the part that fails, e.g. 
[[FoldablePropagation]], so the
+   * caller then handles its equalities as since SPARK-60983. As before, an 
attribute whose type is
+   * not binary stable is replaced only in a comparison with an attribute of 
the same type (see
+   * [[isSameCollationAttrRefComparison]]), one outside of a comparison, e.g. 
in `i IN (1, 2)`, is
+   * kept, and one in the correlation of a subquery in a comparison is 
replaced.
+   */
+  private def replaceConstantsInPlace(
+      condition: Expression,
+      equalityPredicates: AttributeMap[(Literal, BinaryComparison)]): 
Option[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)
+      }
+    }
+    val rewritten = 
condition.transformWithPruning(_.containsPattern(BINARY_COMPARISON)) {
+      case b: BinaryComparison if !predicates.contains(b) => 
replaceInComparison(b)
+    }
+    Some(rewritten).filter(r => r.fastEquals(condition) || 
foldsWithoutError(r))
+  }
+
+  /**
+   * Whether [[ConstantFolding]] folds `e`, an AND in a filter condition, 
without an error, which
+   * it raises for a part of `e` that becomes constant and fails, except in a 
conditional branch.
+   * It tags the parts that fail in one, which can be shared with the plan, so 
the tags it sets
+   * are removed.
+   */
+  private def foldsWithoutError(e: Expression): Boolean = {
+    val tagged = java.util.Collections.newSetFromMap(
+      new java.util.IdentityHashMap[Expression, java.lang.Boolean]())
+    e.foreach(n => if 
(n.getTagValue(ConstantFolding.FAILED_TO_EVALUATE).isDefined) tagged.add(n))
+    try {
+      ConstantFolding.constantFolding(e)
+      true
+    } catch {
+      case NonFatal(_) => false
+    } finally {
+      e.foreach { n =>
+        if (!tagged.contains(n)) 
n.unsetTagValue(ConstantFolding.FAILED_TO_EVALUATE)

Review Comment:
   **[5] `foldsWithoutError` removes `FAILED_TO_EVALUATE` from nodes that other 
plans share, where another thread's `ConstantFolding` may have just set it.**
   
   The nodes of `e` that this rule does not rewrite are those of the plan, and 
the plans of the queries over one DataFrame share them, also when they are 
optimized at the same time on different threads. `ConstantFolding` already sets 
this tag on such shared nodes, and this is the first code that removes it: if 
another thread sets it on a node of `e` between L308 and L315, the node is not 
in `tagged`, so L316 removes the tag. That thread then folds the node again. 
That is mostly extra work, but where `SimplifyConditionals` has taken the node 
out of its branch in the meantime, e.g. out of an `IF` whose condition became 
`TRUE`, `tryFold` then raises the error while the query is optimized, which the 
tag would have left to the rows that reach it.
   
   The timing is narrow, so this is a robustness concern rather than a failure 
I have reproduced. Could the check fold without setting the tag, e.g. with a 
flag on `ConstantFolding.constantFolding`, or fold a copy? That would also save 
the passes at L308 and L315 (see [8]).



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -316,34 +401,89 @@ object ConstantPropagation extends Rule[LogicalPlan] with 
PredicateHelper {
    * Moves the equalities ahead of the other conjuncts of `condition`, the 
rewritten `original`, if
    * one that can fail still refers to a propagated attribute. Such a conjunct 
also runs on rows
    * 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.
+   * 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`. 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. The first rewritten conjunct 
counts too, not only the
+   * ones after it, if it reads such a column, as [[replaceConstants]] 
rewrites its operands as if
+   * the column could not fail, e.g. `id < 3` in `(id < 3 OR i > 0) AND id = 
7`.
+   * `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 [[replaceConstantsInPlace]]), and `original` 
has their constants
+   * already, unless the condition fails to fold with them, where 
`equalityPredicates` are all of
+   * the equalities, as since SPARK-60983. `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 unmasksFailable = firstRewritten >= 0 && 
(columns.reads(conjuncts(firstRewritten)) ||
+      conjuncts.drop(firstRewritten + 
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 its 
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.
+   */
+  private class FailableColumns(plan: LogicalPlan) {
+    private lazy val failable: AttributeSet = failableOutput(plan)

Review Comment:
   **[7] `FailableColumns` walks the plan below every filter again on every 
application, and `reads` copies the set of references even when no column can 
fail.**
   
   Each application creates a `FailableColumns` per filter, and the partition 
at L209 forces `failable` whenever the condition has an equality, which walks 
every projection, filter and sample below the filter. So on a plan with `m` 
filters stacked over projections with a non-deterministic column, which the 
optimizer can neither push nor merge, the work of each application is quadratic 
in `m`, in every iteration of the batch. By a rough count, that is about 5M 
attribute checks for `m` = 300, against about 48K with the result kept per plan 
node. Also, `reads` (L484) goes through `AttributeSet.iterator`, which copies 
the set (AttributeSet.scala:98), for every expression it checks, also when 
`failable` is empty, as it is for most queries.
   
   Could `reads` return `false` right away when `failable` is empty, and could 
one application keep `failableOutput` per plan node, e.g. in an 
`IdentityHashMap`?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -236,6 +256,68 @@ object ConstantPropagation extends Rule[LogicalPlan] with 
PredicateHelper {
   private def safeToReplace(ar: AttributeReference, nullIsFalse: Boolean) =
     !ar.nullable || nullIsFalse
 
+  /**
+   * Replaces the attributes of `equalityPredicates` with their constants in 
the comparisons of
+   * `condition` other than those equalities, where they are written, as 
before SPARK-60983, or
+   * returns None if `condition` would then fail to fold. These are the 
equalities over a column of
+   * the projection below that can fail (see [[FailableColumns]]), e.g. `i = 
1` with `i` the alias
+   * `CAST(s AS INT)`. Such an equality can fail, so it can not go first, as 
it would compute the
+   * column on rows that the conjuncts before it filter out. A comparison that 
it rewrites no longer
+   * reads the column, so the conditions read the column in no more places 
than written. A rewritten
+   * conjunct can fail on a row where the equality does not hold, e.g. `10 / 
(id - 1)` for
+   * `10 / (id - i) > 0 AND i = 1` on a row where `id` is 1 and `i` is 2, a 
conjunct after one that
+   * the constant folds away can run on such a row, e.g. `10 / x > 0` for
+   * `i > 0 AND 10 / x > 0 AND i = 1`, and a rewritten conjunct can pass a row 
on to another such
+   * equality that the written one stops, e.g. `j < 5` for `j < 5 AND i = 2 
AND j = 1`, as before
+   * SPARK-60983. A condition that would fail to fold, outside of a 
conditional branch, e.g. with
+   * `id > 10 / 0` for `i = 0 AND id > 10 / i`, failed the query before 
SPARK-60983, unless a rule
+   * before [[ConstantFolding]] removed the part that fails, e.g. 
[[FoldablePropagation]], so the
+   * caller then handles its equalities as since SPARK-60983. As before, an 
attribute whose type is
+   * not binary stable is replaced only in a comparison with an attribute of 
the same type (see
+   * [[isSameCollationAttrRefComparison]]), one outside of a comparison, e.g. 
in `i IN (1, 2)`, is
+   * kept, and one in the correlation of a subquery in a comparison is 
replaced.
+   */
+  private def replaceConstantsInPlace(
+      condition: Expression,
+      equalityPredicates: AttributeMap[(Literal, BinaryComparison)]): 
Option[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)
+      }
+    }
+    val rewritten = 
condition.transformWithPruning(_.containsPattern(BINARY_COMPARISON)) {
+      case b: BinaryComparison if !predicates.contains(b) => 
replaceInComparison(b)
+    }
+    Some(rewritten).filter(r => r.fastEquals(condition) || 
foldsWithoutError(r))
+  }
+
+  /**
+   * Whether [[ConstantFolding]] folds `e`, an AND in a filter condition, 
without an error, which
+   * it raises for a part of `e` that becomes constant and fails, except in a 
conditional branch.
+   * It tags the parts that fail in one, which can be shared with the plan, so 
the tags it sets
+   * are removed.
+   */
+  private def foldsWithoutError(e: Expression): Boolean = {
+    val tagged = java.util.Collections.newSetFromMap(
+      new java.util.IdentityHashMap[Expression, java.lang.Boolean]())
+    e.foreach(n => if 
(n.getTagValue(ConstantFolding.FAILED_TO_EVALUATE).isDefined) tagged.add(n))
+    try {
+      ConstantFolding.constantFolding(e)

Review Comment:
   **[8] nit: `foldsWithoutError` walks the whole condition three times and 
folds all of it, then throws the result away, each time the in-place rewrite 
changes something.**
   
   It walks the condition for the tags at L308, folds it at L310, and walks it 
again at L315, while only the conjuncts that the constants changed can newly 
fail to fold. As this rule runs before `ConstantFolding`, the fold also 
evaluates the foldable parts that were already there, e.g. a `from_json` or 
`sequence` of literals, only to throw them away, and on a long left-deep `AND` 
it is quadratic in the number of conjuncts, as `foldable` is not cached. Where 
the check fails, the condition keeps the column, so the next iteration rewrites 
it in place, fails the check and falls back again, with one more exception per 
iteration than on master.
   
   Could the check fold only the conjuncts that changed, skip those that 
`ExprUtils.canEvaluateUnconditionally` accepts, and fold without setting the 
tag (see [5])?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -316,34 +401,89 @@ object ConstantPropagation extends Rule[LogicalPlan] with 
PredicateHelper {
    * Moves the equalities ahead of the other conjuncts of `condition`, the 
rewritten `original`, if
    * one that can fail still refers to a propagated attribute. Such a conjunct 
also runs on rows
    * 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.
+   * 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`. 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. The first rewritten conjunct 
counts too, not only the
+   * ones after it, if it reads such a column, as [[replaceConstants]] 
rewrites its operands as if
+   * the column could not fail, e.g. `id < 3` in `(id < 3 OR i > 0) AND id = 
7`.
+   * `equalityPredicates` are the equalities over a column that can not fail, 
which can not fail

Review Comment:
   **[9] nit: The scaladoc says that the equalities `moveEqualitiesFirst` gets 
can not fail, which does not hold in the fallback, and the fallback is 
explained in three places.**
   
   L411-412 say that `equalityPredicates` are over columns that can not fail 
and can not fail themselves, "so running them first raises no error". But the 
fallback at L223-224 passes all of the equalities, also `i = 0` with `i` a cast 
that can fail, and moving it first can then raise an error, as the test at 
ConstantPropagationSuite.scala:412-414 shows with `i = 0` ahead of `id > 5`. 
L414-415 come to the fallback only after that sentence, and L221-222 and 
L272-275 explain it as well.
   
   Could the scaladoc of `moveEqualitiesFirst` describe what it does with the 
equalities it gets, and the call site explain the fallback once? The 21-line 
scaladoc of `replaceConstantsInPlace` could then be shorter too.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/ConstantPropagationSuite.scala:
##########
@@ -324,4 +324,258 @@ 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`. Its constant is
+      // propagated in place, so only `i = 1` reads `i`.
+      val written = $"id" > 5L && $"i".cast(LongType) * $"id" > 0L && $"i" === 
1
+      val expected = $"id" > 5L && Literal(1L) * $"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, expected))
+    }
+  }
+
+  test("SPARK-61437: Propagate an equality over a column that can fail in 
place") {
+    withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+      // Into every conjunct, also one that can fail, as before SPARK-60983, 
so that a conjunct
+      // that it rewrites no longer reads `i`.
+      val twoCasts = projected.select($"s", $"id", $"x", $"i", castS.as("j"))
+      val threeCasts = twoCasts.select($"s", $"id", $"x", $"i", $"j", 
castS.as("k"))
+      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")),
+        (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" > 5L && $"i" > 0 && divide($"x") > 0.0 && $"i" === 1) ->
+          ($"id" > 5L && divide($"x") > 0.0 && $"i" === 1),
+        ($"id" > 5L && $"i" > 0 && divide($"x") > 0.0 && Literal(1) === $"i") 
->
+          ($"id" > 5L && divide($"x") > 0.0 && Literal(1) === $"i"),
+        ($"id" > 5L && $"i" > 0 && divide($"x") > 0.0 && ($"i" <=> 1)) ->
+          ($"id" > 5L && divide($"x") > 0.0 && ($"i" <=> 1)),
+        // The division reads `i` with the constant, so it does not fail on a 
row where `id` is
+        // 8 and `i` is 8, but does on one where `id` is 1 and `i` is 2, as 
before SPARK-60983.
+        (divide($"id" - $"i".cast(LongType)) > 0.0 && $"i" === 1) ->
+          (divide($"id" - 1L) > 0.0 && $"i" === 1),
+        // `id > 0` is rewritten by `id = 7`, which goes first.
+        ($"id" > 0L && divide($"x") > 0.0 && $"i" === 1 && $"i" + 1 > 1 && 
$"id" === 7L) ->
+          ($"id" === 7L && divide($"x") > 0.0 && $"i" === 1),
+        // But `id = 7` rewrites nothing here, so it stays, as on 4.3.0.
+        ($"i" + 1 > 1 && divide($"x") > 0.0 && $"i" === 1 && $"id" === 7L) ->
+          (divide($"x") > 0.0 && $"i" === 1 && $"id" === 7L)
+      ).foreach { case (condition, expected) => checkOrdered(projected, 
condition, expected) }
+      Seq(
+        ($"j" > 0 && $"i" > 0 && $"j" === 2 && divide($"x") > 0.0 && $"i" === 
1) ->
+          ($"j" === 2 && divide($"x") > 0.0 && $"i" === 1),
+        ($"i" > 0 && $"k" > 5 && $"i" === 1 && $"j" + 1 > 1 && $"j" === 2) ->
+          ($"k" > 5 && $"i" === 1 && $"j" === 2),
+        // `i + 1` does not overflow on a row where `i` is the largest integer.
+        ($"i" + 1 > 0 && $"k" > 5 && $"i" === 1) -> ($"k" > 5 && $"i" === 1),
+        // `j < 5` no longer stops a row before `i = 2`, as before SPARK-60983.
+        ($"j" < 5 && $"i" > 0 && $"i" === 2 && $"j" === 1) -> ($"i" === 2 && 
$"j" === 1)
+      ).foreach { case (condition, expected) => checkOrdered(threeCasts, 
condition, expected) }
+
+      // But not where the condition then fails to fold, which would fail the 
query with no row,
+      // unlike in a conditional branch, which is not folded where it fails. 
Then the equalities
+      // are handled as since SPARK-60983, and go first.
+      val failsToFold = $"i" === 0 && $"x".cast(DoubleType) > divide($"i")
+      checkOrdered(projected, failsToFold, failsToFold)
+      checkOrdered(projected,
+        $"id" > 5L && $"i" + 1 > 0 && $"x".cast(DoubleType) > divide($"i") && 
$"i" === 0,
+        $"i" === 0 && $"id" > 5L && $"x".cast(DoubleType) > divide($"i"))
+      // Also where the comparison folds, but the conjunct does not.
+      checkOrdered(projected,
+        $"i" === 0 && ElementAt(CreateArray(Seq(Literal(true))), ($"i" > 
0).cast(IntegerType)),
+        $"i" === 0 && ElementAt(Literal.create(Seq(true), 
ArrayType(BooleanType, false)),
+          ($"i" > 0).cast(IntegerType)))
+      checkOrdered(projected,
+        $"i" === 0 && If($"x" > 0L, divide($"i"), Literal(0.0)) > 0.0,
+        $"i" === 0 && If($"x" > 0L, divide(Literal(0)), Literal(0.0)) > 0.0)
+      checkOrdered(projected,
+        CaseWhen(Seq(($"id" < 0L) -> ($"x".cast(DoubleType) > divide($"i"))), 
$"s".isNotNull) &&
+          $"i" === 0,
+        CaseWhen(Seq(($"id" < 0L) -> ($"x".cast(DoubleType) > 
divide(Literal(0)))),
+          $"s".isNotNull) && $"i" === 0)
+      // Trying to fold it leaves no mark on a part that fails in a 
conditional branch, which
+      // would keep `ConstantFolding` from failing on the same part elsewhere.
+      val byZero = Divide(Literal(10.0), Literal(0.0))
+      val sharesByZero = projected.where($"x".cast(DoubleType) > byZero && 
$"i" === 0 &&
+        If($"x" > 0L, byZero, Literal(0.0)) > $"i".cast(DoubleType)).analyze
+      intercept[ArithmeticException](Optimize.execute(sharesByZero))
+      intercept[ArithmeticException](Optimize.execute(projected
+        .where($"i" === 0 && If($"x" > 0L, byZero, Literal(0.0)) > 
$"i".cast(DoubleType))
+        .select($"id", byZero.as("z")).analyze))
+      // Nor does it remove a mark that is there already.
+      byZero.setTagValue(ConstantFolding.FAILED_TO_EVALUATE, ())
+      Optimize.execute(sharesByZero)
+
+      // Not a string of a trim collation into `length`, as on 4.3.0: a row 
with `u` = 'A '
+      // passes `u = 'A'`.
+      val trimmed = LocalRelation(AttributeReference("s", 
StringType("UTF8_BINARY_RTRIM"))())
+        .select(Upper($"s").as("u"))
+      val lengthOfTrimmed = trimmed.where($"u" === "A" && Length($"u") === 
2).analyze
+      comparePlans(Optimize.execute(lengthOfTrimmed), lengthOfTrimmed)
+    }
+  }
+
+  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. `i > 0` counts as one that can 
not fail there, as
+      // on master, so `id < 3` is rewritten, and the equality goes first, 
ahead of `i > 0`.
+      checkOrdered(projected, ($"id" < 3L || $"i" > 0) && $"id" === 5L, $"id" 
=== 5L && $"i" > 0)
+      // So `id > 0` is rewritten too, and becomes TRUE, also inside another 
operator, so the
+      // operator folds away and `i` is not read.
+      Seq(
+        ($"id" > 0L || $"i" > 0) && $"id" === 7L,
+        ($"id" > 0L || $"x" > 0L || $"i" > 0) && $"id" === 7L
+      ).foreach(condition => checkOrdered(projected, condition, $"id" === 7L))
+      // `NullPropagation`, not in this batch, then drops the operands after 
the 7, and the
+      // equality goes first until then.
+      checkOrdered(projected, (Coalesce(Seq($"id", $"x")) > 0L || $"i" > 0) && 
$"id" === 7L,
+        $"id" === 7L && (Coalesce(Seq(Literal(7L), $"x")) > 0L || $"i" > 0))
+      checkOrdered(projected, Coalesce(Seq($"id", $"i".cast(LongType))) > 0L 
&& $"id" === 7L,
+        $"id" === 7L && Coalesce(Seq(Literal(7L), $"i".cast(LongType))) > 0L)
+      checkOrdered(projected, (($"id" < 0L && $"i" > 0) || $"x" > 0L) && $"id" 
=== 7L,
+        $"id" === 7L && $"x" > 0L)
+
+      // Also one that reads the propagated attribute, which a collation keeps.
+      val lcase = LocalRelation($"s".string, AttributeReference("c", 
StringType("UTF8_LCASE"))())
+        .select($"c", castS.as("i"))
+      checkOrdered(lcase, ($"i" > 0 || Length($"c") > 0) && $"c" === "a",
+        $"c" === "a" && ($"i" > 0 || Length($"c") > 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)
+      // And one that becomes NULL stays NULL, which the `NOT` keeps NULL.
+      checkOrdered(upperNotNull,
+        Not(If($"u" === "X", Literal(null, StringType), $"u") === "Y" && $"u" 
=== "X"),
+        Literal(null, BooleanType) || Not($"u" === "X"))
+    }
+  }
+
+  test("SPARK-61437: A condition that becomes FALSE with the constants is 
FALSE") {

Review Comment:
   **[10] The tests do not cover the cases above, and a few checks test less 
than their comments say.**
   
   - None of [1]-[4] is covered: a `DOUBLE` column that can fail under a cast 
to a string, an equality of each kind where 4.3.0 folds to `FALSE`, a fold that 
fails only with the other constants or after `FoldablePropagation`, and the 
order in the fallback.
   - The first `intercept` at L433 passes without the removal of the tags too: 
the check fails on the first conjunct, `CAST(x AS DOUBLE) > 10.0 / 0.0`, before 
it reaches the `IF`, so it tags nothing. Only the one at L434-436 needs the 
removal.
   - L563-564 say that an alias of `lower` counts as one that can fail, but no 
assertion depends on it: `length(l) > 0` at L566-567 stays where it is either 
way.
   - L540, L545 and L550 give the same plan whether the column counts as one 
that can fail or not, and the cases at L372-378 and L399-404 pass on master 
too, as far as I can tell, so they do not pin the in-place rewrite.
   - From reading the tests, none fails when `|| collationSafeReplacement` is 
removed from expressions.scala:289, although `v = u` in `v = u AND u = 'a'`, 
with `u` and `v` of one collated type and `u` a column that can fail, then 
reads `u` again. Is this the mutant that the description says survives?
   - nit: `twoCasts` and `threeCasts` are defined twice (L369-370, L502-503), 
the new members `strings` and `divide` (L329, L332) are shadowed by the local 
ones of the older tests (L222, L262, L306), and "as on master" at L486, L488 
and L570 will mean something else once this PR is merged.



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