spark-test commented on code in PR #60766:
URL: https://github.com/apache/spark/pull/60766#discussion_r4650643441
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -3145,25 +3158,42 @@ object PushPredicateThroughNonJoin extends
Rule[LogicalPlan] with PredicateHelpe
/**
* Splits `conds`, the conjuncts of a filter in their written order, into
the ones to push below
* an operator and the ones to keep above it. `canPush` tells whether the
operator lets a
- * conjunct through, and `throwable` whether it may throw (e.g.
`raise_error`). Every conjunct
- * written before the first one that cannot be pushed is pushed. After it,
only the conjuncts
- * that are not throwable are pushed, so a throwable conjunct is not
evaluated on rows the
- * conjuncts before it would have filtered out. Moving a non-throwable
conjunct below a
- * throwable one is fine, as it can only reduce the rows the throwable one
sees. The conjuncts
- * to keep above are returned in the order they were written.
+ * conjunct through, `pushedForm` gives the conjunct as it is evaluated
below the operator (e.g.
+ * with the aliases of a projection substituted), and `failable` the columns
it can read that
+ * can fail to compute (see `failableOutput`). Every conjunct written before
the first one that
+ * cannot be pushed is pushed. After it, only the conjuncts that are not
throwable (e.g.
+ * `raise_error`) are pushed, so a throwable conjunct is not evaluated on
rows the conjuncts
+ * before it would have filtered out. Moving a non-throwable conjunct below
a throwable one is
+ * fine, as it can only reduce the rows the throwable one sees. Once a
non-deterministic or
+ * throwable conjunct stays above, only the conjuncts that can not fail are
pushed after it: a
+ * conjunct that [[ExprUtils.canEvaluateUnconditionally]] rejects, or that
reads a column in
+ * `failable`, would be evaluated on rows that conjunct may have filtered
out, e.g. an ANSI
+ * division written after `rand() < 0.1`. The conjuncts to keep above are
returned in the order
+ * they were written.
*/
private def splitPushable[T](conds: Seq[T])(
- canPush: T => Boolean, throwable: T => Boolean): (Seq[T], Seq[T]) = {
+ canPush: T => Boolean,
+ pushedForm: T => Expression,
+ failable: => AttributeSet): (Seq[T], Seq[T]) = {
val (leading, rest) = conds.span(canPush)
- // The head of `rest`, if any, is the first conjunct that cannot be pushed.
- val (pushedRest, stayUp) = rest.drop(1).partition(c => canPush(c) &&
!throwable(c))
- (leading ++ pushedRest, rest.take(1) ++ stayUp)
+ // The head of `rest`, if any, is the first conjunct that cannot be
pushed, so it stays above.
+ // So does the head of `ordered`, if any, as it is non-deterministic or
throwable.
+ val (reorderable, ordered) = rest.span { c =>
+ pushedForm(c).deterministic && !pushedForm(c).throwable
Review Comment:
**Blocking (P1):** In the Project case `canPush` is `isCheap(used)`
(Optimizer.scala:2862), which admits a cheap non-deterministic conjunct such as
`rand(10) < 0.01` or `spark_partition_id() = 0`. When it is written after a
conjunct over an expensive alias, this span stops at it, so it heads `ordered`,
and `ExprUtils.canEvaluateUnconditionally` rejects it because it is
non-deterministic, so it stays above the projection. The base branch pushed it
below (`rest.drop(1).partition(c => canPush(c) && !throwable(c))`).
By this review's reading of the code, with a Scala UDF `score`,
`spark.range(1000000).select($"id", score($"id") as "s").where($"s" > 0.5 &&
rand(10) < 0.01)` was planned as `Filter(s > 0.5)` over the projection over
`Filter(rand(10) < 0.01)`, so `score` ran on about 1% of the rows. Now the rule
returns the filter unchanged and `score` runs on every row, a cost that grows
with the input. With a Python UDF alias, which counts as expensive by default,
each of those rows also goes to the Python worker, so a UDF that raises on a
row the condition drops, such as a row of another partition under
`spark_partition_id() = 0`, now fails a query that returns its rows on the base
branch.
The description says "A conjunct written after a deterministic one that
stays above ... is still pushed unless it is throwable, as before", and the
stated problem does not need this: pushed ahead as before, the
non-deterministic conjunct still keeps every later conjunct that can fail
behind it in the same pushed filter. Letting a cheap, non-throwable conjunct
continue the reorderable part, for example `rest.span(c =>
(pushedForm(c).deterministic || canPush(c)) && !pushedForm(c).throwable)`,
restores the base placement, and only the Project case changes, since every
other caller's `canPush` already requires determinism. If giving a seeded
`rand` the rows the conditions before it keep is the intent, the description
should state that regression and its cost instead.
**Verification:**
- **Regression:** A plan test over a projection with an expensive UDF alias
shows a cheap non-deterministic condition written after a condition over that
alias pushed below the projection, with a cheap ANSI division written after it
pushed in the same filter after it.
- **Behavior:** A plan test with a Python UDF alias and spark_partition_id()
= 0 written after a condition over it shows the partition condition below the
projection, so the UDF evaluation only gets that partition's rows.
- **Regression:** An end-to-end query with rand(10) < 0.0 written between a
condition over one Scala UDF alias and two conditions over a second alias whose
UDF throws on some row returns no row with whole-stage codegen on and off.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2952,7 +2960,8 @@ object PushPredicateThroughNonJoin extends
Rule[LogicalPlan] with PredicateHelpe
case filter @ Filter(condition, union: Union) =>
// Union could change the rows, so non-deterministic predicate can't be
pushed down
- val (pushDown, stayUp) =
splitPushableConjuncts(condition)(_.deterministic)
+ val (pushDown, stayUp) =
+ splitPushableConjuncts(condition,
failableOutput(union))(_.deterministic)
Review Comment:
**Non-blocking (P2):** `failableOutput(union)` is always empty:
`PredicateHelper.failableOutput` (predicates.scala:267-291) has no `Union`
case, so the failable-column test in `splitPushable` never keeps a conjunct
above here. The other push cases pass the plan below the operator
(Optimizer.scala:2864, 2949, 2995, 3093 and 3141).
By this review's reading of the code, in ANSI mode `SELECT * FROM (SELECT
CAST(l.id * 1000000000 AS INT) AS k FROM range(10) AS l JOIN range(3) AS r ON
l.id = r.id UNION ALL SELECT CAST(id AS INT) AS k FROM range(10)) WHERE
rand(10) * 10 > 100 AND k > 0` should return no row, since the first child
computes `k` only for ids 0 to 2. The Union case still pushes `k > 0` into both
children; in the first one the Project case pushes it through the projection as
`CAST(l.id * 1000000000 AS INT) > 0`, and PushPredicateThroughJoin moves it
into `l`, where the cast overflows on id 3. Over a Window partitioned by `k` on
the same join, the PR keeps `k > 0` above and that query returns no row. The
description's own example, `q > 0` over a child computing `10L / (id - 3)`, is
pushed the same way, although the description says the conjunct now stays
above. Passing the children's columns only at this call site would not cover a
nullable column, since InferFiltersFromConstraints also reads `failable
Output` of the union (Optimizer.scala:2377-2391).
See **Shared repair plan 1** in the review body.
##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/FilterPushdownSuite.scala:
##########
@@ -1096,6 +1096,65 @@ class FilterPushdownSuite extends PlanTest {
comparePlans(Optimize.execute(originalQuery.analyze),
correctAnswer.analyze)
}
+ // Built in ANSI mode, where it can fail, whatever the session's mode is.
+ private def ansiDivide(l: Expression, r: Expression): Expression =
+ Divide(l, r, NumericEvalContext(EvalMode.ANSI))
+
+ test("SPARK-62144: a condition that can fail is not pushed through an
aggregate ahead of a " +
Review Comment:
**Nit (P3):** These tests reach the new failable-column argument only
through the Aggregate case (`overFailableKey` at
FilterPushdownSuite.scala:1119-1123), and the barrier only through the
Aggregate, Union and Project-split cases. The Window (Optimizer.scala:2949),
EventTimeWatermark (2995), unary-node (3141) and Project (2864) cases also
gained the argument, but the SPARK-60633 tests that reach them
(FilterPushdownSuite.scala:939-1097) use `LocalRelation` children and write
only conditions that cannot fail after the barrier, so, as this review reads
them, replacing any of those arguments with an empty set would leave every test
green. No test has a cheap non-deterministic condition written after a
condition over an expensive alias, the shape whose placement the Project case
changes, and every new division is built in ANSI mode, so treating a
legacy-mode division as able to fail would not be caught either.
**Verification:**
- **Regression:** Each new per-case plan test fails when that case's
failable columns are replaced by an empty set, and passes with the case as
fixed.
- **Behavior:** The legacy-mode test shows a non-ANSI division written after
Rand(10) > 0.5 pushed below the operator, and the placement test expects the
placement that restoring the base branch's behavior for that condition gives.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2871,11 +2874,14 @@ object PushPredicateThroughNonJoin extends
Rule[LogicalPlan] with PredicateHelpe
// split orders conditions by cost, and cost is no way to decide how
many rows a
// non-deterministic expression sees. Throwable conditions, or
conditions over throwable
// aliases, stay there too: ordering by cost could evaluate them (or
compute the aliases
- // in a lower projection) ahead of the conditions written before them.
+ // in a lower projection) ahead of the conditions written before them.
So do the cheap
+ // conditions: one is only here to keep its order (see
`splitPushable`), and splitting it
+ // off would evaluate it ahead of the conditions written before it all
the same.
val (splitChild, splitAliases, stayUp) =
if (expensiveWithUsed.nonEmpty &&
SQLConf.get.splitProjectionForExpensiveFilters) {
val (splittable, notSplittable) = expensiveWithUsed.partition {
- case (cond, _, replaced) => cond.deterministic &&
!replaced.throwable
+ case (cond, used, replaced) =>
+ cond.deterministic && !replaced.throwable && !isCheap(used)
Review Comment:
**Blocking (P1):** This partition keeps only cheap conditions out of the
split, so an expensive condition that can fail, such as a comparison over a
Scala or Python UDF alias or an RLIKE whose pattern comes from the data, still
goes to `splitProjectForExpensiveConditions` when it is written after a
non-deterministic or throwable condition that stays above. The split orders by
cost and filters it in a lower layer (Optimizer.scala:3304-3327), below the top
filter that keeps that condition, although the new comments at
Optimizer.scala:2857-2859 and 2877-2879 and the `splitPushable` doc say a
condition that can fail written after it is not evaluated ahead of it.
By this review's reading of the code, with Scala UDFs `ok` and `parse`,
where `parse` throws on 'x', `spark.range(10).selectExpr("IF(id = 3, 'x',
CAST(id AS STRING)) AS e").select($"e", ok($"e") as "f", parse($"e") as
"g").where($"f" && rand(10) < 0.0 && $"g" > 0 && $"g" < 100)` returns no row on
the base branch, which pushes `rand(10) < 0.0` below every layer. With this PR,
`rand(10) < 0.0` stays in the top filter, and the split puts `Filter(g > 0 AND
g < 100)` over a projection computing `parse(e)` below it, so `parse` runs on
every row and the query fails on 'x'. With an expensive or throwable barrier,
such as `(Rand(10) > 0.5 || j)` in the SPARK-55014 test at
FilterPushdownSuite.scala:748, the base branch already filters such a condition
below it, and this PR leaves that unchanged. The unchanged tests at
FilterPushdownSuite.scala:748 and 799 expect an RLIKE over `concat(e, tag)`,
whose pattern comes from the data, in a layer below the barrier.
**Recommended change:** In the Project case, also keep out of the split
every kept-above condition written after the first non-deterministic or
throwable condition that stays above when it can fail, that is when
ExprUtils.canEvaluateUnconditionally rejects it with the aliases substituted or
it reads a column failableOutput(grandChild) reports, as the PR already does
for cheap conditions; those conditions stay in the top filter in written order.
Update the comment at Optimizer.scala:2872-2879 and the expected plans of
'SPARK-55014: a non-deterministic condition is not split off into a lower
layer' and 'SPARK-60602: a throwable condition does not keep later conditions
from being split off', and add projection-split plan tests and an end-to-end
UDF query test.
**Why this works:** The split then only receives conditions written before
the first non-deterministic or throwable condition that stays above, or after
it but unable to fail, so whatever layer it puts them in, no condition that can
fail is evaluated ahead of a condition written before it that stays above.
**Risks:** Every condition over an expensive alias written after a
non-deterministic or throwable condition stays in the top filter, since no UDF
or regex passes the never-fail check, so its alias runs on the rows that reach
the top filter rather than on fewer rows in a lower layer, including for UDFs
that never fail; two existing split tests change their expected plans.
Reverting the partition change rolls it back.
**Constraints:** Conditions written before the first non-deterministic or
throwable condition that stays above, and conditions after it that can not
fail, keep going to the split, and the top filter keeps its written order.
**Exclusions:**
- With whole-stage codegen off, a projection computes every alias for every
row it gets, so after an expensive or throwable barrier a query whose top
projection computes an alias that can fail still fails, as on the base branch;
the repair does not change how a projection computes a column.
**Verification:**
- **Regression:** Plan tests with an expensive non-deterministic condition,
and with a throwable condition, followed by an expensive condition over an
RLIKE whose pattern comes from the data keep that condition in the top filter
after the barrier, and the two existing split tests that expect it in a lower
layer are updated to match.
- **Regression:** With whole-stage codegen on, an end-to-end query over a
projection with two Scala UDF aliases f and g, written as (rand(10) < 0.0 OR f)
AND g > 0 AND g < 100, where g's UDF throws on a row on which f is false,
returns the rows the written condition keeps, where the base branch fails.
- **Behavior:** A plan test shows that expensive conditions written before a
barrier are still split into lower layers.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -3145,25 +3158,42 @@ object PushPredicateThroughNonJoin extends
Rule[LogicalPlan] with PredicateHelpe
/**
* Splits `conds`, the conjuncts of a filter in their written order, into
the ones to push below
* an operator and the ones to keep above it. `canPush` tells whether the
operator lets a
- * conjunct through, and `throwable` whether it may throw (e.g.
`raise_error`). Every conjunct
- * written before the first one that cannot be pushed is pushed. After it,
only the conjuncts
- * that are not throwable are pushed, so a throwable conjunct is not
evaluated on rows the
- * conjuncts before it would have filtered out. Moving a non-throwable
conjunct below a
- * throwable one is fine, as it can only reduce the rows the throwable one
sees. The conjuncts
- * to keep above are returned in the order they were written.
+ * conjunct through, `pushedForm` gives the conjunct as it is evaluated
below the operator (e.g.
+ * with the aliases of a projection substituted), and `failable` the columns
it can read that
+ * can fail to compute (see `failableOutput`). Every conjunct written before
the first one that
+ * cannot be pushed is pushed. After it, only the conjuncts that are not
throwable (e.g.
+ * `raise_error`) are pushed, so a throwable conjunct is not evaluated on
rows the conjuncts
+ * before it would have filtered out. Moving a non-throwable conjunct below
a throwable one is
+ * fine, as it can only reduce the rows the throwable one sees. Once a
non-deterministic or
+ * throwable conjunct stays above, only the conjuncts that can not fail are
pushed after it: a
+ * conjunct that [[ExprUtils.canEvaluateUnconditionally]] rejects, or that
reads a column in
+ * `failable`, would be evaluated on rows that conjunct may have filtered
out, e.g. an ANSI
+ * division written after `rand() < 0.1`. The conjuncts to keep above are
returned in the order
+ * they were written.
*/
private def splitPushable[T](conds: Seq[T])(
- canPush: T => Boolean, throwable: T => Boolean): (Seq[T], Seq[T]) = {
+ canPush: T => Boolean,
+ pushedForm: T => Expression,
+ failable: => AttributeSet): (Seq[T], Seq[T]) = {
val (leading, rest) = conds.span(canPush)
- // The head of `rest`, if any, is the first conjunct that cannot be pushed.
- val (pushedRest, stayUp) = rest.drop(1).partition(c => canPush(c) &&
!throwable(c))
- (leading ++ pushedRest, rest.take(1) ++ stayUp)
+ // The head of `rest`, if any, is the first conjunct that cannot be
pushed, so it stays above.
+ // So does the head of `ordered`, if any, as it is non-deterministic or
throwable.
+ val (reorderable, ordered) = rest.span { c =>
+ pushedForm(c).deterministic && !pushedForm(c).throwable
+ }
+ lazy val failableColumns = failable
+ val (pushedReorderable, stayUpReorderable) = reorderable.partition(canPush)
+ val (pushedOrdered, stayUpOrdered) = ordered.partition { c =>
+ canPush(c) && ExprUtils.canEvaluateUnconditionally(pushedForm(c)) &&
+ !pushedForm(c).references.exists(failableColumns.contains)
Review Comment:
**Non-blocking (P2):** This check only sees the columns `failableOutput`
reports for the plan directly below the operator, and `failableOutput`
(predicates.scala:267-291) reports nothing through a Window, Generate, Union,
EventTimeWatermark, Expand or repartition, nor an Aggregate's grouping keys. A
pushed conjunct lands in a filter of its own, where nothing written before it
stays above, so it can move on below the next operator.
By this review's reading of the code, in ANSI mode, with `l(id, b)` holding
a row with `b = 3` whose `id` `r` lacks, `SELECT * FROM (SELECT k, count(*) AS
c FROM (SELECT 10L / (l.b - 3) AS k FROM l JOIN r ON l.id = r.id) GROUP BY k)
WHERE rand(10) * 10 > 100 AND k > 0` should return no row. The Aggregate case
keeps `k > 0` above, but InferFiltersFromConstraints' Filter case
(Optimizer.scala:2377-2391) then adds `isnotnull(k)` ahead of the condition,
because a division is always nullable and `failableOutput` of the Aggregate
reports no grouping key. In the next batch that leading conjunct is pushed
below the aggregate, through the projection as `isnotnull(10L / (l.b - 3))`,
and into `l`, where it divides by zero on the unmatched row, as `k > 0` itself
did on the base branch. A Window partitioned by `k`, a Generate or a watermark
takes the same path. Over a Sort or a repartition above a Window partitioned by
`k`, the unary case gets an empty set and pushes `k > 0` itself below the b
arrier, even when `k` is not nullable.
No new test reaches either path: the optimizer batch in FilterPushdownSuite
runs no InferFiltersFromConstraints, and the DataFrameSuite test only uses
conditions that divide themselves.
See **Shared repair plan 1** in the review body.
--
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]