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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:
##########
@@ -173,8 +174,59 @@ trait GeneratePredicateHelper extends PredicateHelper {
    * Whether evaluating `e` on a row can be observed other than through its 
value: it can raise
    * an error, is nondeterministic or may have side effects, such as a UDF. 
Such an expression
    * has to be evaluated on the rows, and in the order, that `And.eval` 
evaluates it on.
+   *
+   * On top of `ExprUtils.canEvaluateUnconditionally`, a total expression over 
such expressions
+   * is known not to raise: the string functions of `isTotal`, a hash, the 
Bloom filter predicate
+   * of a runtime filter, and the arithmetic of numbers in the legacy 
evaluation mode, which
+   * returns NULL instead of raising. A column that an operator of the same 
stage computes
+   * lazily, such as a projection alias or a result of an aggregate, is judged 
by the expression
+   * that computes it, see `producedBy`, since a check on the column evaluates 
that expression.
+   */
+  protected def mayRaise(e: Expression): Boolean = {

Review Comment:
   The `isTotal` and `producedBy` changes in `mayRaise` apply regardless of 
`spark.sql.legacy.filterLazyNotNullCheckPlacement`, so they also change 
`nullConjunctFlag` and the `afterNullable` branch of `precedingNotNullChecks` 
(SPARK-60315). So setting the legacy config alone doesn't restore the previous 
placement as documented.
   
   For example, with the legacy config `true` and the NULL-conjunct flag 
enabled, `NOT (a > 0 AND b > 0) AND upper(s) = 'X'` no longer gets the flag, 
and a conjunct on an aggregate result column now gets the flag and moved 
checks, so the generated code differs from the parent commit. Should the legacy 
config cover these changes too, or should the doc be updated?
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2260,6 +2260,23 @@ object InferFiltersFromGenerate extends 
Rule[LogicalPlan] {
 object InferFiltersFromConstraints extends Rule[LogicalPlan]
   with PredicateHelper with ConstraintHelper {
 
+  /**
+   * Marks a predicate that this rule infers, as opposed to one written in the 
query. An inferred
+   * `IsNotNull` check is implied by the conjunct it was inferred from, so the 
whole-stage codegen
+   * of a filter keeps generating it lazily, before the first conjunct that 
references its column,
+   * where it generates a check written in the query at its position: before 
an earlier conjunct
+   * that can raise an error, when the check cannot raise one itself, see
+   * `GeneratePredicateHelper.precedingNotNullChecks`.
+   */
+  val INFERRED = TreeNodeTag[Unit]("inferred")
+
+  private def markInferred(predicates: Iterable[Expression]): Seq[Expression] 
= {

Review Comment:
   `markInferred` mutates the tags of the `IsNotNull` instances from 
`filter.constraints`, a lazy val cached on the plan node. An analyzed plan node 
can be shared by multiple Datasets, e.g. queries derived from the same base 
DataFrame, so optimizing them on different threads at the same time can race on 
the unsynchronized tag map of the same instance (`TreeNode._tags`, including 
its lazy initialization), and a tag can be lost. Then the inferred check is 
treated as written and moved earlier, nondeterministically. Could we tag a copy 
instead of the shared instance?
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:
##########
@@ -173,8 +174,59 @@ trait GeneratePredicateHelper extends PredicateHelper {
    * Whether evaluating `e` on a row can be observed other than through its 
value: it can raise
    * an error, is nondeterministic or may have side effects, such as a UDF. 
Such an expression
    * has to be evaluated on the rows, and in the order, that `And.eval` 
evaluates it on.
+   *
+   * On top of `ExprUtils.canEvaluateUnconditionally`, a total expression over 
such expressions
+   * is known not to raise: the string functions of `isTotal`, a hash, the 
Bloom filter predicate
+   * of a runtime filter, and the arithmetic of numbers in the legacy 
evaluation mode, which
+   * returns NULL instead of raising. A column that an operator of the same 
stage computes
+   * lazily, such as a projection alias or a result of an aggregate, is judged 
by the expression
+   * that computes it, see `producedBy`, since a check on the column evaluates 
that expression.
+   */
+  protected def mayRaise(e: Expression): Boolean = {
+    val resolved = e.transform { case a: Attribute => producedBy(a) }
+    !(ExprUtils.canEvaluateUnconditionally(resolved) || isTotal(resolved))
+  }
+
+  private def isTotal(e: Expression): Boolean = e.deterministic && 
isTotalInternal(e)
+
+  // The structural cases of `ExprUtils.canEvaluateUnconditionally`, plus the 
total functions.
+  private def isTotalInternal(e: Expression): Boolean = e match {
+    case _: AttributeReference | _: Literal => true
+    case _: And | _: Or | _: Not | _: BinaryComparison | _: IsNull | _: 
IsNotNull | _: IsNaN |
+         _: NullIf | _: Coalesce | _: In | _: InSet |
+         _: GetStructField | _: GetArrayStructFields | _: GetMapValue |
+         _: Upper | _: Lower | _: Length | _: StringTrim | _: StringTrimLeft |
+         _: StringTrimRight | _: Substring | _: Concat | _: XxHash64 | _: 
Murmur3Hash =>
+      e.children.forall(isTotalInternal)
+    // The Bloom filter is a scalar subquery already evaluated, or a literal.
+    case b: BloomFilterMightContain => isTotalInternal(b.valueExpression)
+    case b: BinaryArithmetic
+        if b.evalMode == EvalMode.LEGACY && 
b.dataType.isInstanceOf[NumericType] =>
+      e.children.forall(isTotalInternal)
+    case _ => false
+  }
+
+  /**
+   * The expression that computes `attr` lazily in this stage, when an 
operator between this one
+   * and the input of the stage does: a projection alias, or a result 
expression of an aggregate,
+   * whose own inputs, the aggregation buffers, are not computed lazily. The 
attribute itself
+   * otherwise: an input of the stage, read from a scan, a columnar batch or 
an exchange, or an
+   * output that its operator computes before this one runs.
    */
-  protected def mayRaise(e: Expression): Boolean = 
!ExprUtils.canEvaluateUnconditionally(e)
+  protected def producedBy(attr: Attribute): Expression = {
+    def substitute(e: Expression, named: Seq[NamedExpression]): Expression = {
+      val aliases =
+        AttributeMap(named.collect { case a @ Alias(child, _) => a.toAttribute 
-> child })
+      e.transform { case a: Attribute if aliases.contains(a) => aliases(a) }
+    }
+    def resolve(plan: SparkPlan, e: Expression): Expression = plan match {
+      case p: ProjectExec => resolve(p.child, substitute(e, p.projectList))
+      case a: BaseAggregateExec => substitute(e, a.resultExpressions)
+      case f: FilterExec => resolve(f.child, e)
+      case _ => e
+    }
+    self.children.headOption.map(resolve(_, attr)).getOrElse(attr)

Review Comment:
   `producedBy` assumes that the stage computes the column lazily, but it 
doesn't check whether the column is actually evaluated already when the 
predicate runs. In the aggregate `FILTER` clause, 
`AggregateCodegenSupport.usedInputs = inputSet` evaluates the child columns 
before the predicate, and a `ProjectExec` alias shared by CSE or a 
nondeterministic alias is evaluated eagerly too. In these cases, the check is 
still judged by the computing expression and keeps the lazy placement, so 
SPARK-60329 is not fixed for them.
   
   For example, in ANSI mode with codegen on:
   
   ```sql
   SELECT count(1) FILTER (WHERE c IS NOT NULL AND y + 1 > 0), max(r)
   FROM (SELECT x * 2 AS c, y, rand() AS r FROM t)
   ```
   
   `rand()` prevents `CollapseProject`, and `c` is already computed as NULL, 
but `producedBy(c) = x * 2` is `mayRaise`, so the check is not moved. Then 
`ARITHMETIC_OVERFLOW` is raised on a row where `x` is NULL and `y` is 
`2147483647`, while codegen off returns `1`.
   



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala:
##########
@@ -3156,6 +3157,119 @@ class WholeStageCodegenSuite extends SharedSparkSession
     }
   }
 
+  test("SPARK-60329: a filter checks a column IS NOT NULL before a conjunct 
that can raise") {
+    withNullConjunctTable(Int.MaxValue) {
+      // `x` is NULL on the first row and `y + 1` overflows on it. With 
codegen off, the FALSE
+      // `x IS NOT NULL` drops the row before the conjunct after it is 
evaluated. With codegen
+      // on, the check was generated just before the first conjunct that 
references `x`, or
+      // after all of them, so the overflow was raised. A check written in the 
query that cannot
+      // raise is now generated before a conjunct that can raise, as with the 
NULL-conjunct flag,
+      // whatever the legacy config, since it is independent of a NULL 
conjunct. A check that the
+      // optimizer inferred keeps the lazy placement, so that its column is 
not loaded before the
+      // conjunct it was inferred from.
+      //
+      // The common `b * 2` takes the CSE path of FilterExec.
+      val cseQuery = "SELECT a FROM t WHERE x IS NOT NULL AND y + 1 > 0 AND " +
+        "b * 2 > 0 AND b * 2 > -1"
+      def multiplyExactCount(filterExecCSE: Boolean): Int = {
+        withSQLConf(
+            SQLConf.ANSI_ENABLED.key -> "true",
+            SQLConf.SUBEXPRESSION_ELIMINATION_FILTER_EXEC_ENABLED.key -> 
filterExecCSE.toString) {
+          val code = codegenString(sql(cseQuery).queryExecution.executedPlan)
+          "multiplyExact".r.findAllIn(code).length
+        }
+      }
+      assert(multiplyExactCount(filterExecCSE = true) < 
multiplyExactCount(filterExecCSE = false))
+
+      Seq("true", "false").foreach { filterExecCSE =>
+        withNullConjunctConfs(
+            SQLConf.ANSI_ENABLED.key -> "true",
+            SQLConf.SUBEXPRESSION_ELIMINATION_FILTER_EXEC_ENABLED.key -> 
filterExecCSE) { _ =>
+          // A check written in the query, with and without a later conjunct 
that references `x`.
+          checkAnswer(sql("SELECT a FROM t WHERE x IS NOT NULL AND y + 1 > 0 
AND x > 0"), Row(0))
+          checkAnswer(sql("SELECT a FROM t WHERE x IS NOT NULL AND y + 1 > 
0"), Row(0))
+          // The same with a common subexpression.
+          checkAnswer(sql(cseQuery), Row(0))
+          // A check on an expression that cannot raise, a struct field or a 
total string
+          // function, is generated at its position too.
+          checkAnswer(sql("SELECT a FROM t WHERE st.x IS NOT NULL AND y + 1 > 
0"), Row(0))
+          checkAnswer(sql("SELECT a FROM t WHERE upper(ns) IS NOT NULL AND y + 
1 > 0"), Row(0))
+          // A check written after the overflowing conjunct stays after it, so 
the query raises.
+          checkArithmeticOverflow("SELECT a FROM t WHERE y + 1 > 0 AND x IS 
NOT NULL")
+        }
+      }
+      // A check on an expression that can raise, `cast(s AS INT) IS NOT 
NULL`, keeps the lazy
+      // placement with codegen on, so the overflowing conjunct raises on the 
first row before
+      // the check does, while codegen off evaluates the check first and 
raises its error.
+      Seq(true, false).foreach { codegen =>
+        withSQLConf(
+            SQLConf.ANSI_ENABLED.key -> "true",
+            SQLConf.PARQUET_FILTER_PUSHDOWN_ENABLED.key -> "false",
+            SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> codegen.toString) {
+          val raisingCheck = "SELECT a FROM t WHERE cast(s AS INT) IS NOT NULL 
AND y + 1 > 0"
+          if (codegen) {
+            checkArithmeticOverflow(raisingCheck)
+          } else {
+            checkCastInvalidInput(raisingCheck)
+          }
+        }
+      }
+      // The legacy config keeps the lazy placement of a check written in the 
query.
+      withSQLConf(
+          SQLConf.ANSI_ENABLED.key -> "true",
+          SQLConf.PARQUET_FILTER_PUSHDOWN_ENABLED.key -> "false",
+          SQLConf.LEGACY_FILTER_LAZY_NOT_NULL_CHECK_PLACEMENT.key -> "true") {
+        checkArithmeticOverflow("SELECT a FROM t WHERE x IS NOT NULL AND y + 1 
> 0")
+      }
+      // `isnotnull(x)` inferred from `x > 0` is implied by it and keeps the 
lazy placement, just
+      // before `x > 0`, so that `x` is not loaded before `y + 1 > 0` rejects 
a row: the query
+      // raises with codegen on, and drops the first row with codegen off.
+      Seq(true, false).foreach { codegen =>
+        withSQLConf(
+            SQLConf.ANSI_ENABLED.key -> "true",
+            SQLConf.PARQUET_FILTER_PUSHDOWN_ENABLED.key -> "false",
+            SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> codegen.toString) {
+          val inferred = "SELECT a FROM t WHERE y + 1 > 0 AND x > 0"
+          if (codegen) checkArithmeticOverflow(inferred) else 
checkAnswer(sql(inferred), Row(0))
+        }
+      }
+      // The aggregate FILTER clause goes through the same code generation.
+      withNullConjunctConfs(SQLConf.ANSI_ENABLED.key -> "true") { _ =>
+        checkAnswer(
+          sql("SELECT count(1) FILTER (WHERE x IS NOT NULL AND y + 1 > 0) FROM 
t"), Row(1))
+      }
+    }
+  }
+
+  test("SPARK-60329: a check on a column computed lazily by the stage keeps 
the lazy placement " +
+      "when the computation can raise") {
+    // A check on such a column evaluates the computation, so it is judged by 
it: `r` is
+    // `sum(a) / sum(b)`, which raises DIVIDE_BY_ZERO on the first group with 
codegen on if the
+    // check is generated before `max(y) + 1 > 0`, which is FALSE and drops 
the group. With
+    // codegen off the aggregate computes `r` eagerly and the query raises.
+    Seq(true, false).foreach { legacy =>
+      withSQLConf(
+          SQLConf.ANSI_ENABLED.key -> "true",
+          SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> "true",
+          SQLConf.LEGACY_FILTER_SHORT_CIRCUIT_ON_NULL_CONJUNCT.key -> 
legacy.toString) {
+        checkAnswer(
+          sql("SELECT k FROM VALUES (1, 1, 0, -5), (2, 1, 1, 0) AS v(k, a, b, 
y) GROUP BY k " +
+            "HAVING sum(a) / sum(b) IS NOT NULL AND max(y) + 1 > 0"),

Review Comment:
   I'm not sure this test exercises `producedBy`.
   
   - For this `HAVING` clause, the analyzer (`buildAggExprList`) only moves the 
`AggregateExpression`s into the `Aggregate`, so the `Divide` stays in the 
`FilterExec`, and `isnotnull(sum(a) / sum(b))` is `mayRaise` by itself.
   - For the query at line 3265, the unused `rand() AS r` seems to be removed 
by `ColumnPruning`, and then the filter is pushed below the projection as 
`isnotnull(cast(s AS INT))`.
   
   If so, both assertions still pass after removing the `BaseAggregateExec` or 
the `ProjectExec` branch of `producedBy`, and regressions like the ones in the 
other comments would not be caught. Could you add queries whose column is 
really computed by the operator below, e.g. `SELECT * FROM (SELECT k, sum(a) / 
sum(b) AS r FROM v GROUP BY k) WHERE r IS NOT NULL AND ...`, or one that 
references `r` in the outer query?
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:
##########
@@ -256,22 +319,25 @@ trait GeneratePredicateHelper extends PredicateHelper {
       k: Int,
       conjunct: Expression,
       afterNullable: Boolean,
-      generated: Array[Boolean]): Seq[Expression] = {
-    if (afterNullable) {
-      val pending = 
notNullPreds.take(precedingNotNulls(k)).zipWithIndex.filterNot {
-        case (_, idx) => generated(idx)
-      }
-      if (pending.nonEmpty && (mayRaise(conjunct) || pending.exists(p => 
mayRaise(p._1)))) {
-        pending.map { case (p, idx) =>
-          generated(idx) = true
-          p
-        }
-      } else {
-        Nil
+      generated: Array[Boolean]): Seq[Int] = {
+    val pending = 
notNullPreds.take(precedingNotNulls(k)).zipWithIndex.filterNot {
+      case (_, idx) => generated(idx)
+    }
+    val conjunctMayRaise = mayRaise(conjunct)
+    val positioned = if (afterNullable &&
+        (conjunctMayRaise || pending.exists(p => mayRaise(p._1)))) {
+      pending
+    } else if (conjunctMayRaise && 
!conf.legacyFilterLazyNotNullCheckPlacement) {

Review Comment:
   This new placement is on by default, and `mayRaise` is true for every 
expression outside the whitelist: ANSI arithmetic and casts (including casts 
that cannot fail, such as INT to BIGINT), `LIKE`, regexp, datetime functions 
and so on. So in ANSI mode, the default in Spark 4, almost every `col IS NOT 
NULL` written in a query is moved earlier, and `col` is decoded on every row.
   
   The benchmark in the PR description shows this: `d IS NOT NULL AND y * 3 > 
1000000 AND d > 5` goes from 0.88 to 2.54 (about 2.9x). This is a regression by 
default until SPARK-60872 lands, and its scope is much wider than "can raise an 
error" in the migration guide suggests. Could we consider keeping it opt-in 
until SPARK-60872, or narrowing which conjuncts move the checks?
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:
##########
@@ -173,8 +174,59 @@ trait GeneratePredicateHelper extends PredicateHelper {
    * Whether evaluating `e` on a row can be observed other than through its 
value: it can raise
    * an error, is nondeterministic or may have side effects, such as a UDF. 
Such an expression
    * has to be evaluated on the rows, and in the order, that `And.eval` 
evaluates it on.
+   *
+   * On top of `ExprUtils.canEvaluateUnconditionally`, a total expression over 
such expressions
+   * is known not to raise: the string functions of `isTotal`, a hash, the 
Bloom filter predicate
+   * of a runtime filter, and the arithmetic of numbers in the legacy 
evaluation mode, which
+   * returns NULL instead of raising. A column that an operator of the same 
stage computes
+   * lazily, such as a projection alias or a result of an aggregate, is judged 
by the expression
+   * that computes it, see `producedBy`, since a check on the column evaluates 
that expression.
+   */
+  protected def mayRaise(e: Expression): Boolean = {
+    val resolved = e.transform { case a: Attribute => producedBy(a) }
+    !(ExprUtils.canEvaluateUnconditionally(resolved) || isTotal(resolved))
+  }
+
+  private def isTotal(e: Expression): Boolean = e.deterministic && 
isTotalInternal(e)
+
+  // The structural cases of `ExprUtils.canEvaluateUnconditionally`, plus the 
total functions.
+  private def isTotalInternal(e: Expression): Boolean = e match {
+    case _: AttributeReference | _: Literal => true
+    case _: And | _: Or | _: Not | _: BinaryComparison | _: IsNull | _: 
IsNotNull | _: IsNaN |
+         _: NullIf | _: Coalesce | _: In | _: InSet |
+         _: GetStructField | _: GetArrayStructFields | _: GetMapValue |
+         _: Upper | _: Lower | _: Length | _: StringTrim | _: StringTrimLeft |
+         _: StringTrimRight | _: Substring | _: Concat | _: XxHash64 | _: 
Murmur3Hash =>

Review Comment:
   `Concat` can raise. For arrays, it throws 
`arrayFunctionWithElementsExceedLimitError` when the number of elements exceeds 
`MAX_ROUNDED_ARRAY_LENGTH`. For strings and binaries, `UTF8String.concat` 
(`Math.toIntExact`) and `ByteArray.concat` (`JavaUtils.checkedCast`) throw when 
the result length overflows `Int`. So it is not total, and treating it as total 
can move a check, or skip the NULL-conjunct flag, wrongly. This is rare, but 
should `Concat` be removed from this list?
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2274,7 +2291,7 @@ object InferFiltersFromConstraints extends 
Rule[LogicalPlan]
       val newFilters = filter.constraints --
         (child.constraints ++ splitConjunctivePredicates(condition))
       if (newFilters.nonEmpty) {
-        Filter(And(newFilters.reduce(And), condition), child)
+        Filter(And(markInferred(newFilters).reduce(And), condition), child)

Review Comment:
   A design question: distinguishing written and inferred checks with a 
`TreeNodeTag` looks fragile to me. The tag has to survive the rest of the 
optimization and planning, every path that infers a check has to set it, and a 
physical operator now depends on an optimizer rule object 
(`InferFiltersFromConstraints.INFERRED`). Even then, the codegen on/off 
mismatch remains for a query like `y + 1 > 0 AND x > 0`.
   
   What about a position-based approach instead: place an inferred check right 
before the conjunct that implies it, rather than at the front of the condition? 
Then the codegen could generate every check that cannot raise at its position 
without any tag, and the order would match the interpreted evaluation, which 
would also remove the remaining mismatch.
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:
##########
@@ -173,8 +174,59 @@ trait GeneratePredicateHelper extends PredicateHelper {
    * Whether evaluating `e` on a row can be observed other than through its 
value: it can raise
    * an error, is nondeterministic or may have side effects, such as a UDF. 
Such an expression
    * has to be evaluated on the rows, and in the order, that `And.eval` 
evaluates it on.
+   *
+   * On top of `ExprUtils.canEvaluateUnconditionally`, a total expression over 
such expressions
+   * is known not to raise: the string functions of `isTotal`, a hash, the 
Bloom filter predicate
+   * of a runtime filter, and the arithmetic of numbers in the legacy 
evaluation mode, which
+   * returns NULL instead of raising. A column that an operator of the same 
stage computes
+   * lazily, such as a projection alias or a result of an aggregate, is judged 
by the expression
+   * that computes it, see `producedBy`, since a check on the column evaluates 
that expression.
+   */
+  protected def mayRaise(e: Expression): Boolean = {
+    val resolved = e.transform { case a: Attribute => producedBy(a) }
+    !(ExprUtils.canEvaluateUnconditionally(resolved) || isTotal(resolved))
+  }
+
+  private def isTotal(e: Expression): Boolean = e.deterministic && 
isTotalInternal(e)
+
+  // The structural cases of `ExprUtils.canEvaluateUnconditionally`, plus the 
total functions.
+  private def isTotalInternal(e: Expression): Boolean = e match {
+    case _: AttributeReference | _: Literal => true
+    case _: And | _: Or | _: Not | _: BinaryComparison | _: IsNull | _: 
IsNotNull | _: IsNaN |
+         _: NullIf | _: Coalesce | _: In | _: InSet |
+         _: GetStructField | _: GetArrayStructFields | _: GetMapValue |
+         _: Upper | _: Lower | _: Length | _: StringTrim | _: StringTrimLeft |
+         _: StringTrimRight | _: Substring | _: Concat | _: XxHash64 | _: 
Murmur3Hash =>
+      e.children.forall(isTotalInternal)
+    // The Bloom filter is a scalar subquery already evaluated, or a literal.
+    case b: BloomFilterMightContain => isTotalInternal(b.valueExpression)
+    case b: BinaryArithmetic
+        if b.evalMode == EvalMode.LEGACY && 
b.dataType.isInstanceOf[NumericType] =>
+      e.children.forall(isTotalInternal)
+    case _ => false
+  }
+
+  /**
+   * The expression that computes `attr` lazily in this stage, when an 
operator between this one
+   * and the input of the stage does: a projection alias, or a result 
expression of an aggregate,
+   * whose own inputs, the aggregation buffers, are not computed lazily. The 
attribute itself
+   * otherwise: an input of the stage, read from a scan, a columnar batch or 
an exchange, or an
+   * output that its operator computes before this one runs.
    */
-  protected def mayRaise(e: Expression): Boolean = 
!ExprUtils.canEvaluateUnconditionally(e)
+  protected def producedBy(attr: Attribute): Expression = {
+    def substitute(e: Expression, named: Seq[NamedExpression]): Expression = {
+      val aliases =
+        AttributeMap(named.collect { case a @ Alias(child, _) => a.toAttribute 
-> child })
+      e.transform { case a: Attribute if aliases.contains(a) => aliases(a) }
+    }
+    def resolve(plan: SparkPlan, e: Expression): Expression = plan match {
+      case p: ProjectExec => resolve(p.child, substitute(e, p.projectList))
+      case a: BaseAggregateExec => substitute(e, a.resultExpressions)
+      case f: FilterExec => resolve(f.child, e)
+      case _ => e

Review Comment:
   `resolve` only descends through `ProjectExec`, `BaseAggregateExec` and 
`FilterExec`, and stops at any other operator with `case _ => e`. However, 
`SampleExec` (`usedInputs = AttributeSet.empty`), 
`LocalLimitExec`/`GlobalLimitExec` (`consume(ctx, input)`) and the codegen of 
`UnionExec` pass the lazily evaluated `ExprCode` of their child through. So a 
raising alias computed by a projection below them is judged as a plain input 
column, which cannot raise.
   
   For example, in ANSI mode, Filter, Sample and Project are in the same stage 
here:
   
   ```scala
   df.selectExpr("cast(s AS INT) AS c", "y").sample(0.9).where("c IS NOT NULL 
AND y + 1 > 0")
   ```
   
   Since `mayRaise(isnotnull(c))` is false, the check is moved before `y + 1 > 
0`, and on a row with `s = 'x'` and `y + 1 <= 0`, the cast is evaluated first 
and raises `CAST_INVALID_INPUT`. Previously, `y + 1 > 0` rejected the row first 
and the query succeeded with codegen on. This contradicts the doc and the 
migration guide, which say that a check on a column that the same stage 
computes by such an expression keeps the previous placement.
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:
##########
@@ -256,22 +319,25 @@ trait GeneratePredicateHelper extends PredicateHelper {
       k: Int,
       conjunct: Expression,
       afterNullable: Boolean,
-      generated: Array[Boolean]): Seq[Expression] = {
-    if (afterNullable) {
-      val pending = 
notNullPreds.take(precedingNotNulls(k)).zipWithIndex.filterNot {
-        case (_, idx) => generated(idx)
-      }
-      if (pending.nonEmpty && (mayRaise(conjunct) || pending.exists(p => 
mayRaise(p._1)))) {
-        pending.map { case (p, idx) =>
-          generated(idx) = true
-          p
-        }
-      } else {
-        Nil
+      generated: Array[Boolean]): Seq[Int] = {
+    val pending = 
notNullPreds.take(precedingNotNulls(k)).zipWithIndex.filterNot {
+      case (_, idx) => generated(idx)
+    }
+    val conjunctMayRaise = mayRaise(conjunct)
+    val positioned = if (afterNullable &&
+        (conjunctMayRaise || pending.exists(p => mayRaise(p._1)))) {
+      pending
+    } else if (conjunctMayRaise && 
!conf.legacyFilterLazyNotNullCheckPlacement) {
+      pending.filter { case (p, _) =>
+        !mayRaise(p) && 
p.getTagValue(InferFiltersFromConstraints.INFERRED).isEmpty

Review Comment:
   The `INFERRED` tag now changes the generated placement, and so the error 
behavior, but tags are ignored by canonicalization, `sameResult` and explain. 
So two plans that differ only in whether a check is written or inferred are 
treated as the same plan, while they behave differently at runtime.
   
   For example, `WHERE y + 1 > 0 AND x > 0` gets an inferred `isnotnull(x)`, 
and `WHERE x IS NOT NULL AND y + 1 > 0 AND x > 0` has a written one. After the 
commutative canonicalization of `And`, both are the same plan, so plan reuse 
such as exchange or subquery reuse, or `sameSemantics`, cannot tell them apart, 
and explain doesn't show why one raises `ARITHMETIC_OVERFLOW` and the other 
doesn't.
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:
##########
@@ -256,22 +319,25 @@ trait GeneratePredicateHelper extends PredicateHelper {
       k: Int,
       conjunct: Expression,
       afterNullable: Boolean,
-      generated: Array[Boolean]): Seq[Expression] = {
-    if (afterNullable) {
-      val pending = 
notNullPreds.take(precedingNotNulls(k)).zipWithIndex.filterNot {
-        case (_, idx) => generated(idx)
-      }
-      if (pending.nonEmpty && (mayRaise(conjunct) || pending.exists(p => 
mayRaise(p._1)))) {
-        pending.map { case (p, idx) =>
-          generated(idx) = true
-          p
-        }
-      } else {
-        Nil
+      generated: Array[Boolean]): Seq[Int] = {
+    val pending = 
notNullPreds.take(precedingNotNulls(k)).zipWithIndex.filterNot {
+      case (_, idx) => generated(idx)
+    }
+    val conjunctMayRaise = mayRaise(conjunct)

Review Comment:
   `mayRaise(conjunct)` is now computed for every conjunct even when `pending` 
is empty, since the former `pending.nonEmpty` guard is gone. The `mayRaise` of 
the same check is also recomputed for each conjunct, and each call walks down 
the plan for every attribute in `producedBy`, building a new `AttributeMap` 
from `projectList` or `resultExpressions` each time. With a wide projection and 
many conjuncts, the codegen cost on the driver grows as O(conjuncts x checks x 
attributes x projectList). How about computing `mayRaise` once per 
`notNullPreds` entry, short-circuiting on an empty `pending`, and building the 
alias map once per operator?
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:
##########
@@ -173,8 +174,59 @@ trait GeneratePredicateHelper extends PredicateHelper {
    * Whether evaluating `e` on a row can be observed other than through its 
value: it can raise
    * an error, is nondeterministic or may have side effects, such as a UDF. 
Such an expression
    * has to be evaluated on the rows, and in the order, that `And.eval` 
evaluates it on.
+   *
+   * On top of `ExprUtils.canEvaluateUnconditionally`, a total expression over 
such expressions
+   * is known not to raise: the string functions of `isTotal`, a hash, the 
Bloom filter predicate
+   * of a runtime filter, and the arithmetic of numbers in the legacy 
evaluation mode, which
+   * returns NULL instead of raising. A column that an operator of the same 
stage computes
+   * lazily, such as a projection alias or a result of an aggregate, is judged 
by the expression
+   * that computes it, see `producedBy`, since a check on the column evaluates 
that expression.
+   */
+  protected def mayRaise(e: Expression): Boolean = {
+    val resolved = e.transform { case a: Attribute => producedBy(a) }
+    !(ExprUtils.canEvaluateUnconditionally(resolved) || isTotal(resolved))
+  }
+
+  private def isTotal(e: Expression): Boolean = e.deterministic && 
isTotalInternal(e)
+
+  // The structural cases of `ExprUtils.canEvaluateUnconditionally`, plus the 
total functions.
+  private def isTotalInternal(e: Expression): Boolean = e match {
+    case _: AttributeReference | _: Literal => true
+    case _: And | _: Or | _: Not | _: BinaryComparison | _: IsNull | _: 
IsNotNull | _: IsNaN |
+         _: NullIf | _: Coalesce | _: In | _: InSet |
+         _: GetStructField | _: GetArrayStructFields | _: GetMapValue |
+         _: Upper | _: Lower | _: Length | _: StringTrim | _: StringTrimLeft |
+         _: StringTrimRight | _: Substring | _: Concat | _: XxHash64 | _: 
Murmur3Hash =>
+      e.children.forall(isTotalInternal)
+    // The Bloom filter is a scalar subquery already evaluated, or a literal.
+    case b: BloomFilterMightContain => isTotalInternal(b.valueExpression)
+    case b: BinaryArithmetic
+        if b.evalMode == EvalMode.LEGACY && 
b.dataType.isInstanceOf[NumericType] =>
+      e.children.forall(isTotalInternal)
+    case _ => false
+  }
+
+  /**
+   * The expression that computes `attr` lazily in this stage, when an 
operator between this one
+   * and the input of the stage does: a projection alias, or a result 
expression of an aggregate,
+   * whose own inputs, the aggregation buffers, are not computed lazily. The 
attribute itself
+   * otherwise: an input of the stage, read from a scan, a columnar batch or 
an exchange, or an
+   * output that its operator computes before this one runs.
    */
-  protected def mayRaise(e: Expression): Boolean = 
!ExprUtils.canEvaluateUnconditionally(e)
+  protected def producedBy(attr: Attribute): Expression = {
+    def substitute(e: Expression, named: Seq[NamedExpression]): Expression = {

Review Comment:
   `substitute` re-implements `AliasHelper.getAliasMap(exprs)` and 
`replaceAlias(expr, aliasMap)`. `GeneratePredicateHelper` already extends 
`AliasHelper` through `PredicateHelper`, so we can use them directly, which 
also keeps the alias handling consistent with the rest of the code base, e.g. 
trimming non-top-level aliases.
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:
##########
@@ -256,22 +319,25 @@ trait GeneratePredicateHelper extends PredicateHelper {
       k: Int,
       conjunct: Expression,
       afterNullable: Boolean,
-      generated: Array[Boolean]): Seq[Expression] = {
-    if (afterNullable) {
-      val pending = 
notNullPreds.take(precedingNotNulls(k)).zipWithIndex.filterNot {
-        case (_, idx) => generated(idx)
-      }
-      if (pending.nonEmpty && (mayRaise(conjunct) || pending.exists(p => 
mayRaise(p._1)))) {
-        pending.map { case (p, idx) =>
-          generated(idx) = true
-          p
-        }
-      } else {
-        Nil
+      generated: Array[Boolean]): Seq[Int] = {

Review Comment:
   Both callers convert the returned indexes back to expressions right away 
with `notNullPreds(i)` (lines 407 and 654). Can we keep returning 
`Seq[Expression]` as before? It would make the diff and the callers simpler.
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:
##########
@@ -173,8 +174,59 @@ trait GeneratePredicateHelper extends PredicateHelper {
    * Whether evaluating `e` on a row can be observed other than through its 
value: it can raise
    * an error, is nondeterministic or may have side effects, such as a UDF. 
Such an expression
    * has to be evaluated on the rows, and in the order, that `And.eval` 
evaluates it on.
+   *
+   * On top of `ExprUtils.canEvaluateUnconditionally`, a total expression over 
such expressions
+   * is known not to raise: the string functions of `isTotal`, a hash, the 
Bloom filter predicate
+   * of a runtime filter, and the arithmetic of numbers in the legacy 
evaluation mode, which
+   * returns NULL instead of raising. A column that an operator of the same 
stage computes
+   * lazily, such as a projection alias or a result of an aggregate, is judged 
by the expression
+   * that computes it, see `producedBy`, since a check on the column evaluates 
that expression.
+   */
+  protected def mayRaise(e: Expression): Boolean = {
+    val resolved = e.transform { case a: Attribute => producedBy(a) }
+    !(ExprUtils.canEvaluateUnconditionally(resolved) || isTotal(resolved))
+  }
+
+  private def isTotal(e: Expression): Boolean = e.deterministic && 
isTotalInternal(e)
+
+  // The structural cases of `ExprUtils.canEvaluateUnconditionally`, plus the 
total functions.
+  private def isTotalInternal(e: Expression): Boolean = e match {

Review Comment:
   This copies the whitelist of `ExprUtils.canEvaluateUnconditionallyInternal`. 
Since `isTotal` accepts a superset of what `canEvaluateUnconditionally` 
accepts, `ExprUtils.canEvaluateUnconditionally(resolved) ||` in `mayRaise` is 
redundant and only traverses the tree twice. And the two lists can drift apart 
when `ExprUtils` changes. How about adding the total functions to `ExprUtils`, 
e.g. as `ExprUtils.isTotal`, and calling it once?
   



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