sarutak commented on code in PR #60516:
URL: https://github.com/apache/spark/pull/60516#discussion_r4642222454


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -313,37 +689,239 @@ 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
+   * Moves `equalityPredicates` 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.
+   * an attribute and a literal can fail only as the attribute does, so the 
caller passes only
+   * equalities over columns that `columns` takes as ones that can not fail.
+   *
+   * A conjunct over a column of the projection below that `columns` takes as 
one that can fail
+   * can fail too, 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`. `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) {
+      // TODO(SPARK-61438): An equality that is NULL on a row does not stop it 
from reaching the
+      // conjuncts after it, e.g. those that its constant rewrote, in an AND 
under an OR.
       reordered.reduce(And)
     } else {
       condition
     }
   }
 
+  /**
+   * What one application of the rule finds for each plan below a filter, as 
the filters above it
+   * look at it too: the columns that can fail, and the foldable ones, each 
only once asked for.
+   */
+  private class ChildColumns(plan: LogicalPlan) {
+    val failable = new java.util.IdentityHashMap[LogicalPlan, AttributeSet]()
+    val foldable = new java.util.IdentityHashMap[LogicalPlan, 
AttributeMap[Expression]]()
+    /** The definitions of the CTEs that are not inlined, by their ids. */
+    lazy val cteDefs: Map[Long, CTERelationDef] = plan.collectWithSubqueries {
+      case w: WithCTE => w.cteDefs
+    }.flatten.map(d => d.id -> d).toMap
+  }
+
+  private def cached[T](cache: java.util.IdentityHashMap[LogicalPlan, T], 
plan: LogicalPlan)(
+      compute: => T): T = {
+    val value = cache.get(plan)
+    if (value != null) {
+      value
+    } else {
+      val computed = compute
+      cache.put(plan, computed)
+      computed
+    }
+  }
+
+  /**
+   * The columns of `plan` that can fail, i.e. those that a projection at its 
top, or below the
+   * filters, samples, limits, offsets, sorts, joins, lateral joins, unions, 
CTEs that are not
+   * inlined and projections there, or, for a reference to a CTE there, in its 
definition, computes
+   * with a deterministic expression that 
[[ExprUtils.canEvaluateUnconditionally]] rejects or that
+   * reads such a column, or passes such a column through, the result columns 
of an aggregation
+   * with grouping keys there whose expression, with each aggregate function 
taken as its value, is
+   * deterministic and rejected by it, and those that a serializer from 
objects there computes with
+   * such an expression.
+   * 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, and so can one over such a result column, which an 
aggregation with grouping
+   * keys computes the same way. 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; nor does a
+   * result column of a global aggregation, which computes it for its one row 
up front.
+   * A limit, an offset, a union in whole-stage codegen and the streamed side 
of a broadcast hash or
+   * nested loop join pass the columns on as they are, in the same stage, and 
so does a sort that
+   * the physical plan removes as its input is sorted already, and a 
`WithCTE`, which
+   * `ReplaceCTERefWithRepartition` removes. A lateral join counts as the join 
that
+   * `RewriteLateralSubquery` turns it into after this rule runs. A reference 
to a CTE reads the
+   * columns its definition computes, where 
`PushdownPredicatesAndPruneColumnsForCTEDef` copies the
+   * conditions over it to, as their OR, which `BooleanSimplification` can 
reorder when there are
+   * several. Otherwise, e.g. below the shuffle of a limit or an offset over 
more than one
+   * partition, on the build side of a join, below a sort or a union outside 
whole-stage codegen, or
+   * for a reference to a CTE where no condition is copied, the columns are 
computed for every row
+   * anyway, but they still count:
+   * the constant of an equality over them then goes into the other conjuncts 
in place, as before
+   * SPARK-60983, which can fail on a row where the equality does not hold, 
where moving the
+   * equality first would not. Other operators are not looked through for the 
columns that can
+   * fail.
+   */
+  private def failableColumnsOf(plan: LogicalPlan, cache: ChildColumns): 
AttributeSet =
+    cached(cache.failable, plan) {
+      plan match {
+        case Project(projectList, child) =>
+          val below = failableColumnsOf(child, cache)
+          AttributeSet(projectList.collect {
+            case a: Alias if a.child.deterministic &&
+                (!ExprUtils.canEvaluateUnconditionally(a.child) ||
+                  a.child.references.exists(below.contains)) => a.toAttribute
+            case a: Attribute if below.contains(a) => a
+          })
+        case Filter(_, child) => failableColumnsOf(child, cache)
+        case s: Sample => failableColumnsOf(s.child, cache)
+        case l: GlobalLimit => failableColumnsOf(l.child, cache)
+        case l: LocalLimit => failableColumnsOf(l.child, cache)
+        case o: Offset => failableColumnsOf(o.child, cache)
+        case s: Sort => failableColumnsOf(s.child, cache)
+        case j: Join => failableColumnsOf(j.left, cache) ++ 
failableColumnsOf(j.right, cache)
+        case l: LateralJoin =>
+          failableColumnsOf(l.left, cache) ++ failableColumnsOf(l.right.plan, 
cache)
+        case w: WithCTE => failableColumnsOf(w.plan, cache)
+        case r: CTERelationRef if !r.recursive =>
+          cache.cteDefs.get(r.cteId).map { d =>
+            val failable = failableColumnsOf(d.child, cache)
+            AttributeSet(r.output.zip(d.output).collect {
+              case (a, b) if failable.contains(b) => a
+            })
+          }.getOrElse(AttributeSet.empty)
+        case s: SerializeFromObject =>
+          AttributeSet(s.serializer.collect {
+            case a: Alias if a.child.deterministic &&
+                !ExprUtils.canEvaluateUnconditionally(a.child) => a.toAttribute
+          })
+        case u: Union =>
+          val children = u.children.map(c => (c.output, failableColumnsOf(c, 
cache)))
+          AttributeSet(u.output.zipWithIndex.collect {
+            case (a, n) if children.exists { case (output, failable) =>
+              failable.contains(output(n))
+            } => a
+          })
+        case agg: Aggregate if agg.groupingExpressions.nonEmpty =>
+          AttributeSet(agg.aggregateExpressions.flatMap {
+            case a: Alias =>
+              val result = a.child.transform { case e: AggregateExpression => 
e.resultAttribute }
+              Some(a.toAttribute).filter(_ =>
+                result.deterministic && 
!ExprUtils.canEvaluateUnconditionally(result))
+            case _ => None
+          })
+        case _ => AttributeSet.empty
+      }
+    }
+
+  /**
+   * The foldable columns of `plan`, with their expressions, as 
[[FoldablePropagation]] finds them
+   * and replaces them in the conditions above. This mirrors 
`propagateFoldables` there.
+   */
+  private def foldableColumnsOf(

Review Comment:
   Done, both. `FoldablePropagation` now finds the foldable columns of each 
plan node, given those of its children, with `propagateFoldablesFromChildren`; 
`propagateFoldables` applies it to every node, and `foldableColumnsOf` calls it 
too, so the two no longer have separate cases to keep in sync. The one 
difference is a parameter: `ConstantPropagation` passes `withoutAliases = 
true`, with which a column is also foldable if its expression is once the 
aliases below its top one are removed, as `CleanupAliases` does, e.g. one that 
renames a foldable column or is computed from one. `FoldablePropagation` finds 
such a column only in its next application, as `Alias` is not foldable, and 
`foldableColumnsOf` found it before too; with `false`, the case in 
`ConstantPropagationSuite` that renames `total` twice fails. 
`FoldablePropagation` passes `false`, so what it does is unchanged. The 
foldable columns now go in only where `spark.sql.optimizer.excludedRules` does 
not exclude `FoldablePropagatio
 n`, with a test.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -236,6 +264,343 @@ object ConstantPropagation extends Rule[LogicalPlan] with 
PredicateHelper {
   private def safeToReplace(ar: AttributeReference, nullIsFalse: Boolean) =
     !ar.nullable || nullIsFalse
 
+  /**
+   * Propagates the equalities of `condition`, an AND, when some of them, 
`failable`, are over a
+   * column of the filter's child that can fail (see [[FailableColumns]]), 
e.g. `i = 1` with `i`
+   * the alias `CAST(s AS INT)`. Such an equality can fail, so it is not moved 
ahead of the
+   * conjuncts written before it, which would compute the column on rows that 
they filter out.
+   * Instead, its constant replaces the column in the other comparisons, where 
they are written,
+   * as before SPARK-60983 (see [[replaceConstantsInPlace]]). The other 
equalities, `movable`, are
+   * propagated and moved as since SPARK-60983, by [[replaceConstants]] and 
[[moveEqualitiesFirst]].
+   *
+   * Before SPARK-60983, the rule put the constants of all of the equalities 
into every
+   * comparison, also those of the equalities whose constant a later iteration 
folds, e.g.
+   * `CAST(7 AS BIGINT)`, unless it is NULL, and [[FoldablePropagation]] puts 
the foldable columns
+   * of the child into the condition too. So the conjuncts that the rewrite 
changes are also
+   * folded with all of them in (see [[foldChanged]]):
+   *  - where one of them then becomes FALSE, or NULL where that means FALSE, 
the condition is
+   *    FALSE, as before SPARK-60983, e.g. with `CASE WHEN 7 > 10 THEN 10 / x 
ELSE 0 END > 1` for
+   *    `CASE WHEN id > 10 THEN 10 / x ELSE 0 END > 1 AND i = 1 AND id = 7`, 
as [[replaceConstants]]
+   *    does not put `id = 7` into a `CASE WHEN` that reads another column;
+   *  - otherwise, where one of them fails to fold with all of the constants 
in, outside of a
+   *    conditional branch, which fails the query while it is optimized, the 
equalities are
+   *    handled as since SPARK-60983, with no column taken as one that can 
fail (see
+   *    [[FailableColumns.none]]), e.g. with `id > 10 / 0` for `i = 0 AND id > 
10 / i`, or with
+   *    `10 / (7 - 6 - 1)` for `10 / (id - 6 - i) > 0 AND i = 1 AND id = 7`;
+   *  - where one of them fails to fold only as rewritten, as 
[[replaceConstants]] does not put
+   *    the constant of `movable` into an operand that decides whether one 
that can fail runs, it
+   *    is replaced with what it folds to with all of the constants in, as 
before SPARK-60983,
+   *    e.g. with TRUE for `x > 0 AND (id > 0 OR 10 / i > 1) AND i = 0 AND id 
= 7`, or `x > 5` for
+   *    `((id > 10 AND 10 / i > 1) OR x > 5) AND i = 0 AND id = 7`. That is 
its value on the rows
+   *    where the equalities hold, and the AND is not TRUE on the others. If 
such a replacement
+   *    can fail, e.g. `10 / x > 5` in place of `x > 5`, the equalities over 
the other columns,
+   *    also those whose constant is not folded yet, but for one over a column 
that can fail, go
+   *    first, so that it runs only on the rows where those hold.
+   */
+  private def propagateInPlace(
+      condition: Expression,
+      failable: AttributeMap[(Literal, BinaryComparison)],
+      movable: AttributeMap[(Literal, BinaryComparison)],
+      nullIsFalse: Boolean,
+      columns: FailableColumns): Expression = {
+    val equalityPredicates = AttributeMap(failable.toSeq ++ movable.toSeq)
+    // `replaceConstants` goes first, on the condition as written, so that it 
reaches and folds
+    // what it does for a column that can not fail. `inPlace` has only the 
constants of
+    // `failable` in, which `moveEqualitiesFirst` compares the rewritten 
condition with.
+    val inPlace = replaceConstantsInPlace(
+      replaceConstants(condition, AttributeMap.empty, failable), failable)
+    val rewritten =
+      replaceConstantsInPlace(replaceConstants(condition, movable, failable), 
failable)
+    val unfolded = unfoldedEqualities(condition, equalityPredicates, 
nullIsFalse)
+    val allEqualities = AttributeMap(equalityPredicates.toSeq ++ unfolded)
+    val all = replaceConstantsInPlace(
+      replaceConstants(condition, AttributeMap.empty, allEqualities), 
allEqualities)
+    val folded = splitConjunctivePredicates(condition)
+      .zip(splitConjunctivePredicates(rewritten))
+      .zip(splitConjunctivePredicates(all))
+      .map { case ((before, after), withAll) =>
+        val afterFolded = foldChanged(before, after, nullIsFalse, columns)
+        val withAllFolded = if (withAll.fastEquals(after)) {

Review Comment:
   Yes, it is expected: the equality over the column that can fail stays in the 
condition, and the check has to tell again whether such a conjunct became 
`FALSE` or fails to fold. It is bounded by the iterations in which another rule 
changes the plan, though, as the batch stops at the first iteration that leaves 
the plan unchanged, which a copy of the filter with the same condition does. I 
counted the calls of `simplify` while optimizing your example with ANSI mode 
on, with `i` the alias `cast(s as int)` and a `rand` column that keeps the 
filter above the projection: 4 over the whole optimization, both with the 
filter at the top and under a `select`, and 12 with three such `OR`s, so it 
grows with the number of such conjuncts. I added a paragraph with your example 
to the scaladoc of `propagateInPlace`.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -236,6 +264,343 @@ object ConstantPropagation extends Rule[LogicalPlan] with 
PredicateHelper {
   private def safeToReplace(ar: AttributeReference, nullIsFalse: Boolean) =
     !ar.nullable || nullIsFalse
 
+  /**
+   * Propagates the equalities of `condition`, an AND, when some of them, 
`failable`, are over a
+   * column of the filter's child that can fail (see [[FailableColumns]]), 
e.g. `i = 1` with `i`
+   * the alias `CAST(s AS INT)`. Such an equality can fail, so it is not moved 
ahead of the
+   * conjuncts written before it, which would compute the column on rows that 
they filter out.
+   * Instead, its constant replaces the column in the other comparisons, where 
they are written,
+   * as before SPARK-60983 (see [[replaceConstantsInPlace]]). The other 
equalities, `movable`, are
+   * propagated and moved as since SPARK-60983, by [[replaceConstants]] and 
[[moveEqualitiesFirst]].
+   *
+   * Before SPARK-60983, the rule put the constants of all of the equalities 
into every
+   * comparison, also those of the equalities whose constant a later iteration 
folds, e.g.
+   * `CAST(7 AS BIGINT)`, unless it is NULL, and [[FoldablePropagation]] puts 
the foldable columns
+   * of the child into the condition too. So the conjuncts that the rewrite 
changes are also
+   * folded with all of them in (see [[foldChanged]]):
+   *  - where one of them then becomes FALSE, or NULL where that means FALSE, 
the condition is
+   *    FALSE, as before SPARK-60983, e.g. with `CASE WHEN 7 > 10 THEN 10 / x 
ELSE 0 END > 1` for
+   *    `CASE WHEN id > 10 THEN 10 / x ELSE 0 END > 1 AND i = 1 AND id = 7`, 
as [[replaceConstants]]
+   *    does not put `id = 7` into a `CASE WHEN` that reads another column;
+   *  - otherwise, where one of them fails to fold with all of the constants 
in, outside of a
+   *    conditional branch, which fails the query while it is optimized, the 
equalities are
+   *    handled as since SPARK-60983, with no column taken as one that can 
fail (see
+   *    [[FailableColumns.none]]), e.g. with `id > 10 / 0` for `i = 0 AND id > 
10 / i`, or with
+   *    `10 / (7 - 6 - 1)` for `10 / (id - 6 - i) > 0 AND i = 1 AND id = 7`;
+   *  - where one of them fails to fold only as rewritten, as 
[[replaceConstants]] does not put
+   *    the constant of `movable` into an operand that decides whether one 
that can fail runs, it
+   *    is replaced with what it folds to with all of the constants in, as 
before SPARK-60983,
+   *    e.g. with TRUE for `x > 0 AND (id > 0 OR 10 / i > 1) AND i = 0 AND id 
= 7`, or `x > 5` for
+   *    `((id > 10 AND 10 / i > 1) OR x > 5) AND i = 0 AND id = 7`. That is 
its value on the rows
+   *    where the equalities hold, and the AND is not TRUE on the others. If 
such a replacement
+   *    can fail, e.g. `10 / x > 5` in place of `x > 5`, the equalities over 
the other columns,
+   *    also those whose constant is not folded yet, but for one over a column 
that can fail, go
+   *    first, so that it runs only on the rows where those hold.
+   */
+  private def propagateInPlace(
+      condition: Expression,
+      failable: AttributeMap[(Literal, BinaryComparison)],
+      movable: AttributeMap[(Literal, BinaryComparison)],
+      nullIsFalse: Boolean,
+      columns: FailableColumns): Expression = {
+    val equalityPredicates = AttributeMap(failable.toSeq ++ movable.toSeq)
+    // `replaceConstants` goes first, on the condition as written, so that it 
reaches and folds
+    // what it does for a column that can not fail. `inPlace` has only the 
constants of
+    // `failable` in, which `moveEqualitiesFirst` compares the rewritten 
condition with.
+    val inPlace = replaceConstantsInPlace(
+      replaceConstants(condition, AttributeMap.empty, failable), failable)
+    val rewritten =
+      replaceConstantsInPlace(replaceConstants(condition, movable, failable), 
failable)
+    val unfolded = unfoldedEqualities(condition, equalityPredicates, 
nullIsFalse)
+    val allEqualities = AttributeMap(equalityPredicates.toSeq ++ unfolded)
+    val all = replaceConstantsInPlace(
+      replaceConstants(condition, AttributeMap.empty, allEqualities), 
allEqualities)
+    val folded = splitConjunctivePredicates(condition)
+      .zip(splitConjunctivePredicates(rewritten))
+      .zip(splitConjunctivePredicates(all))
+      .map { case ((before, after), withAll) =>
+        val afterFolded = foldChanged(before, after, nullIsFalse, columns)
+        val withAllFolded = if (withAll.fastEquals(after)) {
+          afterFolded
+        } else {
+          foldChanged(before, withAll, nullIsFalse, columns)
+        }
+        (after, afterFolded, withAllFolded)
+      }
+    if (folded.exists { case (_, a, w) => a == FoldsToFalse || w == 
FoldsToFalse }) {
+      FalseLiteral
+    } else if (folded.exists {
+        case (_, _, FailsToFold) => true
+        // A replacement with an untagged part that failed in a conditional 
branch fails once
+        // `ConstantFolding` folds it in the plan, if another rule took the 
part out of the branch.
+        case (_, FailsToFold, FoldsTo(_, untagged)) => untagged
+        case _ => false
+      }) {
+      moveEqualitiesFirst(condition, replaceConstants(condition, 
equalityPredicates),
+        equalityPredicates, FailableColumns.none)
+    } else {
+      // A conjunct that fails to fold as rewritten is replaced with what it 
folds to with all of
+      // the constants in, which does not fail to fold.
+      val replacements = folded.collect { case (_, FailsToFold, FoldsTo(e, _)) 
=> e }
+      val replaced = if (replacements.isEmpty) {
+        rewritten
+      } else {
+        folded.map {
+          case (_, FailsToFold, FoldsTo(e, _)) => e
+          case (after, _, _) => after
+        }.reduce(And)
+      }
+      if (replacements.forall(columns.canEvaluateUnconditionally)) {
+        if (movable.isEmpty) replaced else moveEqualitiesFirst(inPlace, 
replaced, movable, columns)
+      } else {
+        // Such a replacement can fail on a row where an equality over a 
column that can not fail
+        // does not hold, also one whose constant is not folded yet, so those 
go first. One over a
+        // column that can fail stays, as its constant goes in place in the 
next iteration.
+        val predicates = (movable.values.map(_._2) ++ unfolded.collect {
+          case (a, (_, b)) if columns.canEvaluateUnconditionally(a) => b
+        }).toSet[Expression]
+        val (equalities, others) =
+          splitConjunctivePredicates(replaced).partition(predicates.contains)
+        (equalities ++ others).reduce(And)
+      }
+    }
+  }
+
+  /**
+   * The equalities of the conjuncts of `condition` between an attribute and a 
foldable expression
+   * that is not a literal yet, e.g. `id = CAST(7 AS BIGINT)` for a BIGINT 
`id`, with the literal
+   * that it folds to, other than those over the attributes of 
`equalityPredicates`.
+   * [[ConstantFolding]] makes such a one a literal for the next iteration. 
One whose constant is
+   * NULL is left out: [[NullPropagation]] makes it NULL, or `IS NULL` for 
`<=>`, before it is
+   * propagated.
+   */
+  private def unfoldedEqualities(
+      condition: Expression,
+      equalityPredicates: AttributeMap[(Literal, BinaryComparison)],
+      nullIsFalse: Boolean): Seq[(Attribute, (Literal, BinaryComparison))] = {
+    def equality(b: BinaryComparison, a: AttributeReference, e: Expression) =
+      if (!e.isInstanceOf[Literal] && e.foldable && safeToReplace(a, 
nullIsFalse) &&
+          !equalityPredicates.contains(a)) {
+        fold(e).filter(_.value != null).map(l => (a: Attribute) -> (l, b))
+      } else {
+        None
+      }
+    splitConjunctivePredicates(condition).flatMap {
+      case b @ EqualTo(a: AttributeReference, e) => equality(b, a, e)
+      case b @ EqualTo(e, a: AttributeReference) => equality(b, a, e)
+      case b @ EqualNullSafe(a: AttributeReference, e) => equality(b, a, e)
+      case b @ EqualNullSafe(e, a: AttributeReference) => equality(b, a, e)
+      case _ => None
+    }
+  }
+
+  /** What a conjunct folds to, see [[foldChanged]]. */
+  private sealed trait Folded
+  /** It is the conjunct as written. */
+  private case object NotChecked extends Folded
+  /** It is FALSE, or NULL where that means FALSE. */
+  private case object FoldsToFalse extends Folded
+  /** It fails to fold, outside of a conditional branch. */
+  private case object FailsToFold extends Folded
+  /**
+   * It folds to `folded`, which can hold a part that failed in a conditional 
branch without its
+   * tag if `untagged`, see [[simplify]].
+   */
+  private case class FoldsTo(folded: Expression, untagged: Boolean = false) 
extends Folded
+
+  /**
+   * What `after`, the conjunct `before` with constants in, folds to with the 
foldable columns of
+   * the filter's child in, if either of them changed it. One that
+   * [[ExprUtils.canEvaluateUnconditionally]] accepts is not folded, as it can 
not fail, and the
+   * constants make it FALSE once they are in the condition, in this or a 
later iteration.
+   */
+  private def foldChanged(
+      before: Expression,
+      after: Expression,
+      nullIsFalse: Boolean,
+      columns: FailableColumns): Folded = {
+    val withFoldables = columns.replaceFoldables(after)
+    if (withFoldables.fastEquals(before)) {
+      NotChecked
+    } else if (ExprUtils.canEvaluateUnconditionally(withFoldables)) {
+      FoldsTo(withFoldables)
+    } else {
+      simplify(withFoldables) match {
+        case None => FailsToFold
+        case Some((FalseLiteral, _)) => FoldsToFalse
+        case Some((Literal(null, BooleanType), _)) if nullIsFalse => 
FoldsToFalse
+        case Some((folded, untagged)) => FoldsTo(folded, untagged)
+      }
+    }
+  }
+
+  /**
+   * Replaces the attributes of `equalityPredicates` with their constants in 
the comparisons of
+   * `condition` other than those equalities, wherever they are, as before 
SPARK-60983. A
+   * comparison that this rewrites no longer reads the column, so the 
conditions read it in no
+   * more places than written, but 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.
+   *
+   * As in [[replaceConstants]], 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. Unlike before SPARK-60983, an 
attribute that
+   * [[hasSignedZero]] marks is kept under an operator that can tell -0.0 from 
0.0, which are
+   * equal, i.e. one that [[keepsEqualValues]] rejects, e.g. in `CAST(x * y AS 
STRING)` for
+   * `x = 0.0`, as [[replaceConstants]] keeps it there. [[replaceConstants]], 
run first, folds such
+   * an operator where it reaches it and all of its attributes get a constant, 
as it does for a
+   * column that can not fail, e.g. `CAST(x AS STRING)` (see its `foldOnly`).
+   */
+  private def replaceConstantsInPlace(
+      condition: Expression,
+      equalityPredicates: AttributeMap[(Literal, BinaryComparison)]): 
Expression = {
+    val constantsMap = AttributeMap(equalityPredicates.map { case (attr, (lit, 
_)) => attr -> lit })
+    val predicates = equalityPredicates.values.map(_._2).toSet
+    def replaceInComparison(b: BinaryComparison): Expression = {
+      val canReplace = replaceableIn(b, constantsMap)
+      val signed = AttributeSet(b.references.filter(a => canReplace(a) &&
+        hasSignedZero(constantsMap(a))))
+      // Replaces the attributes, but keeps those of `signed` under an 
operator that can tell
+      // -0.0 from 0.0.
+      def replace(e: Expression, keepsEqual: Boolean): Expression = e match {
+        case a: AttributeReference if canReplace(a) && (keepsEqual || 
!signed.contains(a)) =>
+          constantsMap(a)
+        case _ => e.mapChildren(replace(_, keepsEqual && keepsEqualValues(e)))
+      }
+      replace(b, keepsEqual = true)
+    }
+    condition.transformWithPruning(_.containsPattern(BINARY_COMPARISON)) {
+      case b: BinaryComparison if !predicates.contains(b) => 
replaceInComparison(b)
+    }
+  }
+
+  /**
+   * Whether `l` may equal a value that an operator can tell from it: a zero 
of a FLOAT or a
+   * DOUBLE, which equals the zero of the other sign, or any value of a type 
with a FLOAT or a
+   * DOUBLE in it, as this does not look into the value.
+   */
+  private def hasSignedZero(l: Literal): Boolean = (l.value, l.dataType) match 
{
+    case (null, _) => false
+    case (d: Double, DoubleType) => d == 0.0
+    case (f: Float, FloatType) => f == 0.0f
+    case (_, dt) => dt.existsRecursively(t => t == FloatType || t == 
DoubleType)
+  }
+
+  /**
+   * Whether `e` gives equal results for equal children, if it does not fail, 
so that a child can
+   * be replaced with a value equal to it: an operator that 
[[ExprUtils.isTotalOperator]] accepts,
+   * or binary arithmetic, which can fail in ANSI mode, but whose results, or 
failures, are
+   * equal for -0.0 and 0.0, e.g. a division by either zero fails, although 
they may differ in the
+   * sign of a zero, which only an operator above it that this rejects can 
tell apart.
+   */
+  private def keepsEqualValues(e: Expression): Boolean =
+    ExprUtils.isTotalOperator(e) || e.isInstanceOf[BinaryArithmetic]
+
+  /**
+   * Simplifies `e` with [[ConstantFolding]] and the other rules of the 
operator optimization
+   * batch that rewrite the condition of a filter (see 
[[SIMPLIFY_RULES_AFTER_FOLDING]]), in the
+   * order of the batch, until it no longer changes, at most 
[[MAX_SIMPLIFY_ITERATIONS]] times,
+   * or returns None if it fails to fold. Like [[ConstantFolding]], it does 
not fold again a part
+   * that failed in a conditional branch, also once another rule rewrites it 
or takes it out of
+   * the branch, or one that an earlier [[ConstantFolding]] tagged so. It tags 
the parts of a copy
+   * of `e`, which may be shared with a plan, so that the other rules copy the 
tag to what they
+   * rewrite a part into, as in the batch. If `e` can not be copied, it keeps 
the parts that failed
+   * in a set of its own instead, which misses a part once another rule 
rewrites it, and leaves
+   * such a part untagged in what it returns, which it then marks so. It runs 
only the rules that
+   * `spark.sql.optimizer.excludedRules` does not exclude, and does not fold 
if that excludes
+   * [[ConstantFolding]].
+   */
+  private def simplify(e: Expression): Option[(Expression, Boolean)] = {
+    val excluded = 
conf.optimizerExcludedRules.toSeq.flatMap(Utils.stringToSeq).toSet
+    def included(rules: Seq[Rule[LogicalPlan]]) = rules.filterNot(r => 
excluded(r.ruleName))
+    val before = included(SIMPLIFY_RULES_BEFORE_FOLDING)
+    val after = included(SIMPLIFY_RULES_AFTER_FOLDING)
+    val copy = copyWithTags(e)

Review Comment:
   Done, both: `simplify` returns before the copy when `ConstantFolding` is 
excluded, and `inPlace` is a `lazy val`.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -313,37 +689,239 @@ 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
+   * Moves `equalityPredicates` 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.
+   * an attribute and a literal can fail only as the attribute does, so the 
caller passes only
+   * equalities over columns that `columns` takes as ones that can not fail.
+   *
+   * A conjunct over a column of the projection below that `columns` takes as 
one that can fail
+   * can fail too, 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`. `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) {
+      // TODO(SPARK-61438): An equality that is NULL on a row does not stop it 
from reaching the
+      // conjuncts after it, e.g. those that its constant rewrote, in an AND 
under an OR.
       reordered.reduce(And)
     } else {
       condition
     }
   }
 
+  /**
+   * What one application of the rule finds for each plan below a filter, as 
the filters above it
+   * look at it too: the columns that can fail, and the foldable ones, each 
only once asked for.
+   */
+  private class ChildColumns(plan: LogicalPlan) {
+    val failable = new java.util.IdentityHashMap[LogicalPlan, AttributeSet]()
+    val foldable = new java.util.IdentityHashMap[LogicalPlan, 
AttributeMap[Expression]]()
+    /** The definitions of the CTEs that are not inlined, by their ids. */
+    lazy val cteDefs: Map[Long, CTERelationDef] = plan.collectWithSubqueries {
+      case w: WithCTE => w.cteDefs
+    }.flatten.map(d => d.id -> d).toMap
+  }
+
+  private def cached[T](cache: java.util.IdentityHashMap[LogicalPlan, T], 
plan: LogicalPlan)(

Review Comment:
   I kept the `get` and `put`, with a comment: `compute` puts the values of the 
plans below into the same map, which the mapping function of 
`Map.computeIfAbsent` should not do, per its contract (`HashMap` throws 
`ConcurrentModificationException` for it). `IdentityHashMap` keeps the default 
implementation, so it would work today, but I'd rather not depend on that.
   



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