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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/PushDownShuffleExchangeThroughUnion.scala:
##########
@@ -0,0 +1,741 @@
+/*
+ * 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, 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 between the smaller and the larger of the replaced exchange's 
count and the
+ * effective initial shuffle partition count 
(`coalescePartitions.initialPartitionNum` when set);
+ * the larger side is scaled by `maxTargetPartitionNumFactor`. A branch that 
is already a query
+ * stage pins the target to the layout it reports. 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.
+ *
+ * The query-wide subquery gate includes optimizer-injected runtime Bloom 
filter builds.
+ * 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.
+ * Recording and push-down share the preparation's effective enablement on 
EnsureRequirements;
+ * classic and disabled preparations do not record these origins.
+ * A proposal that breaks an ancestor requirement or a recorded layout is 
retried once on the
+ * layout of the exchange being removed, which every ancestor was planned 
against.
+ * Every exchange the rewrite inserts or retargets below a union carries a 
[[PushedDownShuffle]]
+ * mark naming its kind. The cost model excludes inserted exchanges, keeps 
retargeted ones
+ * counted, and charges a union one shuffle when a direct child carries the 
mark; a union
+ * without one costs nothing. A branch served by reuse of an already 
materialized stage keeps
+ * that stage's own exchange: reuse of an unmarked exchange adds no shuffle 
and is not charged,
+ * while a marked one, possibly inserted for another site, still is.
+ * 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(
+    ensureRequirements: EnsureRequirements) extends Rule[SparkPlan] {
+
+  override def apply(plan: SparkPlan): SparkPlan = {
+    if (!ensureRequirements.pushDownShuffleThroughUnionEnabled) {
+      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),
+      maxTargetPartitionNumFactor = conf.getConf(
+        
SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_MAX_TARGET_PARTITION_NUM_FACTOR),
+      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
+
+    // Whether every adopted target is the layout of the exchange this rewrite 
removes. The retry
+    // cannot help while this holds.
+    var usedRemovedLayout = true
+    def rewrite(preferRemovedLayout: Boolean): SparkPlan = plan.transformUp {
+      case join: ShuffledJoin if !allowJoinInputs => join
+      case operator: SparkPlan =>
+        val matched = operator.children.map { child =>
+          findPushableShuffle(child, lookThrough, policy)
+        }
+        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])
+            val (candidate, operatorUsedRemovedLayout) = pushDownThroughUnion(
+              operator,
+              matched.zip(requirements),
+              sharedExchangesFunc = sharedExchanges,
+              policy = policy.copy(
+                allowNonCoalescible =
+                  policy.allowNonCoalescible || !allExchangeInputs(operator),
+                preferRemovedLayout = preferRemovedLayout))
+            usedRemovedLayout = usedRemovedLayout && operatorUsedRemovedLayout
+            candidate
+          }
+        }
+    }
+
+    def accepted(candidate: SparkPlan): Boolean = {
+      // 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(candidate, 
required.copy(requireAllClusterKeys = true))
+        case Some(required) =>
+          ValidateRequirements.validate(candidate, required)
+        case None =>
+          ValidateRequirements.validate(candidate)
+      }
+      satisfied && !candidate.exists(node => 
!PartitioningOrigin.validateNode(node))
+    }
+
+    val pushed = rewrite(preferRemovedLayout = false)
+    if (pushed.fastEquals(plan)) {
+      plan
+    } else if (accepted(pushed)) {
+      pushed
+    } else if (usedRemovedLayout) {
+      // Every site already used the layout of the exchange this rewrite 
removes, so the retry
+      // would rebuild the same proposal and fail again.
+      plan
+    } else {
+      // A target can satisfy the consumer and the fixed siblings yet break an 
ancestor, such as
+      // a join that pairs this branch with a different partition count. Retry 
once on the removed
+      // exchange's own layout, which every ancestor was planned against.
+      val retried = rewrite(preferRemovedLayout = true)
+      if (retried.fastEquals(plan)) {
+        plan
+      } else if (accepted(retried)) {
+        retried
+      } 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,
+      maxTargetPartitionNumFactor: Double,
+      keepJoinBranches: Boolean,
+      allowSubsetTargets: Boolean,
+      preferRemovedLayout: Boolean = false)
+
+  /** Lazily discover and rank layouts once per site for both joint and 
fallback attempts. */
+  private class PreparedChild(val pushable: PushableChild, policy: 
LayoutPolicy) {
+    /**
+     * Eligible child layouts in child order, expressed in the union's output 
attributes.
+     * Collections offer their hash members; a child offering nothing takes a 
shuffle.
+     * Equality follows UnionExec's comparison after prepareOutputPartitioning 
rebinding.
+     */
+    lazy val layouts: Seq[Seq[Partitioning with Expression]] = {
+      val union = pushable.union
+      union.prepareOutputPartitioning().zip(union.children).map { case 
(partitioning, child) =>

Review Comment:
   **Finding 14.** This reads the union's child layouts over a plan that the 
same `transformUp` pass may already have rewritten further down, before the 
whole-plan check sees it. An inner site can move to a layout with another 
partition count, which leaves a shuffled join above it with mismatched inputs. 
When an outer site then reads that join's `outputPartitioning`, 
`PartitioningCollection`'s `require` throws during planning. The whole-plan 
check would have rejected the inner proposal, but it never runs.
   
   What I ran, with AQE on, broadcast off and 5 shuffle partitions:
   
   ```scala
   Seq("n1" -> 1000, "n2" -> 2000, "n3" -> 6000, "n4" -> 80, "n5" -> 
700).foreach { case (name, n) =>
     spark.range(n).selectExpr("id % 97 AS k", "id AS 
v").createOrReplaceTempView(name)
   }
   ```
   
   ```sql
   SELECT k, c, sum(c) OVER (PARTITION BY k) AS s FROM (
     SELECT x.k, x.c + x.rn AS c FROM (
       SELECT k, c, row_number() OVER (PARTITION BY k ORDER BY c) AS rn FROM (
         SELECT k, sum(v) AS c FROM n1 GROUP BY k
         UNION ALL SELECT k, v FROM n2
         UNION ALL SELECT k, v FROM (SELECT /*+ REPARTITION(10, k) */ k, v FROM 
n3))) x
     JOIN n4 ON x.k = n4.k
     UNION ALL SELECT k, v FROM n5)
   ```
   
   | settings | result |
   |---|---|
   | push-down off | 7400 rows |
   | on, `keepNonCoalescibleBranches.enabled`, 
`maxTargetPartitionNumFactor=2.0` | `IllegalArgumentException: requirement 
failed: PartitioningCollection requires all of its partitionings have the same 
numPartitions.` |
   | on, coalescing off, `maxTargetPartitionNumFactor=2.0` | the same exception 
|
   | on, coalescing off, factor 1.0 | 7400 rows |
   
   Here is what happens:
   1. The inner window site adopts the 10-partition layout of the 
`REPARTITION(10, k)` branch.
   2. The sort-merge join keeps its 5-partition exchange on `n4`.
   3. The outer site's `prepareOutputPartitioning` reaches 
`SortMergeJoinExec.outputPartitioning`, which throws.
   
   Skipping a site whose union children no longer validate avoids the 
exception. With the change below at 
`PushDownShuffleExchangeThroughUnion.scala:152`, all four arms return 7400 
rows, and `PushDownShuffleExchangeThroughUnionSuite` still passes its 111 tests:
   
   ```scala
           if (matched.forall(_.isEmpty)) {
             operator
           } else if (matched.flatten.exists(_.union.children.exists(c =>
               !ValidateRequirements.validate(c)))) {
             // An earlier site in this pass can leave a union child invalid; 
its layout cannot be read.
             operator
           } else {
   ```
   
   The per-site acceptance deferred at 
[r4346137538](https://github.com/apache/spark/pull/59630#discussion_r4346137538)
 would also prevent this, since no site would be read over an unvalidated one.
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/InsertAdaptiveSparkPlan.scala:
##########
@@ -46,7 +46,9 @@ case class InsertAdaptiveSparkPlan(
 
   override def conf: SQLConf = 
adaptiveExecutionContext.session.sessionState.conf
 
-  override def apply(plan: SparkPlan): SparkPlan = applyInternal(plan, false)
+  override def apply(plan: SparkPlan): SparkPlan = {

Review Comment:
   **Finding 17.** This hunk only wraps the body in braces. It is left over 
from the subquery flag, which now lives in 
`AdaptiveExecutionContext.queryContainsSubqueries`. Restoring the one-line form 
keeps this method out of the diff:
   
   ```scala
     override def apply(plan: SparkPlan): SparkPlan = applyInternal(plan, false)
   ```
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/PushDownShuffleExchangeThroughUnion.scala:
##########
@@ -0,0 +1,741 @@
+/*
+ * 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, 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 between the smaller and the larger of the replaced exchange's 
count and the
+ * effective initial shuffle partition count 
(`coalescePartitions.initialPartitionNum` when set);
+ * the larger side is scaled by `maxTargetPartitionNumFactor`. A branch that 
is already a query
+ * stage pins the target to the layout it reports. 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.
+ *
+ * The query-wide subquery gate includes optimizer-injected runtime Bloom 
filter builds.
+ * 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.
+ * Recording and push-down share the preparation's effective enablement on 
EnsureRequirements;
+ * classic and disabled preparations do not record these origins.
+ * A proposal that breaks an ancestor requirement or a recorded layout is 
retried once on the
+ * layout of the exchange being removed, which every ancestor was planned 
against.
+ * Every exchange the rewrite inserts or retargets below a union carries a 
[[PushedDownShuffle]]
+ * mark naming its kind. The cost model excludes inserted exchanges, keeps 
retargeted ones
+ * counted, and charges a union one shuffle when a direct child carries the 
mark; a union
+ * without one costs nothing. A branch served by reuse of an already 
materialized stage keeps
+ * that stage's own exchange: reuse of an unmarked exchange adds no shuffle 
and is not charged,
+ * while a marked one, possibly inserted for another site, still is.
+ * 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(
+    ensureRequirements: EnsureRequirements) extends Rule[SparkPlan] {
+
+  override def apply(plan: SparkPlan): SparkPlan = {
+    if (!ensureRequirements.pushDownShuffleThroughUnionEnabled) {
+      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),
+      maxTargetPartitionNumFactor = conf.getConf(
+        
SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_MAX_TARGET_PARTITION_NUM_FACTOR),
+      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
+
+    // Whether every adopted target is the layout of the exchange this rewrite 
removes. The retry
+    // cannot help while this holds.
+    var usedRemovedLayout = true
+    def rewrite(preferRemovedLayout: Boolean): SparkPlan = plan.transformUp {
+      case join: ShuffledJoin if !allowJoinInputs => join
+      case operator: SparkPlan =>
+        val matched = operator.children.map { child =>
+          findPushableShuffle(child, lookThrough, policy)
+        }
+        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])
+            val (candidate, operatorUsedRemovedLayout) = pushDownThroughUnion(
+              operator,
+              matched.zip(requirements),
+              sharedExchangesFunc = sharedExchanges,
+              policy = policy.copy(
+                allowNonCoalescible =
+                  policy.allowNonCoalescible || !allExchangeInputs(operator),
+                preferRemovedLayout = preferRemovedLayout))
+            usedRemovedLayout = usedRemovedLayout && operatorUsedRemovedLayout
+            candidate
+          }
+        }
+    }
+
+    def accepted(candidate: SparkPlan): Boolean = {
+      // 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(candidate, 
required.copy(requireAllClusterKeys = true))
+        case Some(required) =>
+          ValidateRequirements.validate(candidate, required)
+        case None =>
+          ValidateRequirements.validate(candidate)
+      }
+      satisfied && !candidate.exists(node => 
!PartitioningOrigin.validateNode(node))
+    }
+
+    val pushed = rewrite(preferRemovedLayout = false)
+    if (pushed.fastEquals(plan)) {
+      plan
+    } else if (accepted(pushed)) {
+      pushed
+    } else if (usedRemovedLayout) {
+      // Every site already used the layout of the exchange this rewrite 
removes, so the retry
+      // would rebuild the same proposal and fail again.
+      plan
+    } else {
+      // A target can satisfy the consumer and the fixed siblings yet break an 
ancestor, such as
+      // a join that pairs this branch with a different partition count. Retry 
once on the removed
+      // exchange's own layout, which every ancestor was planned against.
+      val retried = rewrite(preferRemovedLayout = true)
+      if (retried.fastEquals(plan)) {
+        plan
+      } else if (accepted(retried)) {
+        retried
+      } 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,
+      maxTargetPartitionNumFactor: Double,
+      keepJoinBranches: Boolean,
+      allowSubsetTargets: Boolean,
+      preferRemovedLayout: Boolean = false)
+
+  /** Lazily discover and rank layouts once per site for both joint and 
fallback attempts. */
+  private class PreparedChild(val pushable: PushableChild, policy: 
LayoutPolicy) {
+    /**
+     * Eligible child layouts in child order, expressed in the union's output 
attributes.
+     * Collections offer their hash members; a child offering nothing takes a 
shuffle.
+     * Equality follows UnionExec's comparison after prepareOutputPartitioning 
rebinding.
+     */
+    lazy val layouts: Seq[Seq[Partitioning with Expression]] = {
+      val union = pushable.union
+      union.prepareOutputPartitioning().zip(union.children).map { case 
(partitioning, child) =>
+        if (keepableLayout(child, policy)) {
+          PartitioningCollection.flatten(partitioning).collect {
+            case hash: HashPartitioning => hash
+          }
+        } else {
+          Nil
+        }
+      }
+    }
+
+    lazy val targets: Seq[Partitioning with Expression] = {
+      val minPartitions = math.min(removedLayout.numPartitions, 
conf.numShufflePartitions)
+      val maxPartitions = math.ceil(
+        math.max(removedLayout.numPartitions, conf.numShufflePartitions) *
+          policy.maxTargetPartitionNumFactor).toInt
+      val candidates = candidateTargets(
+        layouts, pushable.union.children, minPartitions, maxPartitions, 
stagedIndices)
+      val limited = if (policy.preferRemovedLayout) {
+        // The whole-plan check failed. Retry on the layout of the exchange 
this rewrite removes:
+        // every ancestor was planned against it. Keys that a look-through 
operator renames match
+        // nothing here, so that site stays unchanged.
+        candidates.filter(_.semanticEquals(removedLayout))
+      } else {
+        candidates
+      }
+      limited.filter { target =>
+        layouts.count(child => !child.contains(target)) <= 
policy.maxMovedBranches
+      }
+    }
+
+    /**
+     * The layout of the exchange this rewrite removes. `findPushableShuffle` 
only admits a hash
+     * shuffle, and every ancestor was planned against this layout, so a 
failed whole-plan check
+     * can fall back to it.
+     */
+    lazy val removedLayout: Partitioning with Expression =
+      pushable.shuffle.outputPartitioning.asInstanceOf[HashPartitioning]
+
+    /**
+     * Indices of branches that are already shuffle query stages. Such a 
branch carries the shuffle
+     * work that laid it out, so laying it out again adds a shuffle on top of 
materialized data.
+     * A target is viable only when every one of these branches already 
reports it, which pins the
+     * layout chosen in the round that created the stage. Non-staged branches 
do not constrain the
+     * target: one that reports it is kept, and one that does not is laid out 
as usual.
+     */
+    private lazy val stagedIndices: Set[Int] =
+      pushable.union.children.indices.filter { index =>
+        pushable.union.children(index).isInstanceOf[ShuffleQueryStageExec]
+      }.toSet
+  }
+
+  /**
+   * 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,
+   * and a union with more children than `maxUnionChildren` is not a site.
+   *
+   * 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,
+      policy: LayoutPolicy,
+      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, policy, found)
+      case shuffle @ ShuffleExchangeExec(_: HashPartitioning, child, 
ENSURE_REQUIREMENTS, _, _)
+          if found.isEmpty =>
+        findPushableShuffle(child, lookThrough, policy, Some(shuffle))
+      // A union is a site only when the shuffle below it was found and it is 
eligible for one.
+      // AttributeMap keeps the last duplicate exprId, while runtime binding 
uses the first;
+      // positional rebinding is ambiguous for those unions, so retain their 
exchange. A union
+      // with too many children is not a site either.
+      case union: UnionExec if found.isEmpty || union.childOutputRepeatsExprId 
||
+          union.children.length > policy.maxUnionChildren =>
+        None
+      // Below it: the operators this rule can cross, down to the union the 
shuffle is moved past.
+      case union: UnionExec =>
+        found.map(PushableChild(_, union))
+      case operator: UnaryExecNode if found.isDefined && lookThrough && 
canCross(operator) =>
+        findPushableShuffle(operator.child, lookThrough, policy, found)
+      case _ => None
+    }
+  }
+
+  /**
+   * Rewrites eligible children in order. If a joint rewrite fails, retry 
individual children
+   * against all current siblings, keeping children without a viable target 
unchanged.
+   *
+   * Returns the rewritten operator and whether every site used the layout of 
the exchange this
+   * rewrite removes; a failed whole-plan check uses the latter to decide 
whether a retry on that
+   * layout can produce a different proposal.
+   *
+   * `pushable` holds one entry per child, in child order: what can be 
rewritten about it, and
+   * what it owes the operator.
+   */
+  private def pushDownThroughUnion(
+      operator: SparkPlan,
+      pushable: Seq[(Option[PushableChild], ClusteredDistribution)],
+      sharedExchangesFunc: => Set[SparkPlan],
+      policy: LayoutPolicy): (SparkPlan, Boolean) = {
+    val children = operator.children
+    val requiredOrderings = operator.requiredChildOrdering
+
+    // Discover layouts and targets before walking the whole plan for shared 
exchanges, so a
+    // site with no viable target is rejected without that walk.
+    val prepared = pushable.map { case (site, _) =>
+      site.map(child => new PreparedChild(child, policy))
+    }
+    if (!prepared.exists(_.exists(_.targets.nonEmpty))) {
+      return (operator, true)
+    }
+    val sharedExchanges = sharedExchangesFunc
+    val movableSites = pushable.zip(prepared).map { case ((site, required), 
child) =>
+      val movable = site.exists { pushableChild =>
+        sharedExchanges.isEmpty || 
!sharedExchanges.contains(pushableChild.shuffle.canonicalized)
+      }
+      (if (movable) child else None, required)
+    }
+
+    val newChildren = new ArrayBuffer[SparkPlan](children.length)
+    // Whether every adopted target is the layout of the exchange this rewrite 
removes. The retry
+    // cannot help while this holds.
+    var usedRemovedLayout = true
+    def rebuildChildren(joint: Boolean): Boolean = {

Review Comment:
   **Finding 16.** This flag is not reset between the joint attempt and the 
per-child fallback.
   - If the joint attempt adopts a non-removed layout for one child and then 
fails on a sibling, the flag stays false.
   - It stays false even when the fallback then adopts only removed layouts.
   - If the whole-plan check then fails, `apply` runs the retry. The retry 
rebuilds the same proposal and fails again.
   
   Resetting the flag at the start of each attempt keeps it to the attempt that 
is used:
   
   ```suggestion
       def rebuildChildren(joint: Boolean): Boolean = {
         usedRemovedLayout = true
   ```
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/PushDownShuffleExchangeThroughUnion.scala:
##########
@@ -0,0 +1,741 @@
+/*
+ * 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, 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 between the smaller and the larger of the replaced exchange's 
count and the
+ * effective initial shuffle partition count 
(`coalescePartitions.initialPartitionNum` when set);
+ * the larger side is scaled by `maxTargetPartitionNumFactor`. A branch that 
is already a query
+ * stage pins the target to the layout it reports. 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.
+ *
+ * The query-wide subquery gate includes optimizer-injected runtime Bloom 
filter builds.
+ * 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.
+ * Recording and push-down share the preparation's effective enablement on 
EnsureRequirements;
+ * classic and disabled preparations do not record these origins.
+ * A proposal that breaks an ancestor requirement or a recorded layout is 
retried once on the
+ * layout of the exchange being removed, which every ancestor was planned 
against.
+ * Every exchange the rewrite inserts or retargets below a union carries a 
[[PushedDownShuffle]]
+ * mark naming its kind. The cost model excludes inserted exchanges, keeps 
retargeted ones
+ * counted, and charges a union one shuffle when a direct child carries the 
mark; a union
+ * without one costs nothing. A branch served by reuse of an already 
materialized stage keeps
+ * that stage's own exchange: reuse of an unmarked exchange adds no shuffle 
and is not charged,
+ * while a marked one, possibly inserted for another site, still is.
+ * 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(
+    ensureRequirements: EnsureRequirements) extends Rule[SparkPlan] {
+
+  override def apply(plan: SparkPlan): SparkPlan = {
+    if (!ensureRequirements.pushDownShuffleThroughUnionEnabled) {
+      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),
+      maxTargetPartitionNumFactor = conf.getConf(
+        
SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_MAX_TARGET_PARTITION_NUM_FACTOR),
+      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
+
+    // Whether every adopted target is the layout of the exchange this rewrite 
removes. The retry
+    // cannot help while this holds.
+    var usedRemovedLayout = true
+    def rewrite(preferRemovedLayout: Boolean): SparkPlan = plan.transformUp {
+      case join: ShuffledJoin if !allowJoinInputs => join
+      case operator: SparkPlan =>
+        val matched = operator.children.map { child =>
+          findPushableShuffle(child, lookThrough, policy)
+        }
+        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])
+            val (candidate, operatorUsedRemovedLayout) = pushDownThroughUnion(
+              operator,
+              matched.zip(requirements),
+              sharedExchangesFunc = sharedExchanges,
+              policy = policy.copy(
+                allowNonCoalescible =
+                  policy.allowNonCoalescible || !allExchangeInputs(operator),
+                preferRemovedLayout = preferRemovedLayout))
+            usedRemovedLayout = usedRemovedLayout && operatorUsedRemovedLayout
+            candidate
+          }
+        }
+    }
+
+    def accepted(candidate: SparkPlan): Boolean = {
+      // 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(candidate, 
required.copy(requireAllClusterKeys = true))
+        case Some(required) =>
+          ValidateRequirements.validate(candidate, required)
+        case None =>
+          ValidateRequirements.validate(candidate)
+      }
+      satisfied && !candidate.exists(node => 
!PartitioningOrigin.validateNode(node))
+    }
+
+    val pushed = rewrite(preferRemovedLayout = false)
+    if (pushed.fastEquals(plan)) {
+      plan
+    } else if (accepted(pushed)) {
+      pushed
+    } else if (usedRemovedLayout) {
+      // Every site already used the layout of the exchange this rewrite 
removes, so the retry
+      // would rebuild the same proposal and fail again.
+      plan
+    } else {
+      // A target can satisfy the consumer and the fixed siblings yet break an 
ancestor, such as
+      // a join that pairs this branch with a different partition count. Retry 
once on the removed
+      // exchange's own layout, which every ancestor was planned against.
+      val retried = rewrite(preferRemovedLayout = true)
+      if (retried.fastEquals(plan)) {
+        plan
+      } else if (accepted(retried)) {
+        retried
+      } 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,
+      maxTargetPartitionNumFactor: Double,
+      keepJoinBranches: Boolean,
+      allowSubsetTargets: Boolean,
+      preferRemovedLayout: Boolean = false)
+
+  /** Lazily discover and rank layouts once per site for both joint and 
fallback attempts. */
+  private class PreparedChild(val pushable: PushableChild, policy: 
LayoutPolicy) {
+    /**
+     * Eligible child layouts in child order, expressed in the union's output 
attributes.
+     * Collections offer their hash members; a child offering nothing takes a 
shuffle.
+     * Equality follows UnionExec's comparison after prepareOutputPartitioning 
rebinding.
+     */
+    lazy val layouts: Seq[Seq[Partitioning with Expression]] = {
+      val union = pushable.union
+      union.prepareOutputPartitioning().zip(union.children).map { case 
(partitioning, child) =>
+        if (keepableLayout(child, policy)) {
+          PartitioningCollection.flatten(partitioning).collect {
+            case hash: HashPartitioning => hash
+          }
+        } else {
+          Nil
+        }
+      }
+    }
+
+    lazy val targets: Seq[Partitioning with Expression] = {
+      val minPartitions = math.min(removedLayout.numPartitions, 
conf.numShufflePartitions)
+      val maxPartitions = math.ceil(
+        math.max(removedLayout.numPartitions, conf.numShufflePartitions) *
+          policy.maxTargetPartitionNumFactor).toInt
+      val candidates = candidateTargets(
+        layouts, pushable.union.children, minPartitions, maxPartitions, 
stagedIndices)
+      val limited = if (policy.preferRemovedLayout) {
+        // The whole-plan check failed. Retry on the layout of the exchange 
this rewrite removes:
+        // every ancestor was planned against it. Keys that a look-through 
operator renames match
+        // nothing here, so that site stays unchanged.
+        candidates.filter(_.semanticEquals(removedLayout))
+      } else {
+        candidates
+      }
+      limited.filter { target =>
+        layouts.count(child => !child.contains(target)) <= 
policy.maxMovedBranches
+      }
+    }
+
+    /**
+     * The layout of the exchange this rewrite removes. `findPushableShuffle` 
only admits a hash
+     * shuffle, and every ancestor was planned against this layout, so a 
failed whole-plan check
+     * can fall back to it.
+     */
+    lazy val removedLayout: Partitioning with Expression =
+      pushable.shuffle.outputPartitioning.asInstanceOf[HashPartitioning]
+
+    /**
+     * Indices of branches that are already shuffle query stages. Such a 
branch carries the shuffle
+     * work that laid it out, so laying it out again adds a shuffle on top of 
materialized data.
+     * A target is viable only when every one of these branches already 
reports it, which pins the
+     * layout chosen in the round that created the stage. Non-staged branches 
do not constrain the
+     * target: one that reports it is kept, and one that does not is laid out 
as usual.
+     */
+    private lazy val stagedIndices: Set[Int] =

Review Comment:
   **Finding 15.** This pins the target to every branch that is a shuffle query 
stage. That includes the stage of a branch the first round could not keep: one 
whose own exchange is on other keys or on a fixed count, so the rule stacked an 
exchange on it. After the first round only that branch's own exchange is 
staged, and the re-planned union's children are the two stages. The one with 
the other layout offers no target, so no target is viable. `EnsureRequirements` 
then puts the exchange back above the union, and AQE adopts that re-plan.
   
   What I ran, with only `pushDownShuffleThroughUnion.enabled` on, AQE on and 5 
shuffle partitions, with coalescing on and off (same result in both):
   
   | window over | initial plan | executed plan |
   |---|---|---|
   | `(t1 DISTRIBUTE BY a, b) UNION ALL (t2 DISTRIBUTE BY b, a)`, as in the 
reversed-keys test | 1 pushed exchange | 0 pushed, 3 shuffles |
   | `agg UNION ALL /*+ REPARTITION(7) */ t2` | 1 pushed exchange | 0 pushed, 3 
shuffles |
   | `agg UNION ALL t2` | 1 pushed exchange | 1 pushed, 2 shuffles |
   
   So nothing is lost against the base, but the push-down the tests show for 
the first two shapes never runs. They assert on `aqeInitialPlan` only. 
Asserting on the executed plan would show this.
   
   One way out, which I have not tried: let the pin skip a staged branch that 
offers no target within the bounds, since the first round had already decided 
to lay it out again.
   



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