dongjoon-hyun commented on code in PR #60351:
URL: https://github.com/apache/spark/pull/60351#discussion_r4604716770
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -3103,53 +3192,137 @@ 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.
+ 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
+ * with a literal pattern of at most 100 characters (UTF-16 code units) that
is null or compiles,
+ * for RLIKE without `(`, `\` or `{`, which version 0 of the regex pattern
cost estimate treats
+ * as expensive (SPARK-60731). This is not `Expression.isTotal` of LIKE and
RLIKE, which would
+ * also apply to the other rules reading it and promise more than not
failing.
+ */
+ private def cannotFail(e: Expression): Boolean = e match {
+ case r: Like => cannotFailPattern(r) && cannotFail(r.left)
+ case r: RLike => cannotFailPattern(r) && cannotFail(r.left)
+ case _ if e.children.isEmpty => ExprUtils.canEvaluateUnconditionally(e)
+ case _ => e.deterministic && ExprUtils.isTotalOperator(e) &&
e.children.forall(cannotFail)
Review Comment:
`cannotFail` re-implements the recursion of
`ExprUtils.canEvaluateUnconditionally`, but only a leaf goes through its
`PLAN_EXPRESSION` check: a node with children is accepted with `e.deterministic
&& isTotalOperator(e)` alone. It works now only because a subquery expression
with children, e.g. a correlated one, is not total; if one declares `NoThrow`
in the future, this would accept it silently. Could we check
`!e.containsPattern(PLAN_EXPRESSION)` on the whole tree once, as
`canEvaluateUnconditionally` does?
In addition, `cannotFailPattern` is the counterpart of `isExpensivePattern`
(both judge a constant pattern), and it repeats the
`Pattern.compile(escape(str), collationRegexFlags)` of
`StringRegexExpression.compile`. How about a `lazy val` in
`StringRegexExpression` next to `_expensivePattern`? As it is not `isTotal`,
the other rules are not affected, and the pattern is compiled once per
expression instead of on every call here.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2721,24 +2728,15 @@ 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. The cheap conditions this
rule pushes below
+ // the projection (cases 1 and 2), non-deterministic ones included,
run before all of
Review Comment:
The description says that, as before and as with the split off, a condition
over no expensive alias, deterministic or not, is pushed below every expensive
condition, e.g. `rand(10) > 0.5` in `f AND rand(10) > 0.5`. So, after this PR,
the position of a non-deterministic condition depends on whether it reads an
expensive alias: `rand(10) > 0.5` in `f >= 50 AND rand(10) > 0.5` is evaluated
on every row, while `rand(10) > 0.5 OR h < 0` in `f >= 50 AND (rand(10) > 0.5
OR h < 0)` is evaluated only on the rows `f >= 50` keeps, as written.
According to your reply to my previous comment, SPARK-61662 will stop
`splitPushable` (and `CombineFilters`) from moving the conjuncts written after
a non-deterministic one ahead of it. Could it also cover this shape, i.e., keep
a non-deterministic conjunct itself above when a conjunct written before it
cannot be pushed? Then both shapes would be evaluated in the written order.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -3103,53 +3192,137 @@ 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.
+ val notComputed = AttributeMap(aliasMap.toSeq.filterNot { case (attr,
_) =>
Review Comment:
nit. `notComputed` is built whenever a deterministic head ends the split,
also when `following` is empty, e.g. when the head is the last condition, where
it is not used. This branch also runs again in the later iterations of the
batch, where the top filter no longer changes. How about making it a `lazy
val`? Likewise, `cannotFail` compiles the regex pattern on every call (see the
comment on `cannotFail`).
--
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]