dongjoon-hyun commented on code in PR #60351:
URL: https://github.com/apache/spark/pull/60351#discussion_r4660981411


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -3244,55 +3336,127 @@ 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, the 
rest, and whether it
+      // is the last layer.
+      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, false))
+      } 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)
+        // With every alias of the projection inlined, and over no column 
below it that can fail
+        // (see the docstring).
+        lazy val failableBelow = failableOutputWith(project.child, 
cannotFailInSplit)
+        val followingCannotFail = following.forall { idx =>
+          val inlined = replaceAlias(conds(idx)._2, aliasMap)
+          cannotFailInSplit(inlined) && 
!inlined.references.exists(failableBelow.contains)
+        }
+        val (deferred, deferredNeeded) = (if (followingCannotFail) following 
else Nil)

Review Comment:
   nit. `failableBelow` is a `lazy val`, but `followingCannotFail` forces it 
before the fold decides whether to take any condition, so this branch walks the 
plan below the projection also when the fold takes none. For example, with the 
RLIKE aliases of the tests under version 0, `f != g AND f AND g` becomes `f != 
g AND g` over a projection computing `g` after the first pass. In every later 
pass of the batch, the split comes back to this branch, inlines `g`, which 
`cannotFailInSplit` accepts, and computes `failableOutputWith(project.child, 
cannotFailInSplit)`, and then the fold takes nothing, as `g` would leave no 
expensive alias for a later layer. As `followingCannotFail` only gates the 
whole fold, how about running the fold first and checking `followingCannotFail` 
only when the fold takes a condition? 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:
##########
@@ -3014,6 +3014,231 @@ 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 too, the split keeps the 
non-deterministic condition
+    // ahead of the conditions written after it, so, with and without codegen, 
it returns the rows
+    // that evaluating the conditions as written gives: `rand(10)` sees every 
row, and the first
+    // condition holds where it is above 0.5. So does the split-off plan:
+    // `InferFiltersFromConstraints` infers no `isnotnull` check over a column 
that can fail
+    // (`failableOutput`, SPARK-61823), such as these.
+    val nullableF = udf((i: Long) => if (i % 7 == 3) null else 
java.lang.Long.valueOf(i))
+    val nullableH = udf((i: Long) => if (i % 5 == 1) null else 
java.lang.Long.valueOf(i))
+    def nullableDf: DataFrame = spark.range(0, 100, 1, 1)
+      .select($"id", nullableF($"id") as "f", nullableH($"id") as "h")
+    def nullableQueries: Seq[DataFrame] = Seq(
+      nullableDf.where((rand(10) > 0.5 || $"h" < 0) && $"f" >= 50),
+      nullableDf.where((rand(10) > 0.5 || $"f" < 0) && $"h" >= 50 && $"f" >= 
50))

Review Comment:
   Both filters write the non-deterministic condition first, so `rand(10)` sees 
every row with the split on and off. When a condition that can be NULL is 
written before it, the two evaluate `rand(10)` on different rows. Since 
SPARK-60315 (`spark.sql.legacy.filterShortCircuitOnNullConjunct`, `false` by 
default), a filter evaluates the remaining conjuncts after a NULL one, with and 
without whole-stage codegen, and only a `FALSE` one stops it, as the 
interpreted `And` does. For example, in `nullableDf.where($"f" >= 50 && 
(rand(10) > 0.5 || $"h" < 0))`:
   - With the split off, the one filter over the projection evaluates 
`rand(10)` on the rows where `f >= 50` is true or NULL, i.e. also on every id 
`i` with `i % 7 = 3`.
   - With the split on, the split computes `f` and filters on `f >= 50` in a 
filter of its own first, which drops the rows where `f` is null before 
`rand(10)` sees them.
   
   So `rand(10)` draws its values for other rows, and the two can return other 
rows. The separate filters of the non-deterministic conditions left above the 
projection (L2902-L2906 of `Optimizer.scala`) drop the rows the same way when a 
condition before them is NULL.
   
   As SQL evaluates `x` in `NULL AND x`, I think the split-off plan gives the 
