sarutak commented on code in PR #60351:
URL: https://github.com/apache/spark/pull/60351#discussion_r4626214542
##########
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:
Thank you, I ran it. After merging master, it fails with
`FAILED_EXECUTE_UDF` with the split on, with and without whole-stage codegen,
as on master, and returns 4 rows with the split off and codegen. You are right
that the deferral read such an alias as a column that cannot fail, and a later
pass of the split did so too, where the aliases computed in a lower layer are
columns below the projection. I changed the check as you suggested: a condition
after the one that ends the split is now judged with every alias of the
projection inlined, computed or not, and must not read, with them inlined, a
column below the projection that can fail, also through a cheap alias of the
projection. For the columns below, it uses a new `failableOutputWith`, which is
`failableOutput` with `cannotFail` in place of `canEvaluateUnconditionally`, so
that a regex that `cannotFail` accepts is not counted; `failableOutput` now
calls it with `canEvaluateUnconditionally`. I first tried the less conservative
ch
eck, rejecting only a computed alias that no filter below reads, but it only
holds within one application of the rule: in the later passes such an alias is
a column below the projection, and on the first version `(f2 > 0 OR j)` below
was still filtered on below `g != j` in the whole batch. So `(NOT j OR f)`,
with a UDF alias `f` that the layer below filters on, now stays above too,
although `f` is already computed there. New cases of the test "the conditions
after the one that ends the split are not filtered on below it when something
there can fail, ..." check, in the whole batch, that `(f2 > 0 OR j)`, over a
UDF alias computed with `g2` because they share work, `(NOT j OR f)`, and `(x
OR j)` with `x` a cheap alias of `f2 > 0` stay above `g != j`. Cases of the
test "the conditions after the one that ends the split that cannot fail are
filtered on below it" check that `(j OR f)` with a regex `f` computed in a
projection below, also two projections below or on one side of a join, or
with the regex result of an aggregation below, is still filtered on below it.
A new part of the `DataFrameSuite` test "a condition that cannot fail written
after the one that ends the split is evaluated before it" checks that `g2 >= 0
AND g != j AND (f2 > 0 OR j)` returns its 11 rows with whole-stage codegen,
with the split on and off, both when the split computes `f2` with `g2` and when
the query computes it in a projection below.
However, your query still fails with the split on, as these changes do not
change its plan: after the split, a later pass pushes `f > 0`, which reads `f`
as a column of the projection below, below the top projection ahead of `j + k >
10`, and `CombineFilters` merges it into the filter of `g >= 0`. Your query
passes with the split off and codegen, so the split exposes it there, but the
same push happens without the split when the projections are written that way:
```scala
spark.range(0, 10, 1, 1)
.select($"id", s($"id") as "g", req(s($"id")) as "f")
.where($"g" >= 0)
.select($"id", $"g", $"f", j($"id") as "j", k($"id") as "k")
.where($"j" + $"k" > 10 && $"f" > 0)
```
returns 4 rows on 4.0.0 and 4.1.4 and fails with `FAILED_EXECUTE_UDF` on
4.2.0, 4.2.1, 4.3.0 and master, with and without codegen, since
`avoidDoubleFilterEval` in 4.2.0 pushes `f > 0` alone: with it off, 4.2.0
returns 4 rows too. As you wrote, SPARK-60730 as planned would not catch it,
since `f > 0` itself is total; it needs the projection case of
`PushPredicateThroughNonJoin` to keep a condition over a column of its child
that can fail where it is, also after a deterministic condition that is not
throwable, which `splitMovable` does not cover either. I filed SPARK-62077 for
it and, as for SPARK-60730, I plan to get it into the same release as the
split. I updated the docstring and the test comment accordingly: the layer
itself only drops rows earlier, and a later pass can still push a condition
over an alias computed in a lower layer that can fail (SPARK-62077).
##########
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:
Thank you, you are right. After merging master, no `isnotnull` is inferred
for these queries, and I re-measured. On master, `(rand(10) > 0.5 OR h < 0) AND
f >= 50` returns 28 rows with the split on and 26 with it off, and `(rand(10) >
0.5 OR f < 0) AND h >= 50 AND f >= 50` returns 20 and 21. With this PR, they
return 26 and 21 with the split on and off, with and without codegen, which is
the written order. `(rand(10) > 0.5 OR f + h < 0) AND f >= 50` now returns 26
in every configuration with this PR, and 28 with the split on on master. No
`isnotnull` is inferred over a column that can fail now, also with the legacy
flag, which only affects whether the inferred condition itself can fail, so the
shape of the earlier comment no longer arises at this filter. I updated the
comment and the description, removed the reference to SPARK-61378, and the test
now checks that the split keeps the written order with null results and that
the split-off plan returns the same rows.
##########
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:
Thank you, updated. The docstring no longer gives `CombineFilters` as a
reason for the separate filters of non-deterministic conditions, only this
rule, and the comment on `cannotFail` refers to `splitMovable`. On using
`failableOutput` in the deferral, please see my reply on the other comment.
##########
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:
Thank you, done: the loop ends after a deferred layer. I checked the three
cases against the code and agree, with one detail for the third: a throwable
alias that shares a Python UDF with an alias a condition needs is pulled into
its unit, so the alias left that shares work is a throwable one sharing no
Python UDF with it, which is never pulled into the unit of a condition that
does not read it. A mutant that keeps looping passes every
`FilterPushdownSuite` test.
##########
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:
Thank you, added `SPARK-60731: patterns that cannotFailPattern accepts match
a long input` to `RegexpExpressionsSuite`: `.*a.*` with RLIKE and `%a%_` with
LIKE over 2^20 supplementary characters (4 MB) on each side of the match, also
with `UTF8_LCASE`, with `checkEvaluation`, which evaluates them interpreted,
with codegen and after optimization.
##########
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:
Thank you, removed.
--
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]