dongjoon-hyun commented on code in PR #60351:
URL: https://github.com/apache/spark/pull/60351#discussion_r4560487094
##########
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:
Since `evaluableTail` lets a deterministic, non-throwable condition join the
filter of the current layer, a later pass can still treat it as a cheap
condition, push it below this layer, and `CombineFilters` merges it into an
earlier filter. As the PR description mentions, `req(f) > 0` in `f >= 0 AND h >
5 AND req(f) > 0 AND k >= 0` (with `req` a UDF requiring its input to be
greater than 5) is evaluated before `h > 5`, so the query fails only with the
split on.
I understand that this is the same as on master and deferred to SPARK-60730.
However, since `spark.sql.optimizer.splitProjectionForExpensiveFilters` is
`true` by default and not released yet, a query which works with the split off
and fails with it on is still a regression from the user's point of view. Can
we make sure SPARK-60730 is resolved before the split ships in a release?
##########
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:
Following the written order and stopping at the first condition that needs
every remaining expensive alias also drops the cost-based deferrals for the
expensive expressions which cannot fail, e.g. `LIKE`/`RLIKE` with a literal
pattern. For example, with regex-only aliases, compared with the current master:
- `(f || g) AND j`: two regexes (`f` and `g`) now run on every row instead
of one (`j`).
- `f != g AND f` (non-nullable): it is no longer split, so `g` runs on every
row.
- `f AND g != j AND j`: `j` is no longer split off below `g != j`.
These are CPU regressions without any safety gain because none of these
expressions can raise. Did you consider keeping the cost order among the
conditions which cannot fail and using the written order only as a barrier for
the conditions and aliases which can fail (non-deterministic, throwable, UDFs)?
##########
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:
The order of non-deterministic conditions is protected here and in the split
loop by building separate `Filter` nodes. It relies on `CombineFilters` not
merging into a non-deterministic filter and on this rule not pushing a `Filter`
through another `Filter`. However, the reordering itself comes from
`splitPushable`, which pushes the cheap, non-throwable conjuncts written after
a non-deterministic one below it.
Have you considered handling it at the source, e.g., making `splitPushable`
keep a non-deterministic conjunct and the conjuncts after it above, like a
barrier? Then, one shared filter would be safe, and we could remove both
special cases and the dependency on the other rules. If it's out of the scope
of this PR because it changes the plans with the split off too, it's fine to do
it as a follow-up.
##########
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(
+ df.where((rand(10) > 0.5 || $"h" < 0) && $"f" >= 50),
+ df.where($"f" >= 20 && $"h" >= 40 && (rand(10) > 0.5 || $"f" < 0) &&
$"k" >= 0),
+ df.where($"f" >= 20 && $"h" >= 40 && (rand(10) > 0.5 || $"f" < 0) &&
$"f" % 3 =!= 0 &&
+ $"k" >= 0),
+ df.where($"f" >= 20 && (rand(10) > 0.5 || $"h" < 0) && $"f" % 3 =!= 0 &&
$"k" >= 0),
+ df.where($"f" >= 20 && $"h" + $"k" >= 60 && (rand(10) > 0.5 || $"f" <
0)),
+ df.where($"f" >= 20 && (rand(10) > 0.5 || $"h" + $"k" < 0) && $"f" % 3
=!= 0))
+ def udfProjects(q: DataFrame): Seq[Project] =
q.queryExecution.optimizedPlan.collect {
+ case p: Project if
p.projectList.exists(_.exists(_.isInstanceOf[ScalaUDF])) => p
+ }
+ val unsplit =
withSQLConf(SQLConf.SPLIT_PROJECTION_FOR_EXPENSIVE_FILTERS.key -> "false") {
+ randQueries.map { q =>
+ assert(udfProjects(q).size === 1, "The split applied with the split
off:\n" +
+ q.queryExecution.optimizedPlan)
+ q.collect().toSeq
+ }
+ }
+ withSQLConf(SQLConf.SPLIT_PROJECTION_FOR_EXPENSIVE_FILTERS.key -> "true") {
+ val split = randQueries.map { q =>
+ assert(udfProjects(q).size > 1, "The split did not apply:\n" +
+ q.queryExecution.optimizedPlan)
+ q.collect().toSeq
+ }
+ assert(split === unsplit)
+ }
+ }
+
+ test("SPARK-60731: a throwable alias sharing work with an earlier
condition's alias is " +
+ "computed above that condition's filter") {
+ // t shares gt5 with f, but is not computed with f: with the split on, it
is computed above
+ // the filter on f, in the layer of its reader or, when no condition reads
it, in the
+ // projection on top, so without codegen it does not raise on the rows f
drops. With the split
+ // off, the single interpreted projection computes it on every row and
raises.
+ val gt5Calls = sparkContext.longAccumulator("gt5Calls")
+ val gt5 = udf((i: Long) => {
+ gt5Calls.add(1)
+ i > 5
+ })
+ def query(readsT: Boolean): DataFrame = spark.range(0, 10, 1, 1)
+ .select($"id", gt5($"id") as "f",
+ when(gt5($"id"), lit(true)).otherwise(raise_error(lit("boom")).isNull)
as "t")
+ .where(if (readsT) $"f" && $"t" else $"f")
+ for (readsT <- Seq(true, false); codegen <- Seq(true, false); split <-
Seq(true, false)) {
+ withSQLConf(
+ SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> codegen.toString,
+ SQLConf.SPLIT_PROJECTION_FOR_EXPENSIVE_FILTERS.key -> split.toString) {
+ gt5Calls.reset()
+ if (codegen || split) {
+ assert(query(readsT).collect().toSeq === (6L until 10L).map(i =>
Row(i, true, true)))
+ // With the split, gt5 runs for f on every row and again for t on
the rows f keeps,
+ // also with codegen. Computing it only once is the subject of
SPARK-61515.
+ if (split) assert(gt5Calls.value === 14)
Review Comment:
nit. This assertion (and `assert(udfProjects.size === 2)` in
`FilterPushdownSuite`) makes the redundant second run an expected behavior.
When SPARK-61515 (or a codegen change) removes it, these tests will fail
although the plan becomes better. How about asserting an upper bound like
`gt5Calls.value <= 14`, with a comment about SPARK-61515?
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -3017,32 +3030,64 @@ object PushPredicateThroughNonJoin extends
Rule[LogicalPlan] with PredicateHelpe
* }}}
* so `rlike(e, 'other')` only runs on the rows where `rlike(e, 'magic')`
was true.
*
- * Conditions are grouped by the aliases they reference, then the group
needing the fewest
- * not-yet-computed aliases is split off first -- least demanding first
keeps the expensive
- * expressions as high in the stack, and so over as few rows, as we can
manage. On a tie, the
- * group making the most conditions evaluable wins, falling back to the
condition written first
- * (the only selectivity signal we have). Whole-stage codegen already defers
a projected
- * expression past a filter that does not need it
(`CodegenSupport.evaluateRequiredVariables`),
- * so this rule only buys the same saving on the paths codegen does not
cover -- interpreted
- * projections, operators it bails out of, Python UDFs.
+ * The conditions are placed in the order they are written (SPARK-60731):
each layer computes
+ * the aliases the next condition needs and filters on it and, when it is
deterministic, on the
+ * deterministic conditions right after it that only need aliases computed
already. A
+ * non-deterministic condition gets a filter of its own, which neither the
conditions before it
+ * nor the ones after it join, and a layer that needs no new alias is a
filter alone. So the
+ * split does not evaluate a condition, nor compute the aliases it needs, on
rows the
+ * conditions written before it would have dropped. The exception: an alias
that shares
+ * expensive work with one an earlier condition needs is computed together
with it (see
+ * below), unless that alias is `throwable`. An expression that can fail
without reporting
+ * `throwable`, such as a UDF or, in ANSI mode, a division by zero, can
still be computed early
+ * this way.
*
- * Two restrictions keep the split from costing more than it saves:
+ * Later passes can still move a deterministic condition that is not
throwable, including one
+ * calling a UDF that can fail, ahead of some of the conditions written
before it: one that only
+ * reads aliases computed in a lower layer is cheap there, and this rule
pushes it, as it does
+ * any cheap condition that is not throwable, no lower than the filter of
the highest layer that
+ * computes an expensive alias it reads. It does not move past the filter of
a non-deterministic
+ * condition, which `CombineFilters` does not merge into. So, when the split
places at least one
+ * condition, the caller gives each non-deterministic condition it leaves
above the projection a
+ * filter of its own too. The projection on top computes the aliases of the
conditions left
+ * above it, as without the split.
+ *
+ * Whole-stage codegen already defers a projected expression past a filter
that does not need
+ * it (`CodegenSupport.evaluateRequiredVariables`), so this rule only buys
the same saving on
+ * the paths codegen does not cover -- interpreted projections, operators it
bails out of,
+ * Python UDFs.
+ *
+ * Two restrictions keep the split from costing more than it saves, with one
exception for
Review Comment:
nit. The reason of the throwable-alias exception is explained in four places
(this restriction bullet, the end-of-split paragraph below, the regex/Python
UDF comment, and the `aliasesSharing` comment), and the reason of the separate
non-deterministic filters is repeated in the caller and in the split loop.
Could we explain each once in this docstring and refer to it from the other
places? It would be easier to review and to keep consistent when SPARK-60730
and SPARK-61515 change the behavior.
##########
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:
I know this was discussed in the previous review and the TODO for
SPARK-61515 was added. One more concern is the cost for a shared Python UDF.
There, the second run is a second `BatchEvalPython`/`ArrowEvalPython` operator,
i.e., another round trip to the Python workers for every surviving row, which
is much more expensive than re-evaluating a JVM expression. It is paid also
when whole-stage codegen already defers the throwable alias safely, and it is
contrary to the intention of the comment above (`two aliases sharing one stay
in one layer and do not run it twice`).
Could we keep the throwable alias in the unit when the shared part is a
Python UDF until SPARK-61515, or is SPARK-61515 planned for the same release?
##########
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:
The fix of the motivating query depends on how the query is written. If the
UDF is used inline instead of through an alias, e.g. `.where($"f" + $"h" > 10
&& g($"id") > 0)`, `g(id) > 0` reads no expensive alias and is not throwable,
so `splitPushable` pushes it below the projection ahead of `f + h > 10`. Then,
`g` runs on all 10 rows and fails with `FAILED_EXECUTE_UDF` with the split on
or off, with or without whole-stage codegen.
This is a pre-existing behavior, but the PR description says `queries like
the one above no longer fail`. Could you clarify this limitation in the PR
description (or in the scope of SPARK-60730)?
##########
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:
nit. The rule for which conditions share a filter (consecutive deterministic
conditions join, a non-deterministic one stands alone) is implemented twice:
with `span` over `pending.tail` in `splitProjectForExpensiveConditions` and
with this `foldLeft` over `stayUp`, with slightly different conditions. Could
we extract a small helper used by both places? Otherwise, a future fix (e.g.
SPARK-60730) needs to update two copies consistently.
##########
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:
These UDFs return a primitive `Long`, so `f`, `h` and `k` are never null.
I'm wondering if `the same rows with the split on and off` holds for nullable
UDF results too. `InferFiltersFromConstraints` prepends the inferred
`isnotnull(...)` to the condition of a filter. For example, in `(rand(10) > 0.5
|| h < 0) && f >= 50` with a nullable `f`, the split-off plan gets
`isnotnull(f)` ahead of `rand(10) > 0.5`, while, with the split on, it lands in
the filter of the layer of `f`, after `rand`. Then, `rand` sees different rows.
Could you add a nullable case (e.g. a UDF returning `java.lang.Long` that
returns `null` for some ids)? `FilterPushdownSuite` doesn't cover this because
its `Optimize` doesn't run `InferFiltersFromConstraints`.
##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/FilterPushdownSuite.scala:
##########
@@ -863,6 +1358,17 @@ class FilterPushdownSuite extends PlanTest {
comparePlans(optimized, correctAnswer)
}
+ // The conjuncts of every filter of `plan`, from the top, in their order,
which `comparePlans`
+ // does not check. Unlike `assertTopFilterConjuncts`, it covers every
filter, and normalizes the
+ // expression IDs, so it can compare two plans built separately. It compares
the conjuncts as
+ // written, operands included. It does not canonicalize them: with every
expression ID
+ // normalized, canonicalized attributes of the same type are equal, so `a >
1` would match
+ // `b > 1`.
+ private def filterConjuncts(plan: LogicalPlan): Seq[Seq[Expression]] =
Review Comment:
nit. This new helper overlaps with `assertTopFilterConjuncts` right below.
The top filter check is basically `filterConjuncts(plan).head`, but one
normalizes the expression IDs and compares the conjuncts as written while the
other compares canonicalized expressions, so they can disagree on the same
plan. Could we use one helper (e.g. implement `assertTopFilterConjuncts` with
`filterConjuncts`) to make it clear which one to use?
--
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]