dongjoon-hyun commented on code in PR #59985:
URL: https://github.com/apache/spark/pull/59985#discussion_r4532540900
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2305,6 +2305,31 @@ 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
Review Comment:
This places an inferred predicate before the first conjunct that references
one of its columns (L2323), but that is not always the conjunct it is inferred
from, so it can still go ahead of an earlier conjunct and hide its error.
For example, in ANSI mode with the config on:
```sql
SELECT a FROM t WHERE coalesce(x, 1) + y > 0 AND x > 0
```
`isnotnull(x)` is inferred from `x > 0`, but it is placed before
`coalesce(x, 1) + y > 0`, which references `x` too. So a row with `x = NULL`
and `y = 2147483647` is dropped without `ARITHMETIC_OVERFLOW`, with codegen on
and off, while the condition as written raises, as `y + 1 > 0 AND x > 0` now
does. A transitive one is the same: in `a = b AND y + 1 > 0 AND b = c`, the
inferred `a = c` goes before `a = b`.
This is not a regression from master, where it is at the front anyway, but
this Scaladoc ("from which it is inferred"), the one of
`precedingNotNullChecks` ("just before the conjunct it is inferred from") and
the PR description ("both evaluation paths follow the condition as written")
say more than the code does. Could we place each predicate just before the
first conjunct at which the conjuncts so far imply it, or else describe the
placement as a best effort? A test case in `InferFiltersFromConstraintsSuite`
would help either way.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:
##########
@@ -253,25 +349,27 @@ 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
- }
+ val pending =
notNullPreds.take(precedingNotNulls(k)).zipWithIndex.filterNot {
Review Comment:
With the config off, this now builds `pending` (`take`, `zipWithIndex` and
`filterNot`) for every conjunct, even when `afterNullable` is false and
`placement` is None, where the result is always `Nil`. On master, it returned
`Nil` right away in that case. It's only at codegen time, but this is the
default path of every filter with whole-stage codegen. Could we return `Nil`
first unless `afterNullable || placement.isDefined`?
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:
##########
@@ -510,11 +617,18 @@ case class FilterExec(condition: Expression, child:
SparkPlan)
//
// `subexpressionElimination.filterExec.enabled` additionally gates this
path so it can be
// turned off independently of subexpression elimination elsewhere.
+ //
+ // With `spark.sql.optimizer.evaluateNotNullChecksInOrder`, the prologue
would evaluate a
+ // column that this stage computes on demand by an expression that can
raise before any
+ // check, so a filter over such a column falls back to
`generatePredicateCode` too
+ // (SPARK-60329).
val (prologueCode, predicateCode) =
if (conf.subexpressionEliminationEnabled &&
conf.subexpressionEliminationFilterExecEnabled &&
otherPreds.nonEmpty &&
otherPredsEquivalentExpressions.getCommonSubexpressions
- .exists(!CollapseProject.isCheap(_))) {
+ .exists(!CollapseProject.isCheap(_)) &&
+ !computesRaisingInput(
+ AttributeSet(otherPreds.flatMap(_.references)), child.output,
input)) {
Review Comment:
nit: `computesRaisingInput` (L207) repeats the `deferred.contains(a) &&
deferredMayRaise(a)` rule of `computesRaising` in `notNullCheckPlacement`
(L234), and `AttributeSet(otherPreds.flatMap(_.references))` here is computed
again at L636. Could we hoist `otherPredInputAttrs` above the `if` and share
one helper for the rule?
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -1833,6 +1833,33 @@ 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, except " +
+ "after a conjunct that can be NULL, as when false. A predicate that
the optimizer " +
+ "infers from a conjunct is placed just before the first conjunct that
references its " +
+ "columns, or at the end if there is none, instead of at the front of
the condition, so " +
+ "with whole-stage codegen off it is evaluated after the
nondeterministic or " +
+ "user-defined function conjuncts that precede that one. A predicate
pushed down to a " +
+ "data source is still evaluated before the others, by the source or
after the scan. " +
Review Comment:
This follows up on the [DSv2
thread](https://github.com/apache/spark/pull/59985#discussion_r4519500502).
For a DSv1 `PrunedFilteredScan` relation, `DataSourceStrategy.selectFilters`
returns `nonconvertiblePredicates ++ unhandledPredicates`
(DataSourceStrategy.scala:816), so a translated filter that the source doesn't
handle goes after the untranslatable ones in the filter after the scan. For
example, with ANSI and the config on, `WHERE x IS NOT NULL AND y + 1 > 0` over
a relation that keeps the default `BaseRelation.unhandledFilters` and doesn't
apply the pushed filters itself becomes `y + 1 > 0 AND isnotnull(x) AND
isnotnull(y)` after the scan. Then a row with `x = NULL` and `y = 2147483647`
raises `ARITHMETIC_OVERFLOW` with codegen on and off, while the interpreted
evaluation of the written condition drops it.
So "still evaluated before the others, by the source or after the scan"
doesn't hold there. Could we limit this sentence to DSv2 sources, or mention
that a DSv1 source can evaluate it after the others?
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:
##########
@@ -581,8 +697,13 @@ case class FilterExec(condition: Expression, child:
SparkPlan)
case ((orig, bound), idx) =>
val afterNullable = nullFlag.isDefined && nullableSeen
precedingNotNullChecks(
- notNullPreds, precedingNotNulls, idx, orig, afterNullable,
- generatedIsNotNullChecks).foreach { p =>
+ notNullPreds, precedingNotNulls, placement, idx, orig,
+ afterNullable, generatedIsNotNullChecks).foreach { p =>
+ // The column of a check generated here needs no synthetic
check below.
+ p match {
+ case IsNotNull(a: Attribute) => extraIsNotNullAttrs += a
Review Comment:
nit: both lockstep paths now record the columns of the checks that
`precedingNotNullChecks` returns in `extraIsNotNullAttrs`, but in two different
styles: `++= preceding.collect { ... }` at L442 and this `match` here. Could we
use the same `collect` here, or let `precedingNotNullChecks` record them, as it
already marks them in `generated`? Then the two paths are less likely to drift
apart.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -1833,6 +1833,33 @@ 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 " +
Review Comment:
This lists the conjuncts that move the checks as the ones that can raise,
are nondeterministic or call a UDF. However, `movesChecks` in
`notNullCheckPlacement` also moves them before a conjunct that evaluates a
column that the same stage computes on demand by an expression that can raise,
as the PR description says. For example, `x IS NOT NULL AND c > 0` over `cast(s
AS INT) AS c` through a sample moves the check on `x` before `c > 0`, which the
test at WholeStageCodegenSuite.scala:3342 relies on. Could we mention this case
here 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]