sarutak commented on code in PR #60351:
URL: https://github.com/apache/spark/pull/60351#discussion_r4608959501


##########
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:
   Yes, I will add this shape to the scope of SPARK-61662: keep a 
non-deterministic conjunct above when a conjunct written before it cannot be 
pushed, in `splitPushable`. (`CombineFilters` already keeps a non-deterministic 
conjunct where it is; its part of SPARK-61662 is the conjuncts written after 
one.) It has a cost to weigh there: in `f >= 50 AND rand(10) > 0.5`, the 
projection then computes `f` on every row instead of on the rows `rand(10) > 
0.5` keeps, also with the split off. That is the order of 4.1: I checked the 
plans of `f AND rand(10) > 0.5`, with `f` an RLIKE and a Scala UDF, on 4.1.4, 
where the whole filter is pushed below the projection with `f` inlined and 
`rand(10) > 0.5` after it, and on 4.2.0, where `rand(10) > 0.5` is pushed below 
the projection ahead of `f`, since `spark.sql.optimizer.avoidDoubleFilterEval` 
(4.2.0, on by default); with it off, 4.2.0 gives the 4.1.4 plans. So it would 
likely go behind the legacy config that SPARK-61662 needs for `splitPushable`, 
an
 d I will compare there the plans and the number of rows `f` is computed on.
   



##########
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:
   Thank you, done. `notComputed` is a `lazy val` now, so it is not built when 
`following` is empty. When it is not, it is still built each time the split 
reaches this branch, which can be more than once in one pass, and so is the 
inlined condition. The pattern check is now a `lazy val` of the regex 
expression (see the reply on `cannotFail`), so it runs once per expression 
instance instead of on every call; a regex in a condition that inlining an 
alias rebuilds is a new instance, which checks its pattern again.
   



##########
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:
   Thank you, done in both. `cannotFail` no longer re-implements the recursion: 
it calls a new `ExprUtils.canEvaluateUnconditionallyWith(e, 
operatorCannotFail)`, which checks `e.deterministic && 
!e.containsPattern(PLAN_EXPRESSION)` on the whole tree once and then recurses 
as `canEvaluateUnconditionally` did, also accepting an operator that the given 
function accepts, with its children checked as those of a total operator. 
`canEvaluateUnconditionally` now calls it with a function that accepts nothing, 
so its result does not change. `ExprUtilsSuite` checks that even when every 
operator is accepted, a non-deterministic tree or one with a subquery is not. I 
also added a case to the test "the conditions after the one that ends the split 
are not filtered on below it when something there can fail, ...": an alias with 
a test-only expression that has a child, declares `NoThrow` and carries the 
`PLAN_EXPRESSION` pattern is not computed in the layer below the condition that 
ends the split; with
 out the whole-tree check, it is.
   
   The pattern check is now `StringRegexExpression.cannotFailPattern`, a `final 
lazy val` next to `_expensivePattern`. It calls `compile` instead of repeating 
`Pattern.compile(escape(str), collationRegexFlags)`, and the restriction on the 
pattern for the stack is a `protected def isStackSafePattern`, `false` by 
default, which `Like` and `RLike` override. It is `private[catalyst]` and not 
`isTotal`, so the other rules are not affected.
   



-- 
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]

Reply via email to