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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/connector/SupportsRuntimeCatalystFiltering.scala:
##########
@@ -72,35 +80,57 @@ trait SupportsRuntimeCatalystFiltering extends Scan {
   def fullyPushedFilterAttributes(): Array[NamedReference] = Array.empty
 
   /**
-   * Filters this scan using runtime Catalyst expressions.
+   * Plans this scan's input partitions with runtime Catalyst expressions 
applied.
    *
-   * The provided expressions must be interpreted as a set of predicates that 
are ANDed together.
-   * Implementations may use the expressions to prune initially planned
-   * [[org.apache.spark.sql.connector.read.InputPartition]]s.
+   * The provided expressions must be interpreted as a set of predicates that 
are ANDed together,
+   * and applied on top of the filters already pushed at query compilation. 
Implementations may use
+   * them to plan fewer [[InputPartition]]s than 
[[org.apache.spark.sql.connector.read.Batch]]
+   * would without them.
+   *
+   * Spark calls this method at execution time for every scan node that has 
runtime filters, with
+   * the ones that survive screening. The array may be empty, which applies no 
runtime filter. The
+   * partitions it returns replace the ones that scan node would otherwise 
have read. Spark may also
+   * call `Batch.planInputPartitions()` on the same scan, so neither method 
may assume it is the
+   * only one used. One scan instance can back several scan nodes (e.g. the 
two branches of a
+   * group-based UPDATE), each with its own runtime filters, so an 
implementation must derive its
+   * result from the given expressions alone and must not carry state over 
from a previous call. A
+   * group-based scan whose write replaces the groups that were read records 
what each call
+   * returned; a scan node without runtime filters reads what 
`planInputPartitions()` returns.
    *
    * Spark currently tracks runtime-filter eligibility by root attribute. If 
[[filterAttributes]]
    * returns a nested reference, an expression may access another nested field 
under the same root.
    * The scan must match each access against its own partition layout and use 
only expressions it
    * can apply.
    *
-   * Spark may call this method more than once for the same scan instance: a 
plan can hold several
-   * scan nodes sharing one scan (e.g. the two branches of a group-based 
UPDATE), and each pushes
-   * its own copy of the runtime filters. Implementations must treat 
successive calls as additive,
-   * ANDing the new expressions with those already pushed rather than 
replacing them.
-   *
    * If the scan also implements
    * [[org.apache.spark.sql.connector.read.SupportsReportPartitioning]], it 
must preserve
-   * the originally reported partitioning during runtime filtering. While 
applying runtime
-   * predicates, the scan may detect that some
-   * [[org.apache.spark.sql.connector.read.InputPartition]]s have no matching 
data, in which
-   * case it can either replace the initially planned
-   * [[org.apache.spark.sql.connector.read.InputPartition]]s that have no 
matching data with
-   * empty [[org.apache.spark.sql.connector.read.InputPartition]]s, or report 
only a subset of
-   * the original partition values (omitting those with no data) via
-   * [[org.apache.spark.sql.connector.read.Batch#planInputPartitions]]. The 
scan must not
-   * report new partition values that were not present in the original 
partitioning.
+   * the originally reported partitioning. While applying runtime predicates, 
the scan may detect
+   * that some [[InputPartition]]s have no matching data, in which case it can 
either replace
+   * them with empty [[InputPartition]]s, or report only a subset of the 
original partition
+   * values (omitting those with no data). The scan must not report new 
partition values that
+   * were not present in the original partitioning.
    *
-   * Note that Spark will call [[Scan.toBatch]] again after filtering the scan 
at runtime.
+   * The default calls the deprecated [[filter]] when `expressions` is not 
empty and then returns
+   * `toBatch.planInputPartitions()`, which is what Spark 4.3 did when a 
runtime filter survived
+   * screening. Like `filter` in Spark 4.3, successive calls on such a scan 
are additive.
+   */
+  @nowarn("cat=deprecation")
+  def planInputPartitionsWithRuntimeFilters(
+      expressions: Array[Expression]): Array[InputPartition] = {
+    if (expressions.nonEmpty) filter(expressions)
+    toBatch.planInputPartitions()
+  }
+
+  /**
+   * Filters this scan with runtime Catalyst expressions, the method Spark 4.3 
called. A scan that
+   * implements only this keeps working through the default of

Review Comment:
   **Nit (P3):** This sentence says a scan that implements only `filter` keeps 
working through the default of `planInputPartitionsWithRuntimeFilters`, but 
that holds only for a Scala scan compiled against this version, which gets a 
forwarder. A class whose methods do not declare the new method, such as one 
built against 4.3.0 or a Java class that overrides only `filter`, is detected 
by `PushDownUtils.implementsOnlyDeprecatedFilter` and goes through 
`pushRuntimeFilters` to `filter` instead. Spark then never calls the new method 
or its default for it, and when screening removes every runtime filter the node 
reads the partitions it planned instead of planning the scan again, which is 
what the `JavaDeprecatedFilterScan` case in 
`DataSourceV2CatalystRuntimeFilterSuite` asserts. The same overstatement 
appears at L90 ("Spark calls this method at execution time for every scan node 
that has runtime filters") and in the `filterAttributes` doc at L45. An 
implementor reading these docs would exp
 ect a legacy filter-only scan to be driven through the default and planned 
again on an empty screen, and neither happens. Naming the reflective 4.3 route 
here, and limiting the L45 and L90 statements to scans that do not take it, 
would make the docs match the code and the PR description.
   
   **Verification:**
   - **Inspection:** The doc of the deprecated filter describes the route of a 
scan whose classes do not declare planInputPartitionsWithRuntimeFilters, such 
as one built against Spark 4.3.0 or a Java class that overrides only filter, as 
the code takes it: the screened runtime filters arrive through filter, the 
planned partitions are read when screening removes every runtime filter, and a 
Scala scan compiled against this version is still described as planned again in 
that case.
   - **Inspection:** The docs of planInputPartitionsWithRuntimeFilters and 
filterAttributes limit their statements that Spark calls 
planInputPartitionsWithRuntimeFilters for scan nodes with runtime filters to 
scans that do not take the deprecated route.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/RuntimePartitionPruningFileScan.scala:
##########
@@ -0,0 +1,124 @@
+/*
+ * 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 scala.util.control.NonFatal
+
+import org.apache.spark.SparkException
+import org.apache.spark.internal.LogKeys
+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, 
PartitionDirectory}
+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`, `planInputPartitions()` and
+ * `planInputPartitionsWithRuntimeFilters` are final here. A scan that reports 
a partitioning or an
+ * ordering should not mix this in. The scan records nothing about what each 
call returned, so Spark
+ * gives it no group filter in a group-based row-level operation.
+ */
+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. Only a
+   * scan with runtime-filterable columns keeps the listing, since nothing 
else reads it again.
+   */
+  private val listing = new TransientBestEffortLazyVal(() => listFiles())
+
+  private val allPartitions = new TransientBestEffortLazyVal(() =>
+    filePartitions(if (filterAttributes().isEmpty) listFiles() else listing()))
+
+  private def listFiles(): Seq[PartitionDirectory] =
+    fileIndex.listFiles(partitionFilters, dataFilters)
+
+  // 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] = {
+    val readFields = 
readSchema().fieldNames.map(normalizePartitionColumnName).toSet
+    readPartitionSchema.fieldNames
+      .filter(name => readFields.contains(normalizePartitionColumnName(name)))
+      .map(FieldReference.column)
+  }
+
+  /**
+   * Keeps the listed partition directories whose values satisfy 
`expressions`, then splits and
+   * packs their files for their own size, as V1 does for 
`dynamicallySelectedPartitions`.
+   *
+   * A filter that fails to evaluate on a directory keeps it, since the join 
or the `FilterExec`
+   * above the scan applies the filter again. Each call logs at most one 
warning for such failures.
+   */
+  final override def planInputPartitionsWithRuntimeFilters(
+      expressions: Array[Expression]): Array[InputPartition] = {
+    if (expressions.isEmpty) return allPartitions().toArray
+    // Directory values follow the table's partition schema, not the read one, 
and bind as V1
+    // binds them: with that schema's types, nullable.
+    val partitionSchema = fileIndex.partitionSchema
+    val fieldIndex = partitionSchema.fieldNames.zipWithIndex
+      .map { case (name, i) => normalizePartitionColumnName(name) -> i }.toMap
+    val predicates = expressions.toSeq.map { e =>
+      e -> Predicate.createInterpreted(e.transform {
+        case a: Attribute =>
+          // PushDownUtils passes only filters over `filterAttributes()`.
+          val i = fieldIndex.getOrElse(normalizePartitionColumnName(a.name),
+            throw SparkException.internalError("A file scan can only apply a 
runtime filter " +
+              s"over its partition columns 
${partitionSchema.fieldNames.mkString("[", ", ", "]")}" +
+              s", got $e"))
+          BoundReference(i, partitionSchema(i).dataType, nullable = true)
+      })
+    }
+    var failedDirs = 0
+    var firstFailure: Option[(Expression, Throwable)] = None
+    val all = listing()
+    val kept = all.filter { dir =>
+      var failure: Option[(Expression, Throwable)] = None
+      val keep = predicates.forall { case (e, predicate) =>

Review Comment:
   **Nit (P3):** This `forall` is the AND of every runtime filter the scan 
receives, and L110-114 count a directory as an evaluation failure only when no 
other filter prunes it, but no test reaches this method with more than one 
expression: every DPP-suite, Avro and Explain case gives the file scan a single 
runtime filter, and the in-memory "two predicates on filter attributes" test 
exercises only the handoff to a fixture scan. Evaluating only the first filter, 
or keeping a directory when any one of them passes, would go unnoticed. Query 
results would stay correct, since the join or the Filter above the scan applies 
each filter again, but pruning and the warning count would regress silently. A 
case with two runtime filters on different partition columns of one file scan, 
such as DPP filters from two dimensions or a DPP filter plus a scalar-subquery 
filter, would pin both.
   
   **Verification:**
   - **Behavior:** With two runtime filters on different partition columns of 
one built-in V2 file scan, the scan reads exactly the directories that satisfy 
both filters, and the query returns the same rows as with runtime pruning off, 
with adaptive query execution on and off.
   - **Regression:** The coverage fails if the scan evaluates only some of 
several runtime filters, or keeps a directory that any one of them prunes.
   - **Regression:** When one runtime filter fails to evaluate on a directory 
that another filter prunes, the coverage asserts that the directory is not read 
and that the evaluation-failure warning does not count it, while a directory 
kept only because a filter failed on it is counted.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/RuntimePartitionPruningFileScan.scala:
##########
@@ -0,0 +1,124 @@
+/*
+ * 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 scala.util.control.NonFatal
+
+import org.apache.spark.SparkException
+import org.apache.spark.internal.LogKeys
+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, 
PartitionDirectory}
+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`, `planInputPartitions()` and
+ * `planInputPartitionsWithRuntimeFilters` are final here. A scan that reports 
a partitioning or an
+ * ordering should not mix this in. The scan records nothing about what each 
call returned, so Spark
+ * gives it no group filter in a group-based row-level operation.
+ */
+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. Only a
+   * scan with runtime-filterable columns keeps the listing, since nothing 
else reads it again.
+   */
+  private val listing = new TransientBestEffortLazyVal(() => listFiles())
+
+  private val allPartitions = new TransientBestEffortLazyVal(() =>
+    filePartitions(if (filterAttributes().isEmpty) listFiles() else listing()))
+
+  private def listFiles(): Seq[PartitionDirectory] =
+    fileIndex.listFiles(partitionFilters, dataFilters)
+
+  // 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] = {
+    val readFields = 
readSchema().fieldNames.map(normalizePartitionColumnName).toSet
+    readPartitionSchema.fieldNames
+      .filter(name => readFields.contains(normalizePartitionColumnName(name)))
+      .map(FieldReference.column)
+  }
+
+  /**
+   * Keeps the listed partition directories whose values satisfy 
`expressions`, then splits and
+   * packs their files for their own size, as V1 does for 
`dynamicallySelectedPartitions`.
+   *
+   * A filter that fails to evaluate on a directory keeps it, since the join 
or the `FilterExec`
+   * above the scan applies the filter again. Each call logs at most one 
warning for such failures.
+   */
+  final override def planInputPartitionsWithRuntimeFilters(
+      expressions: Array[Expression]): Array[InputPartition] = {
+    if (expressions.isEmpty) return allPartitions().toArray
+    // Directory values follow the table's partition schema, not the read one, 
and bind as V1
+    // binds them: with that schema's types, nullable.
+    val partitionSchema = fileIndex.partitionSchema
+    val fieldIndex = partitionSchema.fieldNames.zipWithIndex
+      .map { case (name, i) => normalizePartitionColumnName(name) -> i }.toMap
+    val predicates = expressions.toSeq.map { e =>
+      e -> Predicate.createInterpreted(e.transform {
+        case a: Attribute =>
+          // PushDownUtils passes only filters over `filterAttributes()`.
+          val i = fieldIndex.getOrElse(normalizePartitionColumnName(a.name),
+            throw SparkException.internalError("A file scan can only apply a 
runtime filter " +
+              s"over its partition columns 
${partitionSchema.fieldNames.mkString("[", ", ", "]")}" +
+              s", got $e"))
+          BoundReference(i, partitionSchema(i).dataType, nullable = true)

Review Comment:
   **Nit (P3):** `nullable = true` here is what makes a null partition value (a 
`__HIVE_DEFAULT_PARTITION__` directory) evaluate as null rather than as its 
type's default, but no fixture in `DataSourceV2FileSourceDPPSuite`, 
`AvroV2Suite` or `ExplainSuite` writes a null partition directory, so nothing 
pins it. With `nullable = false`, the interpreted `BoundReference` reads a null 
int partition value as 0, so a runtime filter that is true for null, such as 
`f.part <=> (SELECT ...)` with a subquery that returns null, or `f.part = 
(SELECT ...) OR f.part IS NULL`, would prune that directory and silently drop 
its rows while every current test still passes. A case with a null partition 
directory and such a scalar-subquery filter, run with AQE on and off, would 
catch it.
   
   **Verification:**
   - **Behavior:** With a null partition directory on a primitive-typed 
partition column and a scalar-subquery runtime filter that is true for a null 
value, the scan reads the null directory and the query returns its rows, with 
adaptive query execution on and off.
   - **Regression:** The coverage fails when the scan reads a null partition 
value as its type's default, as a non-nullable binding does, so that a runtime 
filter that is true for null on such a column prunes the directory.



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