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


##########
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:
   Fixed in 94228e373fa. A deferred column is now resolved through projections, 
filters, samples and limits, and any other operator, `UnionExec` included, 
counts as raising, so a check on its columns keeps the previous placement. Your 
`sample(0.9)` example is a test (with `sample(1.0)`), as is a scan column 
through a sample and through a limit, whose check moves.



##########
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:
   Done in 94228e373fa. Whether a column is computed on demand is now read from 
the input variable itself: one whose code is already emitted, such as the 
inputs of the aggregate `FILTER` clause, or a CSE-shared or nondeterministic 
alias of `ProjectExec`, is safe to check early. Your `FILTER (WHERE c IS NOT 
NULL AND y + 1 > 0)` query over `x * 2 AS c` with `rand()` is a test and 
returns 1.



##########
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:
   Agreed. The placement is behind 
`spark.sql.optimizer.evaluateNotNullChecksInOrder`, default `false`, in 
94228e373fa. I'd make it the default together with SPARK-60872.



##########
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:
   Right, neither query reached it. The tests in 94228e373fa reference the 
computed column from an outer query:
   - `r` for `sum(a) / sum(b)` and `mx` for `max(x) * 2.0D`, over a `GROUP BY` 
in the same stage;
   - a cast alias through a sample;
   - scan columns through a sample and a limit;
   - the `FILTER` clause.
   
   Each case of the walk was checked by removing it and seeing the test fail.



##########
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 tag is gone in 94228e373fa. The placement of an inferred check is now 
its position in the condition, which explain shows. Two conditions that differ 
only in the order of their conjuncts are still equal after canonicalization, as 
for any conjuncts that can raise.



##########
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:
   Right. The list of total functions is gone in 94228e373fa; `mayRaise` is 
`ExprUtils.canEvaluateUnconditionally` again, which does not accept `Concat`.



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