dongjoon-hyun commented on code in PR #60351:
URL: https://github.com/apache/spark/pull/60351#discussion_r4624047139
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -3103,55 +3188,120 @@ 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) {
- // 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) {
- searching = false
- } else {
- val (bestUsed, _) = candidates.minBy {
- case (used, conds) => ((used -- computed).size, -conds.size)
+ while (searching && pending.nonEmpty) {
+ val (needed, head) = pending.head
+ val remaining = expensiveAliases -- computed
+ // The aliases the next layer needs, the conditions of its filter, and
the rest.
+ val nextLayer = if (!remaining.subsetOf(needed)) {
+ // The next condition and, when it is deterministic, the deterministic
ones right after it
+ // that only need aliases computed already.
+ val (inFilter, rest) = nextFilter(pending)(
+ _._2.deterministic, { case (condNeeded, _) =>
condNeeded.subsetOf(computed ++ needed) })
+ Some((needed, inFilter, rest))
+ } else if (head.deterministic) {
+ // The head ends the split, but first the conditions after it get a
layer of their own,
+ // when none of them, nor any alias that layer computes, can fail (see
the docstring).
+ val conds = pending.toIndexedSeq
+ val following = conds.indices.tail.takeWhile(idx =>
conds(idx)._2.deterministic)
+ // Over the aliases not computed yet, which a later pass inlines into
a condition it
+ // pushes once the projection on top computes them.
+ lazy val notComputed = AttributeMap(aliasMap.toSeq.filterNot { case
(attr, _) =>
+ computed.contains(attr)
+ })
+ val followingCannotFail =
Review Comment:
The deferral judges a following condition with only the aliases not computed
yet inlined, so it reads a computed alias as a plain column that cannot fail.
That does not hold for an alias that a lower layer computes but no filter there
reads yet, e.g. one pulled into the layer because it shares expensive work with
the alias the head reads. Under whole-stage codegen, `ProjectExec` computes
such a column only when an operator above first reads it, so the deferred
filter is where it runs, ahead of the condition that ends the split.
For example, with `s`, `j` and `k` no-op UDFs and `req` a UDF that requires
its input to be greater than 5:
```scala
spark.range(0, 10, 1, 1)
.select($"id", s($"id") as "g", req(s($"id")) as "f", j($"id") as "j",
k($"id") as "k")
.where($"g" >= 0 && $"j" + $"k" > 10 && $"f" > 0)
```
`f` shares `s(id)` with `g`, so the layer of `g >= 0` computes both. `j + k
> 10` ends the split, and `f > 0`, over the computed `f`, passes `cannotFail`
and is filtered on below it (then `CombineFilters` merges it into the filter of
`g >= 0`). With codegen, `req` then runs on the ids 0 to 5 and fails with
`FAILED_EXECUTE_UDF`, while with the split off it only runs on the 4 rows `j +
k > 10` keeps. I checked this by reading the code only; I did not run it.
The cost order of the merge-base and a later pass over the top filter give
the same failure here, so this is not worse than master. However, the docstring
says that the layer only drops rows earlier, and the test comment says that `a
later pass reads the computed ones as columns`, which does not hold for such a
column. SPARK-60730 as planned (`canEvaluateUnconditionally` of the pushed
form) would not catch it either, as `f > 0` itself is total.
master now has `PredicateHelper.failableOutput` (SPARK-61886, SPARK-61823)
for exactly this. How about also rejecting a following condition that reads
`failableOutput(plan)` after rebasing, or, less conservatively, a computed
alias that can fail and that no filter below reads? This is a new case for the
design discussed in
https://github.com/apache/spark/pull/60351#discussion_r4575518061.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/regexpExpressions.scala:
##########
@@ -741,6 +783,9 @@ case class RLike(left: Expression, right: Expression)
extends StringRegexExpress
override def matches(regex: Pattern, str: String): Boolean =
regex.matcher(str).find(0)
override protected def isExpensivePattern(str: String): Boolean =
StringRegexExpression.isExpensiveRegex(str, matchesWhole = false)
+ // A pattern without `(`, `\` or `{` has no group, no `{}` quantifier and no
`\R` or `\X`.
+ override protected def isStackSafePattern(str: String): Boolean =
Review Comment:
`isStackSafePattern` relies on how `java.util.regex` matches: `*` and `+`
over a single character are matched in a loop (`CharPropertyGreedy`), while a
quantified group or a `{}` quantifier recurses. That is reasonable, but
`RegexpExpressionsSuite` only checks the flag. Could we add a test that matches
a few accepted patterns, e.g. `.*a.*` for RLIKE and `%a%_` for LIKE, against a
long input (a few MB, with supplementary characters), in both interpreted and
codegen mode? Then a change in a future JDK would fail a test instead of a
query.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -3103,55 +3188,120 @@ 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) {
- // 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) {
- searching = false
- } else {
- val (bestUsed, _) = candidates.minBy {
- case (used, conds) => ((used -- computed).size, -conds.size)
+ while (searching && pending.nonEmpty) {
+ val (needed, head) = pending.head
+ val remaining = expensiveAliases -- computed
+ // The aliases the next layer needs, the conditions of its filter, and
the rest.
+ val nextLayer = if (!remaining.subsetOf(needed)) {
+ // The next condition and, when it is deterministic, the deterministic
ones right after it
+ // that only need aliases computed already.
+ val (inFilter, rest) = nextFilter(pending)(
+ _._2.deterministic, { case (condNeeded, _) =>
condNeeded.subsetOf(computed ++ needed) })
+ Some((needed, inFilter, rest))
+ } else if (head.deterministic) {
+ // The head ends the split, but first the conditions after it get a
layer of their own,
+ // when none of them, nor any alias that layer computes, can fail (see
the docstring).
+ val conds = pending.toIndexedSeq
+ val following = conds.indices.tail.takeWhile(idx =>
conds(idx)._2.deterministic)
+ // Over the aliases not computed yet, which a later pass inlines into
a condition it
+ // pushes once the projection on top computes them.
+ lazy val notComputed = AttributeMap(aliasMap.toSeq.filterNot { case
(attr, _) =>
+ computed.contains(attr)
+ })
+ val followingCannotFail =
+ following.forall(idx => cannotFail(replaceAlias(conds(idx)._2,
notComputed)))
+ val (deferred, deferredNeeded) = (if (followingCannotFail) following
else Nil)
+ .foldLeft((Set.empty[Int], AttributeSet.empty)) { case ((taken,
unit), idx) =>
+ val grown = unit ++ conds(idx)._1
+ val newAliases = grown -- computed
+ val left = remaining -- grown
+ // Only while the layer still leaves an expensive alias for a
later one, no alias it
+ // leaves shares expensive work with one it computes, and no alias
it computes, also
+ // one that only shares expensive work with an alias a condition
reads, can fail.
+ if (left.nonEmpty && (partsOf(left) intersect
partsOf(newAliases)).isEmpty &&
+ newAliases.forall(attr => cannotFail(aliasMap(attr).child))) {
+ (taken + idx, grown)
+ } else {
+ (taken, unit)
+ }
+ }
+ Option.when(deferred.nonEmpty) {
+ val (inFilter, rest) = conds.indices.partition(deferred.contains)
+ (deferredNeeded, inFilter.map(conds), rest.map(conds))
}
- val newAliases = orderedAliases.filter(a => bestUsed.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)
- pending = rest
+ } else {
+ None
+ }
+ nextLayer match {
+ case None =>
+ searching = false
+ case Some((layerNeeded, inFilter, rest)) =>
+ val newAliases =
+ orderedAliases.filter(a => layerNeeded.contains(a) &&
!computed.contains(a))
+ computed ++= AttributeSet(newAliases.map(_.toAttribute))
+ val condition = inFilter.map(_._2).reduce(And)
+ plan = if (newAliases.isEmpty) {
+ // When the filter needs no new alias, its first condition or the
one before it is
+ // non-deterministic, or its conditions come from after the
condition that ends the
+ // split; otherwise they would have joined the previous filter. A
projection would
+ // compute nothing here.
+ Filter(condition, plan)
+ } else {
+ // Keep the plan's existing outputs available for later
projections; column pruning
+ // drops the extras.
+ Filter(condition, project.copy(projectList = plan.output ++
newAliases, child = plan))
+ }
+ pending = rest
}
}
- (plan, computed, conditionsOf(pending))
+ (plan, computed, pending.map(_._2))
+ }
+
+ /**
+ * Splits the non-empty `conds` into the conditions of the next filter and
the rest: a
+ * deterministic first condition shares its filter with the deterministic
conditions right after
+ * it that `canJoin` accepts, and a non-deterministic one gets a filter of
its own (see
+ * `splitProjectForExpensiveConditions`).
+ */
+ private def nextFilter[T](conds: Seq[T])(
+ deterministic: T => Boolean, canJoin: T => Boolean): (Seq[T], Seq[T]) = {
+ require(conds.nonEmpty)
+ if (deterministic(conds.head)) {
+ val (joined, rest) = conds.tail.span(c => deterministic(c) && canJoin(c))
+ (conds.head +: joined, rest)
+ } else {
+ (conds.take(1), conds.tail)
+ }
}
+ /**
+ * Whether `e` cannot fail: `ExprUtils.canEvaluateUnconditionally`, also
accepting LIKE and RLIKE
+ * whose pattern `StringRegexExpression.cannotFailPattern` accepts, which
version 0 of the regex
+ * pattern cost estimate treats as expensive (SPARK-60731). `CombineFilters`
uses the narrower
Review Comment:
nit. This sentence, and `and CombineFilters one that cannot fail, ahead of
it` in the docstring above (L3071), describe `CombineFilters` as of the
merge-base. On master, after SPARK-61886 and SPARK-62049 (both merged after the
CI run of this PR), `CombineFilters` uses `splitMovable`, which also keeps a
condition over a column that can fail (`failableOutput`) where it is.
As every expensive alias the split computes is such a column, the
`CombineFilters` part of the reason for the separate filters of
non-deterministic conditions no longer applies to the conditions over them;
only `splitPushable` is left. Could you update these comments after rebasing?
If the deferral uses `failableOutput` too (see my other comment), both would
follow one rule.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -3103,55 +3188,120 @@ 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) {
- // 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) {
- searching = false
- } else {
- val (bestUsed, _) = candidates.minBy {
- case (used, conds) => ((used -- computed).size, -conds.size)
+ while (searching && pending.nonEmpty) {
+ val (needed, head) = pending.head
+ val remaining = expensiveAliases -- computed
+ // The aliases the next layer needs, the conditions of its filter, and
the rest.
+ val nextLayer = if (!remaining.subsetOf(needed)) {
+ // The next condition and, when it is deterministic, the deterministic
ones right after it
+ // that only need aliases computed already.
+ val (inFilter, rest) = nextFilter(pending)(
+ _._2.deterministic, { case (condNeeded, _) =>
condNeeded.subsetOf(computed ++ needed) })
+ Some((needed, inFilter, rest))
+ } else if (head.deterministic) {
+ // The head ends the split, but first the conditions after it get a
layer of their own,
+ // when none of them, nor any alias that layer computes, can fail (see
the docstring).
+ val conds = pending.toIndexedSeq
+ val following = conds.indices.tail.takeWhile(idx =>
conds(idx)._2.deterministic)
+ // Over the aliases not computed yet, which a later pass inlines into
a condition it
+ // pushes once the projection on top computes them.
+ lazy val notComputed = AttributeMap(aliasMap.toSeq.filterNot { case
(attr, _) =>
+ computed.contains(attr)
+ })
+ val followingCannotFail =
+ following.forall(idx => cannotFail(replaceAlias(conds(idx)._2,
notComputed)))
+ val (deferred, deferredNeeded) = (if (followingCannotFail) following
else Nil)
+ .foldLeft((Set.empty[Int], AttributeSet.empty)) { case ((taken,
unit), idx) =>
+ val grown = unit ++ conds(idx)._1
+ val newAliases = grown -- computed
+ val left = remaining -- grown
+ // Only while the layer still leaves an expensive alias for a
later one, no alias it
+ // leaves shares expensive work with one it computes, and no alias
it computes, also
+ // one that only shares expensive work with an alias a condition
reads, can fail.
+ if (left.nonEmpty && (partsOf(left) intersect
partsOf(newAliases)).isEmpty &&
+ newAliases.forall(attr => cannotFail(aliasMap(attr).child))) {
+ (taken + idx, grown)
+ } else {
+ (taken, unit)
+ }
+ }
+ Option.when(deferred.nonEmpty) {
Review Comment:
nit. After a deferred layer, the head is still the condition that ends the
split, so the next iteration comes back to this branch, builds `notComputed`
and inlines the following conditions again. As far as I can see, it can never
add another layer. A condition this branch rejected was rejected because no
expensive alias would be left, because an alias it needs can fail, or because
an alias left shares work with one it needs:
- The first stays true, as `remaining` only shrinks.
- The second too, as such an alias is never computed.
- In the third, the alias left is a throwable one, as the aliases sharing
work that are not throwable are in one unit, and a throwable alias is never
computed either.
How about ending the loop (`searching = false`) after a deferred layer? This
extends my earlier comment on `notComputed`
(https://github.com/apache/spark/pull/60351#discussion_r4604716756).
##########
sql/core/src/test/scala/org/apache/spark/sql/DataFrameSuite.scala:
##########
@@ -2978,6 +2978,206 @@ 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 over UDF
results that are never
+ // null 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)
+ }
+
+ // With UDF results that can be null, the optimizer adds `isnotnull`
checks for the columns
Review Comment:
SPARK-61823, merged on master on Nov 17 and included in the CI run of this
PR, made `InferFiltersFromConstraints` skip an inferred filter that reads a
column that can fail (`failableOutput`), such as these UDF aliases computed by
the projection below. So, on the current master, I think no `isnotnull(f)` or
`isnotnull(h)` is inferred for these queries, with the split on or off, and the
split-off plan also returns the rows of the written order, with and without
codegen.
Then, this comment and the numbers in the PR description (26 and 23, and 18
and 22, with the split off, and 23 rows for `(rand(10) > 0.5 OR f + h < 0) AND
f >= 50`) no longer match master. The assertions still pass, but this part no
longer covers the inferred checks this comment describes. Could you re-measure
after rebasing, and update this comment and the description, including the
reference to SPARK-61378?
##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/FilterPushdownSuite.scala:
##########
@@ -586,16 +591,754 @@ class FilterPushdownSuite extends PlanTest {
val optimized = Optimize.execute(originalQuery)
- // j needs one alias and (f || g) needs two, so j goes first even though
it is projected
- // last -- leaving two expensive elements to run on its survivors.
+ // j needs one alias and (f || g) needs two, but (f || g) is written
first, so f and g are
+ // computed first and j only runs on the rows (f || g) keeps, as written.
val correctAnswer = testStringRelation
- .select($"a", $"b", $"e", expensiveRLike("third") as "j")
+ .select($"a", $"b", $"e", expensiveRLike("magic") as "f",
expensiveRLike("other") as "g")
+ .where($"f" || $"g")
+ .select($"a", $"f", $"g", expensiveRLike("third") as "j")
.where($"j")
- .select($"a", expensiveRLike("magic") as "f", expensiveRLike("other") as
"g", $"j")
+ .analyze
+
+ comparePlans(optimized, correctAnswer)
+ }
+
+ test("SPARK-60731: a throwable condition over computed aliases joins the
filter of the " +
+ "condition written right before it, not an earlier filter over the same
aliases") {
+ val raiseError = IsNull(RaiseError(Literal("boom")))
+ val expensiveInt = If(expensiveRLike("magic"), $"a", $"b")
+ val originalQuery = testStringRelation
+ .select($"a", expensiveInt as "n", expensiveRLike("other") as "g",
+ expensiveRLike("third") as "j")
+ .where($"n" > 1 && $"g" && ($"n" < 10 || raiseError) && $"n" =!= 5 &&
$"j")
+ .analyze
+
+ val optimized = Optimize.execute(originalQuery)
+
+ // The throwable condition only needs n, but is written after g, so it is
evaluated with g,
+ // not with n > 1. A condition that is not throwable, such as n != 5,
joins the filter of g
+ // too, but a later pass pushes it below g, as a cheap condition over the
n computed below.
+ val correctAnswer = testStringRelation
+ .select($"a", $"b", $"e", expensiveInt as "n")
+ .where($"n" > 1 && $"n" =!= 5)
+ .select($"a", $"b", $"e", expensiveRLike("other") as "g", $"n")
+ .where($"g" && ($"n" < 10 || raiseError))
+ .select($"a", $"n", $"g", expensiveRLike("third") as "j")
+ .where($"j")
+ .analyze
+
+ comparePlans(optimized, correctAnswer)
+ assert(filterConjuncts(optimized) === filterConjuncts(correctAnswer))
+ }
+
+ test("SPARK-60731: a non-deterministic condition shares no filter with the
conditions before " +
+ "or after it") {
+ val originalQuery = testStringRelation
+ .select($"a", expensiveRLike("magic") as "f", expensiveRLike("other") as
"g",
+ expensiveRLike("third") as "j")
+ .where($"f" && $"g" && (Rand(10) > 0.5 || $"f") && $"j")
+ .analyze
+
+ val optimized = Optimize.execute(originalQuery)
+
+ // The non-deterministic condition only needs f, but in the filter of g it
would be pushed
+ // below g in a later pass. It filters on its own after g instead.
+ val correctAnswer = testStringRelation
+ .select($"a", $"b", $"e", expensiveRLike("magic") as "f")
+ .where($"f")
+ .select($"a", $"b", $"e", $"f", expensiveRLike("other") as "g")
+ .where($"g")
+ .where(Rand(10) > 0.5 || $"f")
+ .select($"a", $"f", $"g", expensiveRLike("third") as "j")
+ .where($"j")
+ .analyze
+
+ comparePlans(optimized, correctAnswer)
+ assert(filterConjuncts(optimized) === filterConjuncts(correctAnswer))
+
+ // Nor does the condition after it join its filter, where a later pass
would move it ahead.
+ val afterQuery = testStringRelation
+ .select($"a", expensiveRLike("magic") as "f", expensiveRLike("other") as
"g",
+ expensiveRLike("third") as "j")
+ .where($"f" && $"g" && (Rand(10) > 0.5 || $"f") && ($"f" || $"g") &&
$"j")
+ .analyze
+ val afterOptimized = Optimize.execute(afterQuery)
+ val afterAnswer = testStringRelation
+ .select($"a", $"b", $"e", expensiveRLike("magic") as "f")
+ .where($"f")
+ .select($"a", $"b", $"e", $"f", expensiveRLike("other") as "g")
+ .where($"g")
+ .where(Rand(10) > 0.5 || $"f")
.where($"f" || $"g")
+ .select($"a", $"f", $"g", expensiveRLike("third") as "j")
+ .where($"j")
+ .analyze
+ comparePlans(afterOptimized, afterAnswer)
+ assert(filterConjuncts(afterOptimized) === filterConjuncts(afterAnswer))
+ }
+
+ test("SPARK-60731: a later pass does not push a condition past a
non-deterministic filter " +
+ "the split placed") {
+ val originalQuery = testStringRelation
+ .select($"a", expensiveRLike("magic") as "f", expensiveRLike("other") as
"g",
+ expensiveRLike("other2") as "h", expensiveRLike("third") as "j")
+ .where($"f" && (Rand(10) > 0.5 || $"g") && $"h" && ($"f" || $"g") &&
$"j")
+ .analyze
+
+ val optimized = Optimize.execute(originalQuery)
+
+ // (f || g) joins the filter of h, and a later pass pushes it below h, as
a cheap condition
+ // over the f and g computed below, but it stays after the
non-deterministic condition.
+ val correctAnswer = testStringRelation
+ .select($"a", $"b", $"e", expensiveRLike("magic") as "f")
+ .where($"f")
+ .select($"a", $"b", $"e", $"f", expensiveRLike("other") as "g")
+ .where(Rand(10) > 0.5 || $"g")
+ .where($"f" || $"g")
+ .select($"a", $"b", $"e", $"f", $"g", expensiveRLike("other2") as "h")
+ .where($"h")
+ .select($"a", $"f", $"g", $"h", expensiveRLike("third") as "j")
+ .where($"j")
+ .analyze
+
+ comparePlans(optimized, correctAnswer)
+ assert(filterConjuncts(optimized) === filterConjuncts(correctAnswer))
+
+ // Also when it does not read the alias computed with the
non-deterministic condition: it
+ // would otherwise go down to the filter of f.
+ val overF = testStringRelation
+ .select($"a", expensiveRLike("magic") as "f", expensiveRLike("other") as
"g",
+ expensiveRLike("other2") as "h", expensiveRLike("third") as "j")
+ .where($"f" && (Rand(10) > 0.5 || $"g") && $"h" && ($"f" || $"a" > 1) &&
$"j")
+ .analyze
+ val overFOptimized = Optimize.execute(overF)
+ val overFAnswer = testStringRelation
+ .select($"a", $"b", $"e", expensiveRLike("magic") as "f")
+ .where($"f")
+ .select($"a", $"b", $"e", $"f", expensiveRLike("other") as "g")
+ .where(Rand(10) > 0.5 || $"g")
+ .where($"f" || $"a" > 1)
+ .select($"a", $"b", $"e", $"f", $"g", expensiveRLike("other2") as "h")
+ .where($"h")
+ .select($"a", $"f", $"g", $"h", expensiveRLike("third") as "j")
+ .where($"j")
+ .analyze
+ comparePlans(overFOptimized, overFAnswer)
+ assert(filterConjuncts(overFOptimized) === filterConjuncts(overFAnswer))
+ }
+
+ test("SPARK-60731: a non-deterministic condition left above the split
filters on its own") {
+ // (g != j) needs every expensive alias not computed yet, so it ends the
split. In one top
+ // filter, a later pass would push the non-deterministic condition below
the projection, as a
+ // cheap condition over the f computed below, ahead of (g != j).
+ val originalQuery = testStringRelation
+ .select($"a", expensiveRLike("magic") as "f", expensiveRLike("other") as
"g",
+ expensiveRLike("third") as "j")
+ .where($"f" && Not($"g" === $"j") && (Rand(10) > 0.5 || $"f"))
+ .analyze
+ val optimized = Optimize.execute(originalQuery)
+ val correctAnswer = testStringRelation
+ .select($"a", $"b", $"e", expensiveRLike("magic") as "f")
+ .where($"f")
+ .select($"a", $"f", expensiveRLike("other") as "g",
expensiveRLike("third") as "j")
+ .where(Not($"g" === $"j"))
+ .where(Rand(10) > 0.5 || $"f")
+ .analyze
+ comparePlans(optimized, correctAnswer)
+ assert(filterConjuncts(optimized) === filterConjuncts(correctAnswer))
+
+ // Here the non-deterministic condition itself ends the split, and the
condition after it
+ // does not move ahead of it, into the filter of n > 1.
+ val expensiveInt = If(expensiveRLike("magic"), $"a", $"b")
+ val afterQuery = testStringRelation
+ .select($"a", expensiveInt as "n", expensiveRLike("other") as "g",
+ expensiveRLike("third") as "j")
+ .where($"n" > 1 && (Rand(10) > 0.5 || Not($"g" === $"j")) && $"n" < 10)
+ .analyze
+ val afterOptimized = Optimize.execute(afterQuery)
+ val afterAnswer = testStringRelation
+ .select($"a", $"b", $"e", expensiveInt as "n")
+ .where($"n" > 1)
+ .select($"a", $"n", expensiveRLike("other") as "g",
expensiveRLike("third") as "j")
+ .where(Rand(10) > 0.5 || Not($"g" === $"j"))
+ .where($"n" < 10)
+ .analyze
+ comparePlans(afterOptimized, afterAnswer)
+ assert(filterConjuncts(afterOptimized) === filterConjuncts(afterAnswer))
+
+ // Nor do two non-deterministic conditions share a filter: the second,
which only reads the f
+ // computed below, would be pushed below the first.
+ val twoQuery = testStringRelation
+ .select($"a", expensiveRLike("magic") as "f", expensiveRLike("other") as
"g",
+ expensiveRLike("third") as "j")
+ .where($"f" && (Rand(1) > 0.5 || Not($"g" === $"j")) && (Rand(2) > 0.5
|| $"f"))
+ .analyze
+ val twoOptimized = Optimize.execute(twoQuery)
+ val twoAnswer = testStringRelation
+ .select($"a", $"b", $"e", expensiveRLike("magic") as "f")
+ .where($"f")
+ .select($"a", $"f", expensiveRLike("other") as "g",
expensiveRLike("third") as "j")
+ .where(Rand(1) > 0.5 || Not($"g" === $"j"))
+ .where(Rand(2) > 0.5 || $"f")
+ .analyze
+ comparePlans(twoOptimized, twoAnswer)
+ assert(filterConjuncts(twoOptimized) === filterConjuncts(twoAnswer))
+ }
+
+ test("SPARK-60731: a condition needing every expensive alias not computed
yet ends the " +
+ "split") {
+ val raiseError = IsNull(RaiseError(Literal("boom")))
+ // (g != j) needs g and j, so the split ends there. The conditions left
above share one
+ // filter, as they are deterministic, also when one is throwable; a later
pass does not push
+ // the throwable one below (g != j), even in the last case, where it only
reads the f
+ // computed below. Each can fail, and so can the regexes here, whose
patterns are not
+ // literals, so it is not filtered on below (g != j) (see the next tests).
+ Seq[Expression]($"j" || raiseError, $"f" || raiseError).foreach { after =>
+ val originalQuery = testStringRelation
+ .select($"a", expensiveRLike("magic") as "f", expensiveRLike("other")
as "g",
+ expensiveRLike("third") as "j")
+ .where($"f" && Not($"g" === $"j") && after)
+ .analyze
+ val optimized = Optimize.execute(originalQuery)
+ val correctAnswer = testStringRelation
+ .select($"a", $"b", $"e", expensiveRLike("magic") as "f")
+ .where($"f")
+ .select($"a", $"f", expensiveRLike("other") as "g",
expensiveRLike("third") as "j")
+ .where(Not($"g" === $"j") && after)
+ .analyze
+ comparePlans(optimized, correctAnswer)
+ assert(filterConjuncts(optimized) === filterConjuncts(correctAnswer))
+ }
+ }
+
+ test("SPARK-60731: the conditions after the one that ends the split that
cannot fail are " +
+ "filtered on below it") {
+ // RLIKE with a literal pattern cannot fail, and version 0 of the estimate
treats it as
+ // expensive.
+ withSQLConf(SQLConf.REGEX_PATTERN_COST_ESTIMATE_VERSION.key -> "0") {
+ val (f, g, j) = (literalRLike("^1"), literalRLike("^2"),
literalRLike("^3"))
+ def query(cond: Expression): LogicalPlan = testStringRelation
+ .select($"a", f as "f", g as "g", j as "j")
+ .where(cond)
+ .analyze
+ def check(optimized: LogicalPlan, correctAnswer: LogicalPlan): Unit = {
+ comparePlans(optimized, correctAnswer.analyze)
+ assert(filterConjuncts(optimized) ===
filterConjuncts(correctAnswer.analyze))
+ }
+
+ // `f AND g != j AND j` (example 3 of the review): (g != j) ends the
split, and j is
Review Comment:
nit. `(example 3 of the review)` here and `(example 2 of the review)` below
refer to a review comment of this PR, which a reader of the code cannot find.
How about dropping them? The rest of each comment already describes the case.
--
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]