MaxGekk commented on code in PR #59985:
URL: https://github.com/apache/spark/pull/59985#discussion_r4522466338


##########
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:
   Good catch. Fixed in 6c21b2bbbe3 with the fallback you suggested. With the 
config, a filter falls back to `generatePredicateCode` when a column that 
`otherPreds` reads is computed on demand by an expression that can raise 
(`computesRaisingInput`), so the prologue never evaluates such a column. 
Without the config, the CSE branch is the same as on master. Your `cast(s AS 
INT) AS c` example through `sample(1.0)` is a test with 
`spark.sql.subexpressionElimination.filterExec.enabled` on and off. Without the 
fallback, it raises `CAST_INVALID_INPUT`.



##########
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:
   Agreed. Done in 6c21b2bbbe3: such a predicate is appended at the end. Your 
example is a test in `InferFiltersFromConstraintsSuite`: `c > 0`, inferred 
through the child's `a = c`, comes after `b + 1 > 0` and `a > 0`.



##########
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:
   Done in 6c21b2bbbe3, in both branches. The column of an `IsNotNull(a)` that 
`precedingNotNullChecks` generates before a conjunct is recorded like a 
synthetic check, so the conjunct's `nullChecks` skip it. For `WHERE a + 1 > 0 
AND b + 1 > 0` in ANSI mode, the filter now has 4 checks instead of 6. Without 
the config, this only happens after a NULL conjunct, where the synthetic branch 
was already skipped, so the code is the same as on master.



##########
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:
   Done in 6c21b2bbbe3. The `true` description now says that the lazy placement 
of such a check doesn't hold after a conjunct that can be NULL, as with `false`.



##########
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:
   Fixed in 6c21b2bbbe3 in the placement itself. The variables are now paired 
with the last attributes, and an assertion checks that there are no more 
variables than attributes. I didn't change the caller. The hash aggregate's 
`ctx.currentVars` has nulls for the buffer slots, which 
`evaluateRequiredVariables` would dereference, and the existing misalignment 
there is outside this PR.



##########
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:
   Done in 6c21b2bbbe3. The config doc says that with codegen off, an inferred 
predicate is now evaluated after the nondeterministic or UDF conjuncts before 
the conjunct it is inferred from. The PR description says it too.



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