peter-toth commented on code in PR #60752:
URL: https://github.com/apache/spark/pull/60752#discussion_r4647826219


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PerPartitionStorageFilterRDD.scala:
##########
@@ -0,0 +1,145 @@
+/*
+ * 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.concurrent.ConcurrentHashMap
+
+import scala.collection.mutable
+
+import org.apache.spark.{Dependency, NarrowDependency, Partition, 
SparkContext, TaskContext}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, 
Literal}
+import org.apache.spark.sql.catalyst.expressions.aggregate.BloomFilterAggregate
+import org.apache.spark.sql.connector.read.{InputPartition, 
PartitionReaderFactory, StorageFilterRequest}
+import org.apache.spark.sql.execution.metric.SQLMetric
+import org.apache.spark.sql.internal.connector.{StorageFilterImpl, 
StorageFilterRequestImpl}
+import org.apache.spark.sql.types.BinaryType
+import org.apache.spark.util.ArrayImplicits._
+
+/** A split of a [[PerPartitionStorageFilterRDD]], with the partitions of its 
bloom filters. */
+private class PerPartitionStorageFilterPartition(
+    index: Int,
+    inputPartition: Option[InputPartition],
+    val bloomPartitions: Array[Partition])
+  extends DataSourceRDDPartition(index, inputPartition)
+
+/**
+ * The [[DataSourceRDD]] of a [[BatchScanExec]] with a per-partition bloom 
filter. The readers of
+ * each split get `condition` with the bloom filters of the split's partitions 
of `blooms` in place
+ * of `bloomFilter`, ORed into one. Splits of one key have the same partitions 
of `blooms`, so a
+ * task reads them once for all its splits of that key.
+ *
+ * @param bloomPartitions for each split, the partitions of `blooms` that 
report its key
+ * @param bloomOrdinal the position of the bloom filter column in the rows of 
`blooms`
+ */
+private class PerPartitionStorageFilterRDD(
+    sc: SparkContext,
+    inputPartitions: Seq[Option[InputPartition]],
+    partitionReaderFactory: PartitionReaderFactory,
+    columnarReads: Boolean,
+    customMetrics: Map[String, SQLMetric],
+    checkedOutputWidth: Option[Int],
+    @transient private val blooms: RDD[InternalRow],
+    @transient private val bloomPartitions: Array[Array[Int]],
+    bloomOrdinal: Int,
+    condition: Expression,
+    bloomFilter: Attribute,
+    scanOutput: Seq[Attribute],
+    numSkippedSplits: SQLMetric)
+  extends DataSourceRDD(sc, inputPartitions, partitionReaderFactory, 
columnarReads, customMetrics,
+    None, checkedOutputWidth) {
+
+  override protected def getDependencies: Seq[Dependency[_]] =
+    Seq(new PerPartitionStorageFilterDependency(blooms, bloomPartitions))
+
+  override protected def getPartitions: Array[Partition] = {
+    val parents = blooms.partitions
+    super.getPartitions.map {
+      case p: DataSourceRDDPartition =>
+        new PerPartitionStorageFilterPartition(
+          p.index, p.inputPartition, bloomPartitions(p.index).map(parents))
+    }
+  }
+
+  // The request each task built for each set of partitions of `blooms` it 
read. By task attempt,
+  // as `DataSourceRDD` keeps its state.
+  @transient private lazy val taskRequests =
+    new ConcurrentHashMap[Long, mutable.HashMap[Seq[Int], 
Option[StorageFilterRequest]]]()
+
+  override def compute(split: Partition, context: TaskContext): 
Iterator[InternalRow] = {
+    val partition = split.asInstanceOf[PerPartitionStorageFilterPartition]
+    if (partition.inputPartition.isEmpty) {
+      Iterator.empty
+    } else {
+      requestOf(partition, context) match {
+        case Some(request) => computeWith(split, context, Some(request))
+        case None =>
+          numSkippedSplits += 1
+          Iterator.empty
+      }
+    }
+  }
+
+  // The request for the readers of `partition`, None when no bloom filter has 
its key.
+  private def requestOf(
+      partition: PerPartitionStorageFilterPartition,
+      context: TaskContext): Option[StorageFilterRequest] = {
+    val requests = taskRequests.computeIfAbsent(context.taskAttemptId(), _ => 
mutable.HashMap.empty)
+    // Outside `computeIfAbsent`, whose function must not change the map. A 
task that has
+    // completed runs the listener at once, and the listener removes the 
task's entry.
+    if (requests.isEmpty) {
+      context.addTaskCompletionListener[Unit](ctx => 
taskRequests.remove(ctx.taskAttemptId()))
+    }
+    
requests.getOrElseUpdate(partition.bloomPartitions.map(_.index).toImmutableArraySeq,
 {

Review Comment:
   Thanks, added a test in 
[2a0cd98](https://github.com/apache/spark/pull/60752/commits/2a0cd98857d46b6b2bb97d4f9588f5e01fd96277).
 In a storage-partitioned join, and with all the buckets in one task under a 
`coalesce(1)`, `dim` is read at most twice as often as without per-partition 
bloom filters. It fails when each split builds its own request.
   



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/PerPartitionRuntimeFilterSuite.scala:
##########
@@ -518,48 +606,184 @@ class PerPartitionRuntimeFilterSuite extends 
KeyGroupedPartitioningSuiteBase {
       }
     }
 
-    test(s"the semi join follows a renamed join key (AQE $adaptive)") {
+    test(s"the scan keeps its bloom filters below a broadcast join under a 
storage-partitioned " +
+        s"join (AQE $adaptive)") {
+      // The broadcast join with `small` sits between the scan of `fact` and 
the
+      // `GroupPartitionsExec` that groups the scan's splits. That join keeps 
the scan's partitions
+      // as they are. So each task still reads the splits of one key.
+      createTables()
+      createTableWith("small", Array(Column.create("v", IntegerType)), 
Array.empty)
+      sql("INSERT INTO testcat.ns.small VALUES " +
+        (0 until 16).map(i => s"(${i * 10})").mkString(", "))
+      withSQLConf(ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString) {
+        withoutGlobalBloomFilter("dim") {
+          def query: DataFrame = sql("SELECT /*+ BROADCAST(s) */ f.id, f.v " +
+            "FROM testcat.ns.fact f JOIN testcat.ns.small s ON f.v = s.v " +
+            "JOIN testcat.ns.dim d ON f.id = d.id WHERE d.flag = 1")
+          val df = query
+          checkAnswer(df, expectedRows)
+          val plan = df.queryExecution.executedPlan
+          assert(collect(plan) { case j: BroadcastHashJoinExec => j }.size == 
1,
+            s"test setup: `small` must be broadcast:\n$plan")
+          assert(storageFilterScans(plan).map(tableOf) == Seq("fact"), plan)
+          assert(factReadKeysOf(query) == Set("1", "3"))
+        }
+      }
+    }
+
+    test(s"the per-partition bloom filter follows a renamed join key (AQE 
$adaptive)") {
       // The placeholder is pushed below the rename, so it checks `id` rather 
than `fid`.
       createTables()
       withSQLConf(ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString) {
         withoutGlobalBloomFilter("dim") {
-          val df = sql("SELECT f.fid, f.v FROM (SELECT id AS fid, v FROM 
testcat.ns.fact) f " +
-            "JOIN testcat.ns.dim d ON f.fid = d.id WHERE d.flag = 1")
-          val keys =
-            
perPartitionSemiJoins(df).flatMap(PerPartitionRuntimeFilterSubquery.semiJoinKey)
+          def query: DataFrame = sql("SELECT f.fid, f.v FROM (SELECT id AS 
fid, v " +
+            "FROM testcat.ns.fact) f JOIN testcat.ns.dim d ON f.fid = d.id 
WHERE d.flag = 1")
+          val df = query
+          val keys = perPartitionFilters(df).map(_.key)
           assert(keys.map(_.references.map(_.name).toSet) == Seq(Set("id")),
             df.queryExecution.optimizedPlan)
           checkAnswer(df, expectedRows)
           val plan = df.queryExecution.executedPlan
-          assert(executedSemiJoins(plan).size == 1, plan)
+          assert(storageFilterScans(plan).map(tableOf) == Seq("fact"), plan)
+          assert(factReadKeysOf(query) == Set("1", "3"))
+        }
+      }
+    }
+
+    test(s"a later join on the key still gets its bloom filter, which the scan 
also gets " +
+        s"(AQE $adaptive)") {
+      // The creation side of `dim` is too big for one bloom filter of all its 
keys, so its join
+      // gets only the per-partition one. The join with `dim2` on the same key 
still gets its bloom
+      // filter. It reaches the scan of `fact` as a runtime filter and a 
storage filter. Each is a
+      // subquery that the scan node holds, so physical planning plans them.
+      createTables(runtimeFiltering = true)
+      createIdTable("dim2", "flag", "(1, 1), (3, 1)")
+      def query: DataFrame = sql("SELECT f.id, f.v FROM testcat.ns.fact f " +
+        "JOIN testcat.ns.dim d ON f.id = d.id JOIN testcat.ns.dim2 d2 ON f.id 
= d2.id " +
+        "WHERE d.flag = 1 AND d2.flag = 1")
+      withSQLConf(ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString) {
+        withoutGlobalBloomFilter("dim") {
+          val df = query
+          val optimized = df.queryExecution.optimizedPlan
+          assert(perPartitionFilters(df).size == 1, optimized)
+          assert(hasGlobalBloomFilter(optimized), optimized)
+          checkAnswer(df, Seq(Row(1, 10), Row(3, 30)))
+          val plan = df.queryExecution.executedPlan
+          val scans = storageFilterScans(plan)
+          assert(scans.map(tableOf) == Seq("fact"), plan)
+          
assert(scans.head.runtimeFilters.exists(_.exists(_.isInstanceOf[ExecScalarSubquery]))
 &&
+            
scans.head.storageFilters.exists(_.exists(_.isInstanceOf[ExecScalarSubquery])), 
plan)
+          assert(df.queryExecution.explainString(FormattedMode)
+            .contains("might_contain(bloomFilter"))
+          // Each split of bucket 1 gets a filter that keeps only the key 1 of 
`dim` there, since
+          // `dim2` has no 5 or 9.
+          val (rows, reads, probed) = factReadsOf(query, probes = Seq(1L, 3L, 
5L, 9L))
+          assert(rows == Set(Row(1, 10), Row(3, 30)))
+          assert(reads.map(_._1).toSet == Set("1", "3") && reads.map(_._3).sum 
>= 2, reads)
+          assert(probed == Set("1" -> Set(1L), "3" -> Set(3L)), probed)
+        }
+      }
+    }
+
+    test(s"a GroupPartitionsExec above the scan still merges its splits in 
order " +
+        s"(AQE $adaptive)") {
+      // `fact` reports its order by `id`, and has 4 splits in each bucket. 
With order preserved on
+      // coalescing, the join's GroupPartitionsExec merges them in order 
rather than sorting them.
+      // The aggregate under the scan gives the GroupPartitionsExec no rows, 
so the aggregate does
+      // not keep it from merging.
+      createTableWith("fact", Array(Column.create("id", LongType), 
Column.create("v", IntegerType)),
+        Array(bucket(4, "id")), ordering = Array(sort(FieldReference("id"),
+          SortDirection.ASCENDING, NullOrdering.NULLS_FIRST)))
+      sql("INSERT INTO testcat.ns.fact VALUES " +
+        (0 until 16).map(i => s"($i, ${i * 10})").mkString(", "))
+      createIdTable("dim", "flag", "(1, 1), (2, 0), (3, 1), (5, 1), (6, 0), 
(9, 1)")
+      withSQLConf(
+          ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString,
+          V2_BUCKETING_PRESERVE_ORDERING_ON_COALESCE_ENABLED.key -> "true") {
+        withoutGlobalBloomFilter("dim") {
+          val df = join()
+          checkAnswer(df, expectedRows)
+          val plan = df.queryExecution.executedPlan
+          assert(storageFilterScans(plan).map(tableOf) == Seq("fact"), plan)
+          val merges = collect(plan) {
+            case g: GroupPartitionsExec if storageFilterScans(g).nonEmpty => g
+          }
+          assert(merges.size == 1 &&
+            merges.head.execute().isInstanceOf[SortedMergeCoalescedRDD[_]], 
plan)
+        }
+      }
+    }
+
+    test(s"the bloom filter of a split joins the other storage filters of the 
scan " +
+        s"(AQE $adaptive)") {
+      // `fact` gets a bloom filter of all the keys of `small` on `x`, which 
its scan takes as a
+      // storage filter, with the checked column. `dim` gives it a 
per-partition one on `id`.
+      createTwoKeyTables()
+      createTableWith("small", Array(Column.create("x", IntegerType),
+        Column.create("flag", IntegerType)), Array.empty)
+      sql("INSERT INTO testcat.ns.small VALUES (0, 1)")
+      def query: DataFrame = sql("SELECT f.id, f.v FROM testcat.ns.fact f " +
+        "JOIN (SELECT id, flag FROM testcat.ns.dim) d ON f.id = d.id " +
+        "JOIN testcat.ns.small s ON f.x = s.x WHERE d.flag = 1 AND s.flag = 1")
+      withSQLConf(ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString) {
+        withoutGlobalBloomFilter("dim") {
+          val df = query
+          checkAnswer(df, Seq(Row(3, 30), Row(9, 90)))
+          val plan = df.queryExecution.executedPlan
+          val scans = storageFilterScans(plan)
+          assert(scans.map(tableOf) == Seq("fact") && 
scans.head.storageFilters.nonEmpty,
+            s"test setup: the scan must also get the bloom filter of 
`small`:\n$plan")
+          assert(scans.head.appendsCheckedColumn, plan)
+          val (rows, reads, _) = factReadsOf(query)
+          assert(rows == Set(Row(3, 30), Row(9, 90)))
+          assert(reads.map(_._1).toSet == Set("1", "3"), reads)
+          assert(reads.map(_._3).sum == 2, s"the readers keep only ids 3 and 
9: $reads")
         }
       }
     }
   }
 
-  test("the semi joins of a plan optimized with the conf on are judged with it 
off") {
-    // The semi join would shuffle, as in "the semi join goes when it would 
shuffle".
+  test("a plan optimized with per-partition bloom filters on keeps them when 
planned with " +

Review Comment:
   Thanks, added a test in 
[2a0cd98](https://github.com/apache/spark/pull/60752/commits/2a0cd98857d46b6b2bb97d4f9588f5e01fd96277).
 A plan optimized with per-partition bloom filters on, and planned with them 
off, reads without them under a join that shuffles a key's several splits.
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/GroupPartitionsExec.scala:
##########
@@ -261,11 +263,15 @@ case class GroupPartitionsExec(
   // whitelist so the evaluation stays consistent. So is the `DebugExec` that 
the `debug()` helper
   // (`org.apache.spark.sql.execution.debug`) wraps every node in without AQE. 
A rule that breaks
   // this under a planned merge fails the query at execution, see 
`checkPlannedMergeRuns`.
-  @transient private lazy val childIsSafeForKWayMerge: Boolean =
-    !child.exists {
-      case _: SafeForKWayMerge => false
-      case _ => true
-    }
+  @transient private lazy val childIsSafeForKWayMerge: Boolean = 
unsafeForKWayMerge(child).isEmpty
+
+  // The first node from `plan` down through `kWayMergeInputs` that does not 
mix in
+  // `SafeForKWayMerge`, if any.
+  private def unsafeForKWayMerge(plan: SparkPlan): Option[SparkPlan] = plan 
match {
+    case safe: SafeForKWayMerge => 
safe.kWayMergeInputs.iterator.flatMap(unsafeForKWayMerge)

Review Comment:
   Thanks, added a test to `GroupPartitionsExecSuite` in 
[2a0cd98](https://github.com/apache/spark/pull/60752/commits/2a0cd98857d46b6b2bb97d4f9588f5e01fd96277).
 A `DummySparkPlan` below a node that mixes in `SafeForKWayMerge` keeps the 
merge from running, and the planned merge fails naming it.
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/SizePerPartitionStorageFilters.scala:
##########
@@ -0,0 +1,157 @@
+/*
+ * 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 org.apache.spark.sql.catalyst.expressions.{ExprId, Literal}
+import org.apache.spark.sql.catalyst.expressions.aggregate.BloomFilterAggregate
+import 
org.apache.spark.sql.catalyst.optimizer.{PerPartitionRuntimeFilterSubquery, 
PerPartitionSizing}
+import org.apache.spark.sql.catalyst.plans.physical.{Partitioning, 
PartitioningCollection, REPLICATED_FOR_JOIN, SPLIT_FOR_JOIN}
+import org.apache.spark.sql.catalyst.rules.Rule
+import 
org.apache.spark.sql.catalyst.trees.TreePattern.PER_PARTITION_RUNTIME_FILTER_SUBQUERY
+import org.apache.spark.sql.execution.{SnapshotUnionPreparationConf, 
SparkPlan, UnionConfSnapshot}
+import org.apache.spark.sql.execution.aggregate.BaseAggregateExec
+import org.apache.spark.sql.execution.exchange.{EnsureRequirements, Exchange}
+
+/**
+ * Sizes the per-partition bloom filters of each [[BatchScanExec]] that has 
one. It keeps them only
+ * where a task reads all the splits of its keys, or where partially clustered 
distribution
+ * spreads or repeats them.
+ *
+ * Each bloom filter expects an even share of the creation side's items over 
its partition keys.
+ * Without a row count, it also gets an even share of the creation side's 
bits. The scan is planned
+ * without them when the creation side reports no partition keys, or too few 
for each share to be
+ * within the size threshold of a bloom filter's input. An aggregate this rule 
keeps reads a
+ * creation side that reports its partition keys, so `EnsureRequirements` puts 
no exchange below it.
+ * Rules that look for exchanges at the leaves of a plan rely on that, such as
+ * `CoalesceShufflePartitions`.
+ *
+ * Each task reads the partitions of the aggregate with its splits' keys, and 
the creation side
+ * under them. So the scan keeps its bloom filters where a task reads all the 
splits of its keys:
+ *  - when the scan reports one split for each key;
+ *  - when a `GroupPartitionsExec` above the scan groups them with no exchange 
in between, as below
+ *    a storage-partitioned join.
+ * Partially clustered distribution spreads or repeats the splits of a key 
over tasks, and the scan
+ * keeps them there too. Turning it on accepts that each of those tasks reads 
one side's splits of
+ * the key again. The aggregate is read again in each of them too. Under a 
join that shuffles a
+ * scan with several splits for a key, a task reads only some of them, so the 
scan reads without
+ * its bloom filters. To tell, this asks `ensureRequirements`, the one the 
preparation plans with,
+ * how it would plan the query. That planning asks a `UnionExec` what it 
reports, so this first
+ * records `unionConf` on each union, as the preparation does ahead of 
`EnsureRequirements`.
+ *
+ * A `PerPartitionRuntimeFilterSubquery` that no scan took gives way to `true` 
here, since it cannot
+ * be evaluated. The join above it checks its rows anyway. 
`CleanupPerPartitionRuntimeFilters`
+ * keeps only those the V2 scan strategy takes, so one is left when, for 
instance, an optimizer
+ * rule a user added moved it away from its scan.
+ */
+case class SizePerPartitionStorageFilters(
+    ensureRequirements: EnsureRequirements,
+    unionConf: UnionConfSnapshot) extends Rule[SparkPlan] {
+
+  override def apply(plan: SparkPlan): SparkPlan = {
+    val sized = plan.transformUp {
+      case scan @ BatchScanExec(_, _, _, _, _, _, _, _, Some(filter), 
Some(aggregate)) =>
+        sizeOf(aggregate, filter.sizing) match {
+          case Some((numItems, numBits)) =>
+            scan.withNewChildren(Seq(withSize(aggregate, numItems, numBits)))
+          case None => scan.withoutPerPartitionBloomFilter
+        }
+    }
+    readOnce(sized).transformAllExpressionsWithPruning(

Review Comment:
   Thanks, added a test in 
[2a0cd98](https://github.com/apache/spark/pull/60752/commits/2a0cd98857d46b6b2bb97d4f9588f5e01fd96277).
 An extra optimizer rule moves the placeholder above a projection of a random 
column. The query returns the join's rows, and no placeholder is left in its 
executed plan, with AQE on and off.
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/BatchScanExec.scala:
##########
@@ -86,7 +118,10 @@ case class BatchScanExec(
       case _ =>
         SQLMetrics.createMetric(sparkContext, name)
     }
-    Map("numOutputRows" -> metric)
+    Map("numOutputRows" -> metric) ++ perPartitionBloomFilter.map { _ =>
+      "numSkippedSplits" -> SQLMetrics.createMetric(sparkContext,
+        "number of splits skipped by runtime filters")

Review Comment:
   I keep the name. It is meant to cover other runtime filters that skip splits 
later.
   



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