peter-toth commented on code in PR #59866: URL: https://github.com/apache/spark/pull/59866#discussion_r4603052672
########## 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 { + case PerPartitionSemiJoin(_, _, bloomFilter) + if withouts.contains(bloomFilter.exprId) && !kept(bloomFilter.exprId) => + withouts(bloomFilter.exprId) + } + // The expected number of items of each bloom filter of each semi join that stays. + var numItems = Map.empty[ExprId, Long] + var current = new Cost(ensureRequirements.apply(withOnly(Set.empty))) + semiJoins.foreach { case (_, join, bloomFilter) => + val id = bloomFilter.exprId + if (withouts.contains(id)) { + numItemsOf(join, bloomFilter).foreach { n => + val trial = new Cost(ensureRequirements.apply(withOnly(numItems.keySet + id))) + if (isFree(trial, current, withouts(id))) { + numItems += id -> n + current = trial + } + } + } + } + plan.transformDown { + case p @ ProjectExec(_, PerPartitionSemiJoin(_, _, bloomFilter)) + if withouts.contains(bloomFilter.exprId) && !numItems.contains(bloomFilter.exprId) => + withoutRestoringProjection(p, withouts(bloomFilter.exprId)) + case PerPartitionSemiJoin(filter, join, bloomFilter) + if withouts.contains(bloomFilter.exprId) => + numItems.get(bloomFilter.exprId) match { + case Some(n) => filter.withNewChildren(Seq(withNumItems(join, n))) + case None => withouts(bloomFilter.exprId) + } + } + } + } + + // The semi join of a per-partition bloom filter: the filter on the flag of its existence join, + // that join, and the bloom filter column. + private object PerPartitionSemiJoin { + def unapply(plan: SparkPlan): Option[(FilterExec, ShuffledHashJoinExec, Attribute)] = + plan match { + case filter @ FilterExec(_, join: ShuffledHashJoinExec) + if join.joinType.isInstanceOf[ExistenceJoin] => + join.condition.flatMap(perPartitionRuntimeFilter).map { + case (bloomFilter, _) => (filter, join, bloomFilter) + } + case _ => None + } + } + + // The shuffles of a plan, and the tasks of the stage that reads each of its leaves. Those are the + // partitions of the topmost operator above the leaf that no exchange separates from it. An + // operator that reports one partition or none, such as a limit, a write or an `Expand`, does not + // tell how many tasks read its child, so the child counts instead. + private class Cost(plan: SparkPlan) { + val shuffles: Int = plan.collect { case s: ShuffleExchangeLike => s }.size + + private val tasks: Seq[(SparkPlan, Int)] = { + def walk(node: SparkPlan, top: SparkPlan): Seq[(SparkPlan, Int)] = { + if (node.children.isEmpty) { + Seq(node -> top.outputPartitioning.numPartitions) + } else { + val countsChild = node.isInstanceOf[Exchange] || (node.outputPartitioning match { + case SinglePartition => true + case partitioning => partitioning.numPartitions == 0 + }) + node.children.flatMap(child => walk(child, if (countsChild) child else top)) + } + } + walk(plan, plan) + } + + def tasksReading(leaf: SparkPlan): Option[Int] = + tasks.collectFirst { case (l, n) if l eq leaf => n } + } + + // Whether a semi join adds no shuffle, and leaves the stage that reads its application side no + // fewer tasks than it has without the semi join. `withIt` and `withoutIt` are the costs of the + // plan with and without it, and `without` is its application side without it. When the tasks of + // a scan are not found, the semi join is taken as not free. + private def isFree(withIt: Cost, withoutIt: Cost, without: SparkPlan): Boolean = + withIt.shuffles <= withoutIt.shuffles && + without.collectLeaves().forall { scan => + (withIt.tasksReading(scan), withoutIt.tasksReading(scan)) match { + case (Some(tasks), Some(tasksWithout)) => tasks >= tasksWithout + case _ => false + } + } + + // The expected number of items of each bloom filter of the semi join, an even share of the + // creation side's over its partition keys. None when the creation side has fewer partition keys + // than it needs for each share to be within the size threshold, or reports none. + private def numItemsOf(join: ShuffledHashJoinExec, bloomFilter: Attribute): Option[Long] = { + val (numItems, minPartitionKeys) = sizingOf(bloomFilter) + partitionKeysOf(join.right).filter(_ >= minPartitionKeys).map { keys => + ((numItems + keys - 1) / keys).max(1L) + } + } + + // The number of partition keys of the input of the aggregate `plan`, before any exchange. + private def partitionKeysOf(plan: SparkPlan): Option[Long] = plan match { + case aggregate: BaseAggregateExec => partitionKeysOf(aggregate.child) + case input => PartitioningCollection.representativeOf(input.outputPartitioning).map { k => + (if (k.isGrouped) k.numPartitions else k.partitionKeys.distinct.size).toLong + } + } + + // The semi join with each bloom filter of its aggregate expecting `numItems` items. + private def withNumItems(join: ShuffledHashJoinExec, numItems: Long): SparkPlan = { + def sized(plan: SparkPlan): SparkPlan = plan match { + case aggregate: BaseAggregateExec => + aggregate.transformExpressions { + case b: BloomFilterAggregate => + b.withNewChildren(new BloomFilterAggregate(b.child, numItems).children) + }.withNewChildren(Seq(sized(aggregate.child))) + case other => other + } + join.withNewChildren(Seq(join.left, sized(join.right))) + } + + // The application side without the semi join, and without the partition key column it adds. The + // conditions of `filter` other than the one on the join's flag, the last column of its output, + // stay. + private def withoutSemiJoin(filter: FilterExec, join: ShuffledHashJoinExec): Option[SparkPlan] = { + val conditions = splitConjunctivePredicates(filter.condition) + .filterNot(_.references.contains(join.output.last)) + (join.leftKeys, join.left) match { + case (Seq(partitionKey: Attribute), ProjectExec(projectList, child)) + if projectList.exists(_.exprId == partitionKey.exprId) => + val rest = projectList.filterNot(_.exprId == partitionKey.exprId) + val sameOutput = rest.map(_.exprId) == child.output.map(_.exprId) + val without = if (sameOutput) child else ProjectExec(rest, child) + Some(conditions.reduceOption(And).map(FilterExec(_, without)).getOrElse(without)) + case _ => None + } + } + + // The projection `p` above a semi join that goes, which restored the output, over `without`, the + // application side without the semi join. When `without` ends in a projection of its columns, + // the two become one. So that side has the plan it has without per-partition bloom filters, as a + // DPP filter that reuses a broadcast of it expects. + private def withoutRestoringProjection(p: ProjectExec, without: SparkPlan): SparkPlan = Review Comment: Thanks, confirmed. With a computed column or a rename above the side, the DPP filter of `fact` became `true`. A semi join that goes now also merges a projection above it, as physical planning does without the semi join (6249042). The test "a semi join that goes leaves a broadcast that a DPP filter can reuse" now covers the computed column and the rename. The test tables are row-based, so I could not test the columnar scan. I listed it as a known limit, and the description now says what merges. ########## 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 { + application <- partitionTransform(key, plan) + creation <- partitionTransform(creationKey, placeholder.plan) + if application.isSameFunction(creation) + } yield { + val creationPartitionKey = Alias(creation, "partitionKey")() + val bloomFilter = Alias(new BloomFilterAggregate(new XxHash64(Seq(creationKey))) + .toAggregateExpression(), "bloomFilter")( + explicitMetadata = Some(bloomFilterMetadata(placeholder))) + val aggregate = PullOutGroupingExpressions(Aggregate( + Seq(creation), Seq(creationPartitionKey, bloomFilter), placeholder.plan)) + val partitionKey = Alias(application, "partitionKey")() + val condition = And( + EqualTo(partitionKey.toAttribute, creationPartitionKey.toAttribute), + BloomFilterMightContain(bloomFilter.toAttribute, new XxHash64(Seq(key)))) + val exists = AttributeReference("exists", BooleanType, nullable = false)() Review Comment: Thanks, confirmed. Your #60572 fixed it. After the rebase onto master, `fact` is read once and `dim` twice, and the exchange is reused, with AQE on and off. ########## sql/core/src/main/scala/org/apache/spark/sql/execution/WholeStageCodegenExec.scala: ########## @@ -1202,6 +1202,8 @@ case class CollapseCodegenStages( case e: LeafExpression => true // CodegenFallback requires the input to be an InternalRow case e: CodegenFallback => false + // A partition transform generates the code of its function call, which is not a child. + case t: TransformExpression => t.evaluableFunction.isDefined && !t.fallsBackToEval Review Comment: Thanks, confirmed. `supportCodegen` now skips the transforms of a partitioning that a node only reports (6c7df9e), with a test in `KeyGroupedPartitioningSuite`. ########## 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 && Review Comment: Thanks, confirmed. With `dim1` first no semi join stayed, and with `dim2` first `fact` got one. A creation side that needs more partition keys than its buckets and null now gets no placeholder (19848ca). I used the bucket count only. `ChoosePerPartitionRuntimeFilters` still checks the keys the scan reports. ########## 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 { + case PerPartitionSemiJoin(_, _, bloomFilter) + if withouts.contains(bloomFilter.exprId) && !kept(bloomFilter.exprId) => + withouts(bloomFilter.exprId) + } + // The expected number of items of each bloom filter of each semi join that stays. + var numItems = Map.empty[ExprId, Long] + var current = new Cost(ensureRequirements.apply(withOnly(Set.empty))) + semiJoins.foreach { case (_, join, bloomFilter) => + val id = bloomFilter.exprId + if (withouts.contains(id)) { + numItemsOf(join, bloomFilter).foreach { n => + val trial = new Cost(ensureRequirements.apply(withOnly(numItems.keySet + id))) + if (isFree(trial, current, withouts(id))) { + numItems += id -> n + current = trial + } + } + } + } + plan.transformDown { + case p @ ProjectExec(_, PerPartitionSemiJoin(_, _, bloomFilter)) + if withouts.contains(bloomFilter.exprId) && !numItems.contains(bloomFilter.exprId) => + withoutRestoringProjection(p, withouts(bloomFilter.exprId)) + case PerPartitionSemiJoin(filter, join, bloomFilter) + if withouts.contains(bloomFilter.exprId) => + numItems.get(bloomFilter.exprId) match { + case Some(n) => filter.withNewChildren(Seq(withNumItems(join, n))) + case None => withouts(bloomFilter.exprId) + } + } + } + } + + // The semi join of a per-partition bloom filter: the filter on the flag of its existence join, + // that join, and the bloom filter column. + private object PerPartitionSemiJoin { + def unapply(plan: SparkPlan): Option[(FilterExec, ShuffledHashJoinExec, Attribute)] = + plan match { + case filter @ FilterExec(_, join: ShuffledHashJoinExec) + if join.joinType.isInstanceOf[ExistenceJoin] => + join.condition.flatMap(perPartitionRuntimeFilter).map { + case (bloomFilter, _) => (filter, join, bloomFilter) + } + case _ => None + } + } + + // The shuffles of a plan, and the tasks of the stage that reads each of its leaves. Those are the + // partitions of the topmost operator above the leaf that no exchange separates from it. An + // operator that reports one partition or none, such as a limit, a write or an `Expand`, does not + // tell how many tasks read its child, so the child counts instead. + private class Cost(plan: SparkPlan) { + val shuffles: Int = plan.collect { case s: ShuffleExchangeLike => s }.size + + private val tasks: Seq[(SparkPlan, Int)] = { + def walk(node: SparkPlan, top: SparkPlan): Seq[(SparkPlan, Int)] = { + if (node.children.isEmpty) { + Seq(node -> top.outputPartitioning.numPartitions) + } else { + val countsChild = node.isInstanceOf[Exchange] || (node.outputPartitioning match { + case SinglePartition => true + case partitioning => partitioning.numPartitions == 0 + }) + node.children.flatMap(child => walk(child, if (countsChild) child else top)) + } + } + walk(plan, plan) + } + + def tasksReading(leaf: SparkPlan): Option[Int] = + tasks.collectFirst { case (l, n) if l eq leaf => n } + } + + // Whether a semi join adds no shuffle, and leaves the stage that reads its application side no + // fewer tasks than it has without the semi join. `withIt` and `withoutIt` are the costs of the + // plan with and without it, and `without` is its application side without it. When the tasks of + // a scan are not found, the semi join is taken as not free. + private def isFree(withIt: Cost, withoutIt: Cost, without: SparkPlan): Boolean = + withIt.shuffles <= withoutIt.shuffles && + without.collectLeaves().forall { scan => Review Comment: Thanks, confirmed. Both semi joins were built and one stayed. `isFree` now counts only the scans of the application side, and skips the creation side of a semi join in it (2a0a2d7). The new test "a semi join over another one is judged by its own application side" covers your query, with `t.r < 1` in place of `*`. -- 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]
