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


##########
sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/GroupPartitionsExecSuite.scala:
##########
@@ -1134,6 +1151,16 @@ private case class UnsafeColumnarLeaf(override val 
outputPartitioning: Partition
 }
 
 /** A leaf whose ordering follows a config, the way a V2 scan's key-derived 
ordering does. */
+/** A node that returns its child's rows as they are, and mixes in 
SafeForKWayMerge. */
+private case class SafePassThrough(child: SparkPlan) extends UnaryExecNode 
with SafeForKWayMerge {
+  override def output: Seq[Attribute] = child.output
+  override def outputPartitioning: Partitioning = child.outputPartitioning
+  override def outputOrdering: Seq[SortOrder] = child.outputOrdering
+  override protected def doExecute(): RDD[InternalRow] = child.execute()
+  override protected def withNewChildInternal(newChild: SparkPlan): SparkPlan =
+    copy(child = newChild)
+}
+
 private case class ConfOrderedLeaf(

Review Comment:
   **Nit (P3):** The new `SafePassThrough` helper landed between 
`ConfOrderedLeaf`'s Scaladoc and its class, so the comment about a leaf whose 
ordering follows a config now stacks above `SafePassThrough`'s own comment, and 
`ConfOrderedLeaf` at line 1164 has none. Moving the new helper above the old 
comment gives each class its own comment again:
   
   ```suggestion
   /** A node that returns its child's rows as they are, and mixes in 
SafeForKWayMerge. */
   private case class SafePassThrough(child: SparkPlan) extends UnaryExecNode 
with SafeForKWayMerge {
     override def output: Seq[Attribute] = child.output
     override def outputPartitioning: Partitioning = child.outputPartitioning
     override def outputOrdering: Seq[SortOrder] = child.outputOrdering
     override protected def doExecute(): RDD[InternalRow] = child.execute()
     override protected def withNewChildInternal(newChild: SparkPlan): 
SparkPlan =
       copy(child = newChild)
   }
   
   /** A leaf whose ordering follows a config, the way a V2 scan's key-derived 
ordering does. */
   private case class ConfOrderedLeaf(
   ```
   
   **Verification:**
   - **Inspection:** In GroupPartitionsExecSuite.scala, SafePassThrough and 
ConfOrderedLeaf are each directly preceded by exactly one doc comment, the one 
that describes that class, and no two doc comments stand next to each other.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/BatchScanExec.scala:
##########
@@ -55,21 +70,38 @@ case class BatchScanExec(
     @transient table: Table,
     keyGroupedPartitioning: Option[Seq[Expression]] = None,
     storageFilters: Seq[Expression] = Nil,
-    appendsCheckedColumn: Boolean = false
+    appendsCheckedColumn: Boolean = false,
+    perPartitionBloomFilter: Option[PerPartitionBloomFilter] = None,
+    bloomFilterAggregate: Option[SparkPlan] = None
   ) extends DataSourceV2ScanExecBase {
 
   // The readers are asked for the column only with storage filters, and 
append it last.
   require(!appendsCheckedColumn ||
     (storageFilters.nonEmpty && output.lastOption.exists(_.dataType == 
BooleanType)),
     "A checked column comes with storage filters, last in the output")
 
+  require(perPartitionBloomFilter.isDefined == bloomFilterAggregate.isDefined,
+    "A per-partition bloom filter comes with its aggregate")
+
+  override def children: Seq[SparkPlan] = bloomFilterAggregate.toSeq
+
+  override protected def withNewChildrenInternal(newChildren: 
IndexedSeq[SparkPlan]): SparkPlan =
+    sharePlanning(copy(bloomFilterAggregate = newChildren.headOption))

Review Comment:
   **Nit (P3):** This copy, and the one in `withoutPerPartitionBloomFilter` at 
line 232, hand the planned `Batch` and input partitions to the new node, but no 
test pins either. SparkPlanSuite's 'SPARK-60752: copies of a BatchScanExec 
share its Batch and the partitions it planned' covers only `makeCopy`, `clone` 
and the case-class `copy` of a scan with no child, and the in-memory scans of 
`PerPartitionRuntimeFilterSuite` return the same partitions from every 
`toBatch`, so by the review's reading a plain `copy(...)` at either site would 
fail no test. Every scan with a per-partition bloom filter goes through this 
line whenever a rule rewrites its aggregate child, such as 
`SizePerPartitionStorageFilters`, `EnsureRequirements` or the codegen and 
columnar transitions. With a connector whose shared `Scan` another node's 
runtime filter prunes first, the rebuilt scan would then read partitions other 
than the ones `EnsureRequirements` and `GroupPartitionsExec` were planned 
against, the failure
  SPARK-60752 fixed for `makeCopy` and `clone`.
   
   **Verification:**
   - **Regression:** For a BatchScanExec over a Scan whose toBatch returns a 
new Batch with new partitions on each call, a copy made by replacing its bloom 
filter aggregate child and a copy made by dropping its per-partition bloom 
filter report the same Batch and the same input partition objects as the 
original, and the check fails when either copy is built with the case-class 
copy alone.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/BatchScanExec.scala:
##########
@@ -142,16 +180,58 @@ case class BatchScanExec(
       // return an empty RDD with 1 partition if dynamic filtering removed the 
only split
       new EmptyRDDWithPartitions(sparkContext, 1)
     } else {
-      new DataSourceRDD(
+      perPartitionBloomFilterRDD.getOrElse(new DataSourceRDD(
         sparkContext, filteredPartitions, readerFactory, supportsColumnar, 
customMetrics,
-        storageFilterRequest, Option.when(appendsCheckedColumn)(output.length))
+        storageFilterRequest, checkedOutputWidth))
     }
     postDriverMetrics(scan.reportDriverMetrics())
     rdd
   }
 
+  // The RDD whose readers get the per-partition bloom filter of their split's 
partition key. None
+  // without one, with no splits, or when the partition keys of the splits and 
of the aggregate
+  // cannot be matched. The scan then reads every split without the bloom 
filters. The join above
+  // drops the rows they would reject anyway.
+  private def perPartitionBloomFilterRDD: Option[RDD[InternalRow]] =
+    perPartitionBloomFilter.zip(bloomFilterAggregate).flatMap { case (filter, 
aggregate) =>
+      val splitKeys = reportedKeyedPartitioning
+        .map(_.partitionKeys).filter(_.length == filteredPartitions.length)
+      val bloomKeys = 
PartitioningCollection.representativeOf(aggregate.outputPartitioning)
+        .filterNot(_.mayContainUnknownPartitionKeys).map(_.partitionKeys)
+      (splitKeys, bloomKeys) match {
+        case (Some(splitKeys), Some(bloomKeys)) if splitKeys.isEmpty || 
bloomKeys.isEmpty ||
+            splitKeys.head.dataTypes == bloomKeys.head.dataTypes =>
+          val partitionsByKey = bloomKeys.zipWithIndex.groupMap(_._1)(_._2)
+          val bloomPartitions =
+            splitKeys.map(k => partitionsByKey.getOrElse(k, 
Nil).toArray).toArray
+          val blooms = if (aggregate.supportsColumnar) {
+            // The RDD reads each row's bloom filter bytes before it moves to 
the next row.
+            
aggregate.executeColumnar().mapPartitionsInternal(_.flatMap(_.rowIterator().asScala))

Review Comment:
   **Nit (P3):** This read relies on each bloom row's bytes being read before 
the iterator moves on, as the comment at line 208 says, but every columnar run 
in `PerPartitionRuntimeFilterSuite` has one group per creation partition, so 
each aggregate batch holds a single bloom row. The only case with two bloom 
rows in one partition, 'the bloom filter of a split holds the keys whose 
partition transform is null', calls `createTables()` with a row-based fact, so 
it never reads the aggregate through this line. By the review's reading, a 
change here that materialized each `rowIterator()` before the bytes are read, 
or kept only one row of each batch, would fail no test. With a columnar fact 
and that test's null-returning `bucket`, `RowToColumnarExec` puts the groups 
{1, 9} and {5} of bucket 1 into one batch, so under such a change the splits of 
bucket 1 would get only one group's bloom filter and drop rows the join 
matches. (A change in `requestOf` that collected the rows first would still f
 ail the row-based test, because the row-based aggregate also hands out one 
reused `UnsafeRow`.) Running that test with a columnar fact as well closes the 
gap.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60752#issuecomment-7050819002).
   
   **Verification:**
   - **Regression:** Under a columnar scan of the application side, with a 
creation partition that holds two groups in one aggregate batch because the 
transform returns null for one of its keys, the splits of that partition key 
keep the keys of both groups, with adaptive execution on and off, and the check 
fails when the bloom rows of a batch are collected before their bytes are read 
or only one row per batch is kept.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/CleanupPerPartitionRuntimeFilters.scala:
##########
@@ -0,0 +1,225 @@
+/*
+ * 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.catalyst.optimizer
+
+import org.apache.spark.sql.catalyst.expressions.{Alias, And, AttributeSet, 
BloomFilterMightContain, Expression, ExprId, Literal, NamedExpression, 
Predicate, PredicateHelper, SubqueryExpression, TransformExpression, 
Unevaluable, XxHash64}
+import org.apache.spark.sql.catalyst.expressions.aggregate.BloomFilterAggregate
+import 
org.apache.spark.sql.catalyst.optimizer.InjectRuntimeFilter.perPartitionCreationTransform
+import org.apache.spark.sql.catalyst.planning.PhysicalOperation
+import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, Filter, 
HintInfo, LogicalPlan, Subquery}
+import org.apache.spark.sql.catalyst.rules.Rule
+import 
org.apache.spark.sql.catalyst.trees.TreePattern.{PER_PARTITION_RUNTIME_FILTER_SUBQUERY,
 TreePattern}
+import org.apache.spark.sql.catalyst.trees.UnaryLike
+import org.apache.spark.sql.execution.datasources.v2.DataSourceV2ScanRelation
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * The placeholder of a per-partition runtime bloom filter of `key`, the join 
key of the application
+ * side. [[InjectRuntimeFilter]] adds it as a conjunct of a `Filter` when the 
creation side is too
+ * big for a bloom filter of all its keys. `plan` is that creation side, with 
its join key as its
+ * only column. Predicate pushdown moves the placeholder along `key`, and 
`MergeSubplans` merges the
+ * subqueries in `plan` as any others. [[CleanupPerPartitionRuntimeFilters]] 
then keeps it only
+ * where it landed right above a scan that can apply it. The V2 scan strategy 
gives the scan the
+ * bloom filters of an aggregate of `plan`, see `aggregateOf`.
+ *
+ * Like `DynamicPruningSubquery`, it cannot be evaluated. Where no scan takes 
it, it gives way to
+ * `true`.
+ *
+ * `sizing` sizes the bloom filters of its aggregate.
+ */
+case class PerPartitionRuntimeFilterSubquery(
+    key: Expression,
+    plan: LogicalPlan,
+    sizing: PerPartitionSizing,
+    exprId: ExprId = NamedExpression.newExprId)
+  extends SubqueryExpression(plan, Seq(key), exprId, Nil, None)
+  with Predicate
+  with Unevaluable
+  with UnaryLike[Expression] {
+
+  override def child: Expression = key
+
+  override def nullable: Boolean = false
+
+  override def hint: Option[HintInfo] = None
+
+  override def withNewHint(hint: Option[HintInfo]): 
PerPartitionRuntimeFilterSubquery = this
+
+  override def withNewPlan(plan: LogicalPlan): 
PerPartitionRuntimeFilterSubquery =
+    copy(plan = plan)
+
+  override def withNewOuterAttrs(
+      outerAttrs: Seq[Expression]): PerPartitionRuntimeFilterSubquery = {
+    assert(outerAttrs.size == 1)
+    copy(key = outerAttrs.head)
+  }
+
+  final override def nodePatternsInternal(): Seq[TreePattern] =
+    Seq(PER_PARTITION_RUNTIME_FILTER_SUBQUERY)
+
+  override def toString: String = s"per_partition_runtime_filter#${exprId.id} 
$conditionString"
+
+  override lazy val canonicalized: PerPartitionRuntimeFilterSubquery =
+    copy(key = key.canonicalized, plan = plan.canonicalized, exprId = 
ExprId(0))
+
+  override protected def withNewChildInternal(
+      newChild: Expression): PerPartitionRuntimeFilterSubquery = copy(key = 
newChild)
+}
+
+object PerPartitionRuntimeFilterSubquery extends PredicateHelper {
+
+  /**
+   * The columns of `scan` that the V2 scan strategy offers a per-partition 
bloom filter over. Those
+   * are the columns the scan declared, when storage filters are on and every 
operation pushed into
+   * the scan works on each row by itself. Unlike the strategy's other storage 
filters, a
+   * per-partition bloom filter is offered also when the scan reads only the 
filter's columns, since
+   * no filter above the scan drops the rows it rejects. It is not offered to 
the read of a
+   * group-based DELETE. `ReplaceDataExec` counts the deleted rows from the 
rows that read returns.
+   * So the count would leave out the rows the readers reject.
+   */
+  def storageFilterColumnsOf(scan: DataSourceV2ScanRelation): AttributeSet =
+    if (SQLConf.get.v2StorageFilterPushdownEnabled && 
scan.onlyRowWisePushdowns &&

Review Comment:
   **Nit (P3):** No test covers the `scan.onlyRowWisePushdowns` conjunct here. 
`PerPartitionRuntimeFilterSuite`'s in-memory tables push no limit, offset, 
top-N or sample, and its one hand-built relation, in 'no per-partition bloom 
filter for the read of a group-based DELETE', passes `onlyRowWisePushdowns = 
true`. `StorageFilterPushDownSuite`'s 'nothing is offered to a scan that took a 
pushed $op' cases run with per-partition bloom filters off, so they test only 
the whole-side gate in `DataSourceV2Strategy.storageFiltersFor`. By the 
review's reading, dropping the conjunct would fail no test. Since nothing above 
the scan rechecks a per-partition bloom filter, a keyed 
`SupportsStorageFilters` scan that fully took a pushed `ORDER BY v LIMIT 100` 
would then have its readers drop rows before the source applies the limit, so 
the scan would return the top 100 of the filtered rows instead of the table's, 
and the join result would change. A relation with `onlyRowWisePushdowns = 
false` in that 
 DELETE-read test, asserting that `storageFilterColumnsOf` offers it no 
columns, would pin it.
   
   **Verification:**
   - **Regression:** With storage-filter pushdown on, a scan relation that 
declares the key and is not the read of a group-based DELETE gets no 
per-partition bloom filter columns when it took a pushed operation that decides 
which rows it returns, and gets the key when it did not; the check fails when 
the per-partition gate stops testing for such pushed operations.



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/PerPartitionRuntimeFilterSuite.scala:
##########
@@ -591,72 +876,66 @@ class PerPartitionRuntimeFilterSuite extends 
KeyGroupedPartitioningSuiteBase {
     }
   }
 
-  test("the semi join goes when the creation side has too few partition keys 
for the size " +
-      "threshold") {
+  test("the scan reads without the bloom filters when the creation side has 
too few partition " +
+      "keys for the size threshold") {
     // The creation side is 4 times the threshold, but `dim` has only 3 
partition keys. So a share
     // of one partition key would be over the threshold.
     createTables()
     withSQLConf(RUNTIME_BLOOM_FILTER_CREATION_SIDE_THRESHOLD.key ->
         (creationSideSize("dim") / 4).toString) {
       val df = join()
-      assert(perPartitionSemiJoins(df).size == 1, "test setup: the rule added 
it")
+      assert(perPartitionFilters(df).size == 1, "test setup: the rule added 
it")
       checkAnswer(df, expectedRows)
-      assert(executedSemiJoins(df.queryExecution.executedPlan).isEmpty,
-        df.queryExecution.executedPlan)
+      val plan = df.queryExecution.executedPlan
+      assert(storageFilterScans(plan).isEmpty, plan)
+      assert(!plan.exists(_.expressions.exists(
+        _.containsPattern(PER_PARTITION_RUNTIME_FILTER_SUBQUERY))), plan)

Review Comment:
   **Nit (P3):** Under the suite's default adaptive execution, `executedPlan` 
is an `AdaptiveSparkPlanExec`, a leaf with no children and no expressions, and 
`TreeNode.exists` looks only at that node, so this assertion passes whatever 
the final plan holds. The test 'a placeholder that a later optimizer rule moves 
away from its scan gives way to true' checks the same property AQE-aware at 
line 1161:
   
   ```suggestion
         assert(!collectWithSubqueries(plan) { case p => p.expressions }.flatten
           .exists(_.containsPattern(PER_PARTITION_RUNTIME_FILTER_SUBQUERY)), 
plan)
   ```
   
   **Verification:**
   - **Inspection:** The too-few-partition-keys test looks for per-partition 
placeholders in the expressions of every node of the final adaptive plan and of 
its subqueries, the way the test of a placeholder that a later optimizer rule 
moves away from its scan does, rather than at the AdaptiveSparkPlanExec root 
alone.
   - **Behavior:** With adaptive execution at its default, the 
too-few-partition-keys test returns the join's rows, plans the scan without 
bloom filters, and finds no placeholder in the final plan.



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