spark-test commented on code in PR #60696:
URL: https://github.com/apache/spark/pull/60696#discussion_r4624246515


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/dynamicpruning/PartitionPruning.scala:
##########
@@ -60,6 +60,9 @@ object PartitionPruning extends Rule[LogicalPlan] with 
PredicateHelper with Join
   def getFilterableTableScan(a: Expression, plan: LogicalPlan): 
Option[LogicalPlan] = {
     val srcInfo: Option[(Expression, LogicalPlan)] = 
findExpressionAndTrackLineageDown(a, plan)
     srcInfo.flatMap {
+      // The "Extract UDFs" batch evaluates such a UDF in a node of its own, 
between a DPP
+      // filter on this expression and the scan, so the scan could not prune 
with the filter.
+      case (resExp, _) if needsUDFExtraction(Seq(resExp)) => None

Review Comment:
   **Blocking (P1):** This case looks only at the head of 
findExpressionAndTrackAllLineagesDown, which for a union is the first branch 
whose key can be traced to a scan (predicates.scala:120-123, 152-154). If that 
branch computes the key as pyudf(store_id) and a later branch exposes a plain 
partition column, the whole union now gets no DPP filter. On the base branch 
the filter was inserted for that head lineage, the Union pushdown copied it 
into every branch (Optimizer.scala:2958-2987), and the plain branch pruned its 
partitions through the reused broadcast, as the SPARK-39217 test shows for a 
later plain branch (DynamicPartitionPruningSuite.scala:1984-2011).
   
   Reading the code, `SELECT f.date_id, f.store_id FROM (SELECT date_id, 
pyudf(store_id) AS store_id FROM fact_sk UNION ALL SELECT date_id, store_id 
FROM fact_stats) f JOIN dim_store s ON f.store_id = s.store_id WHERE s.country 
= 'NL'` pruned fact_stats on the base branch and now reads all of its 
partitions, while the same query with the two branches swapped keeps the 
pruning. The same holds for any later branch whose key needs no such UDF and 
traces to partition columns or to DSv2 runtime-filter attributes.
   
   One way to fix it: when the first lineage needs UDF extraction, keep the 
base branch's decision if a later lineage needs none and passes the 
per-relation checks, returning that branch's scan, and return None only when no 
branch could prune with the filter.
   
   **Verification:**
   - **Regression:** Join dim_store, filtered on country, to a union of a 
fact_sk branch that projects pyudf(store_id) as the key and a fact_stats branch 
that projects the plain store_id. Run it in both branch orders, in the V1, V2 
and Hive scan variants with adaptive execution on and off. Check that the 
fact_stats scan carries a dynamic pruning partition filter that reuses the 
broadcast, and that the rows match those of the query without dynamic partition 
pruning.
   - **Behavior:** Check that a union whose two branches both project the 
Python UDF of a partition column as the key gets no DPP filter, and that the 
single-scan Python and external UDF keys still get none.



##########
sql/core/src/test/scala/org/apache/spark/sql/DynamicPartitionPruningSuite.scala:
##########
@@ -2009,6 +2010,55 @@ abstract class DynamicPartitionPruningSuiteBase
       
assert(collectDynamicPruningExpressions(df.queryExecution.executedPlan).size 
=== 1)
     }
   }
