cloud-fan commented on code in PR #59630: URL: https://github.com/apache/spark/pull/59630#discussion_r4498525530
########## sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/PushDownShuffleExchangeThroughUnion.scala: ########## @@ -0,0 +1,608 @@ +/* + * 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.adaptive + +import scala.annotation.tailrec +import scala.collection.mutable +import scala.collection.mutable.ArrayBuffer + +import org.apache.spark.SparkException +import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeMap, Expression, SessionWindow, SortOrder} +import org.apache.spark.sql.catalyst.expressions.aggregate.{Partial => PartialAggregate} +import org.apache.spark.sql.catalyst.optimizer.BuildLeft +import org.apache.spark.sql.catalyst.plans.physical.{ClusteredDistribution, HashPartitioning, HashShuffleSpec, Partitioning, PartitioningCollection} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.catalyst.trees.TreeNodeTag +import org.apache.spark.sql.execution.{ + FilterExec, ProjectExec, SortExec, SparkPlan, UnaryExecNode, UnionConfSnapshot, + UnionExec} +import org.apache.spark.sql.execution.aggregate.BaseAggregateExec +import org.apache.spark.sql.execution.exchange.{ENSURE_REQUIREMENTS, EnsureRequirements, Exchange, PartitioningOrigin, REPARTITION_BY_COL, REPARTITION_BY_NUM, ShuffleExchangeExec, ShuffleExchangeLike, ValidateRequirements} +import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec, BroadcastNestedLoopJoinExec, CartesianProductExec, ShuffledJoin} +import org.apache.spark.sql.execution.window.{Partial => PartialWindowGroupLimit, WindowGroupLimitExec} +import org.apache.spark.sql.internal.SQLConf + +/** + * Push down a shuffle [[EnsureRequirements]] put above a [[UnionExec]] below the union. Eligible + * children already reporting the target retain their layouts; other children are retargeted or + * receive a new shuffle. Local sorts above the shuffle and operators between it and the union + * are rebuilt above the union: + * + * {{{ + * SortMergeJoin SortMergeJoin + * :- Sort :- Sort + * : +- Exchange => : +- Union + * : +- Union : :- HashAggregate + * : :- HashAggregate : : +- Exchange + * : : +- Exchange : : +- Scan + * : : +- Scan : +- Exchange + * : +- Project : +- Project + * : +- Scan : +- Scan + * +- ... +- ... + * }}} + * + * The left child already answers the target, since it shuffles on the join key for its aggregate, + * so it keeps its layout and only the right child takes a shuffle. + * + * The operators between the shuffle and the union are looked through only under + * `spark.sql.adaptive.pushDownShuffleThroughUnion.lookThroughOperators.enabled`, and only when + * moving the shuffle past them preserves results: a deterministic project, a local sort, a + * filter, a partial aggregate and a partial window group limit. The reducing ones are why the + * gate exists: the child is then shuffled before the reduction, which can send more data than the + * one shuffle it replaces. + * + * Targets are hash layouts reported by the union's children, ranked by how many children offer + * them when size estimates are unavailable; otherwise estimated bytes kept decide first. The + * count must be at least the smaller of the replaced exchange's count and the effective initial + * shuffle partition count (`coalescePartitions.initialPartitionNum` when set). At least one + * child keeps its layout; others are retargeted or shuffled without changing child order. + * `spark.sql.adaptive.pushDownShuffleThroughUnion.maxMovedBranches` limits moved children, and + * `maxUnionChildren` limits all branches whose tails run within each consumer task. + * The rebuilt child must satisfy its consumer's distribution and pair with fixed siblings. + * + * Removing the union's exchange can reduce AQE join conversion and skew handling opportunities. + * Keeping a shuffled join child's layout can make skew join optimization or local shuffle reads + * invalidate an ancestor's distribution. AQE can discard the optimization for the round, or add + * another shuffle when skew optimization is forced. Join inputs and join branches are opt-in. + * Allowing targets via + * `spark.sql.adaptive.pushDownShuffleThroughUnion.keepNonCoalescibleBranches.enabled` + * can prevent coalescing of the consumer's compatible shuffle group. Forced skew optimization + * can restore a union exchange after moved branches have shuffled, shuffling them a second time. + * + * Allowing subqueries can make pruning builds differ from main-query broadcast builds. With + * broadcast-only dynamic pruning, failed broadcast reuse removes the pruning filter and can scan + * all fact partitions; that cost can outweigh the saved build-side shuffle. + * + * The rule runs only in AQE preparation, after `EnsureRequirements` and before + * `StampUnionDecisions`. It preserves the root distribution and all user repartition layouts + * recorded when `EnsureRequirements` elides exchanges, including requirements below the root. + * These origin checks apply only to this rule's proposals, not to other adaptive optimizations. + * Cost compensation belongs to SimpleCostEvaluator. Custom evaluators should account for the + * one-to-many exchange rewrite when this rule is enabled, or they may reject the entire re-plan. + * + * TODO: support push down of a keyed layout. + */ +case class PushDownShuffleExchangeThroughUnion( + snapshot: UnionConfSnapshot, + ensureRequirements: EnsureRequirements, + queryContainsSubqueries: Boolean) extends Rule[SparkPlan] { + + override def apply(plan: SparkPlan): SparkPlan = { + if (!snapshot.outputPartitioning || + !conf.pushDownShuffleThroughUnionEnabled || + (queryContainsSubqueries && + !conf.getConf(SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ALLOW_WITH_SUBQUERIES_ENABLED))) { + return plan + } + + val lookThrough = + conf.getConf(SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_LOOK_THROUGH_OPERATORS_ENABLED) + val policy = LayoutPolicy( + allowNonCoalescible = !conf.getConf(SQLConf.COALESCE_PARTITIONS_ENABLED) || conf.getConf( + SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_KEEP_NON_COALESCIBLE_BRANCHES_ENABLED), + maxMovedBranches = + conf.getConf(SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_MAX_MOVED_BRANCHES), + maxUnionChildren = + conf.getConf(SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_MAX_UNION_CHILDREN), + keepJoinBranches = + conf.getConf(SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_KEEP_JOIN_BRANCHES_ENABLED), + allowSubsetTargets = conf.getConf(SQLConf + .PUSH_DOWN_SHUFFLE_THROUGH_UNION_ALLOW_PARTITION_KEYS_SUBSET_OF_CLUSTER_KEYS_ENABLED)) + val allowJoinInputs = + conf.getConf(SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ALLOW_JOIN_INPUTS_ENABLED) + + // An exchange the plan reuses elsewhere is worth more than this rewrite: moving it below the + // union loses the stage the others reuse. See `AQEUtils.duplicatedShuffleForms`. With reuse + // off every exchange gets its own stage, so there is nothing to protect. + lazy val sharedExchanges: Set[SparkPlan] = + if (conf.exchangeReuseEnabled) AQEUtils.duplicatedShuffleForms(plan) else Set.empty + + val pushed = plan.transformUp { + case join: ShuffledJoin if !allowJoinInputs => join + case operator: SparkPlan => + val matched = operator.children.map { child => + findPushableShuffle(child, lookThrough).filter { pushable => + pushable.union.children.length <= policy.maxUnionChildren && + (sharedExchanges.isEmpty || + !sharedExchanges.contains(pushable.shuffle.canonicalized)) + } + } + if (matched.forall(_.isEmpty)) { + operator + } else { + // Read requirements only after finding a site; some operators log when asked. + val required = operator.requiredChildDistribution + if (!required.forall(_.isInstanceOf[ClusteredDistribution])) { + operator + } else { + val requirements = required.map(_.asInstanceOf[ClusteredDistribution]) + pushDownThroughUnion( + operator, + matched.zip(requirements), + sharedExchanges = sharedExchanges, + policy = policy.copy(allowNonCoalescible = + policy.allowNonCoalescible || !allExchangeInputs(operator))).getOrElse(operator) + } + } + } + if (pushed.fastEquals(plan)) { + plan + } else { + // Local checks do not cover ancestors or elided repartitions below the root. Reject the + // whole proposal if any plan requirement or recorded output layout is lost. + val satisfied = ensureRequirements.requiredDistribution match { + // A user repartition elided above was asked for on all its keys, so a layout on a subset + // of them does not stand in for it. + case Some(required: ClusteredDistribution) => + ValidateRequirements.validate(pushed, required.copy(requireAllClusterKeys = true)) + case Some(required) => + ValidateRequirements.validate(pushed, required) + case None => + ValidateRequirements.validate(pushed) + } + if (satisfied && !pushed.exists(node => !PartitioningOrigin.validateNode(node))) { + pushed + } else { + plan + } + } + } + + /** + * One of an operator's children this rule can rewrite: the shuffle it moves and the union that + * shuffle is moved past. + */ + private case class PushableChild(shuffle: ShuffleExchangeExec, union: UnionExec) + + /** + * Layout selection settings, read once per pass. + */ + private case class LayoutPolicy( + allowNonCoalescible: Boolean, + maxMovedBranches: Int, + maxUnionChildren: Int, + keepJoinBranches: Boolean, + allowSubsetTargets: Boolean) + + /** + * The shape this rule acts on below one of an operator's children: a pushable shuffle and the + * union it is moved past, with the operators in between looked through to reach it. Only a hash + * shuffle is pushable, since the layout that replaces it comes from the union's own children. + * + * What the child owes its operator is not read here: this is asked of every child of every + * operator, and `requiredChildDistribution` is not free of side effects: `WindowExecBase` logs + * from it for an unpartitioned window. + */ + @tailrec + private def findPushableShuffle( + plan: SparkPlan, + lookThrough: Boolean, + found: Option[ShuffleExchangeExec] = None): Option[PushableChild] = { + plan match { + // A local sort above the shuffle is looked through, since the rebuilt child is sorted back + // to the same requirement; one below it is an operator in between and needs the gate. + case SortExec(_, false, child, _) if found.isEmpty || lookThrough => + findPushableShuffle(child, lookThrough, found) + case shuffle @ ShuffleExchangeExec(partitioning, child, ENSURE_REQUIREMENTS, _, _) + if found.isEmpty && supportPushDown(partitioning) => + findPushableShuffle(child, lookThrough, Some(shuffle)) + // AttributeMap keeps the last duplicate exprId, while runtime binding uses the first. + // Positional rebinding is ambiguous for these unions, so retain their exchange. + case union: UnionExec if union.output.map(_.exprId).distinct.size != union.output.size => None Review Comment: **Blocking (P1):** This check reads `union.output`, which carries the first child's exprIds, so a later child that repeats an exprId still passes. Such a child arises when it is built over a union whose first branch repeats a column, as in `p1.union(p2).repartition(3)` with `p1` selecting `(p, p, w)`: the two positions then hold different values for `p2`'s rows. The analyzer allows that only when `spark.sql.analyzer.unionIsResolvedWhenDuplicatesPerChildResolved` is false, so this needs that setting plus the push-down. When that child is moved, `rebind` turns `hash(c)` into `hash(p#)`, and the new exchange hashes the child's first `p#` column, while `prepareOutputPartitioning` maps `p#` back to the union's later attribute `c`. When it is kept, its own `hash(p#)` layout is mapped to `hash(c)` the same way. Either way the rebuilt union reports a hash on `c` that the child's rows are not partitioned by. The whole-plan validation reads the same mapping, and the consumer keeps no exchange, so a window, aggregate or join on `c` sees one key in several partitions. The existing thread on this line covers both cases. A check of every child of this union would still miss one route, which this review found by reading the code and has not run. A kept child whose own output is unique, such as a local sort over an inner union whose later child repeats an exprId, passes that inner union's mis-mapped layout up: `keepableLayout` walks through the inner union, and `childLayouts` trusts the layout. A deterministic projection would not keep the inner union nested, because the optimizer pushes it through and flattens the union, but a local sort does. This extends an [existing discussion](https://github.com/apache/spark/pull/59630#discussion_r4493199302). **Recommended change:** Make the push-down skip a union when any of its children, not only the union's own output, repeats an exprId, and make the walk that decides whether a child may keep its layout refuse a child whose path to its shuffle boundaries crosses a union that has such a child. Add push-down suite regressions for a later duplicate child that would be moved, one that would be kept, and a kept child whose layout comes through a nested union with a duplicate child. **Why this works:** Positional rebinding and UnionExec's child-to-union mapping are exact only when each child's exprIds are unique. With these checks the rule never rebinds a target into an ambiguous child and never keeps a layout that was reported through an ambiguous mapping, so every union it rebuilds reports only layouts its rows actually have, and any other union keeps the exchange the base branch plans. **Scope:** A tighter eligibility check inside the push-down rule plus regression tests; no change to UnionExec or to plans with the push-down off. **Compatibility:** With the push-down off, plans and results are unchanged, and unions whose children have distinct exprIds keep their current push-down behavior. **Risks:** Unions with a child that repeats an exprId no longer get the push-down even when the repeated column is not a partition key. Only queries that turn off spark.sql.analyzer.unionIsResolvedWhenDuplicatesPerChildResolved produce such unions, since by default the analyzer gives each branch distinct exprIds and the optimizer keeps them; the push-down is off by default, and reverting the checks undoes it. **Constraints:** Plans and results with the push-down off must stay identical to the base branch, so the repair stays inside the rule and leaves UnionExec's mapping unchanged. **Exclusions:** - Fixing UnionExec's child-to-union mapping for the case where every child already reports its layout and no exchange is involved, which returns wrong results on the base branch as well and is better handled in a separate change. **Success:** With the push-down on, a union with any child whose output repeats an exprId keeps the exchange above it, and the query returns the same rows as with the push-down off. A union child whose layout reaches it through a union with such a child, above its shuffle boundaries, is never kept as a push-down target. Unions whose children all have distinct exprIds are pushed down exactly as before. **Verification:** - **Regression:** With the push-down on, unionIsResolvedWhenDuplicatesPerChildResolved and enforceTypeCoercionBeforeUnionDeduplication off, coalescing off and 5 shuffle partitions, and with spark.sql.analyzer.singlePassResolver.dualRunWithLegacy and whole-stage codegen also off, which the test framework needs for a nested union with a repeated column, a row_number window partitioned by the second column over a union whose first child is repartitioned by that column and whose second child is a round-robin repartition over a union with a repeated column returns exactly 1000 first rows, the same as with the push-down off, and keeps the exchange above the outer union. - **Regression:** Under the same settings, when that second child is instead hash-repartitioned on the repeated column and the first child is not partitioned, so the duplicate child would otherwise be kept as the target, the window still returns the push-down-off rows and keeps its exchange. - **Regression:** In a plan-level test, a union child that is a local sort over an inner union whose later child outputs one attribute twice and reports a hash layout on it is not kept as a target, so the exchange above the outer union stays. An end-to-end version needs an operator the optimizer does not push through a union, such as sortWithinPartitions, and returns the same rows as with the push-down off; a deterministic projection is pushed through the inner union and flattened, so it would only repeat the later-child case. - **Behavior:** The existing case where the union's first child repeats an exprId still keeps its exchange, its uniquely aliased control is still pushed down, and the other push-down tests keep their plan shapes. ########## sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala: ########## @@ -8764,6 +8766,139 @@ object SQLConf { .booleanConf .createWithDefault(true) + val PUSH_DOWN_SHUFFLE_THROUGH_UNION_ENABLED = + buildConf("spark.sql.adaptive.pushDownShuffleThroughUnion.enabled") + .internal() + .doc("When true, pushes an EnsureRequirements hash shuffle below a union during AQE " + + "query stage preparation. Eligible children already reporting the selected layout " + + "are retained; other children are retargeted or receive a new exchange. The target " + + "partition count must be at least the smaller of the replaced exchange's count and " + + "the effective initial shuffle count, including " + + "spark.sql.adaptive.coalescePartitions.initialPartitionNum when set. Requires " + + "spark.sql.unionOutputPartitioning to be enabled. Removing the union's direct shuffle " + + "stage can reduce AQE skew handling and join conversion opportunities. Retaining a " + + "shuffled join's layout can make skew optimization or local reads violate ancestor " + + "requirements; AQE may reject the optimization or add a shuffle when skew optimization " + + "is forced. Join inputs and join branches are opt-in. Cost compensation applies only " + + "to SimpleCostEvaluator. Custom evaluators should account for one union exchange " + + "becoming multiple branch exchanges; otherwise AQE may reject a re-plan and its other " + + "runtime optimizations due to the increased exchange count.") + .version("4.4.0") + .withBindingPolicy(ConfigBindingPolicy.SESSION) + .booleanConf + .createWithDefault(false) + + val PUSH_DOWN_SHUFFLE_THROUGH_UNION_LOOK_THROUGH_OPERATORS_ENABLED = + buildConf("spark.sql.adaptive.pushDownShuffleThroughUnion.lookThroughOperators.enabled") + .internal() + .doc("When set to true, the shuffle push-down through a union may look through the " + + "operators between the shuffle and the union: a project, a local sort, a filter, a " + + "partial aggregate and a partial window group limit. A filter, a partial aggregate and " + + "a partial window group limit reduce the data on their way, so the child is then " + + "shuffled before the reduction, which can send substantially more data than the single " + + "shuffle it replaces. The reducing operator remains above the union; target ranking " + + "does not estimate the reduction lost by moved branches, so that cost can outweigh " + + "the shuffle saving on retained branches. Requires " + + s"${PUSH_DOWN_SHUFFLE_THROUGH_UNION_ENABLED.key} to be enabled.") + .version("4.4.0") + .withBindingPolicy(ConfigBindingPolicy.SESSION) + .booleanConf + .createWithDefault(false) + + val PUSH_DOWN_SHUFFLE_THROUGH_UNION_KEEP_NON_COALESCIBLE_BRANCHES_ENABLED = + buildConf( + "spark.sql.adaptive.pushDownShuffleThroughUnion.keepNonCoalescibleBranches.enabled") + .internal() + .doc("When set to true, fixed-count shuffles, bucketed or cached scans, and branches " + + "containing exploding joins may offer push-down targets. This can prevent coalescing " + + "of the consumer's compatible shuffle group or reduce its target partition size. " + + "Rebalance shuffles remain ineligible. This only affects target selection when " + Review Comment: **Nit (P3):** With coalescing on and this setting false, `apply` still lets fixed-count, cached, bucketed and exploding-join branches offer targets when one of the consumer's input paths reaches a non-exchange leaf without crossing an exchange (`policy.allowNonCoalescible || !allExchangeInputs(operator)`). 'a non-exchange sibling permits non-coalescible union targets' pins that: a sort-merge join whose other side is a cached relation keeps a cached union branch. That behavior is fine, since the group can't coalesce anyway, but this sentence reads as if coalescing being off were the only exception. Could the doc name the consumer case too? **Verification:** - **Inspection:** The doc names both conditions under which the setting does not restrict targets, and they match the policy the rule builds for each consumer and the behavior the non-exchange-sibling test asserts. -- 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]
