spark-test commented on code in PR #59985:
URL: https://github.com/apache/spark/pull/59985#discussion_r4505575482
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -1808,6 +1808,21 @@ object SQLConf {
.booleanConf
.createWithDefault(false)
+ val LEGACY_FILTER_LAZY_NOT_NULL_CHECK_PLACEMENT =
+ buildConf("spark.sql.legacy.filterLazyNotNullCheckPlacement")
Review Comment:
**Nit (P3):** `spark.sql.legacy.filterLazyNotNullCheckPlacement` names a
placement rather than saying what happens when it is `true`, which the
boolean-config naming guideline in `ConfigEntry.scala` (item 2) asks for, as in
`spark.shuffle.sort.useRadixSort`. The key is new in 4.4.0, so renaming it now
costs nothing, while after a release it would need an alternative key. A verb
phrase such as `spark.sql.legacy.deferFilterNotNullChecks` would say what
`true` does; the accessor, the scaladoc mention, the migration guide and the
tests would follow the rename.
**Verification:**
- **Inspection:** The key follows the boolean config naming guideline, and
every reference uses the new key.
##########
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) }
Review Comment:
**Blocking (P1):** `mayRaise` now resolves each column through `producedBy`,
and the same predicate also decides the NULL-conjunct flag
(`notNullPreds.exists(mayRaise)`) and the SPARK-60315 branch of
`precedingNotNullChecks` (`pending.exists(p => mayRaise(p._1))`); neither reads
`spark.sql.legacy.filterLazyNotNullCheckPlacement`. A check on a column that a
same-stage keyed aggregate or projection computes with an expression that can
raise therefore turns the flag on where the base branch had none, and after a
conjunct that can be NULL it makes every pending check, itself included, be
generated before the next conjunct, which evaluates the computation.
For example, with ANSI and whole-stage codegen on, `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 > 0` returns no row on
the base branch for a group whose `n` values are all NULL and whose `sum(b)` is
0, because the NULL conjunct drops it. It now fails with `DIVIDE_BY_ZERO`,
whether or not the new config is set. Codegen off already fails there, because
it computes `r` eagerly, but the PR states that a check on such a column keeps
the previous placement and that the new config restores it.
This extends existing discussions
[1](https://github.com/apache/spark/pull/59985#issuecomment-6635773879),
[2](https://github.com/apache/spark/pull/59985#pullrequestreview-5772386863).
**Recommended change:** Make nullConjunctFlag and the afterNullable branch
judge each conjunct and check by its own expression, as the base branch did,
without resolving columns through producedBy. When
spark.sql.legacy.filterLazyNotNullCheckPlacement is set, use the base-branch
classification for every placement decision, so that the config restores the
base placement exactly.
**Why this works:** A check on a lazily computed column then neither creates
the NULL-conjunct flag nor triggers the positioning by itself. The computation
runs only where the base branch ran it, and the legacy config reproduces the
base-branch placement.
**Scope:** Separate the NULL-conjunct decisions from the
producing-expression classification, and make the legacy config select the base
classification.
**Risks:** After a NULL conjunct, a conjunct on a lazily computed column
that can raise is again not evaluated on that row with codegen on, as on the
base branch. Codegen off still raises, because it computes the column eagerly;
that difference predates the PR.
**Constraints:** Keep the SPARK-60315 behavior unchanged for conjuncts and
checks that can raise by their own expression.
**Success:** With ANSI on and codegen on, `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 > 0` returns no row, and no
DIVIDE_BY_ZERO, for a group whose n values are all NULL and whose sum(b) is 0,
whether or not the new config is set. With
spark.sql.legacy.filterLazyNotNullCheckPlacement set, the IS NOT NULL checks
are placed as on the base branch.
**Verification:**
- **Regression:** With ANSI and codegen on, consider a filter over a keyed
aggregate whose check is on a raising select-list alias after a conjunct that
can be NULL. It does not raise on a group that the NULL conjunct drops, under
both settings of the new config.
- **Compatibility:** With the new config set, filters with a NULL conjunct
produce the same results and errors as on the base branch, including the
existing SPARK-60315 cases, with
spark.sql.legacy.filterShortCircuitOnNullConjunct both on and off.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:
##########
@@ -474,7 +540,9 @@ 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 with or without the flag, the ones
written in the
+ // query that cannot raise, inferred ones excluded, are emitted
before an otherPred
+ // that can raise (`precedingNotNullChecks`, SPARK-60329), and a
complex
Review Comment:
**Nit (P3):** The clause added here, "with or without the flag, the ones
written in the query that cannot raise ... (SPARK-60329)", now joins the
following clause about a complex `IsNotNull(expr)` written after the otherPred,
so that clause reads as if it applied with or without the NULL-conjunct flag.
The code defers such a check only after a nullable otherPred: without one, the
`if (!afterNullable)` block still emits it before the otherPred that contains
its expression (SPARK-51356). Since this comment is the contract that keeps the
CSE branch and `generatePredicateCode` in lockstep, a maintainer following it
could drop that ordering in one path. Putting the SPARK-60329 clause in its own
sentence, or before the NULL-conjunct sentence as the comment in
`generatePredicateCode` does, keeps the NULL-conjunct clause scoped.
This extends an [existing
discussion](https://github.com/apache/spark/pull/59985#discussion_r4465352189).
**Verification:**
- **Inspection:** The CSE invariant comment and the generatePredicateCode
comment state the same conditions as the code in both paths.
##########
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
Review Comment:
**Nit (P3):** This says numeric arithmetic in the legacy evaluation mode
"returns NULL instead of raising". In that mode integral `Add`, `Subtract` and
`Multiply` wrap around on overflow and return a non-NULL value; NULL comes back
only for division or remainder by zero and for decimal overflow. The conclusion
that these expressions cannot raise still holds, but a maintainer who extends
the total list from the stated reason could misjudge another expression.
**Recommended change:** Extend the known-total classification with
deterministic expressions verified not to raise in the session's evaluation
mode: StartsWith, EndsWith and Contains, casts that cannot fail for their
source and target types (such as the widening casts that type coercion
inserts), and datetime field extraction such as year. Remove Concat, or admit
it only for inputs that cannot exceed the element and length limits. State the
actual reason for each entry in the scaladoc; for LEGACY arithmetic, that it
returns NULL or wraps around instead of raising.
**Why this works:** A conjunct made only of known-total expressions then no
longer moves the checks before it, so their columns are decoded where the base
branch decoded them. A concat check or conjunct is again treated as able to
raise.
**Scope:** Make the known-total classification match what can raise in the
session's evaluation mode.
**Risks:** A filter with a concat conjunct moves its checks again, which
adds the decode there. An expression added to the list by mistake would move a
check that raises, or skip a conjunct's error after a NULL conjunct, so each
entry needs its own verification.
**Constraints:** Admit an expression only when it cannot raise in the
session's evaluation mode for any input its types allow.
**Success:** With ANSI on and codegen on, `WHERE d IS NOT NULL AND s LIKE
'abc%' AND d > 5`, and `WHERE d IS NOT NULL AND i = l AND d > 5` with i INT and
l BIGINT, decode d only on rows that pass the middle conjunct, as on the base
branch. A concat conjunct is treated as able to raise. The scaladoc states the
actual reason why LEGACY arithmetic cannot raise.
**Verification:**
- **Regression:** With ANSI and codegen on, a filter with a written check
before a LIKE-prefix conjunct or a widening cast loads the checked column in
its generated code where the base branch loads it.
- **Behavior:** A written check before a conjunct that can raise in the
session's mode, such as an ANSI multiplication, still moves before it.
- **Inspection:** The total list does not admit Concat for unbounded inputs,
and its scaladoc reasons match the code.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -1808,6 +1808,21 @@ object SQLConf {
.booleanConf
.createWithDefault(false)
+ val LEGACY_FILTER_LAZY_NOT_NULL_CHECK_PLACEMENT =
+ buildConf("spark.sql.legacy.filterLazyNotNullCheckPlacement")
+ .internal()
+ .doc("When true, whole stage codegen of a filter condition, including
the FILTER clause " +
+ "of an aggregate function, evaluates an IS NOT NULL check just before
the first " +
+ "top-level conjunct that references its column, or after all
conjuncts, even when a " +
+ "conjunct before that position can raise an error, so the error is
raised on a row " +
Review Comment:
**Nit (P3):** The doc says that with `true` a check is evaluated just before
the first conjunct that references its column, "even when a conjunct before
that position can raise an error, so the error is raised on a row that the
check rejects". With `spark.sql.legacy.filterShortCircuitOnNullConjunct` at its
default, though, once a conjunct that can be NULL has been generated, the
NULL-conjunct branch still generates the pending checks before a later conjunct
that can raise, so `WHERE NOT (a > 0 AND b > 0) AND x IS NOT NULL AND y + 1 >
0` drops the row before the overflow. The description of `false` mentions only
conjuncts that can raise, while checks also move before nondeterministic and
UDF conjuncts. Describing the NULL-conjunct handling that still applies under
`true`, and the nondeterministic and UDF conjuncts under `false`, would give
users an accurate picture of the rollback.
This extends an [existing
discussion](https://github.com/apache/spark/pull/59985#discussion_r4470610685).
**Verification:**
- **Inspection:** The config doc describes both values in terms that hold
with spark.sql.legacy.filterShortCircuitOnNullConjunct on and off.
##########
docs/sql-migration-guide.md:
##########
@@ -28,6 +28,7 @@ license: |
## Upgrading from Spark SQL 4.3 to 4.4
+- Since Spark 4.4, with whole-stage codegen enabled, a filter condition,
including the `FILTER` clause of an aggregate function, evaluates an `IS NOT
NULL` check written in the query that cannot raise an error, such as a check on
a column, on a struct field or on a string function of them, before a later
conjunct that can raise an error, is nondeterministic or calls a user-defined
function, in the order of the condition, as Spark already did with whole-stage
codegen disabled. Previously, the check was evaluated just before the first
conjunct that references the column, or after all conjuncts, so a query such as
`SELECT a FROM t WHERE x IS NOT NULL AND y + 1 > 0` could fail with
`ARITHMETIC_OVERFLOW` in ANSI mode on a row where `x` is `NULL` and `y` is
`2147483647`, which is dropped with whole-stage codegen disabled. As a
consequence, a nondeterministic conjunct such as `rand(seed)` after such a
check now runs only on the rows the check keeps, so it can return different
values for th
e same seed and data, and a side-effecting user-defined function is no longer
called on the rows the check rejects. An `IS NOT NULL` check that the optimizer
infers from another conjunct, a check on an expression that can raise an error
itself, such as `cast(s AS INT) IS NOT NULL`, and a check on a column that the
same stage computes by such an expression, such as an aggregate result in a
`HAVING` clause, keep the previous placement, so a later conjunct can still
raise an error on a row that such a check rejects; and a check written after a
conjunct that references its column is still evaluated before that conjunct. To
restore the previous placement, set
`spark.sql.legacy.filterLazyNotNullCheckPlacement` to `true`.
Review Comment:
**Nit (P3):** This gives "an aggregate result in a `HAVING` clause" as a
column that keeps the previous placement. A keyed aggregate evaluates its
aggregate results before the filter, and `producedBy` resolves a `HAVING`
reference such as `sum(a)` to that result, so `... GROUP BY k HAVING sum(a) IS
NOT NULL AND max(y) + 1 > 0` now moves the check. An inline `HAVING sum(a) /
sum(b) IS NOT NULL` keeps its placement only because the division stays in the
filter, as a check on an expression that can raise. Only a raising select-list
expression checked through its alias, such as `sum(a) / sum(b) AS r` checked in
`HAVING` or in an outer filter, matches the sentence; naming that would keep
readers from expecting plain aggregate-result checks to stay where they were.
**Verification:**
- **Inspection:** Every example in the migration note behaves as the note
says, and a check on a plain aggregate result is not presented as keeping the
previous placement.
##########
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") {
Review Comment:
**Nit (P3):** The new branch also generates a written check before a
nondeterministic conjunct or a UDF call, which `mayRaise` reports, and the
migration guide documents the consequences for `rand(seed)` and side-effecting
UDFs. Every new assertion, though, uses an ANSI overflow (`y + 1 > 0`) as the
later conjunct. Narrowing the placement to conjuncts that can throw, or
admitting a nondeterministic expression into the total list, would therefore
keep the suite green while `WHERE x IS NOT NULL AND rand(42) < 0.5` returned a
different sample with codegen on than with it off. A case with a written check
before a seeded `rand` conjunct, and one before a counting UDF, comparing
codegen on with off and asserting that the UDF is not called on rows the check
rejects, would pin the documented behavior.
**Verification:**
- **Behavior:** With codegen on and off, a filter with a written check
before rand(seed) returns the same rows, and a UDF after the check is not
called on rows the check rejects.
##########
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:
**Nit (P3):** "Both unless the flag applies." ends a bullet whose only named
flag is `spark.sql.legacy.filterLazyNotNullCheckPlacement`, while the
NULL-conjunct flag it means is introduced in the next bullet. Read with the
nearest antecedent, the sentence says inferred and raise-capable checks move
when the legacy config is set, but with that config set the new branch is
skipped and only the NULL-conjunct branch moves them. Writing "Both unless the
NULL-conjunct flag applies (`afterNullable`, below)" removes the ambiguity in
the scaladoc that both codegen paths are kept in lockstep with.
**Verification:**
- **Inspection:** Every flag that the placement scaladoc refers to is named
unambiguously.
##########
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:
**Nit (P3):** `substitute` builds its own alias map and replaces attributes
with `transform`, which is `transformDown`, and `mayRaise` substitutes the
`producedBy` results the same way. `transformDown` applies the rule again to
the children of each replacement, so an alias whose child reads its own ExprId
would be substituted without end, and the filter's code generation would fail
with a `StackOverflowError`. `AliasHelper.replaceAlias`, which
`GeneratePredicateHelper` already has through `PredicateHelper`, uses
`transformUp` for exactly this case and also trims inner aliases. No optimizer
or planner rule in the tree builds such an alias below a filter today, so the
risk is limited to plans from optimizer extensions or future rules, but reusing
`getAliasMap` and `replaceAlias` removes it along with the duplicated logic.
This extends an [existing
discussion](https://github.com/apache/spark/pull/59985#discussion_r4470610717).
**Recommended change:** Make producedBy descend through every same-stage
operator that forwards its child's input variables unevaluated, that is, one
whose output is its child's output and which declares no used inputs, as
SampleExec, LocalLimitExec and GlobalLimitExec do. Resolve
SerializeFromObjectExec outputs to their serializer expressions. Substitute
aliases with AliasHelper's getAliasMap and replaceAlias instead of the
hand-written transformDown.
**Why this works:** A check on a column that a forwarding operator passes
through is then judged by the expression that computes it. A check on a raising
alias therefore keeps its placement instead of evaluating the alias early.
replaceAlias substitutes each alias once with transformUp, so an alias that
redefines its own ExprId cannot recurse.
**Scope:** Rework the producing-expression walk that the filter placement
rule uses, and add tests for forwarding operators.
**Compatibility:** A check on a column read from a scan, a columnar batch or
a stage boundary still moves before a later conjunct that can raise.
**Risks:** Checks on columns that reach the filter through a sample or a
limit from a raising projection keep the base-branch placement, so the fix does
not move them, as the PR's rule for lazily computed columns intends. UnionExec
also forwards deferred variables without matching the forwarding rule, but
filter pushdown moves every IS NOT NULL check on a column into the branches of
a union, so no such check reaches the walk above one. Another codegen operator
that forwards deferred variables would need the same treatment.
**Constraints:** Treat an operator as forwarding only when its output is its
child's output and it declares no used inputs, so that the walk never passes an
operator that evaluates or recomputes its inputs. Keep a column read from a
scan, a columnar batch or a stage boundary movable.
**Exclusions:**
- Judging an input that is already evaluated before the predicate as a plain
column belongs to the repair that extends the fix to the exempted checks.
**Success:** With ANSI on and whole-stage codegen on, `df.selectExpr("cast(s
AS INT) AS c", "y").sample(0.9).where("c IS NOT NULL AND y + 1 > 0")`, and the
equivalent LIMIT subquery over a single-partition table, do not evaluate the
cast on a row that `y + 1 > 0` rejects. Alias substitution in the placement
rule goes through AliasHelper and terminates for an alias that redefines its
own ExprId.
**Verification:**
- **Regression:** With ANSI and whole-stage codegen on, consider a filter
whose check is on a raising projection alias that reaches it through a sample
or a limit, followed by a conjunct that rejects a row whose alias raises. It
returns the remaining rows without the alias's error, as on the base branch.
- **Behavior:** A written check on a plain scan column above a sample or a
limit still drops a row before a later conjunct that can raise.
- **Inspection:** The producing-expression walk substitutes aliases through
AliasHelper rather than a hand-written transformDown.
##########
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:
**Nit (P3):** The phrase "whatever the legacy config" here refers to
`spark.sql.legacy.filterShortCircuitOnNullConjunct`, which
`withNullConjunctConfs` toggles, while the later comment "The legacy config
keeps the lazy placement of a check written in the query" refers to the new
`spark.sql.legacy.filterLazyNotNullCheckPlacement`. Read literally, the two
comments contradict each other. Naming the config in each comment makes the
test's intent checkable.
**Verification:**
- **Inspection:** No test comment refers to two different configs by the
same name.
##########
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:
Thanks for the numbers. With the total-function list, the checks no longer
move before `upper`, `length` and the other listed functions, and those ratios
match master. They still move before conjuncts that cannot raise but are not on
the list, so the column is still decoded on rows those conjuncts reject, with
nothing gained. Examples are the `StartsWith` that `s LIKE 'a%'` becomes, casts
that cannot fail, such as the `cast(i AS BIGINT)` that type coercion adds when
an INT column is compared with a BIGINT column, and datetime field extraction
such as `year(dt)`. So this point is still open for those conjuncts.
<!-- SPARK_DEV_REVIEW_REPLY
{"feedback_id":"inline:4465352160","thread_id":"inline:4465352160","verdict_sha256":"eaebc4e5907428970bcd8021d15757448f5b2574c0c49cb7d8a92ce299df09d4"}
-->
##########
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:
The cost you measured for moving inferred checks was for `upper(name) = 'X'
AND d > 5`. With the total-function list in this commit, `upper` no longer
moves any check, so that shape would keep its current placement even with
inferred checks included. Moving inferred checks that cannot raise would add
the decode only before conjuncts that can raise, which is the same cost already
accepted for written checks. Until then, `y + 1 > 0 AND x > 0` still fails only
with codegen on. A check on an expression that can raise, such as `cast(s AS
INT) IS NOT NULL`, can be covered without evaluating it early, by generating
the check on `s` that it implies at its position. So both exemptions still
leave the failure in place for those queries.
<!-- SPARK_DEV_REVIEW_REPLY
{"feedback_id":"inline:4465352168","thread_id":"inline:4465352168","verdict_sha256":"eaebc4e5907428970bcd8021d15757448f5b2574c0c49cb7d8a92ce299df09d4"}
-->
##########
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:
Thanks, `producedBy` now resolves a projection or an aggregate directly
below the filter. The walk still stops at operators that pass deferred values
through without evaluating them, though: `SampleExec` and
`LocalLimitExec`/`GlobalLimitExec` declare no used inputs and forward their
child's unevaluated variables. So for `df.selectExpr("cast(s AS INT) AS c",
"y").sample(0.9).where("c IS NOT NULL AND y + 1 > 0")`, the check on `c` is
still moved before `y + 1 > 0`, and the cast runs on rows that conjunct would
drop. A `LIMIT` subquery over a single-partition table behaves the same way.
<!-- SPARK_DEV_REVIEW_REPLY
{"feedback_id":"inline:4465352174","thread_id":"inline:4465352174","verdict_sha256":"eaebc4e5907428970bcd8021d15757448f5b2574c0c49cb7d8a92ce299df09d4"}
-->
##########
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:
Thanks, the CSE-branch comment now states the rule. The `INFERRED` scaladoc
now says a written check moves only before a conjunct that can raise and only
when it cannot raise itself, but it still says an inferred check is always
generated lazily, while after a NULL conjunct it is generated at its position
as well (SPARK-60315). The new clause in the CSE-branch comment also changes
how the sentence after it reads; this review raises that wording separately.
<!-- SPARK_DEV_REVIEW_REPLY
{"feedback_id":"inline:4465352189","thread_id":"inline:4465352189","verdict_sha256":"eaebc4e5907428970bcd8021d15757448f5b2574c0c49cb7d8a92ce299df09d4"}
-->
--
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]