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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ChoosePerPartitionRuntimeFilters.scala:
##########
@@ -0,0 +1,213 @@
+/*
+ * 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.joins
+
+import org.apache.spark.sql.catalyst.expressions.{And, Attribute, ExprId, 
PredicateHelper}
+import org.apache.spark.sql.catalyst.expressions.aggregate.BloomFilterAggregate
+import 
org.apache.spark.sql.catalyst.optimizer.PerPartitionRuntimeFilterSubquery.{perPartitionRuntimeFilter,
 sizingOf}
+import org.apache.spark.sql.catalyst.plans.ExistenceJoin
+import org.apache.spark.sql.catalyst.plans.physical.{PartitioningCollection, 
SinglePartition}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.execution.{FilterExec, ProjectExec, 
SnapshotUnionPreparationConf, SparkPlan, UnionConfSnapshot}
+import org.apache.spark.sql.execution.aggregate.BaseAggregateExec
+import org.apache.spark.sql.execution.exchange.{EnsureRequirements, Exchange, 
ShuffleExchangeLike}
+
+/**
+ * Keeps each semi join of a per-partition runtime bloom filter that
+ * `InsertPerPartitionRuntimeFilterJoins` built only when it costs the 
application side nothing,
+ * and sizes its bloom filters.
+ *
+ * A semi join costs the application side nothing when it adds no shuffle, and 
the stage that reads
+ * the application side runs at least as many tasks as without it. That holds 
when the join above
+ * is a storage-partitioned join that groups the application side's splits the 
way the semi join
+ * does. So this asks `ensureRequirements`, the one the preparation plans 
with, how it would plan
+ * the query. It starts from the query without the semi joins, and adds them 
back one at a time.
+ * Each stays when it is free against the plan built so far. So a semi join 
that goes cannot make
+ * one that is free look costly. The rule judges every semi join it finds, 
whatever the conf says
+ * now, since a plan optimized with the conf on can be planned with it off.
+ *
+ * That planning asks a `UnionExec` what it reports, so this first records 
`unionConf` on each
+ * union, as the preparation does ahead of `EnsureRequirements`.
+ *
+ * Each bloom filter of a semi join that stays expects an even share of the 
creation side's items
+ * over its partition keys. The semi join also goes when the creation side has 
too few partition
+ * keys for each share to be within the size threshold of a bloom filter's 
input.
+ */
+case class ChoosePerPartitionRuntimeFilters(
+    ensureRequirements: EnsureRequirements,
+    unionConf: UnionConfSnapshot) extends Rule[SparkPlan] with PredicateHelper 
{
+
+  override def apply(plan: SparkPlan): SparkPlan = {
+    val semiJoins = plan.flatMap(PerPartitionSemiJoin.unapply(_))
+    // The application side without each semi join this rule can take out, by 
its bloom filter
+    // column, which stays when a semi join above goes. A semi join of a shape 
this rule does not
+    // know stays as it is.
+    val withouts = semiJoins.flatMap { case (filter, join, bloomFilter) =>
+      withoutSemiJoin(filter, join).map(bloomFilter.exprId -> _)
+    }.toMap
+    if (withouts.isEmpty) {
+      plan
+    } else {
+      new SnapshotUnionPreparationConf(unionConf).apply(plan)
+      // `plan` with only those of the semi joins this rule can take out that 
are in `kept`.
+      def withOnly(kept: Set[ExprId]): SparkPlan = plan.transformDown {

Review Comment:
   Thanks, done with [16]. One `withOnly(kept)` builds the first plan, each 
trial and the result (6249042).
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/InjectRuntimeFilter.scala:
##########
@@ -41,17 +42,143 @@ object InjectRuntimeFilter extends Rule[LogicalPlan] with 
PredicateHelper with J
       plan: LogicalPlan,
       useMaterializedThreshold: Boolean,
       materializedRowCount: Option[BigInt] = None,
-      materializedSizeInBytes: Option[BigInt] = None)
+      materializedSizeInBytes: Option[BigInt] = None) {
 
+    // The creation side's row count, when known. A count of 0 is taken as 
unknown.
+    def rowCount: Option[BigInt] =
+      materializedRowCount.orElse(plan.stats.rowCount).filter(_ > 0)
+
+    // The creation side's size, and the threshold the input of one bloom 
filter must not exceed.
+    def sizeInBytes: BigInt = 
materializedSizeInBytes.getOrElse(plan.stats.sizeInBytes)
+    def sizeThreshold: Long = if (useMaterializedThreshold) {
+      conf.runtimeFilterMaterializedCreationSideThreshold
+    } else {
+      conf.runtimeFilterCreationSideThreshold
+    }
+  }
+
+  // `filterApplicationSidePlan` with a bloom filter of the whole creation 
side, or with the
+  // placeholder of a per-partition one when `perPartition` is true, if it 
gets one. Only a creation
+  // side too big for the former can give the latter.
   private def injectFilter(
       filterApplicationSideKey: Expression,
       filterApplicationSidePlan: LogicalPlan,
-      filterCreationSide: FilterCreationSide): LogicalPlan = {
-    injectBloomFilter(
-      filterApplicationSideKey,
-      filterApplicationSidePlan,
-      filterCreationSide
-    )
+      filterCreationSide: FilterCreationSide,
+      perPartition: Boolean): Option[LogicalPlan] = {
+    if (!perPartition) {
+      Some(injectBloomFilter(
+        filterApplicationSideKey,
+        filterApplicationSidePlan,
+        filterCreationSide
+      )).filterNot(_ eq filterApplicationSidePlan)
+    } else if (filterCreationSide.sizeInBytes > 
filterCreationSide.sizeThreshold &&
+        canGetPerPartitionBloomFilter(
+          filterApplicationSideKey, filterApplicationSidePlan, 
filterCreationSide)) {
+      injectPerPartitionBloomFilter(
+        filterApplicationSideKey, filterApplicationSidePlan, 
filterCreationSide)
+    } else {
+      None
+    }
+  }
+
+  /**
+   * Whether the application side can get a per-partition bloom filter. It 
needs a V2 scan under
+   * each side that reports a keyed partitioning by the same transform of its 
join key. A
+   * per-partition bloom filter is a semi join of the application side with 
one bloom filter per
+   * partition key of the creation side.
+   *
+   * `injectPerPartitionBloomFilter` then adds its 
[[PerPartitionRuntimeFilterSubquery]]. Predicate
+   * pushdown moves it along the key. [[InsertPerPartitionRuntimeFilterJoins]] 
then builds the semi
+   * join where it landed. `ChoosePerPartitionRuntimeFilters` keeps the semi 
join only when it adds
+   * no shuffle and cuts no tasks that read the application side, and the 
creation side has enough
+   * partition keys for the size threshold.
+   *
+   * A key gets one per-partition bloom filter at most, so a later join on the 
same key adds none.
+   */
+  private def canGetPerPartitionBloomFilter(
+      filterApplicationSideKey: Expression,
+      filterApplicationSidePlan: LogicalPlan,
+      filterCreationSide: FilterCreationSide): Boolean = {
+    conf.runtimeBloomFilterPerPartitionEnabled && (for {
+      application <- partitionTransform(filterApplicationSideKey, 
filterApplicationSidePlan)
+      creation <- partitionTransform(filterCreationSide.key, 
filterCreationSide.plan)
+    } yield application.isSameFunction(creation)).getOrElse(false) &&
+      !hasPerPartitionRuntimeFilter(filterApplicationSidePlan, 
filterApplicationSideKey)
+  }
+
+  /**
+   * The partition transform of the V2 scan `key` comes from under `plan`, 
rebuilt over `key`.
+   * Defined when:
+   *  - V2 bucketing is on;
+   *  - `key` is one of the scan's columns, followed down through `plan`;
+   *  - the scan reports a keyed partitioning by a single transform of that 
column;
+   *  - the transform is deterministic, since both sides of the semi join 
evaluate it;
+   *  - Spark can evaluate the transform 
(`TransformExpression.evaluableFunction`).
+   *
+   * The semi join is correct whatever lies between `plan` and the scan, since 
it checks each row
+   * against the bloom filter of its own partition key. A row whose partition 
key is null passes it,
+   * so the transform may return null for any key.
+   */
+  private[optimizer] def partitionTransform(
+      key: Expression,
+      plan: LogicalPlan): Option[TransformExpression] = {
+    if (!conf.v2BucketingEnabled) {
+      None
+    } else {
+      findExpressionAndTrackLineageDown(key, plan).flatMap {
+        case (column: Attribute, scan: DataSourceV2ScanRelation) =>
+          scan.keyGroupedPartitioning.collect {
+            case Seq(t @ TransformExpression(_, Seq(child), _, _))
+                if child.semanticEquals(column) && t.function.isDeterministic 
&&
+                  t.evaluableFunction.isDefined =>
+              t.copy(children = Seq(key))
+          }
+        case _ => None
+      }
+    }
+  }
+
+  // `filterApplicationSidePlan` with the placeholder of a per-partition bloom 
filter of its key.
+  // The aggregate of its semi join reads the creation side again, apart from 
the join. So a
+  // creation side gives none when:
+  //  - it has a Python UDF or is not deterministic, as for the bloom filter 
of the whole creation
+  //    side;
+  //  - it reads a V2 scan with a pushed operation that does not work on each 
row by itself, such as
+  //    a limit. Such a scan can return other rows when read again (see 
`canEvaluateAgain`).
+  private def injectPerPartitionBloomFilter(
+      filterApplicationSideKey: Expression,
+      filterApplicationSidePlan: LogicalPlan,
+      filterCreationSide: FilterCreationSide): Option[LogicalPlan] = {
+    val creationSide = ConstantFolding(ColumnPruning(
+      Project(Seq(Alias(filterCreationSide.key, "key")()), 
filterCreationSide.plan)))
+    if (creationSide.containsPattern(PYTHON_UDF) || 
!creationSide.deterministic ||

Review Comment:
   Thanks. I'd keep them apart here. The bloom filter of the whole creation 
side checks the pushed operations only for a key with a DPP filter, so the 
paths differ on purpose today. A shared helper fits the follow-up that makes 
that check apply always.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/InsertPerPartitionRuntimeFilterJoins.scala:
##########
@@ -0,0 +1,247 @@
+/*
+ * 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, Attribute, 
AttributeReference, BloomFilterMightContain, EqualTo, Expression, ExprId, 
IsNull, Literal, NamedExpression, Or, Predicate, PredicateHelper, 
SubqueryExpression, Unevaluable, XxHash64}
+import org.apache.spark.sql.catalyst.expressions.aggregate.BloomFilterAggregate
+import 
org.apache.spark.sql.catalyst.optimizer.InjectRuntimeFilter.partitionTransform
+import org.apache.spark.sql.catalyst.plans.ExistenceJoin
+import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, Filter, 
HintInfo, Join, JoinHint, LogicalPlan, Project, SHUFFLE_HASH, 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.types.{BooleanType, Metadata, MetadataBuilder}
+
+/**
+ * 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. 
[[InsertPerPartitionRuntimeFilterJoins]] then builds a semi
+ * join from it, with an aggregate of `plan`.
+ *
+ * Like `DynamicPruningSubquery`, it cannot be evaluated. Where it gets no 
semi join, it gives way
+ * to `true`.
+ *
+ * `numItems` is the expected number of items of the whole creation side. 
`minPartitionKeys` is the
+ * number of partition keys it needs at least, so that an even share of it is 
within the size
+ * threshold of a bloom filter's input.
+ */
+case class PerPartitionRuntimeFilterSubquery(
+    key: Expression,
+    plan: LogicalPlan,
+    numItems: Long,
+    minPartitionKeys: Long,
+    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 metadata key of the bloom filter column of a per-partition bloom 
filter's aggregate.
+   * [[InsertPerPartitionRuntimeFilterJoins]] sets it. That is how 
[[InjectRuntimeFilter]] and
+   * `ChoosePerPartitionRuntimeFilters` tell the semi join from one a query 
wrote. Its value holds
+   * the `numItems` and `minPartitionKeys` of the placeholder, for sizing the 
bloom filters.
+   */
+  private val PER_PARTITION_RUNTIME_FILTER = "__per_partition_runtime_filter"
+
+  /**
+   * The metadata of the bloom filter column of the aggregate of 
`placeholder`'s per-partition bloom
+   * filter, with its sizing.
+   */
+  private[optimizer] def bloomFilterMetadata(
+      placeholder: PerPartitionRuntimeFilterSubquery): Metadata = {
+    val sizing = new MetadataBuilder()
+      .putLong("numItems", placeholder.numItems)
+      .putLong("minPartitionKeys", placeholder.minPartitionKeys)
+      .build()
+    new MetadataBuilder().putMetadata(PER_PARTITION_RUNTIME_FILTER, 
sizing).build()
+  }
+
+  /**
+   * For the condition of a semi join of a per-partition bloom filter, the 
bloom filter column and
+   * the key it checks. The column carries [[PER_PARTITION_RUNTIME_FILTER]].
+   */
+  def perPartitionRuntimeFilter(condition: Expression): Option[(Attribute, 
Expression)] =
+    splitConjunctivePredicates(condition).collectFirst {
+      case BloomFilterMightContain(bloomFilter: Attribute, XxHash64(Seq(key), 
_))
+          if bloomFilter.metadata.contains(PER_PARTITION_RUNTIME_FILTER) => 
(bloomFilter, key)
+    }
+
+  /**
+   * The expected number of items of the whole creation side of the 
per-partition bloom filter with
+   * the column `bloomFilter`, and the number of partition keys it needs at 
least.
+   */
+  def sizingOf(bloomFilter: Attribute): (Long, Long) = {
+    val sizing = bloomFilter.metadata.getMetadata(PER_PARTITION_RUNTIME_FILTER)
+    (sizing.getLong("numItems"), sizing.getLong("minPartitionKeys"))
+  }
+
+  /** The key that `plan` checks, when it is the join of a placeholder's semi 
join. */
+  def semiJoinKey(plan: LogicalPlan): Option[Expression] = plan match {
+    case Join(_, _, ExistenceJoin(_), Some(condition), _) =>
+      perPartitionRuntimeFilter(condition).map(_._2)
+    case _ => None
+  }
+
+  /** `child` under the `conjuncts` that are not placeholders. */
+  private[optimizer] def withoutPlaceholders(
+      conjuncts: Seq[Expression],
+      child: LogicalPlan): LogicalPlan =
+    
conjuncts.filterNot(_.isInstanceOf[PerPartitionRuntimeFilterSubquery]).reduceOption(And)
+      .map(Filter(_, child)).getOrElse(child)
+
+  /** A `Filter` with placeholders among its conjuncts, as its conjuncts, 
placeholders and child. */
+  private[optimizer] object WithPlaceholders {
+    def unapply(plan: LogicalPlan): Option[
+        (Seq[Expression], Seq[PerPartitionRuntimeFilterSubquery], 
LogicalPlan)] = plan match {
+      case Filter(condition, child)
+          if condition.containsPattern(PER_PARTITION_RUNTIME_FILTER_SUBQUERY) 
=>
+        val conjuncts = splitConjunctivePredicates(condition)
+        val placeholders = conjuncts.collect { case p: 
PerPartitionRuntimeFilterSubquery => p }
+        if (placeholders.isEmpty) None else Some((conjuncts, placeholders, 
child))
+      case _ => None
+    }
+  }
+}
+
+/**
+ * Replaces each [[PerPartitionRuntimeFilterSubquery]] with its semi join, 
right where predicate
+ * pushdown put it. So the operators the placeholder moved past get only the 
rows the semi join
+ * keeps. The semi join checks each row on its key alone, so it is correct 
wherever the placeholder
+ * is.
+ *
+ * The optimizer runs on each subquery on its own first, as a `Subquery`, and 
there this rule does
+ * nothing. The run on the whole query builds the semi joins in its subqueries 
too, after
+ * `MergeSubplans`.
+ *
+ * A placeholder gives way to `true` when:
+ *  - it has more than one copy, as when pushdown puts one into every branch 
of a union. The semi
+ *    join of each copy would read the creation side again;
+ *  - it is no longer a conjunct of a `Filter`, as when `MergeSubplans` 
propagates its filter into a
+ *    projection;
+ *  - its key no longer has the creation side's partition transform there.
+ *
+ * The rule cannot be excluded, since a placeholder cannot be evaluated.
+ */
+object InsertPerPartitionRuntimeFilterJoins extends Rule[LogicalPlan] {
+  import PerPartitionRuntimeFilterSubquery.{bloomFilterMetadata, 
withoutPlaceholders,
+    WithPlaceholders}
+
+  override def apply(plan: LogicalPlan): LogicalPlan = plan match {
+    case _: Subquery => plan
+    case _ if !plan.containsPattern(PER_PARTITION_RUNTIME_FILTER_SUBQUERY) => 
plan
+    case _ =>
+      // The number of copies of each placeholder, in `plan` and its 
subqueries.
+      val copies = plan.collectWithSubqueries { case node => node.expressions 
}.flatten
+        .flatMap(_.collect { case p: PerPartitionRuntimeFilterSubquery => 
p.exprId })
+        .groupBy(identity).view.mapValues(_.size).toMap
+      val withSemiJoins = plan.transformUpWithSubqueriesAndPruning(
+          _.containsPattern(PER_PARTITION_RUNTIME_FILTER_SUBQUERY)) {
+        case WithPlaceholders(conjuncts, placeholders, child) =>
+          placeholders.filter(p => copies(p.exprId) == 1)
+            .foldLeft(withoutPlaceholders(conjuncts, child)) { (node, p) =>
+              semiJoin(node, p).getOrElse(node)
+            }
+      }
+      withoutLeftovers(withSemiJoins)
+  }
+
+  // `plan` with each placeholder left giving way to `true`, in its subqueries 
too.
+  private def withoutLeftovers(plan: LogicalPlan): LogicalPlan =
+    plan.transformDownWithSubqueriesAndPruning(
+        _.containsPattern(PER_PARTITION_RUNTIME_FILTER_SUBQUERY)) {
+      case node => node.transformExpressionsWithPruning(
+          _.containsPattern(PER_PARTITION_RUNTIME_FILTER_SUBQUERY)) {
+        case _: PerPartitionRuntimeFilterSubquery => Literal.TrueLiteral
+      }
+    }
+
+  /**
+   * `plan` in a semi join with an aggregate of the creation side of 
`placeholder`. The aggregate
+   * groups that side by its partition transform, with a bloom filter of its 
join key per group. The
+   * join checks each row's key against the bloom filter of the row's 
partition key, which the
+   * application side's transform of the key gives. The transform may return 
null for a key that is
+   * not null, and the join above can match such a row. So the semi join is an 
existence join, with
+   * a filter that keeps the rows that pass the check or whose partition key 
is null.
+   *
+   * None when the two keys no longer have the same partition transform there.
+   */
+  private def semiJoin(
+      plan: LogicalPlan,
+      placeholder: PerPartitionRuntimeFilterSubquery): Option[LogicalPlan] = {
+    val creationKey = placeholder.plan.output.head
+    val key = placeholder.key
+    for {

Review Comment:
   Thanks, both rules now use `pairedPartitionTransforms` (19848ca).
   



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