Repository navigation
[SPARK-62191][SQL] Fix query failures by the projection split for expensive filters when a condition follows a non-deterministic or throwable one - #60772
Conversation
spark-test
left a comment
There was a problem hiding this comment.
Review summary
The change stops the projection split at the first non-deterministic or throwable condition, which fixes the PR's example, but two routes in the same Filter-over-Project case still evaluate a condition that can fail ahead of that condition. On the pass after the split, a later condition whose aliases the split computed in a lower layer reads only plain attributes, so the cheap pushdown moves it below the projection; this keeps the PR's own query failing once a condition over the same alias is written before the non-deterministic or throwable one, and makes some queries that succeed on the base branch fail. On the first pass, a later condition that can fail but reads no expensive alias, such as cast(e as int) > 0, is pushed the same way, as on the base branch. Both come from splitPushable holding back only throwable conjuncts, so they share one fix. These conclusions come from reading the code and replaying the rule in a model; neither was run in Spark. A question for the author follows under Decision challenges.
Cross-cutting observations
-
The layered split that the decision challenge listed below proposes would put every later condition above the layer that filters on the non-deterministic or throwable condition, so adopting it would not bring back the pushdown failure in the finding listed below, and fixing that failure does not limit how the later conditions are computed.
The pushdown fix and the answer to the decision challenge can land separately and in either order.
Related:
- Next rule pass pushes a later condition that can fail ahead of a non-deterministic or throwable one
- Conditions after a non-deterministic or throwable condition are never split, even among themselves
Findings
2 total: 0 P0, 1 P1, 1 P2, 0 P3.
Blocking (P1)
- Next rule pass pushes a later condition that can fail ahead of a non-deterministic or throwable one —
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:2880— see inline.
Non-blocking (P2)
- Cheap pushdown still moves a condition that can fail ahead of a non-deterministic or throwable one —
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:2875— see inline.
Shared repair plans
Shared repair plan 1
Covered findings:
- Cheap pushdown still moves a condition that can fail ahead of a non-deterministic or throwable one —
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:2875 - Next rule pass pushes a later condition that can fail ahead of a non-deterministic or throwable one —
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:2880
Recommended change: In sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala, give splitPushable (lines 3148-3164) an optional second check, and have the Filter-over-Project case at lines 2858-2861 supply the test splitMovable applies, over the alias-substituted conjunct and the projection's child: ExprUtils.canEvaluateUnconditionally accepts the conjunct and it reads no column that failableOutput marks as able to fail. Once a non-deterministic or throwable conjunct has stayed above, splitPushable pushes a later conjunct only when it passes that check as well as today's test, and before that it keeps today's decision. The Window, Union, EventTimeWatermark, aggregate and generic unary pushdowns at lines 2944, 2958, 2988, 3082 and 3131 supply no check and keep today's decisions. Rewrite the Filter-over-Project comment at lines 2869-2877, the projection split's docstring at lines 3212-3216 and splitPushable's docstring at lines 3148-3157, which says moving a non-throwable conjunct below a throwable one is fine, so that they state the rule for every conjunct that can fail in a filter over a projection. Add optimizer filter pushdown plan tests and end-to-end DataFrame filter tests for the cases the verification names.
Why this works: After the first non-deterministic or throwable conjunct stays above the projection, every later conjunct that moves below it has passed the same can-not-fail test that splitMovable uses, so none of them can raise an error on a row that conjunct drops. The test runs on every application of the rule, so a condition whose aliases the projection split computed in a lower layer is held back on the next application too, and it runs whether or not the conjunct reads an expensive alias.
Compatibility: Filters with no non-deterministic or throwable conjunct that stays above a projection, every conjunct written before the first such one, filters over every operator other than a projection, and the projection split itself get the same plans as before.
Risks: A conjunct that ExprUtils.canEvaluateUnconditionally rejects although it cannot fail, for example one with IF, CASE WHEN, most string functions or a UDF, or one that reads a column computed below by such an expression, is no longer pushed below a projection, nor on toward the data source, when it is written after a non-deterministic or throwable conjunct that stays above, so such filters can read and process more rows; only a revert restores the old plans, as for the throwable restriction splitPushable already has. In a streaming query whose filter over a projection has such a conjunct after a non-deterministic or throwable one, with an event-time watermark below the projection, the conjunct now stays above the projection instead of moving on below the watermark, so rows it drops still advance the watermark, which can change which late rows the query drops after it restarts on the new version.
Constraints: Keep pushing every conjunct written before the first non-deterministic or throwable one that stays above exactly as today, including the leading pushable conjuncts. Keep pushing a later conjunct that ExprUtils.canEvaluateUnconditionally accepts and that reads no column that can fail, such as a comparison over a plain column after a throwable conjunct, which the existing tests of cheap conditions after a throwable one expect. Keep the projection split's span at Optimizer.scala:2880 and the written order of the conjuncts left above the projection. Keep the decisions of splitPushable's other callers, the Window, Union, EventTimeWatermark, aggregate and generic unary pushdowns, as they are.
Exclusions:
- Splitting the conditions written after the first non-deterministic or throwable condition among themselves, which the decision challenge about the lost split leaves to the author.
- The description's Issue 2 with whole-stage codegen off, where the interpreted top projection computes every alias before the filter, which the PR leaves as it is without the split.
- The Window, Union, EventTimeWatermark, aggregate and generic unary pushdowns, which also move a conjunct that can fail below their operator ahead of a non-deterministic or throwable one, as they do on the base branch; this PR does not change them, so this repair leaves them as they are.
Verification:
- Regression: Under ANSI mode, a DataFrame query that projects a Scala UDF alias and filters on a non-deterministic condition over that alias followed by a cast of a string column to int that reads no UDF alias, where the cast fails only on a row the first condition drops, returns the rows the written order returns with whole-stage codegen on and off, and its optimized plan keeps the cast condition in the filter above the projection, after the non-deterministic one.
- Regression: The PR's new end-to-end query with n > 0 written first, a condition over the same UDF alias as the cast condition, returns its 9 rows under ANSI mode with whole-stage codegen on and off, and its optimized plan keeps the cast condition in the top filter, after the non-deterministic one; the same holds when the earlier condition reads an alias that shares its expensive work with the alias the cast condition reads.
- Regression: A query whose filter has a condition over two UDF aliases, then a non-deterministic condition over a third, then a condition over the third that keeps every row, then a cast condition over the first two that fails only on a row the non-deterministic condition drops, returns the rows it returns on the base branch under ANSI mode with whole-stage codegen on and off.
- Compatibility: A conjunct that ExprUtils.canEvaluateUnconditionally accepts and that reads no column that can fail, such as a comparison over a plain integer column, is still pushed below the projection after a throwable or non-deterministic conjunct that stays above, as the existing tests of cheap conditions after a throwable one expect, and filters without a non-deterministic or throwable conjunct keep their plans, including the projection split's existing plan tests.
- Inspection: Only the Filter-over-Project case supplies the new check to splitPushable, so the Window, Union, EventTimeWatermark, aggregate and generic unary pushdowns decide as before.
- Inspection: The comment in the Filter-over-Project case, the projection split's docstring and splitPushable's docstring state that no conjunct that can fail moves below a projection ahead of a non-deterministic or throwable conjunct written before it, and none still says that moving any non-throwable conjunct below a throwable one is fine.
PR description suggestions
- In the user-facing change section, mention that in master a throwable condition that only raises, such as
g OR raise_error(...), now also runs on the rows that an expensive condition written after it would have dropped first, so a query can now raise where master did not, as it already does with the split turned off.
Decision challenges
Conditions after a non-deterministic or throwable condition are never split, even among themselves
Location: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:2880
Filters that put two or more conditions over different expensive aliases after a non-deterministic or throwable condition now compute all of their aliases in the top projection with no split among them, so on interpreted projections (whole-stage codegen off, or a stage that falls back) and for Python UDF aliases every later alias runs on every row that reaches the projection, and under codegen the later conditions run in written order rather than cost order.
The review leans toward keeping this implementation and recording the deferred work in a TODO, because extra work that only a redesign removes is an accepted cost of restoring correct results once the author defers that redesign, and keeping the PR small is reason enough.
What each side does, in the review's model of the plans: for (rand(10) > 0.5 OR j) AND f AND g over UDF aliases f, g and j, whose first conjunct is the non-deterministic barrier and where f keeps 10% of rows, the base branch stacks layers for f and g below the projection of j, so g runs on 10% of rows, but f and g run ahead of the barrier, which is the failure this PR fixes. With this PR one projection computes f, g and j under a single filter, so with codegen off or for Python UDFs g runs on every row. Under codegen, for barrier AND s1(D, E) AND s2(D) where s2 keeps 5% of rows and the barrier 99%, E runs on 5% of rows on the base branch and on 99% with this PR. The split is in no release, and v4.3.0 computes these aliases as this PR does. Keeping the later conditions behind the barrier is the accepted cost of the fix; the question is only the work beyond it. A cheaper implementation returns the same rows: put the barrier, with any earlier condition left unplaced, in a Filter/Project layer of its own, and split the later conditions by cost in layers stacked above it, so the first example computes g only on rows the barrier and f kept, and the second computes E on about 5% of rows. Its trade-off is a second split pass and the added complexity in the rule. How often filters take this shape, and what it costs them, has not been measured.
What settles it is your choice:
- Keep the implementation and accept the cost:
(rand(10) > 0.5 OR j) AND f AND gkeeps one projection computingf,gandj, and nothing changes. - Keep the implementation and defer the stacked split with a TODO at the
spancall (Optimizer.scala:2880) that names it: the plan for the example stays the same. - Implement the stacked split: run
splitProjectForExpensiveConditionsagain over the conditions after the barrier, above a Filter/Project layer that computes the barrier's aliases and filters on it, keeping aliases that share expensive work in one layer; the example then computesgonly on rows the barrier andfkept.
Generated by Omnigent on Databricks
| val (splitChild, splitAliases, stayUp) = | ||
| if (expensiveWithUsed.nonEmpty && SQLConf.get.splitProjectionForExpensiveFilters) { | ||
| val (splittable, notSplittable) = expensiveWithUsed.partition { | ||
| val (splittable, notSplittable) = expensiveWithUsed.span { |
There was a problem hiding this comment.
Blocking (P1): span keeps the conditions written after the first non-deterministic or throwable condition, the barrier, out of the split only on the pass that performs the split. The split turns every alias it computes in a lower layer into a plain attribute of the top projection (Optimizer.scala:2901), and PushDownPredicates runs again in the fixed-point Operator Optimization batch. On that next pass a later condition that reads only those attributes uses no expensive alias, so isCheap holds (Optimizer.scala:2852), and splitPushable (Optimizer.scala:3158-3164), which holds back only throwable conjuncts once one has stayed above, pushes it below the projection, ahead of the barrier, which is still above it; CombineFilters then merges it after the earlier condition.
This needs a condition written before the barrier whose aliases, or aliases sharing their expensive work, the split computes below; a barrier that still reads an alias left in the top projection; and a later condition that can fail without being marked throwable, such as an ANSI cast or arithmetic, or a UDF applied in the condition. The review's reading of the code, replayed in a model of the rule but not run in Spark, gives two consequences:
-
The PR's own DataFrameSuite query with
$"n" > 0 &&prepended still fails with CAST_INVALID_INPUT, as it does on the base branch:n > 0is split off, and on the next passcast(e as int) + n > 0is pushed under the barrier. -
Some queries that succeed on the base branch now fail. Under ANSI mode, over the PR's test data, with
notXas in the PR's test andlen1,len2two UDFs returninge.length:.select($"e", notX($"e") as "f", len1($"e") as "a", len2($"e") as "b") .where($"a" + $"b" > 0 && (rand(10) * 10 > 100 || $"f") && $"f".cast("string") =!= "" && $"e".cast("int") + $"a" + $"b" > 0)
On the base branch the split places the cheaper group over
ffirst and leavesa + b > 0and the cast in the top filter after the barrier, so the query returns 9 rows, as it does withspark.sql.optimizer.splitProjectionForExpensiveFiltersoff. With this PR onlya + b > 0reaches the split, which places it becausefis still to compute; the next pass then pushes the cast under the barrier, where it casts'x', with whole-stage codegen on and off.
The new comment (Optimizer.scala:2874-2877) and docstring (Optimizer.scala:3214-3216) hold only for the pass that performs the split, and no test has a condition before the barrier that reads the same aliases as a later condition that can fail.
See Shared repair plan 1 in the review body.
There was a problem hiding this comment.
Thank you. I confirmed both consequences in Spark, in ANSI mode with whole-stage codegen on and off:
- The e2e query with
$"n" > 0 &&written first fails withCAST_INVALID_INPUTonmasterand with this PR. - Your second query returns 9 rows on
master, but fails withCAST_INVALID_INPUTwith this PR.
In both, the split computes n, or a and b, in a lower layer, and the next pass of PushPredicateThroughNonJoin pushes the cast below the projection as a cheap conjunct, ahead of the non-deterministic one. Holding such a conjunct back is the splitPushable change of #60766 (SPARK-62144): once a non-deterministic or throwable conjunct stays above, a later conjunct is pushed only when ExprUtils.canEvaluateUnconditionally accepts it and it reads no column that failableOutput reports, such as a UDF column of the lower layer. With #60766 and this PR together, both queries return 9 rows.
So I'll rebase this PR onto #60766 after it is merged, and add both queries to the tests.
There was a problem hiding this comment.
Update: I fixed it in this PR instead of waiting for #60766. The split now leaves at least one expensive alias of each condition written after the non-deterministic or throwable one to the top projection, so the next pass still sees that condition as expensive and keeps it above. Both of your queries now return 9 rows in ANSI mode with whole-stage codegen on and off, with or without #60766. I added the first one to the DataFrameSuite test, and a plan test for the split.
| // 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 all the | ||
| // conditions written after the first of these: each reads an expensive alias, e.g. a UDF |
There was a problem hiding this comment.
Non-blocking (P2): The new code comment scopes the rule to conditions that read an expensive alias, but a condition that can fail and reads none takes the cheap path instead: splitPushable (Optimizer.scala:3158-3164), called from this case at Optimizer.scala:2858-2861, pushes below the projection every cheap conjunct written after the first one that stays above unless it is marked throwable, even when that one is non-deterministic or throwable, and Cast, ANSI arithmetic and ScalaUDF keep Expression.throwable's default (Expression.scala:169). By the review's reading of the code, the PR's DataFrameSuite query without the n term,
.select($"e", notX($"e") as "f")
.where((rand(10) * 10 > 100 || $"f") && $"e".cast("int") > 0)still pushes the cast below the projection and fails with CAST_INVALID_INPUT on 'x', the row the first conjunct drops, with whole-stage codegen on or off and with the split on or off, as on the base branch; with spark.sql.optimizer.avoidDoubleFilterEval off the whole condition is pushed in written order and the query returns 9 rows. Writing the second conjunct as parse($"e") > 0 fails the same way with FAILED_EXECUTE_UDF. splitMovable (predicates.scala:307-320), which CombineFilters and the join rules use and which the PR says it matches, keeps such a conjunct behind a non-deterministic or throwable one, while splitPushable's docstring (Optimizer.scala:3148-3157) still says moving a non-throwable conjunct below a throwable one is fine. No test covers a condition that can fail, reads no expensive alias and follows a non-deterministic or throwable one.
See Shared repair plan 1 in the review body.
There was a problem hiding this comment.
Right. This is the case that #60766 (SPARK-62144) fixes in splitPushable. Your query fails with CAST_INVALID_INPUT on master and with this PR, and returns 8 rows with #60766. I'll keep this PR to the split, and update this comment after rebasing onto #60766, as it keeps such a cheap conjunct above too.
f101a59 to
c7a8fe4
Compare
|
Rebase to master to sync with the latest patches. |
…ensive filters when a condition follows a non-deterministic or throwable one
c7a8fe4 to
0a0e515
Compare
|
Could you review this PR when you have some time, @szehon-ho ? |
What changes were proposed in this pull request?
This PR fixes the projection split of
PushPredicateThroughNonJoin(#58403, SPARK-55014) so that it does not filter on a condition in a lower layer ahead of a non-deterministic or throwable condition written before it.For a filter over a projection,
PushPredicateThroughNonJoinkeeps the conditions over expensive aliases, such as UDFs, above the projection.splitProjectionForExpensiveConditionsthen stacks the deterministic, non-throwable ones in lower layers by cost, each over a projection that computes the aliases it needs, so that an expensive alias only runs on the rows that the layers below kept. A non-deterministic condition stays in the top filter, and so does a throwable one since #59848 (SPARK-60602). But the split still places the conditions written after it in lower layers, so they are evaluated ahead of it, on rows that theANDshort-circuit would have kept from them. Each of these conditions reads an expensive alias, such as a Scala or Python UDF,reflector a regex whose pattern comes from the data, and each of them can fail.This PR stops the split at the first non-deterministic or throwable condition. It and all the conditions written after it stay in the top filter, in their written order. The conditions written before it are split as before, except that the split now leaves at least one expensive alias of each condition written after it to the top projection. Otherwise, when a condition written before it reads the same aliases, the split could compute all of them in a lower layer. The later condition would then only read columns of that layer, and the next pass of
PushPredicateThroughNonJoinwould push it below the projection as a cheap condition, ahead of the non-deterministic or throwable one.This matches
CombineFiltersandPushPredicateThroughJoin(PredicateHelper.splitMovable), which move a condition written after a non-deterministic or throwable one only whenExprUtils.canEvaluateUnconditionallyaccepts it. That check rejects every expensive expression, UDFs and regexes included, so no condition that reaches the split would pass it, and this PR keeps them all in place instead of checking each one. A condition written after a deterministic one is still split ahead of it by cost, as before, like the conditions thatCombineFiltersandPushPredicateThroughJoinmove.Why are the changes needed?
A query that should succeed fails. With ANSI mode, the default since Apache Spark 4.0.0, a cast is enough.
rand(10) * 10 > 100is false on every row, so the conjunct with it is false only for'x', and the cast in Issues 1 and 3 andparsein Issue 2 should never run on it. That conjunct stays in the top filter, as it is non-deterministic, but the split filters on the conjuncts after it in a lower layer, e.g. for Issue 1:In Issue 3, the cast goes to that layer with
n > 0, which reads the same alias. A throwable condition that can filter out rows, such asf OR (e = 'zzz' AND raise_error('boom') IS NULL), fails Issue 1 the same way, and so does a regex whose pattern comes from the data, such ase RLIKE concat(e, s)over an aliass, on a row whose pattern is invalid.Does this PR introduce any user-facing change?
No for the released versions. The projection split of SPARK-55014 is only in
master(4.4.0), not in v4.2.1 (2026-10-21) or v4.3.0 (2026-10-27).In
master, the queries above succeed. Issues 1 and 3 succeed with whole-stage codegen on and off. Issue 2 succeeds with whole-stage codegen on. With it off, Issue 2 still fails, as it does without the split: the top projection computes every alias for every row it gets, includingparseon'x', before the filter. A condition over an expensive alias written after a non-deterministic or throwable one that stays above is no longer split off, so its aliases are computed in the top projection instead of a lower layer. Whole-stage codegen computes such an alias only when the filter reads it, but an interpreted projection or a Python UDF computes it on every row that reaches the top projection, including the rows that a lower layer used to filter out.A throwable condition that only raises, such as
g OR raise_error('boom') IS NULL, now runs on the rows that an expensive condition written after it, such asf, used to filter out first in a lower layer. So such a query can raise wheremasterdid not, as it does with the split disabled.How was this patch tested?
Pass the CIs with the newly added and updated test cases. The new ones fail without this PR.
FilterPushdownSuite:SPARK-60602: a throwable condition does not keep later conditions from being split off, which expected the condition to be split off ahead of the throwable one.SPARK-55014: a non-deterministic condition is not split off into a lower layernow writes the condition over two aliases before the non-deterministic one, so it still checks that the split puts it in the layer that the non-deterministic condition would have taken on cost alone.DataFrameSuite: Issues 1 and 3 return their 9 rows in ANSI mode with whole-stage codegen on and off, instead of failing withCAST_INVALID_INPUT.I also ran the catalyst optimizer suites,
DataFrameSuiteand thePlanStabilitySuites locally. No golden files change. With a temporary suite (not included), I ran Issues 1, 2 and 3, the throwable condition and the regex above, with whole-stage codegen on and off. All of them fail before this PR. After it, all of them succeed, except Issue 2 with whole-stage codegen off, as described above.Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Opus 5.5