LuciferYang commented on code in PR #55579:
URL: https://github.com/apache/spark/pull/55579#discussion_r4505534495


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/RuntimePartitionPruningFileScan.scala:
##########
@@ -0,0 +1,108 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.spark.sql.execution.datasources.v2
+
+import java.util.Locale
+
+import scala.util.control.NonFatal
+
+import org.apache.spark.SparkException
+import org.apache.spark.sql.catalyst.expressions.{Attribute, BoundReference, 
Expression, Predicate}
+import org.apache.spark.sql.connector.expressions.{FieldReference, 
NamedReference}
+import org.apache.spark.sql.connector.read.InputPartition
+import org.apache.spark.sql.execution.datasources.FilePartition
+import org.apache.spark.sql.internal.connector.SupportsRuntimeCatalystFiltering
+import org.apache.spark.util.TransientBestEffortLazyVal
+
+/**
+ * A [[FileScan]] that prunes its partition directories with the runtime 
filters Spark derives over
+ * its partition columns (SPARK-30628). The built-in file formats mix this in.
+ *
+ * Both read paths start from one listing of the file index and split and pack 
the files they
+ * keep through `filePartitions`, so `partitions` and `planInputPartitions()` 
are final here. A
+ * scan that reports a partitioning or an ordering should not mix this in.
+ */
+trait RuntimePartitionPruningFileScan extends FileScan with 
SupportsRuntimeCatalystFiltering {
+
+  /**
+   * The file index listing and its packing, each taken once per scan so 
planning and execution
+   * read one snapshot. A `lazy val` would compute them while holding the 
scan's monitor.
+   */
+  private val listing = new TransientBestEffortLazyVal(() =>
+    fileIndex.listFiles(partitionFilters, dataFilters))
+
+  private val allPartitions = new TransientBestEffortLazyVal(() => 
filePartitions(listing()))
+
+  // Final so that a subclass of a built-in scan cannot change one read path 
without the other.
+  final override protected def partitions: Seq[FilePartition] = allPartitions()
+
+  final override def planInputPartitions(): Array[InputPartition] = 
allPartitions().toArray
+
+  /**
+   * The read partition columns that `readSchema()` still exposes; a 
pushed-down aggregate keeps
+   * only the ones it groups by. None is declared fully pushed, so a scalar 
subquery filter over
+   * them is evaluated again above the scan.
+   */
+  override def filterAttributes(): Array[NamedReference] = {

Review Comment:
   Done in c1ba7eacfd7 and fd6f5adfc85. 
`RowLevelOperationRuntimeGroupFiltering` skips a group-based operation whose 
scan is a `RuntimePartitionPruningFileScan`, as on master, and the trait's 
scaladoc says why. A delta-based operation still gets the group filter, since 
its write does not depend on which groups were read. "no group filter for a 
group-based row-level operation over a built-in file scan" runs the rule on a 
`ReplaceData` over such a scan and expects it unchanged.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PushDownUtils.scala:
##########
@@ -293,11 +347,21 @@ object PushDownUtils extends Logging {
       output: Seq[AttributeReference],
       keyedPartitioning: Option[KeyedPartitioning],
       originalPartitions: => Seq[InputPartition]): Seq[Option[InputPartition]] 
= {
-    val filtered = pushRuntimeFilters(scan, runtimeFilters, table, output)
+    val (filtered, newPartitions) = scan match {
+      // A Catalyst scan is asked even when screening leaves no filter, unless 
it also implements
+      // SupportsRuntimeV2Filtering, which pushRuntimeFilters rejects, or 
declares only the
+      // deprecated `filter`, which pushRuntimeFilters calls as Spark 4.3 did.
+      case catalystScan: SupportsRuntimeCatalystFiltering
+          if runtimeFilters.nonEmpty && 
!catalystScan.isInstanceOf[SupportsRuntimeV2Filtering] &&
+            !implementsOnlyDeprecatedFilter(catalystScan) =>

Review Comment:
   Done in c1ba7eacfd7, as you suggested. The scaladoc of `filter` and the 
description say that a Scala scan recompiled against this version should 
implement `planInputPartitionsWithRuntimeFilters`, since it otherwise plans 
again when screening removes every runtime filter. The comments on 
`LegacyFilterScan` and at L576 say that this Scala fixture takes the general 
path.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PushDownUtils.scala:
##########
@@ -230,48 +238,92 @@ object PushDownUtils extends Logging {
 
         translatedFiltersPushed || partPredicatesPushed
 
-      case catalystScan: SupportsRuntimeCatalystFiltering if 
pushableFilters.nonEmpty =>
-        // A runtime filter is normally evaluated twice: the source prunes 
with it, and the
-        // FilterExec above the scan applies it again. The two have to agree, 
so this screen
-        // pushes only predicates the source can be trusted to evaluate in 
Spark's place.
-        //
-        // But pushing a non-deterministic one would let the source prune on 
its own coin flip and
-        // Spark flip again for the rows that survive, so we handle that 
specially.
-        //
-        // Not pushing a filter is safe only while its FilterExec still 
evaluates it. A fully
-        // pushed filter has none, so the source is its only evaluator. That 
is why
-        // DataSourceV2Strategy deletes a FilterExec at planning time only for 
a filter we push
-        // below, and we use the same method (isPushablePartitionFilter) to 
determine if we
-        // should push it.
-        //
-        // A DPP filter degrades to TrueLiteral once its subquery is pruned 
away, so it matches
-        // every row. The V2 path above drops these implicitly, since 
translateRuntimeFilterV2
-        // returns None; here we push Catalyst expressions directly, so we 
remove them explicitly.
-        val catalystFilters = pushableFilters
-          .flatMap(unwrapRuntimeFilterExpression)
-          .filterNot(_ == Literal.TrueLiteral)
-        if (catalystFilters.nonEmpty) {
-          catalystScan.filter(catalystFilters.toArray)
-          true
-        } else {
-          false
+      case catalystScan: SupportsRuntimeCatalystFiltering
+          if runtimeFilters.nonEmpty && 
implementsOnlyDeprecatedFilter(catalystScan) =>
+        filterWithDeprecatedMethod(catalystScan, runtimeFilters, output)
+
+      case catalystScan: SupportsRuntimeCatalystFiltering =>
+        // Resolved only when a filter could be fully pushed, so a node with 
no such filter does
+        // not ask the scan.
+        lazy val fullyPushedAttrs = 
V2ExpressionUtils.resolveDataSourceRuntimeFilterRefs(
+          catalystScan.fullyPushedFilterAttributes(),
+          output,
+          "fullyPushedFilterAttributes()",
+          catalystScan.getClass.getName)
+        val evaluatedOnlyByScan =
+          runtimeFilters.filter(isFullyPushedRuntimeFilter(_, 
fullyPushedAttrs))
+        if (evaluatedOnlyByScan.nonEmpty) {
+          throw SparkException.internalError(
+            s"${scan.getClass.getName} fully evaluates the runtime filters " +
+            s"${evaluatedOnlyByScan.mkString(", ")}, so they must go through " 
+
+            "PushDownUtils.replanWithRuntimeFilters, not pushRuntimeFilters.")
         }
+        false
 
       case _ =>
         false
     }
   }
 
+  /**
+   * Screens runtime filters for a [[SupportsRuntimeCatalystFiltering]] scan 
and unwraps them to the
+   * Catalyst predicates the scan plans with, untranslated.
+   *
+   * A filter is kept only if it references attributes the scan declared 
filterable and passes
+   * `isPushablePartitionFilter`, the check `DataSourceV2Strategy` uses to 
drop a pushed filter's
+   * `FilterExec`. A DPP filter degraded to true is removed, as the V2 path 
does by not translating
+   * it.
+   */
+  private def catalystRuntimeFilters(
+      scan: SupportsRuntimeCatalystFiltering,
+      runtimeFilters: Seq[Expression],
+      output: Seq[AttributeReference]): Seq[Expression] = {
+    val filterAttrs = V2ExpressionUtils.resolveDataSourceRuntimeFilterRefs(
+      scan.filterAttributes(),
+      output,
+      "filterAttributes()",
+      scan.getClass.getName)
+    runtimeFilters
+      .filter(f => f.references.subsetOf(filterAttrs))
+      .filter(isPushablePartitionFilter(_, includeSubquery = true))
+      .flatMap(unwrapRuntimeFilterExpression)
+      .filterNot(_ == Literal.TrueLiteral)
+  }
+
+  /**
+   * Whether `scan` gets `planInputPartitionsWithRuntimeFilters` from the 
default in
+   * [[SupportsRuntimeCatalystFiltering]], such as a class compiled against 
Spark 4.3 or a Java
+   * class implementing the trait directly that overrides only `filter`. A 
Scala class that mixes in
+   * the trait gets a forwarder, so it and its subclasses take the general 
path.
+   */
+  private def implementsOnlyDeprecatedFilter(scan: 
SupportsRuntimeCatalystFiltering): Boolean =
+    scan.getClass.getMethod("planInputPartitionsWithRuntimeFilters", 
classOf[Array[Expression]])

Review Comment:
   Done in c1ba7eacfd7. The lookup is behind a `ClassValue`, as in 
`CodeGenerator.leavesGenCodeToExpression`. A `LinkageError` answers false, and 
so does any non-fatal exception, since a class loader may reject a class with a 
`RuntimeException` that `getMethods` passes through unwrapped. Such a scan then 
takes the general path, whose default still calls `filter` when a filter 
survives screening. "a scan whose public methods cannot all be resolved still 
gets its runtime filters" loads a Java scan through a loader that refuses a 
class in one of its signatures, once with `ClassNotFoundException` and once 
with `IllegalStateException`.



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