spark-test commented on code in PR #60765:
URL: https://github.com/apache/spark/pull/60765#discussion_r4650670498
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2994,7 +2994,7 @@ object PushPredicateThroughNonJoin extends
Rule[LogicalPlan] with PredicateHelpe
case filter @ Filter(_, u: UnaryNode)
if canPushThrough(u) && u.expressions.forall(_.deterministic) =>
- pushDownPredicate(filter, u.child, keepThrowableUp = canDropRows(u)) {
predicate =>
+ pushDownPredicate(filter, u.child, keepFailableUp = canDropRows(u)) {
predicate =>
Review Comment:
**Non-blocking (P2):** `canDropRows(u)` is true for every `Generate` without
outer, and with this PR that keeps every conjunct the check rejects above the
operator, not only throwable ones. Several generators never output zero rows
for an input row: `json_tuple` returns exactly one row on every path
(JsonExpressionEvalUtils.scala:495-506, and the comment 'A row is always
returned' at jsonExpressions.scala:277-279), `stack(n, ...)` returns n rows
with n of at least 1, checked at analysis (generators.scala:207-212), and
`explode`, `posexplode` or `inline` of a non-empty `array(...)` constructor
returns a row per element. Below them a conjunct over the input columns sees
exactly the rows it sees above, so keeping it above prevents no failure, yet
`SELECT e.p, j.a FROM events e LATERAL VIEW json_tuple(e.payload, 'a') j AS a
WHERE upper(e.p) = 'X'`, with `p` a partition column, no longer prunes
partitions and parses the JSON of every row. The same holds for an ANSI cast in
the WHERE cl
ause, and over `stack` or `explode(array(a, b))`.
The `ReplicateRows` generate that EXCEPT ALL and INTERSECT ALL are rewritten
to is different: it never drops rows either, but a conjunct pushed below it
would be merged after the set operation's count filter by `CombineFilters`
(Optimizer.scala:2629-2634) and then pushed below the aggregate, whose
written-order check stops only throwable conjuncts (Optimizer.scala:3077), so
it has to keep the restriction.
**Recommended change:** Make canDropRows (Optimizer.scala:3027-3031) return
false for a generator without OUTER that always outputs at least one row for
each input row: json_tuple, stack, and explode, posexplode or inline of an
array(...) constructor with at least one element or of a non-empty array
literal. Keep it true for the ReplicateRows generator that the EXCEPT ALL and
INTERSECT ALL rewrites build, and say in its doc why: that generator never
drops rows either, but a condition pushed below it would be merged after the
filter under it that removes the rows the set operation drops, and then moved
below the aggregate. Add filter pushdown optimizer tests in which a conjunct
the check rejects, such as upper of a column or an ANSI cast, is pushed below
json_tuple, stack and explode of a two-element array constructor, while it
still stays above explode of an array column and above the generator of a
rewritten EXCEPT ALL.
**Why this works:** Below a generator that outputs at least one row for
every input row, a condition over the input columns sees exactly the input rows
it sees above it, so it cannot fail there on a row the written query never
gives it, and pushing it below the generator is safe whether or not the check
accepts it, as the base branch did for every condition that is not throwable.
**Compatibility:** The three queries in the PR description still succeed,
and every conjunct the check rejects, apart from a dynamic pruning or runtime
filter whose key cannot fail, still stays above explode of an array column, a
UDTF, a TRANSFORM script and the generator of EXCEPT ALL and INTERSECT ALL.
**Risks:** A throwable condition over these generators, which the base
branch kept above them, is pushed below them again; it sees the same rows
there, so no new failure follows, but the plan differs from the base branch for
such a condition. A condition that can fail and is pushed below one of these
generators again is then moved on by the other pushdown rules as on the base
branch: when the generator reads a grouped subquery with a HAVING filter, the
condition is merged after that filter and pushed below the aggregate, whose
written-order check stops only throwable conditions, so it can fail on the
groups the HAVING filter drops, as on the base branch, while this PR keeps it
above the generator.
**Constraints:** Only generators whose contract guarantees a row for every
input row are matched; explode of an array column, of a map or of an array
built by another expression, and every UDTF, keep the restriction.
**Exclusions:**
- A declaration on each generator of whether it can output no row for an
input row.
- The ReplicateRows generator of EXCEPT ALL and INTERSECT ALL, which never
drops rows either but always sits on the filter that removes the rows the set
operation drops: below it, a condition that can fail would be merged after that
filter and pushed below the aggregate onto those rows, so it keeps the
restriction.
**Verification:**
- **Regression:** In the optimized plan, upper of a column compared with a
literal and an ANSI cast comparison are pushed below json_tuple, stack and
explode of a two-element array constructor, and stay above explode of an array
column and above the generator of a rewritten EXCEPT ALL.
- **Regression:** With ANSI mode on, a filter that casts a string column to
INT above t1 EXCEPT ALL t2, where only t2 holds a value that does not cast,
still returns its rows instead of failing with CAST_INVALID_INPUT.
- **Behavior:** A query that filters upper of a string partition column
above a LATERAL VIEW json_tuple over a partitioned table prunes the scan to the
matching partitions and returns the rows of those partitions.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -3115,14 +3115,16 @@ object PushPredicateThroughNonJoin extends
Rule[LogicalPlan] with PredicateHelpe
private def pushDownPredicate(
filter: Filter,
grandchild: LogicalPlan,
- keepThrowableUp: Boolean)(insertFilter: Expression => LogicalPlan):
LogicalPlan = {
+ keepFailableUp: Boolean)(insertFilter: Expression => LogicalPlan):
LogicalPlan = {
// Only push down the predicates that is deterministic and all the
referenced attributes
- // come from grandchild. With `keepThrowableUp`, a throwable predicate is
not pushed even when
- // it is written first, as the operator in between can drop rows it would
then see.
+ // come from grandchild. With `keepFailableUp`, a predicate that can fail,
i.e. one that
+ // `ExprUtils.canEvaluateUnconditionally` rejects such as a throwable one
or an ANSI division,
+ // is not pushed even when it is written first, as the operator in between
can drop rows it
+ // would then see.
// TODO: non-deterministic predicates could be pushed through some
operators that do not change
// the rows.
val (pushDown, stayUp) = splitPushableConjuncts(filter.condition) { cond =>
- cond.deterministic && !(keepThrowableUp && cond.throwable) &&
+ cond.deterministic && (!keepFailableUp ||
ExprUtils.canEvaluateUnconditionally(cond)) &&
Review Comment:
**Blocking (P1):** In ANSI mode, a query that succeeds on the base branch
now fails when a guard in its WHERE clause stops running ahead of something
that raises on the rows the guard removes. On the base branch, a deterministic,
non-throwable conjunct over the Generate's input was pushed below the Generate,
and from there through the projections below it, so it removed rows before the
generator, its input or a select list below it ran. With `!keepFailableUp ||
ExprUtils.canEvaluateUnconditionally(cond)`, every conjunct the check rejects
now stays above, including ones that cannot fail: `Upper`, `Lower` and `RLike`
do not declare `isTotal`, and every subquery is rejected.
Reading the code, `SELECT id, x FROM range(0, 10, 1, 1) LATERAL VIEW
explode(if(id = 5, array(), array(10L / (id - 3)))) t AS x WHERE upper(CAST(id
AS STRING)) = '4'` returns `(4, 10.0)` on the base branch, where the filter is
pushed below the generate and removes id 3, and fails with `DIVIDE_BY_ZERO`
with this PR, because the generator now evaluates `10L / 0` for id 3. A more
typical shape is a validating guard such as `WHERE s RLIKE
'^[0-9]+(,[0-9]+)*$'` over `LATERAL VIEW explode(transform(split(s, ','), v ->
CAST(v AS INT)))`, which now hits `CAST_INVALID_INPUT`. The same applies to a
cast in the select list of a subquery or view under the LATERAL VIEW, and to a
filter over EXCEPT ALL or INTERSECT ALL, which are rewritten to such a
generate. These queries also succeed on v4.3.0, and no conf restores the old
plan. The PR description says these conditions are no longer pushed, but not
that such queries start to fail.
**Recommended change:** Add an entry to the SQL migration guide
(docs/sql-migration-guide.md) in the section of the release that first ships
the change: the section for upgrading from Spark SQL 4.3 to 4.4, beside the
entries for inferred filters and filter short-circuiting, if the change is also
merged to branch-4.4 as those fixes were, and otherwise the section for
upgrading from Spark SQL 4.4 to 5.0. The entry states that a filter condition,
or a LEFT SEMI or LEFT ANTI JOIN condition, that can fail, or that the
optimizer cannot show cannot fail, such as upper(s) = 'X', s RLIKE '^[0-9]+$'
or an IN subquery, is no longer evaluated below a generator without OUTER that
can output no row for an input row, such as explode of an array column or a
UDTF, or below a TRANSFORM script, and that a filter with such a condition over
EXCEPT ALL or INTERSECT ALL no longer reaches their inputs. It says that such a
condition therefore no longer reaches partition pruning or data source pushdown
the
re and no longer removes rows before the operator and the plan below it run,
so a query that fails on such a row, for example on a cast that the condition
was guarding in ANSI mode in the generator's input, in the select list of a
subquery below the LATERAL VIEW or in an input of the set operation, now fails;
it gives an example and the rewrite that keeps such a guard ahead of what it
guards, filtering in a subquery below the LATERAL VIEW or in each input of the
set operation. The PR description states the same change and names the
alternative that avoids most of it, also pushing a non-failing relaxed copy of
the condition below the operator, with the reason the PR does not adopt it.
**Why this works:** Stating the change in the migration guide and in the PR
description, with the alternative and the reason it is not adopted, is how the
author accepts a regression that directly follows the intended behavior, and
the documented rewrite gives affected users a way to keep their guard ahead of
the generator without any setting.
**Compatibility:** The fix stays as it is: a condition that can fail still
stays above a generator without OUTER that can output no row for an input row,
above the generator of EXCEPT ALL and INTERSECT ALL, and above a TRANSFORM
script, so the three queries in the PR description still succeed.
**Risks:** The entry only makes the change visible: a query that relied on
such a guard still fails after an upgrade until it is rewritten, and no setting
restores the old plan unless a legacy conf is also added. If a relaxed copy is
adopted, the entry has to narrow to the conditions the copy cannot cover, those
with a subquery or a Python or external UDF.
**Constraints:** The entry follows the neighboring entries for inferred
filters and filter short-circuiting (docs/sql-migration-guide.md:88-89), names
the release that first ships the change, and covers the semi and anti join
conditions that the semi and anti join repair keeps above the same operators.
It describes only the generators that still keep conditions above after
json_tuple, stack and array constructors are treated as generators that always
output a row, and if a legacy conf is added for the rollback question, it names
that conf as the way to restore the previous behavior.
**Exclusions:**
- Pushing a relaxed copy of the kept-above conditions below the operator,
and adding a legacy conf, which remain open author decisions.
**Verification:**
- **Inspection:** The migration-guide entry is in the section of the release
that first ships the change and names the affected operators, EXCEPT ALL and
INTERSECT ALL included, the kinds of conditions affected, the new failure,
whether the generator, its input or an expression below it raises, with an
example query in ANSI mode, and the rewrite that filters in a subquery below
the LATERAL VIEW.
- **Behavior:** With ANSI mode on and whole-stage codegen on and off, the
documented example fails with the documented error, and its documented rewrite,
with the guard in a subquery below the LATERAL VIEW, returns the guarded rows.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -3115,14 +3115,16 @@ object PushPredicateThroughNonJoin extends
Rule[LogicalPlan] with PredicateHelpe
private def pushDownPredicate(
filter: Filter,
grandchild: LogicalPlan,
- keepThrowableUp: Boolean)(insertFilter: Expression => LogicalPlan):
LogicalPlan = {
+ keepFailableUp: Boolean)(insertFilter: Expression => LogicalPlan):
LogicalPlan = {
// Only push down the predicates that is deterministic and all the
referenced attributes
- // come from grandchild. With `keepThrowableUp`, a throwable predicate is
not pushed even when
- // it is written first, as the operator in between can drop rows it would
then see.
+ // come from grandchild. With `keepFailableUp`, a predicate that can fail,
i.e. one that
+ // `ExprUtils.canEvaluateUnconditionally` rejects such as a throwable one
or an ANSI division,
+ // is not pushed even when it is written first, as the operator in between
can drop rows it
+ // would then see.
// TODO: non-deterministic predicates could be pushed through some
operators that do not change
// the rows.
val (pushDown, stayUp) = splitPushableConjuncts(filter.condition) { cond =>
- cond.deterministic && !(keepThrowableUp && cond.throwable) &&
+ cond.deterministic && (!keepFailableUp ||
ExprUtils.canEvaluateUnconditionally(cond)) &&
Review Comment:
**Non-blocking (P2):** `ExprUtils.canEvaluateUnconditionally` rejects every
expression with a subquery (ExprUtils.scala:296-298), so with `keepFailableUp`
it also stops the optimizer's own runtime filters above a `Generate` without
outer: the `DynamicPruningSubquery` that `PartitionPruning` adds after
following the join key through the generate, and the `BloomFilterMightContain`
and `PerPartitionRuntimeFilterSubquery` filters that `InjectRuntimeFilter`
adds. For `SELECT g.id, g.i FROM (SELECT id, part, i FROM fact LATERAL VIEW
explode(items) t AS i) g JOIN dim d ON g.part = d.k WHERE d.name = 'x'` over a
`fact` table partitioned by `part`, the DPP filter now stays above the
generate, `CleanupDynamicPruningFilters` replaces it with `true` because it is
not over a scan (CleanupDynamicPruningFilters.scala:107-113), and
`InjectRuntimeFilter` had already skipped a bloom filter for that key because
of the DPP filter (InjectRuntimeFilter.scala:699-701, 719-721), so the scan
reads every p
artition. Results stay correct, but the base branch pushed these filters to
the scan, as none of them is throwable. They exist only to reach the scan and
can fail on a dropped row only through their key: a DPP filter is planned as a
partition filter or dropped, and a bloom filter's subquery runs once wherever
the filter sits.
Consider letting a `DynamicPruningSubquery`, a `BloomFilterMightContain`
over an uncorrelated scalar subquery, or a `PerPartitionRuntimeFilterSubquery`
conjunct through these operators when its key passes
`ExprUtils.canEvaluateUnconditionally`, as the base branch did, and keeping
every other conjunct under the new check, with optimizer and dynamic partition
pruning tests over an explode.
**Verification:**
- **Regression:** A query joining a dimension table, with a selective filter
on it, to a subquery that explodes an array of a partitioned fact table prunes
the fact scan through dynamic partition pruning, and returns the same rows as
the same query with dynamic partition pruning off.
- **Behavior:** In the optimized plan, a filter of a dynamic pruning
subquery, and one of a bloom-filter predicate, above a generator without OUTER
is pushed below the generator when its key is a column and stays above it when
its key is an ANSI cast that can fail.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -3115,14 +3115,16 @@ object PushPredicateThroughNonJoin extends
Rule[LogicalPlan] with PredicateHelpe
private def pushDownPredicate(
filter: Filter,
grandchild: LogicalPlan,
- keepThrowableUp: Boolean)(insertFilter: Expression => LogicalPlan):
LogicalPlan = {
+ keepFailableUp: Boolean)(insertFilter: Expression => LogicalPlan):
LogicalPlan = {
// Only push down the predicates that is deterministic and all the
referenced attributes
- // come from grandchild. With `keepThrowableUp`, a throwable predicate is
not pushed even when
- // it is written first, as the operator in between can drop rows it would
then see.
+ // come from grandchild. With `keepFailableUp`, a predicate that can fail,
i.e. one that
Review Comment:
**Nit (P3):** The `i.e.` equates a predicate that can fail with one that
`ExprUtils.canEvaluateUnconditionally` rejects, but the helper is conservative:
its documentation says that anything outside the trees it accepts
'conservatively returns false' (ExprUtils.scala:289). It also rejects conjuncts
that cannot fail, such as `upper(s) = 'X'` (`Upper` does not declare
`isTotal`), a CASE WHEN, any subquery predicate, or a cast of a DOUBLE to a
STRING, which its documentation says can not fail (ExprUtils.scala:286-288).
The PR description accepts keeping those above these operators as the cost of
the conservative check, but a reader of the rule cannot tell that from the
code. Consider saying that the check is conservative and also keeps some
conjuncts that cannot fail above, such as `upper(s) = 'X'` or a subquery
predicate, and adding a TODO that a more precise check is deferred.
**Verification:**
- **Inspection:** The comment at the check in pushDownPredicate says that
ExprUtils.canEvaluateUnconditionally is conservative, gives an example of a
conjunct that cannot fail but stays above, carries a TODO for a more precise
check, and matches the check and any exemption next to it.
##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/FilterPushdownSuite.scala:
##########
@@ -1001,6 +1001,24 @@ class FilterPushdownSuite extends PlanTest {
comparePlans(Optimize.execute(outerQuery), outerAnswer)
}
+ test("SPARK-62143: a condition that can fail is not pushed through a
generate that can drop " +
Review Comment:
**Nit (P3):** This test and the new DataFrameSuite test both cover a
non-outer `Explode`. Nothing covers the `ScriptTransformation` case of
`canDropRows` (Optimizer.scala:3029) that Issue 3 in the PR description depends
on: FilterPushdownSuite builds no `ScriptTransformation`, and the
script-transformation suites and `transform.sql` filter only below the script
or on its output, which cannot be pushed. Removing that case, or passing
`keepFailableUp = false` for a script, would let Issue 3 fail again with
`DIVIDE_BY_ZERO` without failing any test. A script's output replaces its
input, so only a conjunct that reads no column can be pushed below it; consider
a case here with such a conjunct that can fail, for example an ANSI `Divide` of
literals with a zero divisor, or a comparison with a scalar subquery, above a
`ScriptTransformation` node, asserting that it stays above.
**Verification:**
- **Regression:** Above a ScriptTransformation, a conjunct that reads no
column and can fail in ANSI mode stays above the script in the optimized plan,
and the test fails when ScriptTransformation is no longer treated as an
operator that can drop rows.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2994,7 +2994,7 @@ object PushPredicateThroughNonJoin extends
Rule[LogicalPlan] with PredicateHelpe
case filter @ Filter(_, u: UnaryNode)
if canPushThrough(u) && u.expressions.forall(_.deterministic) =>
- pushDownPredicate(filter, u.child, keepThrowableUp = canDropRows(u)) {
predicate =>
+ pushDownPredicate(filter, u.child, keepFailableUp = canDropRows(u)) {
predicate =>
Review Comment:
**Non-blocking (P2):** This gates only `PushPredicateThroughNonJoin`. The
unary-node case of `PushDownLeftSemiAntiJoin`
(PushDownLeftSemiAntiJoin.scala:106-110) still moves a LEFT SEMI or LEFT ANTI
join below any operator that `canPushThrough` accepts, a `Generate` without
outer and a `ScriptTransformation` included, with every ON conjunct that reads
the operator's input and the right side, and checks neither `canDropRows` nor
whether the conjunct can fail. Reading the code, in ANSI mode `SELECT * FROM
(SELECT id, explode(if(id = 3, array(), array(1))) x FROM range(0, 10, 1, 1)) t
LEFT SEMI JOIN range(1, 2) r ON 10L / (t.id - 3) > r.id` should return the rows
for id 4 to 9, but the join is moved below the Project and then below the
generate, evaluates `10L / 0` for id 3, which the explode drops, and fails with
`DIVIDE_BY_ZERO`, while the same condition in a WHERE clause over the same
subquery succeeds with this PR. A LEFT ANTI JOIN, or an equi-join key such as
`r.id = 10 / (t.id -
3)`, is pushed the same way.
**Recommended change:** In the unary-node case of PushDownLeftSemiAntiJoin
(PushDownLeftSemiAntiJoin.scala:106-110), when
PushPredicateThroughNonJoin.canDropRows holds for the operator, count an ON
conjunct as pushable only if ExprUtils.canEvaluateUnconditionally also accepts
it, through one helper that both rules call, with canDropRows made visible in
the optimizer package. A rejected conjunct then keeps the join above the
operator when it reads the right side, and otherwise stays in the filter that
pushDownJoin already keeps above a semi join. Add semi and anti join pushdown
optimizer tests over an explode with an ON conjunct that can fail and one that
cannot, and an end-to-end ANSI test of the LEFT SEMI JOIN example.
**Why this works:** Making the join rule take the same decision as the
filter rule keeps an ON condition that can fail off the rows the operator
drops, so the join evaluates it only on rows the written query gives it.
**Risks:** A semi or anti join whose ON condition the conservative check
rejects although it cannot fail, such as upper(t.s) = r.s, is no longer pushed
below an explode or a script, so the join runs on the exploded rows, and it no
longer removes rows before the generator runs, so a query whose generator fails
on rows such a join would remove now fails, as for filters; a legacy conf added
for the filter rule should restore both. Over the generator of EXCEPT ALL and
INTERSECT ALL, which keeps the restriction, a semi or anti join with such a
condition, or with one that can fail, is kept above that generator too,
although the join could not move past the filter under it anyway, so the join
runs on the replicated rows.
**Constraints:** Both rules use the same canDropRows, so the treatment of
generators that always output a row applies to semi and anti joins too.
**Exclusions:**
- Making the can-fail check more precise, which the PR defers for both rules.
**Verification:**
- **Regression:** In ANSI mode, with whole-stage codegen on and off, a LEFT
SEMI JOIN and a LEFT ANTI JOIN of a subquery that explodes if(id = 3, array(),
array(1)) over range(0, 10) with an ON condition that divides by id - 3 return
their expected rows instead of failing with DIVIDE_BY_ZERO.
- **Compatibility:** In the optimized plan, a semi join whose ON conjuncts
compare columns is still pushed below an explode, as the existing
partial-pushdown case expects, while a semi join with an ANSI division in its
ON condition stays above it.
--
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]