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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2305,6 +2305,29 @@ object InferFiltersFromConstraints extends 
Rule[LogicalPlan]
       }
   }
 
+  /**
+   * 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 that
+   * references one of its columns, from which it is inferred, 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`.
+   */
+  private def withInferredPredicates(
+      inferred: Seq[Expression],
+      condition: Expression): Expression = {
+    if (conf.evaluateNotNullChecksInOrder) {
+      val conjuncts = splitConjunctivePredicates(condition)
+      val byPosition = inferred.groupBy { p =>
+        conjuncts.indexWhere(c => 
c.references.intersect(p.references).nonEmpty)
+      }
+      (byPosition.getOrElse(-1, Nil) ++ conjuncts.zipWithIndex.flatMap { case 
(c, k) =>

Review Comment:
   An inferred predicate that shares no column with any conjunct (`indexWhere` 
returns -1) still goes to the front of the condition, so it can hide an error 
of an earlier conjunct as before. IIUC, this happens for a predicate inferred 
through a constraint of the child. For example, in ANSI mode with the config on:
   
   ```scala
   spark.table("t").where("a = d AND rand() < 2").where("y + 1 > 0 AND a > 0")
   ```
   
   The nondeterministic child filter is neither combined nor pushed through, so 
`d > 0` is inferred from `a > 0` and the child's `a = d`, and it is placed in 
front of `y + 1 > 0`. Then a row with `a = d = 0` and `y = 2147483647` is 
dropped without `ARITHMETIC_OVERFLOW`, with codegen on and off, while the 
condition as written raises. Since such a predicate is implied by the condition 
together with the child's constraints, how about appending it at the end 
instead?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2305,6 +2305,29 @@ object InferFiltersFromConstraints extends 
Rule[LogicalPlan]
       }
   }
 
+  /**
+   * 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 that
+   * references one of its columns, from which it is inferred, 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`.
+   */
+  private def withInferredPredicates(
+      inferred: Seq[Expression],
+      condition: Expression): Expression = {
+    if (conf.evaluateNotNullChecksInOrder) {
+      val conjuncts = splitConjunctivePredicates(condition)
+      val byPosition = inferred.groupBy { p =>
+        conjuncts.indexWhere(c => 
c.references.intersect(p.references).nonEmpty)

Review Comment:
   With the config, an inferred check also moves after a nondeterministic or 
UDF conjunct that precedes the conjunct it is inferred from. With codegen on, 
nothing changes, since the check was generated lazily anyway. With codegen off, 
however, `WHERE my_udf(y) AND x > 0` now calls `my_udf` also on the rows where 
`x` is NULL, and `WHERE rand(42) < 0.5 AND x > 0` can return a different 
sample, because `isnotnull(x)` was evaluated first before.
   
   It now matches codegen on, so it looks fine to me. However, the config doc 
only mentions the other direction, a check moved before such a conjunct. Could 
we mention this too?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:
##########
@@ -335,7 +405,7 @@ trait GeneratePredicateHelper extends PredicateHelper {
     val generated = otherPreds.zip(boundOtherPreds).zipWithIndex.map { case 
((c, bound), k) =>
       val afterNullable = nullFlag.isDefined && nullableSeen
       val precedingChecks = precedingNotNullChecks(
-        notNullPreds, precedingNotNulls, k, c, afterNullable,
+        notNullPreds, precedingNotNulls, atPosition, movesChecks, k, c, 
afterNullable,

Review Comment:
   When `precedingNotNullChecks` moves `isnotnull(a)` here, it marks the check 
as generated. Then the `nullChecks` of the same conjunct goes to the `else if` 
at line 421: `!afterNullable` holds and `a` is in `nonNullAttrExprIds`, so a 
synthetic `IsNotNull(a)` is emitted right after the moved one. Since the 
optimizer now places an inferred check just before its conjunct, e.g. `WHERE a 
+ 1 > 0 AND b + 1 > 0` in ANSI mode gets the same null check twice for each 
column. The CSE branch has the same pattern at line 675.
   
   It's cheap, but this is the perf-sensitive path. Could we skip the synthetic 
check for a column whose check was just moved before this conjunct, as it is 
skipped after a nullable conjunct?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:
##########
@@ -176,6 +177,59 @@ trait GeneratePredicateHelper extends PredicateHelper {
    */
   protected def mayRaise(e: Expression): Boolean = 
!ExprUtils.canEvaluateUnconditionally(e)
 
+  /**
+   * With `spark.sql.optimizer.evaluateNotNullChecksInOrder` (SPARK-60329), 
returns 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, or Nil without
+   * the config. A check can when it cannot raise itself and does not evaluate 
a computation
+   * that can. A conjunct moves them 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]): (Seq[Boolean], Seq[Boolean]) = {
+    if (conf.evaluateNotNullChecksInOrder) {
+      val deferred = AttributeSet(inputAttrs.zip(inputExprCode).collect {

Review Comment:
   This `zip` assumes that `inputAttrs` and `inputExprCode` are aligned, but 
the aggregate `FILTER` clause calls `generatePredicateCode(ctx, condition, 
inputAttrs, input)` with `inputAttrs = aggBufferAttributes ++ inputAttributes` 
and only the child's `input` 
(`AggregateCodegenSupport.generateEvalCodeForAggFuncs`). So `deferred` is built 
from shifted pairs there.
   
   It's harmless today, because `usedInputs = inputSet` evaluates all the 
inputs before the predicate and `deferred` is empty. The same misalignment 
already exists for `evaluateRequiredVariables`, but this adds a new consumer 
that depends on it. Could we pass `bufVars.flatten ++ input` there, which 
matches `ctx.currentVars`, or at least assert that the lengths match?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:
##########
@@ -527,6 +600,9 @@ case class FilterExec(condition: Expression, child: 
SparkPlan)
           
ctx.subexpressionEliminationForWholeStageCodegen(otherPredsEquivalentExpressions)
 
         val nullFlag = nullConjunctFlag(ctx, otherPreds, boundOtherPreds, 
notNullPreds)
+        // After the input variables of `otherPreds` are evaluated above.
+        val (atPosition, movesChecks) =
+          notNullCheckPlacement(notNullPreds, otherPreds, child.output, input)

Review Comment:
   `notNullCheckPlacement` is called after `inputVarsEvalCode`, which has 
already evaluated every input column of `otherPreds`, including a column that 
this stage computes on demand with an expression that can raise. So the CSE 
branch never sees such a column as deferred, which doesn't match the Scaladoc 
of `notNullCheckPlacement` ("`inputExprCode` must be the input variables of the 
predicate before any code is generated for it"), and the raising computation 
runs in the prologue before any check.
   
   For example, in ANSI mode with the config on, the shared `c * 2` makes this 
filter take the CSE branch:
   
   ```scala
   df.selectExpr("cast(s AS INT) AS c", "x").sample(1.0)
     .where("x IS NOT NULL AND c * 2 > 0 AND c * 2 > -1")
   ```
   
   On a row with `x = NULL` and `s = 'x'`, the non-CSE branch drops the row 
with the `x` check first, as the interpreted evaluation does, while the CSE 
branch raises `CAST_INVALID_INPUT` from the prologue. So the result depends on 
`spark.sql.subexpressionElimination.filterExec.enabled`, and the new tests 
cover only the non-CSE branch. Could we fall back to `generatePredicateCode` 
when the config is on and a deferred input of `otherPreds` can raise? Or, at 
least, could we add a CSE case and document it?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2305,6 +2305,29 @@ object InferFiltersFromConstraints extends 
Rule[LogicalPlan]
       }
   }
 
+  /**
+   * 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 that
+   * references one of its columns, from which it is inferred, 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`.
+   */
+  private def withInferredPredicates(
+      inferred: Seq[Expression],
+      condition: Expression): Expression = {
+    if (conf.evaluateNotNullChecksInOrder) {

Review Comment:
   This relies on the order of the conjuncts surviving until the physical plan. 
However, for a DSv2 source with `SupportsPushDownFilters`, 
`PushDownUtils.pushFilters` returns the post-scan filters as `postScanFilters 
++ untranslatableExprs` in "Early Filter and Projection Push-Down", which runs 
after this rule. So for `WHERE y + 1 > 0 AND x > 0`, the translatable 
`isnotnull(x)` and `x > 0` go back in front of `y + 1 > 0`, or are evaluated by 
the source itself, and the row is dropped without the overflow, with codegen on 
and off.
   
   A pushed filter can drop rows before a raising conjunct anyway, so this may 
be acceptable. Could we mention it as a limitation in the config doc or the PR 
description?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -1833,6 +1833,28 @@ 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 or calls a user-defined function, 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. A check " +

Review Comment:
   This follows up on 
https://github.com/apache/spark/pull/59985#discussion_r4505575496.
   
   With `true`, "a check whose column the same stage has not computed yet, by 
an expression that can raise, keeps the latter placement" doesn't hold after a 
conjunct that can be NULL. The `afterNullable` branch of 
`precedingNotNullChecks` moves all the pending checks, including such a check, 
before a conjunct that can raise. For example, with ANSI on:
   
   ```sql
   SELECT k FROM (SELECT k, sum(a) / sum(b) AS r, max(n) AS m, max(w) AS mw, 
max(z) AS mz FROM v GROUP BY k)
   WHERE NOT (m > 0 AND mw > 0) AND r IS NOT NULL AND mz + 1 > 0
   ```
   
   For a group whose `n` values are all NULL, the check on `r` is generated 
before `mz + 1 > 0`, so the division is evaluated there and can raise 
`DIVIDE_BY_ZERO`. This is the SPARK-60315 behavior on master, so only the doc 
needs a change. Could we mention the NULL-conjunct exception in the description 
of `true` too?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:
##########
@@ -253,25 +315,29 @@ trait GeneratePredicateHelper extends PredicateHelper {
   protected def precedingNotNullChecks(
       notNullPreds: Seq[Expression],
       precedingNotNulls: Seq[Int],
+      atPosition: Seq[Boolean],
+      movesChecks: Seq[Boolean],
       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
-      }
+    val pending = 
notNullPreds.take(precedingNotNulls(k)).zipWithIndex.filterNot {
+      case (_, idx) => generated(idx)
+    }
+    val positioned = if (pending.isEmpty) {
+      Nil
+    } else if (afterNullable && (mayRaise(conjunct) || pending.exists(p => 
mayRaise(p._1)))) {
+      pending
+    } else if (movesChecks.nonEmpty && movesChecks(k) &&

Review Comment:
   nit: `pending.exists { case (_, idx) => atPosition(idx) }` looks redundant. 
When it's false, `pending.filter { ... }` is empty, which is the same as `Nil`.
   
   ```scala
   } else if (movesChecks.nonEmpty && movesChecks(k)) {
     pending.filter { case (_, idx) => atPosition(idx) }
   }
   ```
   
   Also, the `movesChecks.nonEmpty` guard comes from the `(Nil, Nil)` sentinel 
of `notNullCheckPlacement`. Returning an `Option` might make it simpler.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/InferFiltersFromConstraintsSuite.scala:
##########
@@ -26,7 +26,7 @@ import org.apache.spark.sql.catalyst.rules._
 import org.apache.spark.sql.internal.SQLConf
 import org.apache.spark.sql.types._
 
-class InferFiltersFromConstraintsSuite extends PlanTest {
+class InferFiltersFromConstraintsSuite extends PlanTest with PredicateHelper {

Review Comment:
   nit: `PlanTest` already mixes in `PredicateHelper` through `PlanTestBase`, 
so `with PredicateHelper` is not needed.



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