rows of the written order here, and `which is what evaluating the conditions as 
written gives` in the PR description only holds when the non-deterministic 
condition comes first. Could you add such a case and either keep these rows 
with the split on or describe the difference in the docstring and the PR 
description? I checked this by reading the code only; I did not run it.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -3244,55 +3336,127 @@ 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, the 
rest, and whether it
+      // is the last layer.
+      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, false))
+      } 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)
+        // With every alias of the projection inlined, and over no column 
below it that can fail
+        // (see the docstring).
+        lazy val failableBelow = failableOutputWith(project.child, 
cannotFailInSplit)
+        val followingCannotFail = following.forall { idx =>
+          val inlined = replaceAlias(conds(idx)._2, aliasMap)
+          cannotFailInSplit(inlined) && 
!inlined.references.exists(failableBelow.contains)
+        }
+        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 => 
cannotFailInSplit(aliasMap(attr).child))) {
+              (taken + idx, grown)
+            } else {
+              (taken, unit)
+            }
+          }
+        Option.when(deferred.nonEmpty) {
+          val (inFilter, rest) = conds.indices.partition(deferred.contains)
+          // The head still ends the split after this layer, and no condition 
this layer leaves
+          // could join another one: the expensive aliases left only shrink, 
this layer computes
+          // no alias that can fail, and a throwable alias sharing no Python 
UDF with an alias a
+          // condition needs is never pulled into the unit of a condition that 
does not read it.
+          (deferredNeeded, inFilter.map(conds), rest.map(conds), true)
         }
-        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, last)) =>
+          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
+          searching = !last

Review Comment:
   nit. Where the loop ends is now expressed in three ways: `searching`, the 
`last` of `nextLayer`, and `pending.nonEmpty`. As the deferral branch is always 
the last step, either ending the loop (`None`) or adding the last layer (`last 
= true`), how about running it once after the loop? Then the loop only adds the 
layers before the condition that ends the split, the code adding a layer could 
be a local function used by both, and `searching`, `last` and the 4-tuple would 
no longer be needed.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -3244,55 +3336,127 @@ 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, the 
rest, and whether it
+      // is the last layer.
+      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, false))
+      } 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)
+        // With every alias of the projection inlined, and over no column 
below it that can fail
+        // (see the docstring).
+        lazy val failableBelow = failableOutputWith(project.child, 
cannotFailInSplit)
+        val followingCannotFail = following.forall { idx =>
+          val inlined = replaceAlias(conds(idx)._2, aliasMap)
+          cannotFailInSplit(inlined) && 
!inlined.references.exists(failableBelow.contains)

Review Comment:
   nit. This is the check of `PredicateHelper.splitMovable` 
(`ExprUtils.canEvaluateUnconditionally(cond) && 
!cond.references.exists(failable.contains)`) with `cannotFailInSplit` in place 
of `canEvaluateUnconditionally`, as `failableOutputWith` is `failableOutput` 
with it. How about a small helper in `PredicateHelper` that takes the check and 
is used by `splitMovable` and here? Then the deferral and `CombineFilters` 
follow one rule for a column that can fail, as discussed in 
https://github.com/apache/spark/pull/60351#discussion_r4624047152, and a change 
to that rule does not need to update two copies.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -3244,55 +3336,127 @@ 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, the 
rest, and whether it
+      // is the last layer.
+      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, false))
+      } 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)
+        // With every alias of the projection inlined, and over no column 
below it that can fail
+        // (see the docstring).
+        lazy val failableBelow = failableOutputWith(project.child, 
cannotFailInSplit)
+        val followingCannotFail = following.forall { idx =>
+          val inlined = replaceAlias(conds(idx)._2, aliasMap)
+          cannotFailInSplit(inlined) && 
!inlined.references.exists(failableBelow.contains)
+        }
+        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 => 
cannotFailInSplit(aliasMap(attr).child))) {
+              (taken + idx, grown)
+            } else {
+              (taken, unit)
+            }
+          }
+        Option.when(deferred.nonEmpty) {
+          val (inFilter, rest) = conds.indices.partition(deferred.contains)
+          // The head still ends the split after this layer, and no condition 
this layer leaves
+          // could join another one: the expensive aliases left only shrink, 
this layer computes
+          // no alias that can fail, and a throwable alias sharing no Python 
UDF with an alias a
+          // condition needs is never pulled into the unit of a condition that 
does not read it.
+          (deferredNeeded, inFilter.map(conds), rest.map(conds), true)
         }
-        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, last)) =>
+          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
+          searching = !last
       }
     }
-    (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:
   This docstring and the deferral tests over LIKE and RLIKE aliases consider 
version 0 of the regex pattern cost estimate: every one of those tests sets 
`REGEX_PATTERN_COST_ESTIMATE_VERSION` to `0`. However, with the default version 
1, a pattern that `cannotFailPattern` accepts and that the estimate counts as 
expensive also makes an expensive alias, e.g. LIKE `'%a%b%c%'` and RLIKE 
`'.*a.*b'`, which `RegexpExpressionsSuite` checks as expensive. So the deferral 
applies to them with the default configuration, and no test covers it. Could we 
add such a case under the default version, e.g. `f AND g != j AND j` with those 
patterns, and mention version 1 in this docstring?



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