LuciferYang commented on code in PR #55579:
URL: https://github.com/apache/spark/pull/55579#discussion_r4505536077
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/dynamicpruning/PartitionPruning.scala:
##########
@@ -233,6 +233,10 @@ object PartitionPruning extends Rule[LogicalPlan] with
PredicateHelper with Join
private def hasSelectivePredicate(plan: LogicalPlan): Boolean = plan.exists {
case f: Filter => isLikelySelective(f.condition)
+ // A built-in V2 file scan takes its partition filters in without leaving
a `Filter` above it,
+ // where V1 keeps one.
+ case r: DataSourceV2ScanRelation if
r.scan.isInstanceOf[RuntimePartitionPruningFileScan] =>
Review Comment:
Done in c1ba7eacfd7. `hasSelectivePredicate` now reads the `pushedFilters`
of any `DataSourceV2ScanRelation`, and the description says that a connector
dimension can now trigger DPP. "DPP for a dimension whose filter a connector
scan took in fully" runs a dimension on the in-memory catalog, whose scan takes
`dp IN (1, 3)` in fully, and expects DPP and a fact scan that reads only the
matching partitions.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/dynamicpruning/CleanupDynamicPruningFilters.scala:
##########
@@ -79,9 +90,14 @@ object CleanupDynamicPruningFilters extends
Rule[LogicalPlan] with PredicateHelp
case p @ NodeWithOnlyDeterministicProjectAndFilter(
HiveTableRelation(_, _, _, _, _)) =>
removeUnnecessaryDynamicPruningSubquery(p)
- case p @ NodeWithOnlyDeterministicProjectAndFilter(
- _: DataSourceV2ScanRelation) =>
- removeUnnecessaryDynamicPruningSubquery(p)
+ // Only a built-in file scan is known to prune what it plans with a
partition filter it fully
+ // took. Another DSv2 source may apply such a filter row by row and
leave the pruning to DPP.
Review Comment:
Done in c1ba7eacfd7. The comment keeps the reason without contrasting it
with the `Filter` path: another DSv2 source may apply such a filter row by row
and leave the pruning to DPP, so its pushed filters are left out.
##########
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))
Review Comment:
Done in c1ba7eacfd7, with the scaladoc. It says that `DataSourceV2Strategy`
already plans only filters over the declared attributes, so the check matters
only for a scan node built elsewhere.
##########
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] = {
+ val readFields = readSchema().fieldNames.map(normalizePartitionName).toSet
+ readPartitionSchema.fieldNames
+ .filter(name => readFields.contains(normalizePartitionName(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.
+ */
+ 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) => normalizePartitionName(name) -> i }.toMap
+ val predicates = expressions.toSeq.map { e =>
+ Predicate.createInterpreted(e.transform {
+ case a: Attribute =>
+ // PushDownUtils passes only filters over `filterAttributes()`.
+ val i = fieldIndex.getOrElse(normalizePartitionName(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)
+ })
+ }
+ val all = listing()
+ val kept = all.filter { dir =>
+ predicates.forall { predicate =>
+ try predicate.eval(dir.values) catch { case NonFatal(_) => true }
+ }
+ }
+ if (kept.length == all.length) allPartitions().toArray else
filePartitions(kept).toArray
+ }
+
+ // Read when the scan is built, as `FileScan` does.
+ private val isCaseSensitive = conf.caseSensitiveAnalysis
+
+ private def normalizePartitionName(name: String): String = {
Review Comment:
Done in c1ba7eacfd7, with your helper.
`FileScan.normalizePartitionColumnName` is `private[v2]` and calls
`normalizeName`, and the trait's copy of the rule is gone.
--
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]