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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2443,6 +2443,38 @@ object InferFiltersFromConstraints extends 
Rule[LogicalPlan]
       j.copy(left = newLeft, right = newRight)
   }
 
+  /**
+   * Adds the predicates inferred from the conjuncts of `condition` to it: at 
the front, or, with
+   * `spark.sql.optimizer.evaluateNotNullChecksInOrder`, each just before the 
first conjunct at
+   * which the conjuncts so far, with the constraints of `child`, imply it, so 
that evaluating the
+   * condition in its order does not evaluate it before the conjuncts that 
precede that one, whose
+   * errors it would hide, e.g. `isnotnull(x)` from `x > 0` in `y + 1 > 0 AND 
x > 0`, or in
+   * `coalesce(x, 1) + y > 0 AND x > 0`. The constraints of the filter are 
computed for each
+   * prefix of the condition until every predicate is placed.
+   */
+  private def withInferredPredicates(
+      inferred: Seq[Expression],
+      condition: Expression,
+      child: LogicalPlan): Expression = {
+    if (conf.evaluateNotNullChecksInOrder) {
+      val conjuncts = splitConjunctivePredicates(condition)
+      val placed = Array.fill(conjuncts.length)(Seq.empty[Expression])
+      var remaining = inferred
+      var k = 0
+      while (remaining.nonEmpty && k < conjuncts.length) {
+        val implied = Filter(conjuncts.take(k + 1).reduce(And), 
child).constraints

Review Comment:
   Following up on my suggestion in the 
[thread](https://github.com/apache/spark/pull/59985#discussion_r4532540900): 
thank you for placing each predicate where the conjuncts so far imply it. 
However, this computes the full `constraints` of a new `Filter` for each 
prefix, that is, the union with the child's constraints, 
`inferAdditionalConstraints` and `constructIsNotNullConstraints`, until every 
inferred predicate is placed. The last conjunct often implies one of them, e.g. 
the `isnotnull(z)` of a trailing `z > 0`, so the loop usually runs to the end, 
and a filter with n conjuncts pays n constraint propagations instead of one. 
For a long generated condition over a join with many constraints, this can be a 
noticeable part of the optimizer time with the config on.
   
   Since the constraints only grow with the prefix, could we find the first 
implying prefix of each remaining predicate with a binary search instead?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:
##########
@@ -289,25 +375,28 @@ trait GeneratePredicateHelper extends PredicateHelper {
   protected def precedingNotNullChecks(
       notNullPreds: Seq[Expression],
       precedingNotNulls: Seq[Int],
+      placement: Option[NotNullCheckPlacement],
       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
-      }
+    lazy val pending = 
notNullPreds.take(precedingNotNulls(k)).zipWithIndex.filterNot {
+      case (_, idx) => generated(idx)
+    }
+    // Without the config, only the NULL-conjunct flag moves the checks.
+    val positioned = if ((!afterNullable && placement.isEmpty) || 
pending.isEmpty) {
+      Nil
+    } else if (afterNullable && (mayRaise(conjunct) || pending.exists(p => 
mayRaise(p._1)))) {
+      pending
+    } else if (placement.exists(_.movesChecks(k))) {
+      pending.takeWhile { case (_, idx) => placement.get.atPosition(idx) }

Review Comment:
   With `takeWhile`, every check after the first one that 
`notNullCheckPlacement` doesn't allow at its position stays lazy, including the 
checks that cannot raise. So the conjunct can raise again on a row that such a 
check rejects, which is the codegen-only error that this PR fixes.
   
   For example, in ANSI mode with the config on, over the `t` of the test at 
WholeStageCodegenSuite.scala:3956:
   
   ```sql
   SELECT a FROM t WHERE upper(s) IS NOT NULL AND x IS NOT NULL AND y + 1 > 0
   ```
   
   `Upper` is not total, so `isnotnull(upper(s))` stops `takeWhile`, and 
`isnotnull(x)` is generated after all the conjuncts. With codegen on, `y + 1` 
raises `ARITHMETIC_OVERFLOW` on the first row, while codegen off drops that row 
at `x IS NOT NULL` and returns `Row(0)`. With the `filter` of the parent 
commit, both returned `Row(0)`. The same happens after `cast(s AS INT) IS NOT 
NULL` on a row with `s = '1'`, and after a check on a column computed by an 
operator that `deferredMayRaise` doesn't look into.
   
   On the row where the earlier check raises, `filter` lets codegen drop the 
row without the error instead. However, the raising check keeps the lazy 
placement anyway, so a later conjunct already hides its error in the same way, 
e.g. `cast(s AS INT) IS NOT NULL AND x = 0` on the first row. Could we go back 
to `filter`? Or, if codegen should raise there too, could the check that stops 
`takeWhile` be generated at its position as well, as the `afterNullable` branch 
does? If `takeWhile` stays, the config doc ("a check that cannot raise an error 
is evaluated at its position before a conjunct that can raise one", 
SQLConf.scala:1919-1920) needs this exception.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:
##########
@@ -177,6 +178,80 @@ trait GeneratePredicateHelper extends PredicateHelper {
    */
   protected def mayRaise(e: Expression): Boolean = 
!ExprUtils.canEvaluateUnconditionally(e)
 
+  /**
+   * The placement of the IsNotNull checks with 
`spark.sql.optimizer.evaluateNotNullChecksInOrder`
+   * (SPARK-60329): for each of `notNullPreds`, whether it can be generated at 
its position in the
+   * condition, and for each of `otherPreds`, whether the checks that precede 
it are generated
+   * before it, see `notNullCheckPlacement`.
+   */
+  protected case class NotNullCheckPlacement(atPosition: Seq[Boolean], 
movesChecks: Seq[Boolean])
+
+  /**
+   * The columns of `inputAttrs` whose variables in `inputExprCode` are 
evaluated on demand, that
+   * is, whose code is not empty. The aggregate `FILTER` clause passes the 
attributes of the
+   * aggregation buffers before those of its input, with the variables of its 
input only, so the
+   * variables are paired with the last attributes.
+   */
+  private def deferredInputs(
+      inputAttrs: Seq[Attribute],
+      inputExprCode: Seq[ExprCode]): AttributeSet = {
+    assert(inputAttrs.length >= inputExprCode.length)
+    
AttributeSet(inputAttrs.takeRight(inputExprCode.length).zip(inputExprCode).collect
 {
+      case (a, ev) if ev.code.nonEmpty => a
+    })
+  }
+
+  /**
+   * With `spark.sql.optimizer.evaluateNotNullChecksInOrder` (SPARK-60329), 
returns the placement
+   * of `notNullPreds` before `otherPreds`, or None without the config. A 
check can be generated
+   * at its position when it cannot raise itself and does not evaluate a 
computation that can. A
+   * conjunct moves the checks that precede it when evaluating it can be 
observed: it `mayRaise`,
+   * or evaluates a computation that can. `inputExprCode` must be the input 
variables of the
+   * predicate before any code is generated for it: a variable whose code is 
not empty is
+   * evaluated on demand, so a check or a conjunct on its column evaluates the 
expression that
+   * computes it, see `deferredMayRaise`. Each column is judged once.
+   */
+  protected def notNullCheckPlacement(
+      notNullPreds: Seq[Expression],
+      otherPreds: Seq[Expression],
+      inputAttrs: Seq[Attribute],
+      inputExprCode: Seq[ExprCode]): Option[NotNullCheckPlacement] = {
+    if (conf.evaluateNotNullChecksInOrder) {
+      val deferred = deferredInputs(inputAttrs, inputExprCode)
+      val raisingDeferred = mutable.HashMap.empty[Attribute, Boolean]
+      def computesRaising(e: Expression): Boolean = e.references.exists { a =>
+        deferred.contains(a) && raisingDeferred.getOrElseUpdate(a, 
deferredMayRaise(a))
+      }
+      Some(NotNullCheckPlacement(
+        notNullPreds.map(p => !mayRaise(p) && !computesRaising(p)),
+        otherPreds.map(c => mayRaise(c) || computesRaising(c))))
+    } else {
+      None
+    }
+  }
+
+  /**
+   * Whether the expression that computes the column `attr`, which this stage 
evaluates on
+   * demand, can raise: a projection alias, or a result of an aggregate, 
possibly through an
+   * operator that forwards the variables of its child, such as a filter, a 
sample or a limit.
+   * A column read from the input of the stage, a scan, a columnar batch or an 
exchange, cannot.
+   * Any other operator is not looked into, and its columns are taken to raise.
+   */
+  private def deferredMayRaise(attr: Attribute): Boolean = {
+    def resolve(plan: SparkPlan, e: Expression): Option[Expression] = plan 
match {
+      case p: ProjectExec => resolve(p.child, replaceAlias(e, 
getAliasMap(p.projectList)))
+      case f: FilterExec => resolve(f.child, e)

Review Comment:
   The PR description says that each walk case was checked by removing it and 
seeing a test fail, but none of the new tests seems to have a filter below the 
filter in the same stage, so they still pass without this case. Then a column 
that a filter below forwards is taken to raise, and its check silently keeps 
the lazy placement.
   
   For example, in ANSI mode with the config on, the nondeterministic filter 
below is not combined with the one above:
   
   ```scala
   spark.table("t").select("a", "x", "y").where("rand() < 2")
     .where("x IS NOT NULL AND y + 1 > 0").select("a")
   ```
   
   With this case, it returns `Row(0)` with codegen on and off. Without it, 
codegen raises `ARITHMETIC_OVERFLOW`. Could we add it next to the sample and 
limit cases?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -1910,6 +1910,35 @@ object SQLConf {
       .booleanConf
       .createWithDefault(false)
 
+  val EVALUATE_NOT_NULL_CHECKS_IN_ORDER =
+    buildConf("spark.sql.optimizer.evaluateNotNullChecksInOrder")
+      .internal()
+      .doc("When true, an IS NOT NULL check in a filter condition, including 
the FILTER clause " +
+        "of an aggregate function, is evaluated in the order of the condition, 
as the " +
+        "interpreted evaluation does, so that it drops a row before an error 
that a later " +
+        "conjunct raises on the row. With whole-stage codegen, a check that 
cannot raise an " +
+        "error is evaluated at its position before a conjunct that can raise 
one, is " +
+        "nondeterministic, calls a user-defined function, or evaluates a 
column that the same " +
+        "stage computes on demand by an expression that can raise, instead of 
just before the " +
+        "first conjunct that references its column; a check whose column the 
same stage has " +
+        "not computed yet, by an expression that can raise, keeps the latter 
placement, except " +
+        "after a conjunct that can be NULL, as when false. A predicate that 
the optimizer " +
+        "infers from the condition is placed just before the first conjunct at 
which the " +
+        "conjuncts so far imply it, instead of at the front of the condition, 
so with " +
+        "whole-stage codegen off it is evaluated after the nondeterministic or 
user-defined " +

Review Comment:
   Following up on the 
[thread](https://github.com/apache/spark/pull/59985#discussion_r4519500497): 
thank you for adding this. The same placement also moves an inferred predicate 
after the conjuncts that can raise, so with codegen off, `WHERE y + 1 > 0 AND x 
> 0` now raises `ARITHMETIC_OVERFLOW` on a row where `x` is NULL, while without 
the config the inferred `isnotnull(x)` dropped the row first, as the tests at 
WholeStageCodegenSuite.scala:3928 and 3946 show. Since this doc opens by saying 
that a check drops a row before an error, could we mention this direction too?



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/InferFiltersFromConstraintsSuite.scala:
##########
@@ -63,6 +63,61 @@ class InferFiltersFromConstraintsSuite extends PlanTest {
     comparePlans(optimized, correctAnswer)
   }
 
+  test("SPARK-60329: evaluateNotNullChecksInOrder places an inferred predicate 
just before the " +
+      "first conjunct that references its columns") {
+    val originalQuery = testRelation.where($"b" + 1 > 0 && $"a" > 0 && $"c" 
=== $"a").analyze
+    def conjuncts(conf: Boolean): Seq[Expression] = {
+      withSQLConf(SQLConf.EVALUATE_NOT_NULL_CHECKS_IN_ORDER.key -> 
conf.toString) {
+        val Filter(condition, _) = Optimize.execute(originalQuery)
+        splitConjunctivePredicates(condition)
+      }
+    }
+    val Seq(a, b, c) = originalQuery.output
+    def positions(conf: Boolean, exprs: Expression*): Seq[Int] = {
+      val canonicalized = conjuncts(conf).map(_.canonicalized)
+      exprs.map(e => canonicalized.indexOf(e.canonicalized))
+    }
+    // Each inferred check is just before the first conjunct on its column, 
after the conjuncts
+    // before that one: `isnotnull(c)` before `c = a`, after `a > 0`.
+    val Seq(notNullB, written1, notNullA, written2, notNullC, written3) = 
positions(conf = true,
+      IsNotNull(b), b + 1 > 0, IsNotNull(a), a > 0, IsNotNull(c), c === a)
+    assert(notNullB == 0 && written1 == 1 && written1 < notNullA && notNullA < 
written2 &&
+      written2 < notNullC && notNullC < written3, conjuncts(conf = true))
+    // Otherwise the inferred predicates are at the front of the condition.
+    assert(conjuncts(conf = false).takeRight(3).map(_.canonicalized) ===
+      Seq(b + 1 > 0, a > 0, c === a).map(_.canonicalized))
+  }
+
+  test("SPARK-60329: evaluateNotNullChecksInOrder places an inferred predicate 
just before the " +
+      "first conjunct at which the conjuncts so far imply it") {
+    withSQLConf(SQLConf.EVALUATE_NOT_NULL_CHECKS_IN_ORDER.key -> "true") {
+      def positions(query: LogicalPlan, exprs: Expression*): Seq[Int] = {

Review Comment:
   nit: this `positions` repeats the one in the previous test (L76-79) with a 
different signature. Could the two tests share one private helper that 
optimizes a query with the config and returns the positions?



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala:
##########
@@ -3883,6 +3883,212 @@ class WholeStageCodegenSuite extends SharedSparkSession
     }
   }
 
+  private val notNullChecksInOrder = 
SQLConf.EVALUATE_NOT_NULL_CHECKS_IN_ORDER.key -> "true"
+
+  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 is generated just before the first conjunct that 
references `x`, or after
+      // all of them, so the overflow is raised, unless `notNullChecksInOrder` 
generates a check
+      // that cannot raise at its position before a conjunct that can.
+      //
+      // 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(
+            notNullChecksInOrder,
+            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 =>
+        // With codegen on and off, and 
`spark.sql.legacy.filterShortCircuitOnNullConjunct` on and
+        // off.
+        withNullConjunctConfs(
+            notNullChecksInOrder,
+            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.
+          checkAnswer(sql("SELECT a FROM t WHERE st.x 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")
+          // `isnotnull(x)`, inferred from `x > 0`, is placed just before it, 
after the
+          // overflowing conjunct, so the query raises with codegen on and off 
alike.
+          checkArithmeticOverflow("SELECT a FROM t WHERE y + 1 > 0 AND x > 0")
+        }
+      }
+      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) {
+          withClue(s"wholeStage=$codegen: ") {
+            // Without `notNullChecksInOrder`, codegen keeps the lazy 
placement, and the inferred
+            // `isnotnull(x)` is at the front of the condition.
+            val written = "SELECT a FROM t WHERE x IS NOT NULL AND y + 1 > 0"
+            val inferred = "SELECT a FROM t WHERE y + 1 > 0 AND x > 0"
+            if (codegen) {
+              checkArithmeticOverflow(written)
+              checkArithmeticOverflow(inferred)
+            } else {
+              checkAnswer(sql(written), Row(0))
+              checkAnswer(sql(inferred), Row(0))
+            }
+            // 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.
+            withSQLConf(notNullChecksInOrder) {
+              val raisingCheck = "SELECT a FROM t WHERE cast(s AS INT) IS NOT 
NULL AND y + 1 > 0"
+              // A check that cannot raise, after one that can, stays lazy 
too: generated before
+              // the overflowing conjunct, the FALSE `x IS NOT NULL` would 
drop the first row on
+              // which the cast check, written before it, raises with codegen 
off.
+              val afterRaisingCheck = "SELECT a FROM t WHERE cast(s AS INT) IS 
NOT NULL AND " +

Review Comment:
   This case asserts the error that `takeWhile` gives on the first row, where 
the cast check raises with codegen off. However, the table has no row on which 
the earlier check is TRUE and `x IS NOT NULL` is FALSE, where `takeWhile` 
raises with codegen on only (basicPhysicalOperators.scala:392). So the case 
doesn't show that the check on `x` still drops a row before the overflow when 
the earlier check passes. Could we add a query such as `upper(s) IS NOT NULL 
AND x IS NOT NULL AND y + 1 > 0`, which should return `Row(0)` with codegen on 
and off, or a row like `('1', NULL, Int.MaxValue)` for `s`, `x` and `y`?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:
##########
@@ -177,6 +178,80 @@ trait GeneratePredicateHelper extends PredicateHelper {
    */
   protected def mayRaise(e: Expression): Boolean = 
!ExprUtils.canEvaluateUnconditionally(e)
 
+  /**
+   * The placement of the IsNotNull checks with 
`spark.sql.optimizer.evaluateNotNullChecksInOrder`
+   * (SPARK-60329): for each of `notNullPreds`, whether it can be generated at 
its position in the
+   * condition, and for each of `otherPreds`, whether the checks that precede 
it are generated
+   * before it, see `notNullCheckPlacement`.
+   */
+  protected case class NotNullCheckPlacement(atPosition: Seq[Boolean], 
movesChecks: Seq[Boolean])
+
+  /**
+   * The columns of `inputAttrs` whose variables in `inputExprCode` are 
evaluated on demand, that
+   * is, whose code is not empty. The aggregate `FILTER` clause passes the 
attributes of the
+   * aggregation buffers before those of its input, with the variables of its 
input only, so the
+   * variables are paired with the last attributes.
+   */
+  private def deferredInputs(
+      inputAttrs: Seq[Attribute],
+      inputExprCode: Seq[ExprCode]): AttributeSet = {
+    assert(inputAttrs.length >= inputExprCode.length)
+    
AttributeSet(inputAttrs.takeRight(inputExprCode.length).zip(inputExprCode).collect
 {
+      case (a, ev) if ev.code.nonEmpty => a
+    })
+  }
+
+  /**
+   * With `spark.sql.optimizer.evaluateNotNullChecksInOrder` (SPARK-60329), 
returns the placement
+   * of `notNullPreds` before `otherPreds`, or None without the config. A 
check can be generated
+   * at its position when it cannot raise itself and does not evaluate a 
computation that can. A
+   * conjunct moves the checks that precede it when evaluating it can be 
observed: it `mayRaise`,
+   * or evaluates a computation that can. `inputExprCode` must be the input 
variables of the
+   * predicate before any code is generated for it: a variable whose code is 
not empty is
+   * evaluated on demand, so a check or a conjunct on its column evaluates the 
expression that
+   * computes it, see `deferredMayRaise`. Each column is judged once.
+   */
+  protected def notNullCheckPlacement(
+      notNullPreds: Seq[Expression],
+      otherPreds: Seq[Expression],
+      inputAttrs: Seq[Attribute],
+      inputExprCode: Seq[ExprCode]): Option[NotNullCheckPlacement] = {
+    if (conf.evaluateNotNullChecksInOrder) {

Review Comment:
   nit: following up on the 
[thread](https://github.com/apache/spark/pull/59985#discussion_r4470610699), 
this still computes `mayRaise` of every conjunct, and walks the plan for the 
deferred columns they reference, when `notNullPreds` is empty. Then `pending` 
is always empty, so `precedingNotNullChecks` never uses the placement. Could we 
return None also when `notNullPreds` is empty?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2443,6 +2443,38 @@ object InferFiltersFromConstraints extends 
Rule[LogicalPlan]
       j.copy(left = newLeft, right = newRight)
   }
 
+  /**
+   * Adds the predicates inferred from the conjuncts of `condition` to it: at 
the front, or, with
+   * `spark.sql.optimizer.evaluateNotNullChecksInOrder`, each just before the 
first conjunct at
+   * which the conjuncts so far, with the constraints of `child`, imply it, so 
that evaluating the
+   * condition in its order does not evaluate it before the conjuncts that 
precede that one, whose
+   * errors it would hide, e.g. `isnotnull(x)` from `x > 0` in `y + 1 > 0 AND 
x > 0`, or in
+   * `coalesce(x, 1) + y > 0 AND x > 0`. The constraints of the filter are 
computed for each
+   * prefix of the condition until every predicate is placed.
+   */
+  private def withInferredPredicates(
+      inferred: Seq[Expression],
+      condition: Expression,
+      child: LogicalPlan): Expression = {
+    if (conf.evaluateNotNullChecksInOrder) {
+      val conjuncts = splitConjunctivePredicates(condition)
+      val placed = Array.fill(conjuncts.length)(Seq.empty[Expression])
+      var remaining = inferred
+      var k = 0
+      while (remaining.nonEmpty && k < conjuncts.length) {
+        val implied = Filter(conjuncts.take(k + 1).reduce(And), 
child).constraints
+        val (now, later) = remaining.partition(implied.contains)
+        placed(k) = now
+        remaining = later
+        k += 1
+      }
+      // The whole condition implies every inferred predicate, so `remaining` 
is empty here.
+      (conjuncts.zip(placed).flatMap { case (c, ps) => ps :+ c } ++ 
remaining).reduce(And)

Review Comment:
   With the config, this rebuilds the whole condition as a left-deep chain of 
`And`, while without it only the inferred predicates are put in front and 
`condition` keeps its shape. The parser builds a balanced tree for a long chain 
of `AND`, since "regular left recursive trees cause considerable performance 
degradations and can cause stack overflows" (`AstBuilder.visitLogicalBinary`). 
So a generated filter with thousands of conjuncts becomes thousands of levels 
deep here, and the recursive passes after this rule can hit a 
`StackOverflowError` only with the config on. Could we use 
`buildBalancedPredicate(..., And)` from `PredicateHelper`, which keeps the 
order of the conjuncts?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2443,6 +2443,38 @@ object InferFiltersFromConstraints extends 
Rule[LogicalPlan]
       j.copy(left = newLeft, right = newRight)
   }
 
+  /**
+   * Adds the predicates inferred from the conjuncts of `condition` to it: at 
the front, or, with
+   * `spark.sql.optimizer.evaluateNotNullChecksInOrder`, each just before the 
first conjunct at
+   * which the conjuncts so far, with the constraints of `child`, imply it, so 
that evaluating the
+   * condition in its order does not evaluate it before the conjuncts that 
precede that one, whose
+   * errors it would hide, e.g. `isnotnull(x)` from `x > 0` in `y + 1 > 0 AND 
x > 0`, or in
+   * `coalesce(x, 1) + y > 0 AND x > 0`. The constraints of the filter are 
computed for each
+   * prefix of the condition until every predicate is placed.
+   */
+  private def withInferredPredicates(
+      inferred: Seq[Expression],
+      condition: Expression,
+      child: LogicalPlan): Expression = {
+    if (conf.evaluateNotNullChecksInOrder) {
+      val conjuncts = splitConjunctivePredicates(condition)
+      val placed = Array.fill(conjuncts.length)(Seq.empty[Expression])
+      var remaining = inferred
+      var k = 0
+      while (remaining.nonEmpty && k < conjuncts.length) {
+        val implied = Filter(conjuncts.take(k + 1).reduce(And), 
child).constraints
+        val (now, later) = remaining.partition(implied.contains)
+        placed(k) = now
+        remaining = later
+        k += 1
+      }
+      // The whole condition implies every inferred predicate, so `remaining` 
is empty here.

Review Comment:
   nit: as this comment says, `remaining` is always empty here, so `++ 
remaining` is dead code, and if the invariant ever broke, a predicate would 
silently go to the end. Could we drop it, or assert `remaining.isEmpty`?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2385,7 +2385,7 @@ object InferFiltersFromConstraints extends 
Rule[LogicalPlan]
           canAdd(c) && !c.references.exists(failable.contains)
         }
       if (newFilters.nonEmpty) {
-        Filter(And(newFilters.reduce(And), condition), child)
+        Filter(withInferredPredicates(newFilters, condition, child), child)

Review Comment:
   nit: the comment of this case at L2377-2378 says "The new filters go ahead 
of the condition", which no longer holds with the config, where each one goes 
just before the first conjunct at which the conjuncts so far imply it. Could 
the comment say where they go with the config, and why the `failableOutput` 
guard is still needed there?



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/InferFiltersFromConstraintsSuite.scala:
##########
@@ -63,6 +63,61 @@ class InferFiltersFromConstraintsSuite extends PlanTest {
     comparePlans(optimized, correctAnswer)
   }
 
+  test("SPARK-60329: evaluateNotNullChecksInOrder places an inferred predicate 
just before the " +

Review Comment:
   nit: this name and the comment at L80 ("Each inferred check is just before 
the first conjunct on its column") describe the placement before 85af45e80f6. 
Now a predicate goes just before the first conjunct at which the conjuncts so 
far imply it, and the next test has a case where that is not the first conjunct 
on its column, `coalesce(a, 1) + b > 0 AND a > 0`. Could we update them?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:
##########
@@ -267,16 +342,27 @@ trait GeneratePredicateHelper extends PredicateHelper {
 
   /**
    * Returns the checks of `notNullPreds` that precede the k-th other conjunct 
`conjunct` in the
-   * condition and are not generated yet, and marks them generated, when 
`afterNullable` is set
-   * and the conjunct or one of these checks `mayRaise`, or Nil.
+   * condition, are not generated yet, and are to be generated before it, and 
marks them
+   * generated. The checks are otherwise generated lazily, before the first 
conjunct that
+   * references their column, or after all conjuncts, so that a column is not 
loaded until a
+   * conjunct needs it. `And.eval` evaluates the condition in its order 
instead, so a check is
+   * generated at its position when the difference is observable:
    *
-   * With the NULL-conjunct flag, a NULL conjunct no longer drops the row, so 
the conjuncts after
-   * it are evaluated in the order of the condition, as `And.eval` does: a 
FALSE IsNotNull check
-   * drops the row before an error a later conjunct raises on it 
(SPARK-60315). `afterNullable`
-   * is set once a conjunct that can be NULL has been generated. The conjuncts 
before it are
-   * never reached after a NULL conjunct, so the checks before them keep the 
lazy placement. So
-   * do the checks before a conjunct when neither it nor one of them can 
raise: their order is
-   * not observable, and the checks are still generated before the next 
conjunct that can raise.
+   *  - With `spark.sql.optimizer.evaluateNotNullChecksInOrder`, before a 
conjunct that
+   *    `placement` moves the checks before, the pending checks up to the 
first one that it does
+   *    not allow at its position, see `notNullCheckPlacement` (SPARK-60329). 
A check after that
+   *    one stays lazy too: generated before it, it could drop a row on which 
the earlier check
+   *    raises an error, as `And.eval` does.
+   *    Such a check only drops a row before an error the conjunct raises on 
it, as `And.eval`

Review Comment:
   nit: the sentence added at L353-355 now sits between the first sentence of 
this bullet and "Such a check only drops a row before an error the conjunct 
raises on it", which is about the checks that are moved, so "Such a check" now 
reads as the lazy one. Also, "it could drop a row on which the earlier check 
raises an error, as `And.eval` does" can be read as `And.eval` dropping the 
row, while it raises there. If `takeWhile` stays (L392), could the new sentence 
go at the end of the bullet, e.g. "... it could drop a row on which `And.eval` 
raises the error of the earlier check"? Separately, the next bullet (L364-365) 
lost the end of master's sentence, "so the checks before them keep the lazy 
placement", so "The conjuncts before the first one that can be NULL are never 
reached after a NULL conjunct" no longer says what follows from it.



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

To unsubscribe, e-mail: [email protected]

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


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

Reply via email to