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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:
##########
@@ -230,17 +282,28 @@ 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.
+   * Returns the indexes in `notNullPreds` of the checks that precede the k-th 
other conjunct
+   * `conjunct` in the 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.
+   *  - Before a conjunct that `mayRaise`, the checks written in the query 
that cannot raise
+   *    (SPARK-60329), unless 
`spark.sql.legacy.filterLazyNotNullCheckPlacement` is set. Such a
+   *    check only drops a row before an error the conjunct raises on it, as 
`And.eval` does. A
+   *    conjunct known not to raise, such as a string function, does not move 
the checks, so
+   *    that their columns are not loaded before it. A check that 
`InferFiltersFromConstraints`
+   *    inferred is implied by the conjunct it was inferred from, so it keeps 
the lazy placement,
+   *    which does not load its column before that conjunct; so does a check 
on an expression
+   *    that can raise itself, or on a column that the stage computes lazily 
by such an
+   *    expression, past a conjunct that may reject the row (SPARK-56032). 
Both unless the flag

Review Comment:
   Rewritten in 94228e373fa. The bullets name the config and the NULL-conjunct 
flag (`afterNullable`) explicitly.



##########
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) }

Review Comment:
   Done in 94228e373fa. It uses `replaceAlias`, and the walk descends through 
filters, samples and limits. I did not add `SerializeFromObjectExec`. Any 
operator the walk does not know counts as raising, so a check on its columns 
keeps the previous placement rather than moving wrongly.



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

Review Comment:
   Done in 94228e373fa: the test comments name 
`spark.sql.legacy.filterShortCircuitOnNullConjunct`, and the new config is not 
a legacy one.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:
##########
@@ -256,22 +263,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) {

Review Comment:
   With 94228e373fa this follows `ExprUtils.canEvaluateUnconditionally`, which 
now accepts the `StartsWith` of `LIKE 'a%'`, the widening casts and the date 
fields, so a check no longer moves before them. The placement is also opt-in 
now, until SPARK-60872 removes the decode.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:
##########
@@ -256,22 +263,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) {
+      pending.filter { case (p, _) =>
+        !mayRaise(p) && 
p.getTagValue(InferFiltersFromConstraints.INFERRED).isEmpty

Review Comment:
   Inferred checks are placed by position in 94228e373fa, just before the first 
conjunct on their columns, so `y + 1 > 0 AND x > 0` raises with codegen on and 
off alike, without decoding `x` early. A check that can raise itself keeps the 
lazy placement. Generating the check on `s` that `cast(s AS INT) IS NOT NULL` 
implies is a separate change, which I'd leave out of this PR.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:
##########
@@ -256,22 +263,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) {
+      pending.filter { case (p, _) =>
+        !mayRaise(p) && 
p.getTagValue(InferFiltersFromConstraints.INFERRED).isEmpty

Review Comment:
   Fixed in 94228e373fa. The walk descends through samples and limits, and the 
sample example is a test.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:
##########
@@ -474,7 +484,8 @@ case class FilterExec(condition: Expression, child: 
SparkPlan)
     //       got synthetic coverage) emit after all otherPreds. With the 
NULL-conjunct
     //       flag, once an otherPred that can be NULL is emitted, the 
notNullPreds that
     //       precede a later otherPred in the condition are emitted before it 
first, when it
-    //       or one of them can raise (`precedingNotNullChecks`), and a complex
+    //       or one of them can raise, and the plain-column ones are before an 
otherPred that

Review Comment:
   The tag and its Scaladoc are gone in 94228e373fa.



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