sarutak commented on code in PR #60351:
URL: https://github.com/apache/spark/pull/60351#discussion_r4575517751
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -3079,53 +3135,58 @@ object PushPredicateThroughNonJoin extends
Rule[LogicalPlan] with PredicateHelpe
var grew = true
while (grew) {
val next = unit.flatMap(expensiveParts).foldLeft(unit) {
- case (acc, part) => acc ++ aliasesSharing(part)
+ case (acc, part) => acc ++ aliasesSharing.getOrElse(part,
AttributeSet.empty)
}
grew = next.size > unit.size
unit = next
}
unit
}
- val indexed = expensiveConds.zipWithIndex.map {
- case ((cond, used), idx) => (unitOf(AttributeSet(used.keys)), idx, cond)
- }
- // Group conditions over the same aliases; group on sorted exprIds (not
AttributeSet) for
- // stable hashing, and order groups by first condition to keep plans
stable.
- var pending: Seq[(AttributeSet, Seq[(Int, Expression)])] = indexed
- .groupBy { case (used, _, _) => used.toSeq.map(_.exprId.id).sorted }
- .toSeq
- .map { case (_, group) => (group.head._1, group.map { case (_, idx,
cond) => (idx, cond) }) }
- .sortBy { case (_, conds) => conds.head._1 }
- def conditionsOf(groups: Seq[(AttributeSet, Seq[(Int, Expression)])]):
Seq[Expression] =
- groups.flatMap(_._2).sortBy(_._1).map(_._2)
-
// Projection order is stable, unlike the alias map's iteration order.
val orderedAliases = project.projectList.collect { case a: Alias => a }
+ var pending: Seq[(AttributeSet, Expression)] = expensiveConds.map {
+ case (cond, used) => (unitOf(AttributeSet(used.keys)), cond)
+ }
var plan = baseChild
var computed = AttributeSet.empty
var searching = true
- while (searching) {
+ while (searching && pending.nonEmpty) {
+ val (needed, head) = pending.head
// Only split while it leaves an expensive alias for a later layer.
- val stillToCompute = expensiveAliases -- computed
- val candidates = pending.filter { case (used, _) =>
!stillToCompute.subsetOf(used) }
- if (candidates.isEmpty) {
+ if ((expensiveAliases -- computed).subsetOf(needed)) {
searching = false
} else {
- val (bestUsed, _) = candidates.minBy {
- case (used, conds) => ((used -- computed).size, -conds.size)
- }
- val newAliases = orderedAliases.filter(a => bestUsed.contains(a) &&
!computed.contains(a))
+ val newAliases = orderedAliases.filter(a => needed.contains(a) &&
!computed.contains(a))
computed ++= AttributeSet(newAliases.map(_.toAttribute))
- // Keep the plan's existing outputs available for later projections;
column pruning drops
- // the extras.
- val newProject = project.copy(projectList = plan.output ++ newAliases,
child = plan)
- val (evaluable, rest) = pending.partition { case (used, _) =>
used.subsetOf(computed) }
- plan = Filter(conditionsOf(evaluable).reduce(And), newProject)
+ // The next condition, and the deterministic ones after it that only
need aliases
+ // computed already. A non-deterministic condition shares no filter
with the conditions
+ // before or after it: in a later pass, a condition that only reads
aliases computed
+ // below would be pushed below the conditions before it, or the ones
after it would be
+ // moved ahead of it. It filters on its own instead, which a later
pass does not merge
+ // with the filters below it, nor push below them.
+ val (evaluableTail, rest) = if (head.deterministic) {
Review Comment:
Yes, I plan to get SPARK-60730 (#59940) into the same release as the split,
on master and branch-4.x; it is held only until this PR and its other
prerequisites are merged. I expect it to fix this shape, and when I rebase it,
I will add this shape (`req(f) > 0` over an alias computed in a lower layer) to
its tests to confirm that.
One related shape is not the same as on master, though: a condition that can
fail over a throwable alias, such as `u(t)` in `t AND g AND u(t)` with a UDF
`u`. Master kept it in the top filter, after `g`, as a throwable condition.
This PR computes `t` in a lower layer, where `u(t)` reads `t` as a column and
is no longer throwable, so a later pass pushes it ahead of `g`, as for `req(f)
> 0` above. The PR description now says so, and I will add this shape to the
#59940 tests too.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2697,24 +2699,16 @@ object PushPredicateThroughNonJoin extends
Rule[LogicalPlan] with PredicateHelpe
} else {
grandChild
}
- // Case 3: split the projection around the expensive conditions.
Non-deterministic
- // conditions stay in the top filter, as they do everywhere else in
this rule -- the
- // 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.
+ // Case 3: split the projection around the expensive conditions, in
their written order
+ // (see `splitProjectForExpensiveConditions`). Whatever it does not
place stays above
+ // the projection, in the written order too; from the lowest filter
there, a later pass
+ // can still push a deterministic condition that is not throwable and
only reads aliases
+ // computed below. The cheap conditions this rule pushes below the
projection (cases 1 and
+ // 2), non-deterministic ones included, run before all of these (see
`splitPushable`).
Review Comment:
Thank you, I measured it: `f + h > 10 AND g(id) > 0` fails with
`FAILED_EXECUTE_UDF` with the split on and off, with and without whole-stage
codegen, both on the merge-base and with this PR, as `g(id) > 0` reads no alias
and is pushed below the projection. I updated the description: the user-facing
bullet now says that the queries reading the UDF through an alias no longer
fail, and the paragraph on what stays as before says that a condition calling a
UDF directly is still pushed below the projection, which is also the subject of
SPARK-60730. #59940 has a test for this shape (`f > 5 && h($"id") > 0`), which
passes in its CI.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -3068,7 +3114,17 @@ object PushPredicateThroughNonJoin extends
Rule[LogicalPlan] with PredicateHelpe
})
def expensiveParts(attr: Attribute): Set[Expression] =
expensivePartsOf.getOrElse(attr, Set.empty)
+ // A throwable alias is not pulled into the unit of an alias it shares
work with, so it is
+ // not computed ahead of the first condition that reads it, even when that
evaluates the
+ // shared part twice. It still pulls in the aliases that are not throwable.
+ // TODO(SPARK-61515): Compute the shared part only once, e.g. by having
the layer that computes
+ // the alias sharing it also output the shared part as a column (unless
that alias is the
+ // shared part itself), for the throwable alias, computed in a later layer
or on top, to read.
+ // That is only valid when that alias evaluates the shared part
unconditionally, not only in
+ // some branches or inside a lambda; otherwise keep the second run, as the
part would run, and
+ // could fail, on rows it does not run on now.
val aliasesSharing = expensivePartsOf.toSeq
+ .filterNot { case (attr, _) => aliasMap(attr).child.throwable }
Review Comment:
Good point, I took your suggestion: a throwable alias now stays in the unit
of the aliases sharing its work when the shared part has a Python UDF, so the
Python UDF is in one projection, as with the split off. Without whole-stage
codegen, such a throwable alias can then raise on the rows the earlier
conditions drop, as before this PR and as with the split off. For the other
shared work, the throwable alias is still left out of the unit. The docstring,
the comment you quoted and the PR description say so, and `FilterPushdownSuite`
checks it in `a throwable alias sharing a Python UDF with an earlier
condition's alias is computed with it` and in a new test with the shared work
going through another alias, a split ended by the shared Python UDF, two
throwable aliases sharing it, and a throwable alias with a Python UDF of its
own that shares only a regex. A new `ExtractPythonUDFsSuite` test checks the
executed plan: the shared UDF is evaluated once, and twice without the
exception.
I plan to get SPARK-61515 into the same release; computing the shared part
once would also let us drop this exception.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -3079,53 +3135,58 @@ object PushPredicateThroughNonJoin extends
Rule[LogicalPlan] with PredicateHelpe
var grew = true
while (grew) {
val next = unit.flatMap(expensiveParts).foldLeft(unit) {
- case (acc, part) => acc ++ aliasesSharing(part)
+ case (acc, part) => acc ++ aliasesSharing.getOrElse(part,
AttributeSet.empty)
}
grew = next.size > unit.size
unit = next
}
unit
}
- val indexed = expensiveConds.zipWithIndex.map {
- case ((cond, used), idx) => (unitOf(AttributeSet(used.keys)), idx, cond)
- }
- // Group conditions over the same aliases; group on sorted exprIds (not
AttributeSet) for
- // stable hashing, and order groups by first condition to keep plans
stable.
- var pending: Seq[(AttributeSet, Seq[(Int, Expression)])] = indexed
- .groupBy { case (used, _, _) => used.toSeq.map(_.exprId.id).sorted }
- .toSeq
- .map { case (_, group) => (group.head._1, group.map { case (_, idx,
cond) => (idx, cond) }) }
- .sortBy { case (_, conds) => conds.head._1 }
- def conditionsOf(groups: Seq[(AttributeSet, Seq[(Int, Expression)])]):
Seq[Expression] =
- groups.flatMap(_._2).sortBy(_._1).map(_._2)
-
// Projection order is stable, unlike the alias map's iteration order.
val orderedAliases = project.projectList.collect { case a: Alias => a }
+ var pending: Seq[(AttributeSet, Expression)] = expensiveConds.map {
+ case (cond, used) => (unitOf(AttributeSet(used.keys)), cond)
+ }
var plan = baseChild
var computed = AttributeSet.empty
var searching = true
- while (searching) {
+ while (searching && pending.nonEmpty) {
+ val (needed, head) = pending.head
// Only split while it leaves an expensive alias for a later layer.
- val stillToCompute = expensiveAliases -- computed
- val candidates = pending.filter { case (used, _) =>
!stillToCompute.subsetOf(used) }
- if (candidates.isEmpty) {
+ if ((expensiveAliases -- computed).subsetOf(needed)) {
Review Comment:
Thank you. This PR now does part of that: it fixes examples 2 and 3, which
were regressions that the stop rule of this PR introduced, but keeps no cost
order among the conditions that cannot fail. Before a deterministic condition
ends the split, the conditions written after it, up to the first
non-deterministic one, that cannot fail are filtered on in a layer below it, in
their written order, but only when nothing that layer computes, or lets a later
pass move, can fail: every alias it computes cannot fail, and no condition
after the ending one, up to the first non-deterministic one, can fail over the
aliases not computed yet, which a later pass inlines into a condition it
pushes. For this, `ExprUtils.canEvaluateUnconditionally` is used with one
addition local to this rule: LIKE and RLIKE with a literal pattern of at most
100 characters that is null or compiles, for RLIKE without `(`, `\` or `{`.
(Java's regex engine recurses once per node of the pattern, once per repetition
of a
quantified group such as `(a|b)*`, and, for a `{}` quantifier or `\R` or `\X`,
each time the length of a match changes, as for `.` over supplementary
characters; this overflows the stack on a long pattern or input, so a regex can
fail there.) So, with such regex aliases under version 0 of the estimate, `f !=
g AND f` filters on `f` below `f != g`, and `f AND g != j AND j` on `j` below
`g != j`, as on master. The check is conservative: when the layer would compute
an alias that can fail, such as a UDF, or a condition after the ending one can
fail, the split still ends there, as the cost order would compute such an alias
ahead of conditions written before it. I chose this over predicting which
conditions later rules and execution would move or where they would compute the
aliases, as such predictions kept missing cases in my own reviews; with nothing
there that can fail, a wrong prediction can only cost time. The new tests are
`the conditions after the one that ends the split that can
not fail are filtered on below it` and `... are not filtered on below it when
something there can fail, past a non-deterministic condition, or when they
would leave nothing to defer or split shared work` in `FilterPushdownSuite`,
and `a condition that cannot fail written after the one that ends the split is
evaluated before it` in `DataFrameSuite`.
Example 1 needs more: filtering on `j` first computes `j` ahead of `f || g`,
so besides `j` itself not failing, it needs an order by cost among the
conditions that cannot fail. I filed SPARK-61680 for that; it would also cover
`f != g AND j AND f`, where the split computes `f` and `g` before filtering on
`j`.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2732,8 +2726,27 @@ object PushPredicateThroughNonJoin extends
Rule[LogicalPlan] with PredicateHelpe
if (stayUp.isEmpty) {
topProjection
- } else {
+ } else if (splitAliases.isEmpty) {
+ // Nothing was split off, so this is the same plan as with the
split off.
Filter(stayUp.reduce(And), topProjection)
+ } else {
+ // As in the split, a non-deterministic condition left above gets
a filter of its own:
Review Comment:
Yes, `splitPushable` is one source, and I filed SPARK-61662 to change it as
a follow-up. It changes the plans with the split off too, at every operator
that uses `splitPushable` (`Project`, `Window`, `Union`, `Aggregate` and
others), and pushing those conjuncts ahead of a non-deterministic one is the
behavior of the released versions (for `Project`, since `avoidDoubleFilterEval`
in 4.2.0), so it likely needs a legacy config. There is a second source,
though: since SPARK-60882, `CombineFilters` merges a condition that cannot
fail, written after a non-deterministic one, into the filter below, ahead of
it. So a shared filter would also need `CombineFilters` to stop at a
non-deterministic condition; I will add that to the scope of SPARK-61662 and
check there whether the separate filters here can then be dropped.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2732,8 +2726,27 @@ object PushPredicateThroughNonJoin extends
Rule[LogicalPlan] with PredicateHelpe
if (stayUp.isEmpty) {
topProjection
- } else {
+ } else if (splitAliases.isEmpty) {
+ // Nothing was split off, so this is the same plan as with the
split off.
Filter(stayUp.reduce(And), topProjection)
+ } else {
+ // As in the split, a non-deterministic condition left above gets
a filter of its own:
+ // in a shared filter, a later pass would push it below the
conditions before it, or
+ // move the ones after it ahead of it, as cheap conditions over
the aliases the split
+ // computed. Every alias is computed below these filters, so,
unlike in the split,
+ // whether a condition joins the filter before it depends only on
whether it and the
+ // conditions of that filter are deterministic. A throwable
condition shares a filter
+ // with the deterministic ones before it, as it does in the split
when it needs no new
+ // alias, and in the original filter.
+ val filters = stayUp.foldLeft(Vector.empty[Seq[Expression]]) {
(filters, cond) =>
Review Comment:
Done. Both places now use a new helper, `nextFilter`: a deterministic
condition shares its filter with the deterministic conditions right after it
that the caller accepts (in the split, those that only need aliases computed
already; above the projection, every deterministic one), and a
non-deterministic one gets a filter of its own. The layer added for your
comment on the regex regressions does not use it, as it filters on conditions
it picks from after the condition that ends the split, which need not be next
to each other.
##########
sql/core/src/test/scala/org/apache/spark/sql/DataFrameSuite.scala:
##########
@@ -2978,6 +2978,121 @@ class DataFrameSuite extends SharedSparkSession
}
}
+ test("SPARK-60731: the projection split places filter conditions in written
order") {
+ val gCalls = sparkContext.longAccumulator("gCalls")
+ val f = udf((i: Long) => i)
+ val h = udf((i: Long) => i)
+ val g = udf((i: Long) => {
+ gCalls.add(1)
+ require(i > 5, s"g called with $i")
+ i
+ })
+ // `g > 0` needs one alias and `f + h > 10` two, but `g` only works for
the ids
+ // `f + h > 10` keeps, so it must only be computed after it, as written.
+ def query(): DataFrame = spark.range(0, 10, 1, 1)
+ .select($"id", f($"id") as "f", h($"id") as "h", g($"id") as "g")
+ .where($"f" + $"h" > 10 && $"g" > 0)
+ val expected = (6L until 10L).map(i => Row(i, i, i, i))
+ // An interpreted projection computes every projected column for every row
it gets, so
+ // without codegen only the split keeps `g` away from the other rows.
+ for (codegen <- Seq(true, false); split <- Seq(true, false) if codegen ||
split) {
+ withSQLConf(
+ SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> codegen.toString,
+ SQLConf.SPLIT_PROJECTION_FOR_EXPENSIVE_FILTERS.key -> split.toString) {
+ gCalls.reset()
+ // Collect, not checkAnswer, so the plan runs exactly once.
+ assert(query().collect().toSeq === expected)
+ if (!codegen) assert(gCalls.value === 4)
+ }
+ }
+ // Without codegen and the split, the single interpreted projection
computes g on every row.
+ withSQLConf(
+ SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> "false",
+ SQLConf.SPLIT_PROJECTION_FOR_EXPENSIVE_FILTERS.key -> "false") {
+ val e = intercept[SparkException](query().collect())
+ assert(e.getMessage.contains("FAILED_EXECUTE_UDF"))
+ assert(e.getMessage.contains("g called with"))
+ }
+
+ // Each of these filters with a non-deterministic condition is split
(asserted below), and
+ // returns the same rows with the split on as with it off. The
non-deterministic condition:
+ // (1) is written first;
+ // (2) is written after two conditions and reads only the alias of the
first;
+ // (3) is the same, with a condition after it that only reads computed
aliases;
+ // (4) is written after one condition, reads a new alias, and has a
condition after it that
+ // only reads computed aliases;
+ // (5) is left above the split after the condition that ends it, reading
only the alias of
+ // the first condition;
+ // (6) ends the split itself, and has a condition after it that only
reads computed aliases.
+ // In (2) and (3), the non-deterministic condition needs no new alias, so
it would join the
+ // filter before it if the split allowed that. In (5) and (6), a later
pass would swap it with
+ // another condition if they shared the top filter, and the rows would
differ.
+ val k = udf((i: Long) => i)
+ def df: DataFrame = spark.range(0, 100, 1, 1)
+ .select($"id", f($"id") as "f", h($"id") as "h", k($"id") as "k")
+ def randQueries: Seq[DataFrame] = Seq(
Review Comment:
Thank you, you are right that the inferred checks break it: in your example
without codegen, and in other shapes also with codegen. I measured it with UDF
results that can be null (`f` null for the ids `i` with `i % 7 = 3`, `h` for `i
% 5 = 1`). The split-off plan evaluates the inferred `isnotnull` checks ahead
of the non-deterministic condition: without codegen ahead of all the
conditions, and with codegen just before the first condition reading the
column, so only when the non-deterministic condition is the first condition
reading it. So the split-off plan itself can return other rows with and without
codegen.
| Filter | Written order | Split on (codegen on / off) | Split off (codegen
on / off) |
|---|---|---|---|
| `(rand(10) > 0.5 OR h < 0) AND f >= 50` | 26 | 26 / 26 | 26 / 23 |
| `(rand(10) > 0.5 OR f < 0) AND h >= 50 AND f >= 50` | 21 | 21 / 21 | 18 /
22 |
| `(rand(10) > 0.5 OR f + h < 0) AND f >= 50` | 26 | 23 / 23 | 23 / 23 |
On the merge-base, the first filter returns 28 rows with the split on, with
and without codegen.
When the split places the conditions before the checks are inferred, as in
the first two, it keeps the non-deterministic condition ahead of the conditions
written after it, so it returns the rows of the written order. In the third,
the first condition needs every expensive alias, so the first pass places
nothing, and the split happens only after the checks are inferred, with them
first, as in the split-off plan. I added the first two filters to the test,
which compares the split, with and without codegen, with the rows of the
written order, and the description describes all three. Where the optimizer
puts the inferred checks is the subject of SPARK-61378.
--
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]