+
+  // These tests drop their function themselves, as `withUserDefinedFunction` 
checks the drop with
+  // a lookup that fails in the V2 suites, whose default catalog has no 
functions.
+  test("SPARK-62052: no DPP filter on a pruning key with a Python UDF") {

Review Comment:
   **Nit (P3):** The new tests only assert the declining direction 
(DynamicPartitionPruningSuite.scala:2029-2031 and 2054-2056), and the 
SPARK-61824 tests put their UDFs on the filtering side. A pruning side that 
applies pyudf to a column other than the join key, such as `SELECT f.d, 
f.store_id FROM (SELECT pyudf(date_id) AS d, store_id FROM fact_sk) f JOIN 
dim_store s ON f.store_id = s.store_id WHERE s.country = 'NL'`, must keep its 
DPP partition filter, but nothing checks that, so a check widened to the 
pruning plan's expressions would drop that pruning with no test failing. 
Consider adding that case to this test and asserting that the fact_sk scan 
keeps a dynamic pruning partition filter that reuses the broadcast.
   
   **Verification:**
   - **Behavior:** Run the new query and check that its pruned scan carries a 
dynamic pruning partition filter reusing the broadcast and that its rows match 
those of the query without dynamic partition pruning.
   - **Regression:** Temporarily make the UDF check test the pruning plan's 
expressions instead of the key's lineage, and confirm that the new assertion 
fails.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/dynamicpruning/PartitionPruning.scala:
##########
@@ -60,6 +60,9 @@ object PartitionPruning extends Rule[LogicalPlan] with 
PredicateHelper with Join
   def getFilterableTableScan(a: Expression, plan: LogicalPlan): 
Option[LogicalPlan] = {
     val srcInfo: Option[(Expression, LogicalPlan)] = 
findExpressionAndTrackLineageDown(a, plan)
     srcInfo.flatMap {
+      // The "Extract UDFs" batch evaluates such a UDF in a node of its own, 
between a DPP
+      // filter on this expression and the scan, so the scan could not prune 
with the filter.
+      case (resExp, _) if needsUDFExtraction(Seq(resExp)) => None

Review Comment:
   **Non-blocking (P2):** Besides pruning nothing, the DPP filter this case 
removes was a row filter over the reused broadcast, and pushdown placed it 
below the fact side's other work, such as another UDF column, a lower join, a 
window or an aggregate on the key (Optimizer.scala:2836-2956, 3353). Without 
it, that work now runs on every fact row instead of the matching ones.
   
   For a key aliased in a subquery that can be null, the removed filter added 
no UDF evaluation on the base branch. At default settings it stays above the 
projection that evaluates the UDF once (Optimizer.scala:2836-2913, 3311-3325), 
and where pushdown substitutes the alias, as below an aggregate, it shares the 
evaluation of the null filter that the join infers on the key 
(Optimizer.scala:2393-2401, 2633-2647, 3057-3088; 
ExtractPythonUDFs.scala:302-306). So for such keys the PR saves only the 
filter's set lookups, and the claim that the UDF is evaluated once instead of 
twice holds for a key written with the UDF in the join condition. Reading the 
code, `SELECT f.date_id, f.u FROM (SELECT date_id, pyudf(store_id) AS store_id, 
other_udf(units_sold) AS u FROM fact_sk) f JOIN dim_store s ON f.store_id = 
s.store_id WHERE s.country = 'NL'` evaluated other_udf only on the rows of the 
NL stores on the base branch and now evaluates it on every fact row.
   
   Please state this trade-off in the PR description and in the comment on this 
check, and say which alternative you rejected and why.
   
   **Verification:**
   - **Inspection:** Read the PR description and the comment on the UDF check 
in getFilterableTableScan. Confirm that both state the lost row reduction under 
a broadcast join, limit the once-instead-of-twice claim to a key written with 
the UDF in the join condition and to an aliased key that pushdown substitutes 
when the join infers no null filter on it, and name the rejected alternative of 
testing the join key as written, which keeps the filter for a key aliased in a 
subquery, with the reason it was rejected.



##########
sql/core/src/test/scala/org/apache/spark/sql/DynamicPartitionPruningSuite.scala:
##########
@@ -2009,6 +2010,55 @@ abstract class DynamicPartitionPruningSuiteBase
       
assert(collectDynamicPruningExpressions(df.queryExecution.executedPlan).size 
=== 1)
     }
   }
+
+  // These tests drop their function themselves, as `withUserDefinedFunction` 
checks the drop with
+  // a lookup that fails in the V2 suites, whose default catalog has no 
functions.
+  test("SPARK-62052: no DPP filter on a pruning key with a Python UDF") {
+    import IntegratedUDFTestUtils._
+    assume(shouldTestPythonUDFs)
+    try {
+      registerTestUDF(TestPythonUDF("pyudf"), spark)
+      Seq(
+        "fact_sk f JOIN dim_store s ON pyudf(f.store_id) = s.store_id",
+        "(SELECT date_id, pyudf(store_id) AS store_id FROM fact_sk) f " +
+          "JOIN dim_store s ON f.store_id = s.store_id").foreach { join =>
+        val df = sql(s"SELECT f.date_id, f.store_id FROM $join WHERE s.country 
= 'NL'")
+        checkAnswer(df, Row(1000, 1) :: Row(1010, 2) :: Row(1020, 2) :: Nil)
+        // A scan cannot evaluate the UDF to prune partitions, so a DPP filter 
would only filter
+        // rows, above another evaluation of the UDF.

Review Comment:
   **Nit (P3):** For the aliased query 
(DynamicPartitionPruningSuite.scala:2023-2024), the base branch's DPP filter 
references the expensive alias store_id, so at default settings pushdown keeps 
it above the projection, which evaluates pyudf once and also feeds the join key 
(Optimizer.scala:2836-2913, 3311-3325). There is no other evaluation, so 
evals.size === 1 already passes on the base branch for that query, and only 
!checkUnpushedFilters(df) distinguishes the revisions. The second evaluation 
applies to the key written with the UDF in the join condition.
   
   ```suggestion
           // rows, and for a key written with the UDF, above another 
evaluation of it.
   ```
   
   **Verification:**
   - **Inspection:** Read the comment above the Python UDF test's assertions 
and confirm that it ties the second evaluation to the key written with the UDF 
in the join condition and makes no such claim for the aliased query.



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