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


##########
sql/core/src/test/scala/org/apache/spark/sql/DataFrameSuite.scala:
##########
@@ -2978,6 +2978,121 @@ 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 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)
+    }
+  }
+
+  test("SPARK-60731: a throwable alias sharing work with an earlier 
condition's alias is " +
+    "computed above that condition's filter") {
+    // t shares gt5 with f, but is not computed with f: with the split on, it 
is computed above
+    // the filter on f, in the layer of its reader or, when no condition reads 
it, in the
+    // projection on top, so without codegen it does not raise on the rows f 
drops. With the split
+    // off, the single interpreted projection computes it on every row and 
raises.
+    val gt5Calls = sparkContext.longAccumulator("gt5Calls")
+    val gt5 = udf((i: Long) => {
+      gt5Calls.add(1)
+      i > 5
+    })
+    def query(readsT: Boolean): DataFrame = spark.range(0, 10, 1, 1)
+      .select($"id", gt5($"id") as "f",
+        when(gt5($"id"), lit(true)).otherwise(raise_error(lit("boom")).isNull) 
as "t")
+      .where(if (readsT) $"f" && $"t" else $"f")
+    for (readsT <- Seq(true, false); codegen <- Seq(true, false); split <- 
Seq(true, false)) {
+      withSQLConf(
+        SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> codegen.toString,
+        SQLConf.SPLIT_PROJECTION_FOR_EXPENSIVE_FILTERS.key -> split.toString) {
+        gt5Calls.reset()
+        if (codegen || split) {
+          assert(query(readsT).collect().toSeq === (6L until 10L).map(i => 
Row(i, true, true)))
+          // With the split, gt5 runs for f on every row and again for t on 
the rows f keeps,
+          // also with codegen. Computing it only once is the subject of 
SPARK-61515.
+          if (split) assert(gt5Calls.value === 14)

Review Comment:
   Done: the `DataFrameSuite` test now asserts `(10L to 
14L).contains(gt5Calls.value)`, with a comment that SPARK-61515 is to bring it 
down to 10. In `FilterPushdownSuite`, the Python UDF test no longer expects the 
second run: with your other suggestion, a throwable alias sharing a Python UDF 
is computed with the alias sharing it, and the test checks that the Python UDF 
is in one projection. The plan tests of a throwable alias sharing a regex still 
have the second run in their expected plans, as a plan test has to state the 
plan; their comments say that SPARK-61515 would change them.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -3017,32 +3030,64 @@ object PushPredicateThroughNonJoin extends 
Rule[LogicalPlan] with PredicateHelpe
    * }}}
    * so `rlike(e, 'other')` only runs on the rows where `rlike(e, 'magic')` 
was true.
    *
-   * Conditions are grouped by the aliases they reference, then the group 
needing the fewest
-   * not-yet-computed aliases is split off first -- least demanding first 
keeps the expensive
-   * expressions as high in the stack, and so over as few rows, as we can 
manage. On a tie, the
-   * group making the most conditions evaluable wins, falling back to the 
condition written first
-   * (the only selectivity signal we have). Whole-stage codegen already defers 
a projected
-   * expression past a filter that does not need it 
(`CodegenSupport.evaluateRequiredVariables`),
-   * so this rule only buys the same saving on the paths codegen does not 
cover -- interpreted
-   * projections, operators it bails out of, Python UDFs.
+   * The conditions are placed in the order they are written (SPARK-60731): 
each layer computes
+   * the aliases the next condition needs and filters on it and, when it is 
deterministic, on the
+   * deterministic conditions right after it that only need aliases computed 
already. A
+   * non-deterministic condition gets a filter of its own, which neither the 
conditions before it
+   * nor the ones after it join, and a layer that needs no new alias is a 
filter alone. So the
+   * split does not evaluate a condition, nor compute the aliases it needs, on 
rows the
+   * conditions written before it would have dropped. The exception: an alias 
that shares
+   * expensive work with one an earlier condition needs is computed together 
with it (see
+   * below), unless that alias is `throwable`. An expression that can fail 
without reporting
+   * `throwable`, such as a UDF or, in ANSI mode, a division by zero, can 
still be computed early
+   * this way.
    *
-   * Two restrictions keep the split from costing more than it saves:
+   * Later passes can still move a deterministic condition that is not 
throwable, including one
+   * calling a UDF that can fail, ahead of some of the conditions written 
before it: one that only
+   * reads aliases computed in a lower layer is cheap there, and this rule 
pushes it, as it does
+   * any cheap condition that is not throwable, no lower than the filter of 
the highest layer that
+   * computes an expensive alias it reads. It does not move past the filter of 
a non-deterministic
+   * condition, which `CombineFilters` does not merge into. So, when the split 
places at least one
+   * condition, the caller gives each non-deterministic condition it leaves 
above the projection a
+   * filter of its own too. The projection on top computes the aliases of the 
conditions left
+   * above it, as without the split.
+   *
+   * Whole-stage codegen already defers a projected expression past a filter 
that does not need
+   * it (`CodegenSupport.evaluateRequiredVariables`), so this rule only buys 
the same saving on
+   * the paths codegen does not cover -- interpreted projections, operators it 
bails out of,
+   * Python UDFs.
+   *
+   * Two restrictions keep the split from costing more than it saves, with one 
exception for

Review Comment:
   Done. The reason for the throwable-alias exception is given once, in the 
restriction bullet of the docstring; the other places state the rule and refer 
to it. The reason for the separate filters of non-deterministic conditions is 
now only in the docstring's paragraph on later passes, and the comments in the 
caller and in the split loop were reduced accordingly.
   



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/FilterPushdownSuite.scala:
##########
@@ -863,6 +1358,17 @@ class FilterPushdownSuite extends PlanTest {
     comparePlans(optimized, correctAnswer)
   }
 
+  // The conjuncts of every filter of `plan`, from the top, in their order, 
which `comparePlans`
+  // does not check. Unlike `assertTopFilterConjuncts`, it covers every 
filter, and normalizes the
+  // expression IDs, so it can compare two plans built separately. It compares 
the conjuncts as
+  // written, operands included. It does not canonicalize them: with every 
expression ID
+  // normalized, canonicalized attributes of the same type are equal, so `a > 
1` would match
+  // `b > 1`.
+  private def filterConjuncts(plan: LogicalPlan): Seq[Seq[Expression]] =

Review Comment:
   Done: `assertTopFilterConjuncts` now uses `filterConjuncts`, so both compare 
the conjuncts as written, with normalized expression IDs.
   



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