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


##########
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:
   **Nit (P3):** `PerPartitionStorageFilterRDD.compute` increments this metric 
only for a split whose partition key has no per-partition bloom filter, and 
returns without counting for a split that the scan's runtime filters pruned. 
The node lists those runtime filters as `RuntimeFilters: [...]`, so in the SQL 
UI a reader would take this count for the splits they pruned. Naming the 
per-partition bloom filters keeps the metric's key and what it counts:
   
   ```suggestion
           "number of splits skipped by per-partition bloom filters")
   ```
   
   **Verification:**
   - **Inspection:** The skipped-splits metric's label names per-partition 
bloom filters, its key and what it counts are unchanged, and no code or 
document still describes it as counting splits skipped by runtime filters.



##########
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:
   **Nit (P3):** This descent replaces `child.exists`, but no test exercises it 
below the first level: `GroupPartitionsExecSuite`'s negative cases put an 
unsafe `DummySparkPlan` directly under the `GroupPartitionsExec`, and the new 
merge test in `PerPartitionRuntimeFilterSuite` covers only `BatchScanExec`'s 
empty `kWayMergeInputs`. If the walk stopped at the first `SafeForKWayMerge` 
node, a merge planned over `ProjectExec(DummySparkPlan)` would be judged safe 
and run over the unsafe node without the error `checkPlannedMergeRuns` raises, 
and every test would still pass.
   
   **Verification:**
   - **Regression:** A GroupPartitionsExec over a node that mixes in 
SafeForKWayMerge above a node that does not plans no k-way merge, and a merge 
planned over that child anyway fails naming the unsafe node; the check fails if 
the safety walk stops at the first safe node.



##########
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:
   **Nit (P3):** On the base branch no placeholder left the optimizer. Here one 
can reach physical planning outside a scan when an optimizer rule a user adds 
(the User Provided Optimizers batch runs after 
`CleanupPerPartitionRuntimeFilters`) or an extension's strategy moves its 
filter, for example above a projection with a nondeterministic column: 
`PhysicalOperation` does not push a filter through such a projection, so 
`BasicOperators` plans the placeholder in a `FilterExec`. This replacement is 
then all that keeps the query from evaluating an `Unevaluable` expression, but 
no test reaches it: the only check for placeholders in an executed plan 
(PerPartitionRuntimeFilterSuite.scala lines 830-831) follows a scan whose 
placeholder the V2 strategy had already taken, so it passes without this code. 
A regression here would fail such queries at execution while every test still 
passes.
   
   **Verification:**
   - **Regression:** With an extra optimizer rule that moves a kept 
per-partition placeholder away from its scan, so that it reaches physical 
planning in a filter above the scan, the query returns the join's rows and no 
placeholder remains in its executed plan, with adaptive execution on and off, 
and the check fails at execution if leftover placeholders are no longer 
replaced.



##########
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:
   **Nit (P3):** This test runs the default storage-partitioned fixture, where 
the scan keeps its bloom filters whether or not 
`SizePerPartitionStorageFilters` judges it, so it cannot fail if the rule stops 
running while the per-partition conf is off. The base branch's test 'the semi 
joins of a plan optimized with the conf on are judged with it off' ran with 
`V2_BUCKETING_PUSH_PART_VALUES_ENABLED` false, where the rule had to drop the 
filter, and no test covers that mode any more. A conf check added to the rule 
would leave a scan planned with the conf off, with four splits per key under a 
shuffle, keeping bloom filters of the default size: each split's task would 
read its key's aggregate, and `dim` under it, again, and every test would still 
pass.
   
   **Verification:**
   - **Regression:** A plan optimized with per-partition bloom filters on and 
planned with them off, in which the join shuffles a scan with several splits 
per key, returns the join's rows and its scan reads without per-partition bloom 
filters, and the check fails if the sizing rule is skipped while the 
per-partition conf is off.



##########
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:
   **Non-blocking (P2):** Nothing in the suite would fail if this cache stopped 
working. The only count of `dim`'s reads (`plainReadsOf("dim")`, 
PerPartitionRuntimeFilterSuite.scala lines 370-373) is in a test whose scan 
drops its bloom filters, and the tests that keep them assert rows, `fact`'s 
reads, probes and `numSkippedSplits`, which come out the same if each split 
builds its own request. In the default fixture, with four splits of `fact` per 
bucket and one task per bucket, a cache that always missed would compute each 
key's aggregate partition, and read `dim`'s splits under it, four times per 
task instead of once. The results stay correct, so only a count of the creation 
side's reads in a layout that keeps the bloom filters can catch such a 
regression.
   
   **Verification:**
   - **Regression:** In a storage-partitioned join in which each task reads 
several splits of one key, the scan keeps its per-partition bloom filters and 
every task of the scan returns rows, the creation side is read exactly twice as 
often as with per-partition bloom filters off, once by the join and once by the 
bloom filter aggregate, with adaptive execution on and off, and the check fails 
when each split builds its own request.



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