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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/PushDownKeyedShuffleExchange.scala:
##########
@@ -0,0 +1,208 @@
+/*
+ * 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 org.apache.spark.sql.catalyst.expressions.{Alias, Attribute, 
AttributeMap, AttributeReference, Expression}
+import org.apache.spark.sql.catalyst.optimizer.{BuildLeft, BuildSide}
+import org.apache.spark.sql.catalyst.plans.physical.{ClusteredDistribution, 
HashPartitioning, KeyedPartitioning, PartitioningCollection}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.execution.{BinaryExecNode, FilterExec, 
GenerateExec, ProjectExec, SortExec, SparkPlan, UnaryExecNode}
+import org.apache.spark.sql.execution.aggregate.BaseAggregateExec
+import org.apache.spark.sql.execution.exchange.{ENSURE_REQUIREMENTS, 
EnsureRequirements, PartitioningOrigin, ShuffleExchangeExec, 
ValidateRequirements}
+import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec, 
BroadcastNestedLoopJoinExec}
+import org.apache.spark.sql.execution.window.{Final => FinalWindowGroupLimit, 
WindowExecBase, WindowGroupLimitExec}
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Moves a keyed shuffle down through operators clustered on its keys onto the 
hash shuffle that
+ * feeds them, so that one shuffle serves both:
+ *
+ * {{{
+ *   Before:                                     After:
+ *   SortMergeJoin                               SortMergeJoin
+ *    :- Sort                                     :- Sort
+ *    :  +- Exchange(keyed [item_id])             :  +- HashAggregate(key = 
[item_id])
+ *    :     +- HashAggregate(key = [item_id])     :     +- Exchange(keyed 
[item_id])
+ *    :        +- Exchange(hash [item_id])        :        +- 
HashAggregate(partial)
+ *    :           +- HashAggregate(partial)       :           +- ...
+ *    +- BatchScan(items, keyed [item_id])        +- BatchScan(items, keyed 
[item_id])
+ * }}}
+ *
+ * `EnsureRequirements` plans the join's keyed shuffle above the aggregate and 
the aggregate's own
+ * hash shuffle below it independently; a layout that serves the aggregate's 
clustering as well as
+ * the hash one lets the hash shuffle take the keyed layout. The walk crosses 
a grouped aggregate, a
+ * partitioned window, a final window group limit, a deterministic projection 
or filter, a local
+ * sort, a generate and a broadcast join's streamed side, and retargets only 
when the plan reuses
+ * neither shuffle, the layout offers at least the hash shuffle's partition 
count, no crossed
+ * expression evaluates differently, and the whole plan still validates under 
the preparation's root
+ * distribution.
+ */
+case class PushDownKeyedShuffleExchange(
+    ensureRequirements: EnsureRequirements,
+    queryContainsSubqueries: Boolean) extends Rule[SparkPlan] {
+
+  override def apply(plan: SparkPlan): SparkPlan = {
+    if (!conf.getConf(SQLConf.PUSH_DOWN_KEYED_SHUFFLE_ENABLED) ||
+        (queryContainsSubqueries &&
+          
!conf.getConf(SQLConf.PUSH_DOWN_KEYED_SHUFFLE_ALLOW_WITH_SUBQUERIES_ENABLED)) ||
+        !conf.v2BucketingShuffleEnabled || 
conf.v2BucketingPartiallyClusteredDistributionEnabled) {
+      return plan
+    }
+
+    lazy val sharedExchanges: Set[SparkPlan] =
+      if (conf.exchangeReuseEnabled) AQEUtils.duplicatedShuffleForms(plan) 
else Set.empty
+
+    val pushed = plan.transformUp {
+      // The layout has to be able to serve as a shuffle's template, as
+      // `KeyedShuffleSpec.canCreatePartitioning` asks of one it lays another 
child out on.
+      case keyedExchange @ ShuffleExchangeExec(
+          keyed: KeyedPartitioning, _, ENSURE_REQUIREMENTS, _, _) if 
keyed.canTemplateShuffle =>
+        pushDown(keyedExchange, sharedExchanges).getOrElse(keyedExchange)

Review Comment:
   **Blocking (P1):** Replacing the keyed exchange with its rebuilt child also 
removes the only query stage on this side of the join whose runtime statistics 
describe the output of the operators it crosses. On the base branch, AQE 
materializes the keyed stage above them, maps it to the logical operator 
(`replaceWithQueryStagesInLogicalPlan`, AdaptiveSparkPlanExec.scala:1130-1159), 
and re-plans the join from that output size: a broadcast hash join when it fits 
`spark.sql.adaptive.autoBroadcastJoinThreshold`, or no join at all when it is 
empty (`AQEPropagateEmptyRelation`). After this rewrite the only stage is the 
retargeted shuffle below the final aggregate, and 
`LogicalQueryStage.computeStats` (LogicalQueryStage.scala:55-72) reports that 
stage's rows, the partial-aggregate output, so the broadcast check fails 
whenever the partial output exceeds the threshold, and the result stage follows 
without another re-plan.
   
   Reading the AQE code, an inner join of a large table laid out as `bucket(n, 
user_id)` with `SELECT user_id, sum(amount) FROM purchases GROUP BY user_id`, 
whose partial output exceeds 10MB while its final output does not, becomes a 
broadcast hash join on the base branch but stays a sort-merge join with this 
rule. Because the scan derives no ordering for a transform layout, each join 
task then sorts its storage partition, work that grows with the storage table, 
to save a keyed shuffle of at most the threshold's worth of rows. Identity 
layouts, whose scan derives the join ordering by default, need no such sort. 
The rule is on by default for every user of the one-side shuffle, the config 
doc does not mention the trade-off, and every test in the suite runs with 
broadcast joins disabled.
   
   **Recommended change:** Make spark.sql.adaptive.pushDownKeyedShuffle.enabled 
default to false (SQLConf.scala lines 9225-9239) and extend its doc, as the 
union push-down's doc does at SQLConf.scala lines 9080-9081, to say that the 
rewrite removes the shuffle stage above the operator, whose statistics describe 
the operator's output, so AQE can no longer use that output's size to turn the 
join into a broadcast hash join or to drop the join when that output is empty. 
In PushDownKeyedShuffleExchangeSuite, enable the flag in the shared conf helper 
(lines 75-81) and in 'a layout that cannot serve as a shuffle template is not 
pushed down' (lines 736-804), and add a case that enables adaptive broadcast, 
which the suite's sparkConf disables. Update the PR description, which says the 
flag defaults to true.
   
   **Why this works:** With the flag off by default, the rule returns every 
plan unchanged at its first check (PushDownKeyedShuffleExchange.scala lines 
60-65), so a query using the one-side shuffle keeps the base branch's keyed 
shuffle above the operator and AQE keeps re-planning the join from that stage's 
statistics; a user who turns the flag on takes the trade-off the doc then names.
   
   **Compatibility:** With the flag on, the rule's plans, admission checks and 
query results stay as they are in this PR.
   
   **Risks:** Users who enable the one-side shuffle no longer get the shuffle 
saving unless they also set spark.sql.adaptive.pushDownKeyedShuffle.enabled, an 
internal flag; setting it to true restores the current behavior. Defaulting the 
flag off also gives up the saving for identity layouts, whose scan derives the 
join ordering by default and for which no regression is established.
   
   **Constraints:** With the flag off, every plan must stay equal to the base 
branch's plan, and the subquery opt-in must keep applying only when the flag is 
on.
   
   **Exclusions:**
   - Keeping runtime join re-selection while the rewrite is on, which would 
need the operator's output size before the join stage runs.
   
   **Verification:**
   - **Regression:** A join of a table laid out by a bucket transform with an 
aggregate whose final output fits the adaptive broadcast threshold while its 
partial output does not ends in a broadcast hash join under the default 
configuration, as on the base branch, and stays a sort-merge join when the 
rewrite is enabled.
   - **Compatibility:** Under the default configuration, every target shape the 
push-down cases cover keeps the base branch's two shuffles, and with the 
rewrite enabled each loses one, as those cases expect now.
   - **Inspection:** The rewrite flag defaults to false and its documentation 
says the rewrite removes the stage whose statistics AQE uses to broadcast or 
drop the join.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/PushDownKeyedShuffleExchange.scala:
##########
@@ -0,0 +1,208 @@
+/*
+ * 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 org.apache.spark.sql.catalyst.expressions.{Alias, Attribute, 
AttributeMap, AttributeReference, Expression}
+import org.apache.spark.sql.catalyst.optimizer.{BuildLeft, BuildSide}
+import org.apache.spark.sql.catalyst.plans.physical.{ClusteredDistribution, 
HashPartitioning, KeyedPartitioning, PartitioningCollection}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.execution.{BinaryExecNode, FilterExec, 
GenerateExec, ProjectExec, SortExec, SparkPlan, UnaryExecNode}
+import org.apache.spark.sql.execution.aggregate.BaseAggregateExec
+import org.apache.spark.sql.execution.exchange.{ENSURE_REQUIREMENTS, 
EnsureRequirements, PartitioningOrigin, ShuffleExchangeExec, 
ValidateRequirements}
+import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec, 
BroadcastNestedLoopJoinExec}
+import org.apache.spark.sql.execution.window.{Final => FinalWindowGroupLimit, 
WindowExecBase, WindowGroupLimitExec}
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Moves a keyed shuffle down through operators clustered on its keys onto the 
hash shuffle that
+ * feeds them, so that one shuffle serves both:
+ *
+ * {{{
+ *   Before:                                     After:
+ *   SortMergeJoin                               SortMergeJoin
+ *    :- Sort                                     :- Sort
+ *    :  +- Exchange(keyed [item_id])             :  +- HashAggregate(key = 
[item_id])
+ *    :     +- HashAggregate(key = [item_id])     :     +- Exchange(keyed 
[item_id])
+ *    :        +- Exchange(hash [item_id])        :        +- 
HashAggregate(partial)
+ *    :           +- HashAggregate(partial)       :           +- ...
+ *    +- BatchScan(items, keyed [item_id])        +- BatchScan(items, keyed 
[item_id])
+ * }}}
+ *
+ * `EnsureRequirements` plans the join's keyed shuffle above the aggregate and 
the aggregate's own
+ * hash shuffle below it independently; a layout that serves the aggregate's 
clustering as well as
+ * the hash one lets the hash shuffle take the keyed layout. The walk crosses 
a grouped aggregate, a
+ * partitioned window, a final window group limit, a deterministic projection 
or filter, a local
+ * sort, a generate and a broadcast join's streamed side, and retargets only 
when the plan reuses
+ * neither shuffle, the layout offers at least the hash shuffle's partition 
count, no crossed
+ * expression evaluates differently, and the whole plan still validates under 
the preparation's root
+ * distribution.
+ */
+case class PushDownKeyedShuffleExchange(
+    ensureRequirements: EnsureRequirements,
+    queryContainsSubqueries: Boolean) extends Rule[SparkPlan] {
+
+  override def apply(plan: SparkPlan): SparkPlan = {
+    if (!conf.getConf(SQLConf.PUSH_DOWN_KEYED_SHUFFLE_ENABLED) ||
+        (queryContainsSubqueries &&
+          
!conf.getConf(SQLConf.PUSH_DOWN_KEYED_SHUFFLE_ALLOW_WITH_SUBQUERIES_ENABLED)) ||
+        !conf.v2BucketingShuffleEnabled || 
conf.v2BucketingPartiallyClusteredDistributionEnabled) {
+      return plan
+    }
+
+    lazy val sharedExchanges: Set[SparkPlan] =
+      if (conf.exchangeReuseEnabled) AQEUtils.duplicatedShuffleForms(plan) 
else Set.empty
+
+    val pushed = plan.transformUp {
+      // The layout has to be able to serve as a shuffle's template, as
+      // `KeyedShuffleSpec.canCreatePartitioning` asks of one it lays another 
child out on.
+      case keyedExchange @ ShuffleExchangeExec(
+          keyed: KeyedPartitioning, _, ENSURE_REQUIREMENTS, _, _) if 
keyed.canTemplateShuffle =>
+        pushDown(keyedExchange, sharedExchanges).getOrElse(keyedExchange)
+    }
+    if (pushed.fastEquals(plan) ||
+        !ValidateRequirements.validateWithOrigins(
+          pushed, ensureRequirements.requiredDistribution)) {
+      plan
+    } else {
+      pushed
+    }
+  }
+
+  /**
+   * `keyedExchange`'s child with the hash shuffle below it retargeted to the 
layout
+   * `keyedExchange` reports, or `None` when the walk cannot reach a hash 
shuffle that can take
+   * the layout, or the plan reuses both shuffles. The result reports the 
layout.
+   */
+  private def pushDown(
+      keyedExchange: ShuffleExchangeExec,
+      sharedExchanges: => Set[SparkPlan]): Option[SparkPlan] = {
+    // The pattern in `apply` pinned the layout.
+    val layout = 
keyedExchange.outputPartitioning.asInstanceOf[KeyedPartitioning]
+
+    // A broadcast join reports the streamed side's partitioning for the join 
types that do, so
+    // only that side is crossed and the build side is left alone. The final 
layout check rejects a
+    // join type that reports something else.
+    def retargetStreamed(
+        join: BinaryExecNode,
+        buildSide: BuildSide,
+        layout: KeyedPartitioning): Option[SparkPlan] = {
+      val streamed = if (buildSide == BuildLeft) join.right else join.left
+      retarget(streamed, layout).map { child =>
+        val children = if (buildSide == BuildLeft) {
+          Seq(join.left, child)
+        } else {
+          Seq(child, join.right)
+        }
+        join.withNewChildren(children)
+      }
+    }
+
+    // `operator` with its child retargeted to `childLayout`, once `admit` 
accepts that layout.
+    def retargetChild(
+        operator: UnaryExecNode,
+        childLayout: KeyedPartitioning,
+        admit: KeyedPartitioning => Boolean = _ => true): Option[SparkPlan] = {
+      if (admit(childLayout)) {
+        retarget(operator.child, childLayout).map(child => 
operator.withNewChildren(Seq(child)))
+      } else {
+        None
+      }
+    }
+
+    def retarget(plan: SparkPlan, layout: KeyedPartitioning): 
Option[SparkPlan] = plan match {
+      case hashExchange @ ShuffleExchangeExec(hash: HashPartitioning, _, 
ENSURE_REQUIREMENTS, _, _)
+          if hash.numPartitions <= layout.numPartitions &&
+            
layout.expressions.forall(_.references.subsetOf(hashExchange.child.outputSet)) 
&&
+            !sharedExchanges.contains(keyedExchange.canonicalized) &&
+            !sharedExchanges.contains(hashExchange.canonicalized) =>
+        // `EnsureRequirements` builds the layout with 
`KeyedShuffleSpec.createPartitioning`, which
+        // leaves it unmarked, so this shuffle routes undeclared rows by hash 
as the layout claims.

Review Comment:
   **Nit (P3):** `KeyedShuffleSpec.createPartitioning` always returns the 
layout with `unknownKeysOrigin = Some(HASH_ROUTING)` 
(partitioning.scala:2704-2706), so the layout this rule moves is marked, not 
unmarked. The retarget is sound because of that marker: `canTemplateShuffle` 
admits it through `unknownKeysRouted`, and the retargeted shuffle's partitioner 
sends a key the layout does not declare to its hash partition. The comment 
gives the opposite premise for the right conclusion, which could lead a 
maintainer to relax the `unknownKeysRouted` gate.
   
   ```suggestion
           // `EnsureRequirements` builds the layout with 
`KeyedShuffleSpec.createPartitioning`, which
           // marks it `HASH_ROUTING`, and this shuffle routes undeclared rows 
by hash, as marked.
   ```
   
   **Verification:**
   - **Inspection:** The comment that justifies the retarget names the 
HASH_ROUTING marker that createPartitioning sets and no longer calls the layout 
unmarked.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/PushDownKeyedShuffleExchange.scala:
##########
@@ -0,0 +1,208 @@
+/*
+ * 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 org.apache.spark.sql.catalyst.expressions.{Alias, Attribute, 
AttributeMap, AttributeReference, Expression}
+import org.apache.spark.sql.catalyst.optimizer.{BuildLeft, BuildSide}
+import org.apache.spark.sql.catalyst.plans.physical.{ClusteredDistribution, 
HashPartitioning, KeyedPartitioning, PartitioningCollection}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.execution.{BinaryExecNode, FilterExec, 
GenerateExec, ProjectExec, SortExec, SparkPlan, UnaryExecNode}
+import org.apache.spark.sql.execution.aggregate.BaseAggregateExec
+import org.apache.spark.sql.execution.exchange.{ENSURE_REQUIREMENTS, 
EnsureRequirements, PartitioningOrigin, ShuffleExchangeExec, 
ValidateRequirements}
+import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec, 
BroadcastNestedLoopJoinExec}
+import org.apache.spark.sql.execution.window.{Final => FinalWindowGroupLimit, 
WindowExecBase, WindowGroupLimitExec}
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Moves a keyed shuffle down through operators clustered on its keys onto the 
hash shuffle that
+ * feeds them, so that one shuffle serves both:
+ *
+ * {{{
+ *   Before:                                     After:
+ *   SortMergeJoin                               SortMergeJoin
+ *    :- Sort                                     :- Sort
+ *    :  +- Exchange(keyed [item_id])             :  +- HashAggregate(key = 
[item_id])
+ *    :     +- HashAggregate(key = [item_id])     :     +- Exchange(keyed 
[item_id])
+ *    :        +- Exchange(hash [item_id])        :        +- 
HashAggregate(partial)
+ *    :           +- HashAggregate(partial)       :           +- ...
+ *    +- BatchScan(items, keyed [item_id])        +- BatchScan(items, keyed 
[item_id])
+ * }}}
+ *
+ * `EnsureRequirements` plans the join's keyed shuffle above the aggregate and 
the aggregate's own
+ * hash shuffle below it independently; a layout that serves the aggregate's 
clustering as well as
+ * the hash one lets the hash shuffle take the keyed layout. The walk crosses 
a grouped aggregate, a
+ * partitioned window, a final window group limit, a deterministic projection 
or filter, a local
+ * sort, a generate and a broadcast join's streamed side, and retargets only 
when the plan reuses
+ * neither shuffle, the layout offers at least the hash shuffle's partition 
count, no crossed
+ * expression evaluates differently, and the whole plan still validates under 
the preparation's root
+ * distribution.
+ */
+case class PushDownKeyedShuffleExchange(
+    ensureRequirements: EnsureRequirements,
+    queryContainsSubqueries: Boolean) extends Rule[SparkPlan] {
+
+  override def apply(plan: SparkPlan): SparkPlan = {
+    if (!conf.getConf(SQLConf.PUSH_DOWN_KEYED_SHUFFLE_ENABLED) ||
+        (queryContainsSubqueries &&
+          
!conf.getConf(SQLConf.PUSH_DOWN_KEYED_SHUFFLE_ALLOW_WITH_SUBQUERIES_ENABLED)) ||
+        !conf.v2BucketingShuffleEnabled || 
conf.v2BucketingPartiallyClusteredDistributionEnabled) {
+      return plan
+    }
+
+    lazy val sharedExchanges: Set[SparkPlan] =
+      if (conf.exchangeReuseEnabled) AQEUtils.duplicatedShuffleForms(plan) 
else Set.empty
+
+    val pushed = plan.transformUp {
+      // The layout has to be able to serve as a shuffle's template, as
+      // `KeyedShuffleSpec.canCreatePartitioning` asks of one it lays another 
child out on.
+      case keyedExchange @ ShuffleExchangeExec(
+          keyed: KeyedPartitioning, _, ENSURE_REQUIREMENTS, _, _) if 
keyed.canTemplateShuffle =>
+        pushDown(keyedExchange, sharedExchanges).getOrElse(keyedExchange)
+    }
+    if (pushed.fastEquals(plan) ||
+        !ValidateRequirements.validateWithOrigins(
+          pushed, ensureRequirements.requiredDistribution)) {
+      plan
+    } else {
+      pushed
+    }
+  }
+
+  /**
+   * `keyedExchange`'s child with the hash shuffle below it retargeted to the 
layout
+   * `keyedExchange` reports, or `None` when the walk cannot reach a hash 
shuffle that can take
+   * the layout, or the plan reuses both shuffles. The result reports the 
layout.

Review Comment:
   **Nit (P3):** The hash-exchange arm refuses as soon as either the keyed or 
the hash shuffle is in `sharedExchanges` (lines 131-132), and the class doc and 
the config doc both describe that either-shuffle condition. A reader who aligns 
the code with this doc, refusing only when both are shared, would retarget a 
hash shuffle that another branch reuses and lose that stage.
   
   ```suggestion
      * the layout, or the plan reuses either shuffle. The result reports the 
layout.
   ```
   
   **Verification:**
   - **Inspection:** The pushDown method doc says the rewrite is refused when 
either shuffle is reused, matching the guard and the class doc.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/PushDownKeyedShuffleExchange.scala:
##########
@@ -0,0 +1,208 @@
+/*
+ * 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 org.apache.spark.sql.catalyst.expressions.{Alias, Attribute, 
AttributeMap, AttributeReference, Expression}
+import org.apache.spark.sql.catalyst.optimizer.{BuildLeft, BuildSide}
+import org.apache.spark.sql.catalyst.plans.physical.{ClusteredDistribution, 
HashPartitioning, KeyedPartitioning, PartitioningCollection}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.execution.{BinaryExecNode, FilterExec, 
GenerateExec, ProjectExec, SortExec, SparkPlan, UnaryExecNode}
+import org.apache.spark.sql.execution.aggregate.BaseAggregateExec
+import org.apache.spark.sql.execution.exchange.{ENSURE_REQUIREMENTS, 
EnsureRequirements, PartitioningOrigin, ShuffleExchangeExec, 
ValidateRequirements}
+import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec, 
BroadcastNestedLoopJoinExec}
+import org.apache.spark.sql.execution.window.{Final => FinalWindowGroupLimit, 
WindowExecBase, WindowGroupLimitExec}
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Moves a keyed shuffle down through operators clustered on its keys onto the 
hash shuffle that
+ * feeds them, so that one shuffle serves both:
+ *
+ * {{{
+ *   Before:                                     After:
+ *   SortMergeJoin                               SortMergeJoin
+ *    :- Sort                                     :- Sort
+ *    :  +- Exchange(keyed [item_id])             :  +- HashAggregate(key = 
[item_id])
+ *    :     +- HashAggregate(key = [item_id])     :     +- Exchange(keyed 
[item_id])
+ *    :        +- Exchange(hash [item_id])        :        +- 
HashAggregate(partial)
+ *    :           +- HashAggregate(partial)       :           +- ...
+ *    +- BatchScan(items, keyed [item_id])        +- BatchScan(items, keyed 
[item_id])
+ * }}}
+ *
+ * `EnsureRequirements` plans the join's keyed shuffle above the aggregate and 
the aggregate's own
+ * hash shuffle below it independently; a layout that serves the aggregate's 
clustering as well as
+ * the hash one lets the hash shuffle take the keyed layout. The walk crosses 
a grouped aggregate, a
+ * partitioned window, a final window group limit, a deterministic projection 
or filter, a local
+ * sort, a generate and a broadcast join's streamed side, and retargets only 
when the plan reuses
+ * neither shuffle, the layout offers at least the hash shuffle's partition 
count, no crossed
+ * expression evaluates differently, and the whole plan still validates under 
the preparation's root
+ * distribution.
+ */
+case class PushDownKeyedShuffleExchange(
+    ensureRequirements: EnsureRequirements,
+    queryContainsSubqueries: Boolean) extends Rule[SparkPlan] {
+
+  override def apply(plan: SparkPlan): SparkPlan = {
+    if (!conf.getConf(SQLConf.PUSH_DOWN_KEYED_SHUFFLE_ENABLED) ||
+        (queryContainsSubqueries &&
+          
!conf.getConf(SQLConf.PUSH_DOWN_KEYED_SHUFFLE_ALLOW_WITH_SUBQUERIES_ENABLED)) ||
+        !conf.v2BucketingShuffleEnabled || 
conf.v2BucketingPartiallyClusteredDistributionEnabled) {
+      return plan
+    }
+
+    lazy val sharedExchanges: Set[SparkPlan] =
+      if (conf.exchangeReuseEnabled) AQEUtils.duplicatedShuffleForms(plan) 
else Set.empty
+
+    val pushed = plan.transformUp {
+      // The layout has to be able to serve as a shuffle's template, as
+      // `KeyedShuffleSpec.canCreatePartitioning` asks of one it lays another 
child out on.
+      case keyedExchange @ ShuffleExchangeExec(
+          keyed: KeyedPartitioning, _, ENSURE_REQUIREMENTS, _, _) if 
keyed.canTemplateShuffle =>
+        pushDown(keyedExchange, sharedExchanges).getOrElse(keyedExchange)
+    }
+    if (pushed.fastEquals(plan) ||
+        !ValidateRequirements.validateWithOrigins(
+          pushed, ensureRequirements.requiredDistribution)) {
+      plan
+    } else {
+      pushed
+    }
+  }
+
+  /**
+   * `keyedExchange`'s child with the hash shuffle below it retargeted to the 
layout
+   * `keyedExchange` reports, or `None` when the walk cannot reach a hash 
shuffle that can take
+   * the layout, or the plan reuses both shuffles. The result reports the 
layout.
+   */
+  private def pushDown(
+      keyedExchange: ShuffleExchangeExec,
+      sharedExchanges: => Set[SparkPlan]): Option[SparkPlan] = {
+    // The pattern in `apply` pinned the layout.
+    val layout = 
keyedExchange.outputPartitioning.asInstanceOf[KeyedPartitioning]
+
+    // A broadcast join reports the streamed side's partitioning for the join 
types that do, so
+    // only that side is crossed and the build side is left alone. The final 
layout check rejects a
+    // join type that reports something else.
+    def retargetStreamed(
+        join: BinaryExecNode,
+        buildSide: BuildSide,
+        layout: KeyedPartitioning): Option[SparkPlan] = {
+      val streamed = if (buildSide == BuildLeft) join.right else join.left
+      retarget(streamed, layout).map { child =>
+        val children = if (buildSide == BuildLeft) {
+          Seq(join.left, child)
+        } else {
+          Seq(child, join.right)
+        }
+        join.withNewChildren(children)
+      }
+    }
+
+    // `operator` with its child retargeted to `childLayout`, once `admit` 
accepts that layout.
+    def retargetChild(
+        operator: UnaryExecNode,
+        childLayout: KeyedPartitioning,
+        admit: KeyedPartitioning => Boolean = _ => true): Option[SparkPlan] = {
+      if (admit(childLayout)) {
+        retarget(operator.child, childLayout).map(child => 
operator.withNewChildren(Seq(child)))
+      } else {
+        None
+      }
+    }
+
+    def retarget(plan: SparkPlan, layout: KeyedPartitioning): 
Option[SparkPlan] = plan match {
+      case hashExchange @ ShuffleExchangeExec(hash: HashPartitioning, _, 
ENSURE_REQUIREMENTS, _, _)
+          if hash.numPartitions <= layout.numPartitions &&
+            
layout.expressions.forall(_.references.subsetOf(hashExchange.child.outputSet)) 
&&
+            !sharedExchanges.contains(keyedExchange.canonicalized) &&
+            !sharedExchanges.contains(hashExchange.canonicalized) =>
+        // `EnsureRequirements` builds the layout with 
`KeyedShuffleSpec.createPartitioning`, which
+        // leaves it unmarked, so this shuffle routes undeclared rows by hash 
as the layout claims.
+        val retargeted = hashExchange.copy(outputPartitioning = layout)
+        // A custom strategy can plan a user repartition right above this 
shuffle, and its
+        // elision records the user layout here; keep it so the check below 
can refuse.

Review Comment:
   **Nit (P3):** `EnsureRequirements` records an elided user repartition's 
layout only when `pushDownShuffleThroughUnionEnabled` is set 
(EnsureRequirements.scala:1472-1473), and AQE sets that from 
`spark.sql.adaptive.pushDownShuffleThroughUnion.enabled`, an internal config 
that defaults to false, not from this rule's config. Under the default 
configuration nothing is recorded, so neither `validateNode` on line 139 nor 
the origin clause of `validateWithOrigins` can refuse a rewrite, and an elided 
user repartition on the walk loses its hash layout to the keyed one. Query 
results do not change, but the comment presents an inert check as a protection; 
stating the condition keeps readers from relying on it.
   
   ```suggestion
           // A custom strategy can plan a user repartition right above this 
shuffle, and its
           // elision records the user layout here; keep it so the check below 
can refuse. Only
           // union shuffle push-down makes `EnsureRequirements` record it, so 
with that off an
           // elided user layout on the walk is replaced by the keyed one.
   ```
   
   **Verification:**
   - **Inspection:** The comment above the tag copy names the union push-down 
condition under which EnsureRequirements records the user layout the check 
validates.



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/PushDownKeyedShuffleExchangeSuite.scala:
##########
@@ -0,0 +1,853 @@
+/*
+ * 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.connector
+
+import org.apache.spark.SparkConf
+import org.apache.spark.sql.Row
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Add, Alias, 
AttributeReference, Expression, Literal, TransformExpression}
+import org.apache.spark.sql.catalyst.expressions.aggregate.Partial
+import org.apache.spark.sql.catalyst.optimizer.BuildLeft
+import org.apache.spark.sql.catalyst.plans.physical.{HashPartitioning, 
KeyedPartitioning, ROUTING_LOST}
+import org.apache.spark.sql.connector.catalog.{Column, Identifier}
+import org.apache.spark.sql.connector.catalog.functions._
+import org.apache.spark.sql.connector.expressions.Expressions._
+import org.apache.spark.sql.execution.{FilterExec, GenerateExec, 
LocalTableScanExec, ProjectExec, SortExec, SparkPlan}
+import org.apache.spark.sql.execution.adaptive.{PushDownKeyedShuffleExchange, 
ShuffleQueryStageExec}
+import org.apache.spark.sql.execution.aggregate.{BaseAggregateExec, 
MergingSessionsExec, ObjectHashAggregateExec}
+import org.apache.spark.sql.execution.exchange.{ENSURE_REQUIREMENTS, 
EnsureRequirements, ReusedExchangeExec, ShuffleExchangeExec, 
ShuffleExchangeLike, ValidateRequirements}
+import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec, 
BroadcastNestedLoopJoinExec}
+import org.apache.spark.sql.execution.window.{Final, Partial => WGLPartial, 
WindowExec, WindowGroupLimitExec}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{LongType, StringType}
+
+class PushDownKeyedShuffleExchangeSuite extends 
KeyGroupedPartitioningSuiteBase {
+
+  private val functions = Seq(
+    UnboundYearsFunction,
+    UnboundDaysFunction,
+    UnboundBucketFunction,
+    UnboundTruncateFunction)
+
+  override def sparkConf: SparkConf = super.sparkConf
+    .set(SQLConf.V2_BUCKETING_ENABLED, true)
+    .set(SQLConf.AUTO_BROADCASTJOIN_THRESHOLD, -1L)
+
+  before {
+    functions.foreach { f =>
+      catalog.createFunction(Identifier.of(Array.empty, f.name()), f)
+    }
+  }
+
+  after {
+    catalog.clearTables()
+    catalog.clearFunctions()
+  }
+
+  private def shuffles(plan: SparkPlan): Seq[ShuffleExchangeLike] =
+    collect(plan) { case s: ShuffleExchangeLike => s }
+
+  /** Whether a keyed shuffle sits below the final aggregate, i.e. right above 
a partial one. */
+  private def isPushedDown(plan: SparkPlan): Boolean = shuffles(plan).exists { 
s =>
+    s.outputPartitioning.isInstanceOf[KeyedPartitioning] &&
+      s.child.collectFirst { case a: BaseAggregateExec => a }
+        .exists(_.aggregateExpressions.forall(_.mode == Partial))
+  }
+
+  // Dynamic partition pruning injects a pruning subquery on a filtered join 
side, and the rule's
+  // query-wide subquery gate then keeps both shuffles; "disabled for a query 
with subqueries"
+  // covers that gate directly.
+  private def withPushDownConf[T](confs: (String, String)*)(f: => T): T = {
+    withSQLConf(Seq(
+        SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
+        SQLConf.DYNAMIC_PARTITION_PRUNING_ENABLED.key -> "false",
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.SHUFFLE_PARTITIONS.key -> "2") ++ confs: _*)(f)
+  }
+
+  /** Runs `query`, checks its answer and returns its final adaptive plan. */
+  private def run(query: String, expected: Seq[Row]): SparkPlan = {
+    val df = sql(query)
+    checkAnswer(df, expected)
+    // `checkAnswer` runs a copy; execute `df` itself so its adaptive plan is 
final.
+    df.collect()

Review Comment:
   **Nit (P3):** `QueryTest.checkAnswer` ends by calling `df.collect()` on this 
same Dataset (CheckAnswerHelper.scala:91-94), and no base class of the suite 
overrides it, so `df`'s adaptive plan is already final when `checkAnswer` 
returns. The extra `collect()` reruns the query's final stage for every case 
that goes through `run` or `check`, and the comment misdescribes `checkAnswer`.
   
   ```suggestion
       checkAnswer(df, expected)
   ```
   
   **Verification:**
   - **Behavior:** With the extra collect removed, the plan the helper returns 
after checkAnswer is the final adaptive plan, so the push-down cases' 
shuffle-count and plan-shape assertions still hold.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/PushDownKeyedShuffleExchange.scala:
##########
@@ -0,0 +1,208 @@
+/*
+ * 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 org.apache.spark.sql.catalyst.expressions.{Alias, Attribute, 
AttributeMap, AttributeReference, Expression}
+import org.apache.spark.sql.catalyst.optimizer.{BuildLeft, BuildSide}
+import org.apache.spark.sql.catalyst.plans.physical.{ClusteredDistribution, 
HashPartitioning, KeyedPartitioning, PartitioningCollection}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.execution.{BinaryExecNode, FilterExec, 
GenerateExec, ProjectExec, SortExec, SparkPlan, UnaryExecNode}
+import org.apache.spark.sql.execution.aggregate.BaseAggregateExec
+import org.apache.spark.sql.execution.exchange.{ENSURE_REQUIREMENTS, 
EnsureRequirements, PartitioningOrigin, ShuffleExchangeExec, 
ValidateRequirements}
+import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec, 
BroadcastNestedLoopJoinExec}
+import org.apache.spark.sql.execution.window.{Final => FinalWindowGroupLimit, 
WindowExecBase, WindowGroupLimitExec}
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Moves a keyed shuffle down through operators clustered on its keys onto the 
hash shuffle that
+ * feeds them, so that one shuffle serves both:
+ *
+ * {{{
+ *   Before:                                     After:
+ *   SortMergeJoin                               SortMergeJoin
+ *    :- Sort                                     :- Sort
+ *    :  +- Exchange(keyed [item_id])             :  +- HashAggregate(key = 
[item_id])
+ *    :     +- HashAggregate(key = [item_id])     :     +- Exchange(keyed 
[item_id])
+ *    :        +- Exchange(hash [item_id])        :        +- 
HashAggregate(partial)
+ *    :           +- HashAggregate(partial)       :           +- ...
+ *    +- BatchScan(items, keyed [item_id])        +- BatchScan(items, keyed 
[item_id])
+ * }}}
+ *
+ * `EnsureRequirements` plans the join's keyed shuffle above the aggregate and 
the aggregate's own
+ * hash shuffle below it independently; a layout that serves the aggregate's 
clustering as well as
+ * the hash one lets the hash shuffle take the keyed layout. The walk crosses 
a grouped aggregate, a
+ * partitioned window, a final window group limit, a deterministic projection 
or filter, a local
+ * sort, a generate and a broadcast join's streamed side, and retargets only 
when the plan reuses
+ * neither shuffle, the layout offers at least the hash shuffle's partition 
count, no crossed
+ * expression evaluates differently, and the whole plan still validates under 
the preparation's root
+ * distribution.
+ */
+case class PushDownKeyedShuffleExchange(
+    ensureRequirements: EnsureRequirements,
+    queryContainsSubqueries: Boolean) extends Rule[SparkPlan] {
+
+  override def apply(plan: SparkPlan): SparkPlan = {
+    if (!conf.getConf(SQLConf.PUSH_DOWN_KEYED_SHUFFLE_ENABLED) ||
+        (queryContainsSubqueries &&
+          
!conf.getConf(SQLConf.PUSH_DOWN_KEYED_SHUFFLE_ALLOW_WITH_SUBQUERIES_ENABLED)) ||
+        !conf.v2BucketingShuffleEnabled || 
conf.v2BucketingPartiallyClusteredDistributionEnabled) {
+      return plan
+    }
+
+    lazy val sharedExchanges: Set[SparkPlan] =
+      if (conf.exchangeReuseEnabled) AQEUtils.duplicatedShuffleForms(plan) 
else Set.empty
+
+    val pushed = plan.transformUp {
+      // The layout has to be able to serve as a shuffle's template, as
+      // `KeyedShuffleSpec.canCreatePartitioning` asks of one it lays another 
child out on.
+      case keyedExchange @ ShuffleExchangeExec(
+          keyed: KeyedPartitioning, _, ENSURE_REQUIREMENTS, _, _) if 
keyed.canTemplateShuffle =>
+        pushDown(keyedExchange, sharedExchanges).getOrElse(keyedExchange)
+    }
+    if (pushed.fastEquals(plan) ||
+        !ValidateRequirements.validateWithOrigins(

Review Comment:
   **Nit (P3):** No case in `PushDownKeyedShuffleExchangeSuite` carries a 
`PartitioningOrigin` record: the suite never enables 
`spark.sql.adaptive.pushDownShuffleThroughUnion.enabled`, without which 
`EnsureRequirements` records none, and its one user-repartition case elides 
nothing. Replacing `validateWithOrigins` with `ValidateRequirements.validate` 
in this check, or dropping the `copyTagsFrom` call on line 138, keeps every 
test green. With union push-down on, a `/*+ REPARTITION(item_id) */` over the 
grouped subquery of `aggregateJoin` is elided and recorded on the final 
aggregate, and only the origin clause of this check refuses the rewrite; the 
tag copy matters only for a layout recorded on the hash shuffle itself, which 
only a plan-level case can build.
   
   **Verification:**
   - **Regression:** With the rewrite and union shuffle push-down enabled, a 
join whose aggregated side carries a repartition hint on the join key that 
EnsureRequirements elides keeps both shuffles, and with union shuffle push-down 
disabled the same query loses one.
   - **Regression:** With the rewrite enabled, a plan whose EnsureRequirements 
hash shuffle under a keyed shuffle carries a recorded user hash layout is left 
unchanged by the rule, while the same plan without the record is rewritten.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/PushDownKeyedShuffleExchange.scala:
##########
@@ -0,0 +1,208 @@
+/*
+ * 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 org.apache.spark.sql.catalyst.expressions.{Alias, Attribute, 
AttributeMap, AttributeReference, Expression}
+import org.apache.spark.sql.catalyst.optimizer.{BuildLeft, BuildSide}
+import org.apache.spark.sql.catalyst.plans.physical.{ClusteredDistribution, 
HashPartitioning, KeyedPartitioning, PartitioningCollection}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.execution.{BinaryExecNode, FilterExec, 
GenerateExec, ProjectExec, SortExec, SparkPlan, UnaryExecNode}
+import org.apache.spark.sql.execution.aggregate.BaseAggregateExec
+import org.apache.spark.sql.execution.exchange.{ENSURE_REQUIREMENTS, 
EnsureRequirements, PartitioningOrigin, ShuffleExchangeExec, 
ValidateRequirements}
+import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec, 
BroadcastNestedLoopJoinExec}
+import org.apache.spark.sql.execution.window.{Final => FinalWindowGroupLimit, 
WindowExecBase, WindowGroupLimitExec}
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Moves a keyed shuffle down through operators clustered on its keys onto the 
hash shuffle that
+ * feeds them, so that one shuffle serves both:
+ *
+ * {{{
+ *   Before:                                     After:
+ *   SortMergeJoin                               SortMergeJoin
+ *    :- Sort                                     :- Sort
+ *    :  +- Exchange(keyed [item_id])             :  +- HashAggregate(key = 
[item_id])
+ *    :     +- HashAggregate(key = [item_id])     :     +- Exchange(keyed 
[item_id])
+ *    :        +- Exchange(hash [item_id])        :        +- 
HashAggregate(partial)
+ *    :           +- HashAggregate(partial)       :           +- ...
+ *    +- BatchScan(items, keyed [item_id])        +- BatchScan(items, keyed 
[item_id])
+ * }}}
+ *
+ * `EnsureRequirements` plans the join's keyed shuffle above the aggregate and 
the aggregate's own
+ * hash shuffle below it independently; a layout that serves the aggregate's 
clustering as well as
+ * the hash one lets the hash shuffle take the keyed layout. The walk crosses 
a grouped aggregate, a
+ * partitioned window, a final window group limit, a deterministic projection 
or filter, a local
+ * sort, a generate and a broadcast join's streamed side, and retargets only 
when the plan reuses
+ * neither shuffle, the layout offers at least the hash shuffle's partition 
count, no crossed
+ * expression evaluates differently, and the whole plan still validates under 
the preparation's root
+ * distribution.
+ */
+case class PushDownKeyedShuffleExchange(
+    ensureRequirements: EnsureRequirements,
+    queryContainsSubqueries: Boolean) extends Rule[SparkPlan] {
+
+  override def apply(plan: SparkPlan): SparkPlan = {
+    if (!conf.getConf(SQLConf.PUSH_DOWN_KEYED_SHUFFLE_ENABLED) ||
+        (queryContainsSubqueries &&
+          
!conf.getConf(SQLConf.PUSH_DOWN_KEYED_SHUFFLE_ALLOW_WITH_SUBQUERIES_ENABLED)) ||
+        !conf.v2BucketingShuffleEnabled || 
conf.v2BucketingPartiallyClusteredDistributionEnabled) {
+      return plan
+    }
+
+    lazy val sharedExchanges: Set[SparkPlan] =
+      if (conf.exchangeReuseEnabled) AQEUtils.duplicatedShuffleForms(plan) 
else Set.empty
+
+    val pushed = plan.transformUp {
+      // The layout has to be able to serve as a shuffle's template, as
+      // `KeyedShuffleSpec.canCreatePartitioning` asks of one it lays another 
child out on.
+      case keyedExchange @ ShuffleExchangeExec(
+          keyed: KeyedPartitioning, _, ENSURE_REQUIREMENTS, _, _) if 
keyed.canTemplateShuffle =>
+        pushDown(keyedExchange, sharedExchanges).getOrElse(keyedExchange)
+    }
+    if (pushed.fastEquals(plan) ||
+        !ValidateRequirements.validateWithOrigins(
+          pushed, ensureRequirements.requiredDistribution)) {
+      plan
+    } else {
+      pushed
+    }
+  }
+
+  /**
+   * `keyedExchange`'s child with the hash shuffle below it retargeted to the 
layout
+   * `keyedExchange` reports, or `None` when the walk cannot reach a hash 
shuffle that can take
+   * the layout, or the plan reuses both shuffles. The result reports the 
layout.
+   */
+  private def pushDown(
+      keyedExchange: ShuffleExchangeExec,
+      sharedExchanges: => Set[SparkPlan]): Option[SparkPlan] = {
+    // The pattern in `apply` pinned the layout.
+    val layout = 
keyedExchange.outputPartitioning.asInstanceOf[KeyedPartitioning]
+
+    // A broadcast join reports the streamed side's partitioning for the join 
types that do, so
+    // only that side is crossed and the build side is left alone. The final 
layout check rejects a
+    // join type that reports something else.
+    def retargetStreamed(
+        join: BinaryExecNode,
+        buildSide: BuildSide,
+        layout: KeyedPartitioning): Option[SparkPlan] = {
+      val streamed = if (buildSide == BuildLeft) join.right else join.left
+      retarget(streamed, layout).map { child =>
+        val children = if (buildSide == BuildLeft) {
+          Seq(join.left, child)
+        } else {
+          Seq(child, join.right)
+        }
+        join.withNewChildren(children)
+      }
+    }
+
+    // `operator` with its child retargeted to `childLayout`, once `admit` 
accepts that layout.
+    def retargetChild(
+        operator: UnaryExecNode,
+        childLayout: KeyedPartitioning,
+        admit: KeyedPartitioning => Boolean = _ => true): Option[SparkPlan] = {
+      if (admit(childLayout)) {
+        retarget(operator.child, childLayout).map(child => 
operator.withNewChildren(Seq(child)))
+      } else {
+        None
+      }
+    }
+
+    def retarget(plan: SparkPlan, layout: KeyedPartitioning): 
Option[SparkPlan] = plan match {
+      case hashExchange @ ShuffleExchangeExec(hash: HashPartitioning, _, 
ENSURE_REQUIREMENTS, _, _)
+          if hash.numPartitions <= layout.numPartitions &&
+            
layout.expressions.forall(_.references.subsetOf(hashExchange.child.outputSet)) 
&&
+            !sharedExchanges.contains(keyedExchange.canonicalized) &&
+            !sharedExchanges.contains(hashExchange.canonicalized) =>
+        // `EnsureRequirements` builds the layout with 
`KeyedShuffleSpec.createPartitioning`, which
+        // leaves it unmarked, so this shuffle routes undeclared rows by hash 
as the layout claims.
+        val retargeted = hashExchange.copy(outputPartitioning = layout)
+        // A custom strategy can plan a user repartition right above this 
shuffle, and its
+        // elision records the user layout here; keep it so the check below 
can refuse.
+        retargeted.copyTagsFrom(hashExchange)
+        Option.when(PartitioningOrigin.validateNode(retargeted))(retargeted)
+
+      case project: ProjectExec if project.expressions.forall(_.deterministic) 
=>
+        rebind(layout, project).flatMap(retargetChild(project, _))
+      case filter: FilterExec if filter.expressions.forall(_.deterministic) =>
+        retargetChild(filter, layout)
+      case sort: SortExec if !sort.global =>
+        retargetChild(sort, layout)
+      case generate: GenerateExec if 
generate.expressions.forall(_.deterministic) =>
+        retargetChild(generate, layout)
+
+      case aggregate: BaseAggregateExec
+          if !aggregate.isStreaming && 
aggregate.expressions.forall(_.deterministic) =>
+        rebind(layout, aggregate).flatMap(childLayout =>
+          retargetChild(aggregate, childLayout, layout =>
+            
aggregate.requiredChildDistributionExpressions.exists(servesClustering(layout, 
_))))
+      case window: WindowExecBase =>

Review Comment:
   **Nit (P3):** The Project, Filter, Generate, aggregate and broadcast-join 
arms all require deterministic expressions (lines 141-163), and the class doc 
says the rule retargets only when no crossed expression evaluates differently, 
but this arm checks only the partition spec. A user aggregate built with 
`functions.udaf(...).asNondeterministic()` stays in the `WindowExec`, because 
analysis pulls out only its arguments and specs and `CheckAnalysis` admits 
non-deterministic window expressions, so the window is crossed and the function 
runs under the keyed layout's task partitioning, while the same function under 
`GROUP BY` is refused by the aggregate arm. `WindowExec` seeds no expression 
with the partition index, so results stay admissible; the inconsistency is with 
the documented guarantee and the sibling arms.
   
   ```suggestion
         case window: WindowExecBase if 
window.expressions.forall(_.deterministic) =>
   ```
   
   **Verification:**
   - **Behavior:** With the rewrite enabled, a window over a user aggregate 
function marked non-deterministic and partitioned by the join key keeps both 
shuffles, while the same window over a deterministic function loses one.



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/PushDownKeyedShuffleExchangeSuite.scala:
##########
@@ -0,0 +1,853 @@
+/*
+ * 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.connector
+
+import org.apache.spark.SparkConf
+import org.apache.spark.sql.Row
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Add, Alias, 
AttributeReference, Expression, Literal, TransformExpression}
+import org.apache.spark.sql.catalyst.expressions.aggregate.Partial
+import org.apache.spark.sql.catalyst.optimizer.BuildLeft
+import org.apache.spark.sql.catalyst.plans.physical.{HashPartitioning, 
KeyedPartitioning, ROUTING_LOST}
+import org.apache.spark.sql.connector.catalog.{Column, Identifier}
+import org.apache.spark.sql.connector.catalog.functions._
+import org.apache.spark.sql.connector.expressions.Expressions._
+import org.apache.spark.sql.execution.{FilterExec, GenerateExec, 
LocalTableScanExec, ProjectExec, SortExec, SparkPlan}
+import org.apache.spark.sql.execution.adaptive.{PushDownKeyedShuffleExchange, 
ShuffleQueryStageExec}
+import org.apache.spark.sql.execution.aggregate.{BaseAggregateExec, 
MergingSessionsExec, ObjectHashAggregateExec}
+import org.apache.spark.sql.execution.exchange.{ENSURE_REQUIREMENTS, 
EnsureRequirements, ReusedExchangeExec, ShuffleExchangeExec, 
ShuffleExchangeLike, ValidateRequirements}
+import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec, 
BroadcastNestedLoopJoinExec}
+import org.apache.spark.sql.execution.window.{Final, Partial => WGLPartial, 
WindowExec, WindowGroupLimitExec}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{LongType, StringType}
+
+class PushDownKeyedShuffleExchangeSuite extends 
KeyGroupedPartitioningSuiteBase {
+
+  private val functions = Seq(
+    UnboundYearsFunction,
+    UnboundDaysFunction,
+    UnboundBucketFunction,
+    UnboundTruncateFunction)
+
+  override def sparkConf: SparkConf = super.sparkConf
+    .set(SQLConf.V2_BUCKETING_ENABLED, true)
+    .set(SQLConf.AUTO_BROADCASTJOIN_THRESHOLD, -1L)
+
+  before {
+    functions.foreach { f =>
+      catalog.createFunction(Identifier.of(Array.empty, f.name()), f)
+    }
+  }
+
+  after {
+    catalog.clearTables()
+    catalog.clearFunctions()
+  }
+
+  private def shuffles(plan: SparkPlan): Seq[ShuffleExchangeLike] =
+    collect(plan) { case s: ShuffleExchangeLike => s }
+
+  /** Whether a keyed shuffle sits below the final aggregate, i.e. right above 
a partial one. */
+  private def isPushedDown(plan: SparkPlan): Boolean = shuffles(plan).exists { 
s =>
+    s.outputPartitioning.isInstanceOf[KeyedPartitioning] &&
+      s.child.collectFirst { case a: BaseAggregateExec => a }
+        .exists(_.aggregateExpressions.forall(_.mode == Partial))
+  }
+
+  // Dynamic partition pruning injects a pruning subquery on a filtered join 
side, and the rule's
+  // query-wide subquery gate then keeps both shuffles; "disabled for a query 
with subqueries"
+  // covers that gate directly.
+  private def withPushDownConf[T](confs: (String, String)*)(f: => T): T = {
+    withSQLConf(Seq(
+        SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
+        SQLConf.DYNAMIC_PARTITION_PRUNING_ENABLED.key -> "false",
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.SHUFFLE_PARTITIONS.key -> "2") ++ confs: _*)(f)
+  }
+
+  /** Runs `query`, checks its answer and returns its final adaptive plan. */
+  private def run(query: String, expected: Seq[Row]): SparkPlan = {
+    val df = sql(query)
+    checkAnswer(df, expected)
+    // `checkAnswer` runs a copy; execute `df` itself so its adaptive plan is 
final.
+    df.collect()
+    val plan = df.queryExecution.executedPlan
+    assert(ValidateRequirements.validate(stripAQEPlan(plan)), s"plan does not 
validate:\n$plan")
+    plan
+  }
+
+  private def check(
+      query: String,
+      expected: Seq[Row],
+      expectedShuffles: Int,
+      confs: (String, String)*): SparkPlan = withPushDownConf(confs: _*) {
+    val plan = run(query, expected)
+    assert(shuffles(plan).size == expectedShuffles,
+      s"expected $expectedShuffles shuffles, got 
${shuffles(plan).size}:\n$plan")
+    plan
+  }
+
+  private def loadData(): Unit = {
+    createTable(items, itemsColumns, Array(identity("id")))
+    sql(s"INSERT INTO testcat.ns.$items VALUES " +
+      "(1, 'aa', 40.0, cast('2020-01-01' as timestamp)), " +
+      "(1, 'aa', 41.0, cast('2020-01-02' as timestamp)), " +
+      "(2, 'bb', 10.0, cast('2020-01-01' as timestamp)), " +
+      "(3, 'cc', 15.5, cast('2020-02-01' as timestamp))")
+    createTable(purchases, purchasesColumns, Array.empty)
+    sql(s"INSERT INTO testcat.ns.$purchases VALUES " +
+      "(1, 40.0, cast('2020-01-01' as timestamp)), " +
+      "(2, 10.0, cast('2020-01-02' as timestamp)), " +
+      "(3, 25.5, cast('2020-01-03' as timestamp)), " +
+      "(4, 20.0, cast('2020-01-04' as timestamp))")
+  }
+
+  private val aggregateJoin =
+    s"""SELECT i.id, p.total FROM testcat.ns.$items i
+       |JOIN (
+       |  SELECT item_id, sum(price) AS total
+       |  FROM testcat.ns.$purchases GROUP BY item_id
+       |) p ON i.id = p.item_id""".stripMargin
+  private val aggregateJoinAnswer =
+    Seq(Row(1L, 40.0), Row(1L, 40.0), Row(2L, 10.0), Row(3L, 25.5))
+
+  test("aggregate runs on the keyed shuffle") {
+    loadData()
+    val plan = check(aggregateJoin, aggregateJoinAnswer, expectedShuffles = 1)
+    val stages = collect(plan) { case s: ShuffleQueryStageExec => s }
+    assert(stages.size == 1, plan)
+    
assert(stages.head.shuffle.outputPartitioning.isInstanceOf[KeyedPartitioning], 
plan)
+    assert(isPushedDown(plan), plan)
+    // With more shuffle partitions than the keyed side's 3, 
`EnsureRequirements` shuffles both
+    // sides on hash, so there is no keyed shuffle to push down.
+    check(aggregateJoin, aggregateJoinAnswer, expectedShuffles = 2,
+      SQLConf.SHUFFLE_PARTITIONS.key -> "8")
+  }
+
+  test("disabled by config, without the one-side shuffle or under partial 
clustering") {
+    loadData()
+    check(aggregateJoin, aggregateJoinAnswer, expectedShuffles = 2,
+      SQLConf.PUSH_DOWN_KEYED_SHUFFLE_ENABLED.key -> "false")
+    check(aggregateJoin, aggregateJoinAnswer, expectedShuffles = 2,
+      SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "false")
+    // `KeyedShuffleSpec.canCreatePartitioning` plans no keyed shuffle here, 
so both sides take a
+    // hash shuffle with or without the rule's own gate.
+    check(aggregateJoin, aggregateJoinAnswer, expectedShuffles = 2,
+      SQLConf.V2_BUCKETING_PARTIALLY_CLUSTERED_DISTRIBUTION_ENABLED.key -> 
"true")
+  }
+
+  test("disabled for a query with subqueries") {
+    loadData()
+    val query =
+      s"""SELECT i.id, p.total FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT item_id, sum(price) AS total
+         |  FROM testcat.ns.$purchases GROUP BY item_id
+         |) p ON i.id = p.item_id
+         |WHERE p.total > (SELECT avg(price) FROM 
testcat.ns.$purchases)""".stripMargin
+    val expected = Seq(Row(1L, 40.0), Row(1L, 40.0), Row(3L, 25.5))
+    check(query, expected, expectedShuffles = 2)
+    check(query, expected, expectedShuffles = 1,
+      SQLConf.PUSH_DOWN_KEYED_SHUFFLE_ALLOW_WITH_SUBQUERIES_ENABLED.key -> 
"true")
+  }
+
+  test("non-adaptive plans keep both shuffles") {
+    loadData()
+    withSQLConf(
+        SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.SHUFFLE_PARTITIONS.key -> "2") {
+      val df = sql(aggregateJoin)
+      checkAnswer(df, aggregateJoinAnswer)
+      assert(shuffles(df.queryExecution.executedPlan).size == 2)
+    }
+  }
+
+  test("session window aggregate") {
+    createTable(items, itemsColumns, Array(identity("id")))
+    sql(s"INSERT INTO testcat.ns.$items VALUES " +
+      "(1, 'aa', 40.0, cast('2020-01-01' as timestamp)), " +
+      "(2, 'bb', 10.0, cast('2020-01-01' as timestamp)), " +
+      "(3, 'cc', 15.5, cast('2020-02-01' as timestamp))")
+    createTable(purchases, purchasesColumns, Array.empty)
+    sql(s"INSERT INTO testcat.ns.$purchases VALUES " +
+      "(1, 10.0, cast('2020-01-01 00:00:00' as timestamp)), " +
+      "(1, 20.0, cast('2020-01-01 12:00:00' as timestamp)), " +
+      "(1, 30.0, cast('2020-01-20 00:00:00' as timestamp)), " +
+      "(2, 40.0, cast('2020-01-01 00:00:00' as timestamp)), " +
+      "(2, 50.0, cast('2020-01-01 06:00:00' as timestamp)), " +
+      "(4, 60.0, cast('2020-01-01 00:00:00' as timestamp))")
+    val query =
+      s"""SELECT i.id, p.cnt FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT item_id, count(*) AS cnt
+         |  FROM testcat.ns.$purchases
+         |  GROUP BY item_id, session_window(time, '1 day')
+         |) p ON i.id = p.item_id""".stripMargin
+    // Item 1 has two sessions (two rows within a day, one 19 days later), 
item 2 has one.
+    val expected = Seq(Row(1L, 2L), Row(1L, 1L), Row(2L, 2L))
+    val plan = check(query, expected, expectedShuffles = 1)
+    assert(collect(plan) { case m: MergingSessionsExec => m }.nonEmpty, plan)
+    // Only the merge step's input sort: `MergingSessionsExec` reports it, so 
the final
+    // aggregate above needs none of its own.
+    assert(collect(plan) { case s: SortExec => s }.size == 1, plan)
+    assert(isPushedDown(plan), plan)
+    // The same rows come from a hash shuffle over the whole grouping.
+    check(query, expected, expectedShuffles = 2,
+      SQLConf.PUSH_DOWN_KEYED_SHUFFLE_ENABLED.key -> "false")
+  }
+
+  test("a filter between the aggregate and the keyed shuffle") {
+    loadData()
+    val plan = check(
+      s"""SELECT i.id, p.total FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT item_id, sum(price) AS total
+         |  FROM testcat.ns.$purchases GROUP BY item_id HAVING sum(price) > 15
+         |) p ON i.id = p.item_id""".stripMargin,
+      Seq(Row(1L, 40.0), Row(1L, 40.0), Row(3L, 25.5)),
+      expectedShuffles = 1)
+    assert(collect(plan) {
+      case f: FilterExec if f.child.isInstanceOf[BaseAggregateExec] => f
+    }.nonEmpty, plan)
+    assert(isPushedDown(plan), plan)
+  }
+
+  test("rows of one key stay together, declared by the keyed side or not") {
+    createTable(items, itemsColumns, Array(identity("id")))
+    sql(s"INSERT INTO testcat.ns.$items VALUES " +
+      "(1, 'aa', 40.0, cast('2020-01-01' as timestamp)), " +
+      "(1, 'aa', 41.0, cast('2020-01-02' as timestamp)), " +
+      "(2, 'bb', 10.0, cast('2020-01-01' as timestamp)), " +
+      "(3, 'cc', 15.5, cast('2020-02-01' as timestamp))")
+    createTable(purchases, purchasesColumns, Array.empty)
+    // One row per split. Keys 1, 4 and 5 repeat across splits, and the keyed 
side does not declare
+    // 4 or 5, so the keyed shuffle routes those by hash.
+    val rows = Seq(1 -> 1.0, 1 -> 2.0, 1 -> 4.0, 2 -> 8.0, 4 -> 16.0, 4 -> 
32.0, 4 -> 64.0,
+      5 -> 128.0, 5 -> 256.0, 3 -> 512.0)
+    sql(s"INSERT INTO testcat.ns.$purchases VALUES " + rows.zipWithIndex.map {
+      case ((k, p), i) => s"($k, $p, cast('2020-01-0${i % 9 + 1}' as 
timestamp))"
+    }.mkString(", "))
+    Seq(
+      s"""SELECT p.item_id, p.total, p.c, i.id FROM (
+         |  SELECT item_id, sum(price) AS total, count(*) AS c
+         |  FROM testcat.ns.$purchases GROUP BY item_id
+         |) p LEFT JOIN testcat.ns.$items i ON i.id = p.item_id""".stripMargin,
+      s"""SELECT p.item_id, p.c, i.id FROM (
+         |  SELECT item_id, count(DISTINCT price) AS c
+         |  FROM testcat.ns.$purchases GROUP BY item_id
+         |) p FULL OUTER JOIN testcat.ns.$items i ON i.id = 
p.item_id""".stripMargin,
+      s"""SELECT p.item_id, p.rn, i.id FROM (
+         |  SELECT item_id, row_number() OVER (PARTITION BY item_id ORDER BY 
price) AS rn
+         |  FROM testcat.ns.$purchases
+         |) p LEFT JOIN testcat.ns.$items i ON i.id = p.item_id""".stripMargin
+    ).foreach { query =>
+      val (expected, base) =
+        withPushDownConf(SQLConf.PUSH_DOWN_KEYED_SHUFFLE_ENABLED.key -> 
"false") {
+          val df = sql(query)
+          val rows = df.collect().toSeq
+          (rows, shuffles(df.queryExecution.executedPlan).size)
+        }
+      val plan = withPushDownConf() { run(query, expected) }
+      assert(shuffles(plan).size == base - 1, plan)
+    }
+  }
+
+  test("a non-deterministic operator ends the walk") {
+    loadData()
+    def query(column: String): String =
+      s"""SELECT i.id, p.total FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT item_id, total, $column AS r FROM (
+         |    SELECT item_id, sum(price) AS total
+         |    FROM testcat.ns.$purchases GROUP BY item_id)
+         |) p ON i.id = p.item_id AND p.r >= 0""".stripMargin
+    check(query("total * 2"), aggregateJoinAnswer, expectedShuffles = 1)
+    check(query("rand(1)"), aggregateJoinAnswer, expectedShuffles = 2)

Review Comment:
   **Nit (P3):** The optimizer folds `item_id, total, rand(1) AS r` into the 
aggregate below it (`CollapseProject` merges a projection into an `Aggregate` 
when the expressions it inlines are deterministic and used once), so `rand(1)` 
ends up in the aggregate's result expressions and this case is refused by the 
aggregate arm (PushDownKeyedShuffleExchange.scala:151), not by the Project arm 
(line 141 of that file). No case has a non-deterministic generator either, 
since 'generate is crossed' uses `explode(array(total, total))`. Deleting the 
Project guard or the Generate guard (line 147) therefore keeps the suite green, 
although both are reachable: a projection over a `HAVING` filter is not 
collapsed, and `GenerateExec` seeds a non-deterministic generator such as 
`explode(array(total, rand(1)))` with the partition index.
   
   **Verification:**
   - **Regression:** With the rewrite enabled, a non-deterministic generator 
above the aggregate and a non-deterministic projection above a HAVING filter 
each keep both shuffles, while their deterministic counterparts lose one.



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/PushDownKeyedShuffleExchangeSuite.scala:
##########
@@ -0,0 +1,853 @@
+/*
+ * 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.connector
+
+import org.apache.spark.SparkConf
+import org.apache.spark.sql.Row
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Add, Alias, 
AttributeReference, Expression, Literal, TransformExpression}
+import org.apache.spark.sql.catalyst.expressions.aggregate.Partial
+import org.apache.spark.sql.catalyst.optimizer.BuildLeft
+import org.apache.spark.sql.catalyst.plans.physical.{HashPartitioning, 
KeyedPartitioning, ROUTING_LOST}
+import org.apache.spark.sql.connector.catalog.{Column, Identifier}
+import org.apache.spark.sql.connector.catalog.functions._
+import org.apache.spark.sql.connector.expressions.Expressions._
+import org.apache.spark.sql.execution.{FilterExec, GenerateExec, 
LocalTableScanExec, ProjectExec, SortExec, SparkPlan}
+import org.apache.spark.sql.execution.adaptive.{PushDownKeyedShuffleExchange, 
ShuffleQueryStageExec}
+import org.apache.spark.sql.execution.aggregate.{BaseAggregateExec, 
MergingSessionsExec, ObjectHashAggregateExec}
+import org.apache.spark.sql.execution.exchange.{ENSURE_REQUIREMENTS, 
EnsureRequirements, ReusedExchangeExec, ShuffleExchangeExec, 
ShuffleExchangeLike, ValidateRequirements}
+import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec, 
BroadcastNestedLoopJoinExec}
+import org.apache.spark.sql.execution.window.{Final, Partial => WGLPartial, 
WindowExec, WindowGroupLimitExec}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{LongType, StringType}
+
+class PushDownKeyedShuffleExchangeSuite extends 
KeyGroupedPartitioningSuiteBase {
+
+  private val functions = Seq(
+    UnboundYearsFunction,
+    UnboundDaysFunction,
+    UnboundBucketFunction,
+    UnboundTruncateFunction)
+
+  override def sparkConf: SparkConf = super.sparkConf
+    .set(SQLConf.V2_BUCKETING_ENABLED, true)
+    .set(SQLConf.AUTO_BROADCASTJOIN_THRESHOLD, -1L)
+
+  before {
+    functions.foreach { f =>
+      catalog.createFunction(Identifier.of(Array.empty, f.name()), f)
+    }
+  }
+
+  after {
+    catalog.clearTables()
+    catalog.clearFunctions()
+  }
+
+  private def shuffles(plan: SparkPlan): Seq[ShuffleExchangeLike] =
+    collect(plan) { case s: ShuffleExchangeLike => s }
+
+  /** Whether a keyed shuffle sits below the final aggregate, i.e. right above 
a partial one. */
+  private def isPushedDown(plan: SparkPlan): Boolean = shuffles(plan).exists { 
s =>
+    s.outputPartitioning.isInstanceOf[KeyedPartitioning] &&
+      s.child.collectFirst { case a: BaseAggregateExec => a }
+        .exists(_.aggregateExpressions.forall(_.mode == Partial))
+  }
+
+  // Dynamic partition pruning injects a pruning subquery on a filtered join 
side, and the rule's
+  // query-wide subquery gate then keeps both shuffles; "disabled for a query 
with subqueries"
+  // covers that gate directly.
+  private def withPushDownConf[T](confs: (String, String)*)(f: => T): T = {
+    withSQLConf(Seq(
+        SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
+        SQLConf.DYNAMIC_PARTITION_PRUNING_ENABLED.key -> "false",
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.SHUFFLE_PARTITIONS.key -> "2") ++ confs: _*)(f)
+  }
+
+  /** Runs `query`, checks its answer and returns its final adaptive plan. */
+  private def run(query: String, expected: Seq[Row]): SparkPlan = {
+    val df = sql(query)
+    checkAnswer(df, expected)
+    // `checkAnswer` runs a copy; execute `df` itself so its adaptive plan is 
final.
+    df.collect()
+    val plan = df.queryExecution.executedPlan
+    assert(ValidateRequirements.validate(stripAQEPlan(plan)), s"plan does not 
validate:\n$plan")
+    plan
+  }
+
+  private def check(
+      query: String,
+      expected: Seq[Row],
+      expectedShuffles: Int,
+      confs: (String, String)*): SparkPlan = withPushDownConf(confs: _*) {
+    val plan = run(query, expected)
+    assert(shuffles(plan).size == expectedShuffles,
+      s"expected $expectedShuffles shuffles, got 
${shuffles(plan).size}:\n$plan")
+    plan
+  }
+
+  private def loadData(): Unit = {
+    createTable(items, itemsColumns, Array(identity("id")))
+    sql(s"INSERT INTO testcat.ns.$items VALUES " +
+      "(1, 'aa', 40.0, cast('2020-01-01' as timestamp)), " +
+      "(1, 'aa', 41.0, cast('2020-01-02' as timestamp)), " +
+      "(2, 'bb', 10.0, cast('2020-01-01' as timestamp)), " +
+      "(3, 'cc', 15.5, cast('2020-02-01' as timestamp))")
+    createTable(purchases, purchasesColumns, Array.empty)
+    sql(s"INSERT INTO testcat.ns.$purchases VALUES " +
+      "(1, 40.0, cast('2020-01-01' as timestamp)), " +
+      "(2, 10.0, cast('2020-01-02' as timestamp)), " +
+      "(3, 25.5, cast('2020-01-03' as timestamp)), " +
+      "(4, 20.0, cast('2020-01-04' as timestamp))")
+  }
+
+  private val aggregateJoin =
+    s"""SELECT i.id, p.total FROM testcat.ns.$items i
+       |JOIN (
+       |  SELECT item_id, sum(price) AS total
+       |  FROM testcat.ns.$purchases GROUP BY item_id
+       |) p ON i.id = p.item_id""".stripMargin
+  private val aggregateJoinAnswer =
+    Seq(Row(1L, 40.0), Row(1L, 40.0), Row(2L, 10.0), Row(3L, 25.5))
+
+  test("aggregate runs on the keyed shuffle") {
+    loadData()
+    val plan = check(aggregateJoin, aggregateJoinAnswer, expectedShuffles = 1)
+    val stages = collect(plan) { case s: ShuffleQueryStageExec => s }
+    assert(stages.size == 1, plan)
+    
assert(stages.head.shuffle.outputPartitioning.isInstanceOf[KeyedPartitioning], 
plan)
+    assert(isPushedDown(plan), plan)
+    // With more shuffle partitions than the keyed side's 3, 
`EnsureRequirements` shuffles both
+    // sides on hash, so there is no keyed shuffle to push down.
+    check(aggregateJoin, aggregateJoinAnswer, expectedShuffles = 2,
+      SQLConf.SHUFFLE_PARTITIONS.key -> "8")
+  }
+
+  test("disabled by config, without the one-side shuffle or under partial 
clustering") {
+    loadData()
+    check(aggregateJoin, aggregateJoinAnswer, expectedShuffles = 2,
+      SQLConf.PUSH_DOWN_KEYED_SHUFFLE_ENABLED.key -> "false")
+    check(aggregateJoin, aggregateJoinAnswer, expectedShuffles = 2,
+      SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "false")
+    // `KeyedShuffleSpec.canCreatePartitioning` plans no keyed shuffle here, 
so both sides take a
+    // hash shuffle with or without the rule's own gate.
+    check(aggregateJoin, aggregateJoinAnswer, expectedShuffles = 2,
+      SQLConf.V2_BUCKETING_PARTIALLY_CLUSTERED_DISTRIBUTION_ENABLED.key -> 
"true")
+  }
+
+  test("disabled for a query with subqueries") {
+    loadData()
+    val query =
+      s"""SELECT i.id, p.total FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT item_id, sum(price) AS total
+         |  FROM testcat.ns.$purchases GROUP BY item_id
+         |) p ON i.id = p.item_id
+         |WHERE p.total > (SELECT avg(price) FROM 
testcat.ns.$purchases)""".stripMargin
+    val expected = Seq(Row(1L, 40.0), Row(1L, 40.0), Row(3L, 25.5))
+    check(query, expected, expectedShuffles = 2)
+    check(query, expected, expectedShuffles = 1,
+      SQLConf.PUSH_DOWN_KEYED_SHUFFLE_ALLOW_WITH_SUBQUERIES_ENABLED.key -> 
"true")
+  }
+
+  test("non-adaptive plans keep both shuffles") {
+    loadData()
+    withSQLConf(
+        SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.SHUFFLE_PARTITIONS.key -> "2") {
+      val df = sql(aggregateJoin)
+      checkAnswer(df, aggregateJoinAnswer)
+      assert(shuffles(df.queryExecution.executedPlan).size == 2)
+    }
+  }
+
+  test("session window aggregate") {
+    createTable(items, itemsColumns, Array(identity("id")))
+    sql(s"INSERT INTO testcat.ns.$items VALUES " +
+      "(1, 'aa', 40.0, cast('2020-01-01' as timestamp)), " +
+      "(2, 'bb', 10.0, cast('2020-01-01' as timestamp)), " +
+      "(3, 'cc', 15.5, cast('2020-02-01' as timestamp))")
+    createTable(purchases, purchasesColumns, Array.empty)
+    sql(s"INSERT INTO testcat.ns.$purchases VALUES " +
+      "(1, 10.0, cast('2020-01-01 00:00:00' as timestamp)), " +
+      "(1, 20.0, cast('2020-01-01 12:00:00' as timestamp)), " +
+      "(1, 30.0, cast('2020-01-20 00:00:00' as timestamp)), " +
+      "(2, 40.0, cast('2020-01-01 00:00:00' as timestamp)), " +
+      "(2, 50.0, cast('2020-01-01 06:00:00' as timestamp)), " +
+      "(4, 60.0, cast('2020-01-01 00:00:00' as timestamp))")
+    val query =
+      s"""SELECT i.id, p.cnt FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT item_id, count(*) AS cnt
+         |  FROM testcat.ns.$purchases
+         |  GROUP BY item_id, session_window(time, '1 day')
+         |) p ON i.id = p.item_id""".stripMargin
+    // Item 1 has two sessions (two rows within a day, one 19 days later), 
item 2 has one.
+    val expected = Seq(Row(1L, 2L), Row(1L, 1L), Row(2L, 2L))
+    val plan = check(query, expected, expectedShuffles = 1)
+    assert(collect(plan) { case m: MergingSessionsExec => m }.nonEmpty, plan)
+    // Only the merge step's input sort: `MergingSessionsExec` reports it, so 
the final
+    // aggregate above needs none of its own.
+    assert(collect(plan) { case s: SortExec => s }.size == 1, plan)
+    assert(isPushedDown(plan), plan)
+    // The same rows come from a hash shuffle over the whole grouping.
+    check(query, expected, expectedShuffles = 2,
+      SQLConf.PUSH_DOWN_KEYED_SHUFFLE_ENABLED.key -> "false")
+  }
+
+  test("a filter between the aggregate and the keyed shuffle") {
+    loadData()
+    val plan = check(
+      s"""SELECT i.id, p.total FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT item_id, sum(price) AS total
+         |  FROM testcat.ns.$purchases GROUP BY item_id HAVING sum(price) > 15
+         |) p ON i.id = p.item_id""".stripMargin,
+      Seq(Row(1L, 40.0), Row(1L, 40.0), Row(3L, 25.5)),
+      expectedShuffles = 1)
+    assert(collect(plan) {
+      case f: FilterExec if f.child.isInstanceOf[BaseAggregateExec] => f
+    }.nonEmpty, plan)
+    assert(isPushedDown(plan), plan)
+  }
+
+  test("rows of one key stay together, declared by the keyed side or not") {
+    createTable(items, itemsColumns, Array(identity("id")))
+    sql(s"INSERT INTO testcat.ns.$items VALUES " +
+      "(1, 'aa', 40.0, cast('2020-01-01' as timestamp)), " +
+      "(1, 'aa', 41.0, cast('2020-01-02' as timestamp)), " +
+      "(2, 'bb', 10.0, cast('2020-01-01' as timestamp)), " +
+      "(3, 'cc', 15.5, cast('2020-02-01' as timestamp))")
+    createTable(purchases, purchasesColumns, Array.empty)
+    // One row per split. Keys 1, 4 and 5 repeat across splits, and the keyed 
side does not declare
+    // 4 or 5, so the keyed shuffle routes those by hash.
+    val rows = Seq(1 -> 1.0, 1 -> 2.0, 1 -> 4.0, 2 -> 8.0, 4 -> 16.0, 4 -> 
32.0, 4 -> 64.0,
+      5 -> 128.0, 5 -> 256.0, 3 -> 512.0)
+    sql(s"INSERT INTO testcat.ns.$purchases VALUES " + rows.zipWithIndex.map {
+      case ((k, p), i) => s"($k, $p, cast('2020-01-0${i % 9 + 1}' as 
timestamp))"
+    }.mkString(", "))
+    Seq(
+      s"""SELECT p.item_id, p.total, p.c, i.id FROM (
+         |  SELECT item_id, sum(price) AS total, count(*) AS c
+         |  FROM testcat.ns.$purchases GROUP BY item_id
+         |) p LEFT JOIN testcat.ns.$items i ON i.id = p.item_id""".stripMargin,
+      s"""SELECT p.item_id, p.c, i.id FROM (
+         |  SELECT item_id, count(DISTINCT price) AS c
+         |  FROM testcat.ns.$purchases GROUP BY item_id
+         |) p FULL OUTER JOIN testcat.ns.$items i ON i.id = 
p.item_id""".stripMargin,
+      s"""SELECT p.item_id, p.rn, i.id FROM (
+         |  SELECT item_id, row_number() OVER (PARTITION BY item_id ORDER BY 
price) AS rn
+         |  FROM testcat.ns.$purchases
+         |) p LEFT JOIN testcat.ns.$items i ON i.id = p.item_id""".stripMargin
+    ).foreach { query =>
+      val (expected, base) =
+        withPushDownConf(SQLConf.PUSH_DOWN_KEYED_SHUFFLE_ENABLED.key -> 
"false") {
+          val df = sql(query)
+          val rows = df.collect().toSeq
+          (rows, shuffles(df.queryExecution.executedPlan).size)
+        }
+      val plan = withPushDownConf() { run(query, expected) }
+      assert(shuffles(plan).size == base - 1, plan)
+    }
+  }
+
+  test("a non-deterministic operator ends the walk") {
+    loadData()
+    def query(column: String): String =
+      s"""SELECT i.id, p.total FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT item_id, total, $column AS r FROM (
+         |    SELECT item_id, sum(price) AS total
+         |    FROM testcat.ns.$purchases GROUP BY item_id)
+         |) p ON i.id = p.item_id AND p.r >= 0""".stripMargin
+    check(query("total * 2"), aggregateJoinAnswer, expectedShuffles = 1)
+    check(query("rand(1)"), aggregateJoinAnswer, expectedShuffles = 2)
+  }
+
+  test("aliased group key") {
+    loadData()
+    check(
+      s"""SELECT i.id, p.k FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT item_id AS k, sum(price) AS total
+         |  FROM testcat.ns.$purchases GROUP BY item_id
+         |) p ON i.id = p.k""".stripMargin,
+      Seq(Row(1L, 1L), Row(1L, 1L), Row(2L, 2L), Row(3L, 3L)),
+      expectedShuffles = 1)
+  }
+
+  test("a join key computed by the aggregate keeps both shuffles") {
+    loadData()
+    check(
+      s"""SELECT i.id, p.cnt FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT item_id, count(*) AS cnt
+         |  FROM testcat.ns.$purchases GROUP BY item_id
+         |) p ON i.id = p.cnt""".stripMargin,
+      Seq.fill(8)(Row(1L, 1L)),
+      expectedShuffles = 2)
+  }
+
+  test("a layout on a subset of the group keys is admitted") {
+    loadData()
+    // The keyed layout on `item_id` alone covers only part of the aggregate's 
keys. Groups are
+    // still co-located, in coarser partitions, as they are for a source 
reporting this layout.
+    check(
+      s"""SELECT i.id, p.cnt FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT item_id, price, count(*) AS cnt
+         |  FROM testcat.ns.$purchases GROUP BY item_id, price
+         |) p ON i.id = p.item_id""".stripMargin,
+      Seq(Row(1L, 1L), Row(1L, 1L), Row(2L, 1L), Row(3L, 1L)),
+      expectedShuffles = 1)
+  }
+
+  test("window runs on the keyed shuffle") {
+    loadData()
+    val plan = check(
+      s"""SELECT i.id, p.item_id, p.rn FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT item_id, row_number() OVER (PARTITION BY item_id ORDER BY 
price) AS rn
+         |  FROM testcat.ns.$purchases
+         |) p ON i.id = p.item_id""".stripMargin,
+      Seq(Row(1L, 1L, 1), Row(1L, 1L, 1), Row(2L, 2L, 1), Row(3L, 3L, 1)),
+      expectedShuffles = 1,
+      SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> "false")
+    // The window's input sort also serves the join, so it is the only one.
+    val sorts = collect(plan) { case s: SortExec => s }
+    assert(sorts.size == 1, plan)
+    val window = collect(plan) { case w: WindowExec => w }.head
+    assert(window.child.fastEquals(sorts.head), plan)
+    // The keyed shuffle is below that sort, so the window reads the storage 
layout.
+    assert(collect(sorts.head) {
+      case s: ShuffleQueryStageExec
+          if s.shuffle.outputPartitioning.isInstanceOf[KeyedPartitioning] => s
+    }.nonEmpty, plan)
+    check(
+      s"""SELECT i.id, p.k, p.rn FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT item_id AS k,
+         |    row_number() OVER (PARTITION BY item_id ORDER BY price) AS rn
+         |  FROM testcat.ns.$purchases
+         |) p ON i.id = p.k""".stripMargin,
+      Seq(Row(1L, 1L, 1), Row(1L, 1L, 1), Row(2L, 2L, 1), Row(3L, 3L, 1)),
+      expectedShuffles = 1)
+  }
+
+  test("window group limit runs on the keyed shuffle") {
+    loadData()
+    val plan = check(
+      s"""SELECT i.id, p.price FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT item_id, price FROM (
+         |    SELECT item_id, price,
+         |      rank() OVER (PARTITION BY item_id ORDER BY price) AS rk
+         |    FROM testcat.ns.$purchases)
+         |  WHERE rk = 1
+         |) p ON i.id = p.item_id""".stripMargin,
+      Seq(Row(1L, 40.0f), Row(1L, 40.0f), Row(2L, 10.0f), Row(3L, 25.5f)),
+      expectedShuffles = 1)
+    assert(collect(plan) {
+      case l: WindowGroupLimitExec if l.mode == Final => l
+    }.nonEmpty, plan)
+    assert(shuffles(plan).exists { s =>
+      s.outputPartitioning.isInstanceOf[KeyedPartitioning] &&
+        s.child.collectFirst { case l: WindowGroupLimitExec => l 
}.exists(_.mode == WGLPartial)
+    }, plan)
+  }
+
+  test("a non-deterministic filter ends the walk") {
+    loadData()
+    def query(having: String): String =
+      s"""SELECT i.id, p.total FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT item_id, sum(price) AS total
+         |  FROM testcat.ns.$purchases GROUP BY item_id HAVING $having
+         |) p ON i.id = p.item_id""".stripMargin
+    check(query("sum(price) > 15"),
+      Seq(Row(1L, 40.0), Row(1L, 40.0), Row(3L, 25.5)), expectedShuffles = 1)
+    // A partition-seeded condition keeps a different set of rows under 
another partitioning.
+    withPushDownConf() {
+      val df = sql(query("rand(1) < 0.5"))
+      df.collect()
+      assert(shuffles(df.queryExecution.executedPlan).size == 2,
+        df.queryExecution.executedPlan)
+    }
+  }
+
+  test("a window expression mentioning a non-deterministic seed is pulled 
below the window") {
+    loadData()
+    withPushDownConf() {
+      val df = sql(
+        s"""SELECT i.id, p.f FROM testcat.ns.$items i
+           |JOIN (
+           |  SELECT item_id, first_value(rand()) OVER (PARTITION BY item_id 
ORDER BY price) AS f
+           |  FROM testcat.ns.$purchases
+           |) p ON i.id = p.item_id""".stripMargin)
+      df.collect()
+      val plan = df.queryExecution.executedPlan
+      assert(collect(plan) { case w: WindowExec => w }
+        .forall(_.expressions.forall(_.deterministic)), plan)
+      assert(shuffles(plan).size == 1, plan)
+    }
+  }
+
+  test("window on other keys keeps both shuffles") {
+    loadData()
+    check(
+      s"""SELECT i.id, p.item_id, p.rn FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT item_id, row_number() OVER (PARTITION BY price ORDER BY 
item_id) AS rn
+         |  FROM testcat.ns.$purchases
+         |) p ON i.id = p.item_id""".stripMargin,
+      Seq(Row(1L, 1L, 1), Row(1L, 1L, 1), Row(2L, 2L, 1), Row(3L, 3L, 1)),
+      expectedShuffles = 2)
+    check(
+      s"""SELECT i.id, p.item_id FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT item_id, sum(item_id) OVER (PARTITION BY item_id) AS total
+         |  FROM testcat.ns.$purchases
+         |) p ON i.id = p.total""".stripMargin,
+      Seq(Row(1L, 1L), Row(1L, 1L), Row(2L, 2L), Row(3L, 3L)),
+      expectedShuffles = 2)
+  }
+
+  test("aggregate under a window over the same keys") {
+    loadData()
+    check(
+      s"""SELECT i.id, p.total, p.rn FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT item_id, total, row_number() OVER (PARTITION BY item_id 
ORDER BY total) AS rn
+         |  FROM (
+         |    SELECT item_id, sum(price) AS total FROM testcat.ns.$purchases 
GROUP BY item_id)
+         |) p ON i.id = p.item_id""".stripMargin,
+      Seq(Row(1L, 40.0, 1), Row(1L, 40.0, 1), Row(2L, 10.0, 1), Row(3L, 25.5, 
1)),
+      expectedShuffles = 1)
+  }
+
+  test("object hash aggregate runs on the keyed shuffle") {
+    loadData()
+    val plan = check(
+      s"""SELECT i.id, p.prices FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT item_id, collect_list(price) AS prices
+         |  FROM testcat.ns.$purchases GROUP BY item_id
+         |) p ON i.id = p.item_id""".stripMargin,
+      Seq(Row(1L, Seq(40.0f)), Row(1L, Seq(40.0f)), Row(2L, Seq(10.0f)),
+        Row(3L, Seq(25.5f))),
+      expectedShuffles = 1)
+    assert(collect(plan) { case a: ObjectHashAggregateExec => a }.nonEmpty, 
plan)
+    // The aggregate reports no ordering, so the join keeps its own sort above 
it.
+    assert(collect(plan) { case s: SortExec => s }.size == 1, plan)
+    assert(isPushedDown(plan), plan)
+  }
+
+  test("sort aggregate drops the join's sort") {
+    loadData()
+    val plan = check(
+      s"""SELECT i.id, p.total FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT item_id, max(cast(price as string)) AS total
+         |  FROM testcat.ns.$purchases GROUP BY item_id
+         |) p ON i.id = p.item_id""".stripMargin,
+      Seq(Row(1L, "40.0"), Row(1L, "40.0"), Row(2L, "10.0"), Row(3L, "25.5")),
+      expectedShuffles = 1,
+      SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> "false")
+    // The aggregate's output is ordered on the join key, so the join needs no 
sort above it.
+    val sortsOverAggregate = collect(plan) {
+      case s: SortExec if s.child.isInstanceOf[BaseAggregateExec] => s
+    }
+    assert(sortsOverAggregate.isEmpty, plan)
+    // One sort for the final aggregate and one for the partial one; nothing 
else.
+    assert(collect(plan) { case s: SortExec => s }.size == 2, plan)
+    assert(isPushedDown(plan), plan)
+  }
+
+  test("broadcast join is crossed through its streamed side") {
+    loadData()
+    val plan = check(
+      s"""SELECT i.id, p.total FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT /*+ BROADCAST(b) */ a.item_id, a.total
+         |  FROM (
+         |    SELECT item_id, sum(price) AS total
+         |    FROM testcat.ns.$purchases GROUP BY item_id) a
+         |  JOIN (
+         |    SELECT item_id FROM testcat.ns.$purchases WHERE price >= 0) b
+         |  ON a.item_id = b.item_id
+         |) p ON i.id = p.item_id""".stripMargin,
+      Seq(Row(1L, 40.0), Row(1L, 40.0), Row(2L, 10.0), Row(3L, 25.5)),
+      expectedShuffles = 1)
+    val broadcast = collect(plan) { case j: BroadcastHashJoinExec => j }.head
+    // The keyed shuffle now feeds the streamed side's aggregate, under the 
broadcast join.
+    val streamed = if (broadcast.buildSide == BuildLeft) broadcast.right else 
broadcast.left
+    assert(collect(streamed) {
+      case s: ShuffleQueryStageExec
+          if s.shuffle.outputPartitioning.isInstanceOf[KeyedPartitioning] => s
+    }.nonEmpty, plan)
+    assert(isPushedDown(plan), plan)
+  }
+
+  test("generate is crossed") {
+    loadData()
+    val plan = check(
+      s"""SELECT i.id, g.x FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT item_id, explode(array(total, total)) AS x
+         |  FROM (
+         |    SELECT item_id, sum(price) AS total
+         |    FROM testcat.ns.$purchases GROUP BY item_id)
+         |) g ON i.id = g.item_id""".stripMargin,
+      Seq(Row(1L, 40.0), Row(1L, 40.0), Row(1L, 40.0), Row(1L, 40.0),
+        Row(2L, 10.0), Row(2L, 10.0), Row(3L, 25.5), Row(3L, 25.5)),
+      expectedShuffles = 1)
+    val generate = collect(plan) { case g: GenerateExec => g }.head
+    assert(collect(generate) {
+      case s: ShuffleQueryStageExec
+          if s.shuffle.outputPartitioning.isInstanceOf[KeyedPartitioning] => s
+    }.nonEmpty, plan)
+    assert(isPushedDown(plan), plan)
+  }
+
+  test("a broadcast join's build-side column as the join key keeps both 
shuffles") {
+    createTable(items, itemsColumns, Array(identity("id")))
+    sql(s"INSERT INTO testcat.ns.$items VALUES " +
+      "(1, 'aa', 40.0, cast('2020-01-01' as timestamp)), " +
+      "(2, 'bb', 10.0, cast('2020-01-01' as timestamp)), " +
+      "(3, 'cc', 15.5, cast('2020-02-01' as timestamp))")
+    createTable(purchases, purchasesColumns, Array.empty)
+    sql(s"INSERT INTO testcat.ns.$purchases VALUES " +
+      "(1, 1.0, cast('2020-01-01' as timestamp)), " +
+      "(2, 2.0, cast('2020-01-02' as timestamp)), " +
+      "(3, 3.0, cast('2020-01-03' as timestamp))")
+    // Only the build side provides `k`, so the streamed side's shuffle cannot 
be laid out on it.
+    check(
+      s"""SELECT i.id, p.total FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT /*+ BROADCAST(b) */ a.item_id, a.total, b.k
+         |  FROM (
+         |    SELECT item_id, sum(price) AS total
+         |    FROM testcat.ns.$purchases GROUP BY item_id) a
+         |  JOIN (
+         |    SELECT item_id, item_id AS k FROM testcat.ns.$purchases WHERE 
price >= 0) b
+         |  ON a.item_id = b.item_id
+         |) p ON i.id = p.k""".stripMargin,
+      Seq(Row(1L, 1.0), Row(2L, 2.0), Row(3L, 3.0)),
+      expectedShuffles = 2)
+  }
+
+  test("a user repartition below the operator keeps both shuffles") {
+    createTable(items, itemsColumns, Array(identity("id")))
+    sql(s"INSERT INTO testcat.ns.$items VALUES " +
+      "(1, 'aa', 40.0, cast('2020-01-01' as timestamp)), " +
+      "(2, 'bb', 10.0, cast('2020-01-01' as timestamp)), " +
+      "(3, 'cc', 15.5, cast('2020-02-01' as timestamp))")
+    createTable(purchases, purchasesColumns, Array.empty)
+    sql(s"INSERT INTO testcat.ns.$purchases VALUES " +
+      "(1, 40.0, cast('2020-01-01' as timestamp)), " +
+      "(2, 10.0, cast('2020-01-02' as timestamp)), " +
+      "(3, 25.5, cast('2020-01-03' as timestamp)), " +
+      "(4, 20.0, cast('2020-01-04' as timestamp))")
+    // The aggregate's input is the user's own repartition, which the rule 
does not retarget.
+    check(
+      s"""SELECT i.id, p.total FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT item_id, sum(price) AS total
+         |  FROM (SELECT /*+ REPARTITION(2, item_id) */ * FROM 
testcat.ns.$purchases)
+         |  GROUP BY item_id
+         |) p ON i.id = p.item_id""".stripMargin,
+      Seq(Row(1L, 40.0), Row(2L, 10.0), Row(3L, 25.5)),
+      expectedShuffles = 2)
+  }
+
+  test("broadcast nested loop join is crossed through its streamed side") {
+    createTable(items, itemsColumns, Array(identity("id")))
+    sql(s"INSERT INTO testcat.ns.$items VALUES " +
+      "(1, 'aa', 40.0, cast('2020-01-01' as timestamp)), " +
+      "(2, 'bb', 10.0, cast('2020-01-01' as timestamp)), " +
+      "(3, 'cc', 15.5, cast('2020-02-01' as timestamp))")
+    createTable(purchases, purchasesColumns, Array.empty)
+    sql(s"INSERT INTO testcat.ns.$purchases VALUES " +
+      "(1, 40.0, cast('2020-01-01' as timestamp)), " +
+      "(2, 10.0, cast('2020-01-02' as timestamp)), " +
+      "(3, 25.5, cast('2020-01-03' as timestamp)), " +
+      "(4, 20.0, cast('2020-01-04' as timestamp))")
+    val plan = check(
+      s"""SELECT i.id, x.item_id FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT /*+ BROADCAST(b) */ a.item_id, a.total
+         |  FROM (
+         |    SELECT item_id, sum(price) AS total
+         |    FROM testcat.ns.$purchases GROUP BY item_id) a
+         |  JOIN (SELECT 1 AS one) b ON a.total > 0
+         |) x ON i.id = x.item_id""".stripMargin,
+      Seq(Row(1L, 1L), Row(2L, 2L), Row(3L, 3L)),
+      expectedShuffles = 1)
+    assert(collect(plan) { case j: BroadcastNestedLoopJoinExec => j 
}.nonEmpty, plan)
+    assert(isPushedDown(plan), plan)
+  }
+
+  test("broadcast join building the left side is crossed through its streamed 
side") {
+    createTable(items, itemsColumns, Array(identity("id")))
+    sql(s"INSERT INTO testcat.ns.$items VALUES " +
+      "(1, 'aa', 40.0, cast('2020-01-01' as timestamp)), " +
+      "(2, 'bb', 10.0, cast('2020-01-01' as timestamp)), " +
+      "(3, 'cc', 15.5, cast('2020-02-01' as timestamp))")
+    createTable(purchases, purchasesColumns, Array.empty)
+    sql(s"INSERT INTO testcat.ns.$purchases VALUES " +
+      "(1, 40.0, cast('2020-01-01' as timestamp)), " +
+      "(2, 10.0, cast('2020-01-02' as timestamp)), " +
+      "(3, 25.5, cast('2020-01-03' as timestamp)), " +
+      "(4, 20.0, cast('2020-01-04' as timestamp))")
+    val plan = check(
+      s"""SELECT i.id, x.item_id FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT /*+ BROADCAST(b) */ a.item_id, a.total
+         |  FROM (SELECT item_id FROM testcat.ns.$purchases WHERE price >= 0) b
+         |  JOIN (
+         |    SELECT item_id, sum(price) AS total
+         |    FROM testcat.ns.$purchases GROUP BY item_id) a
+         |  ON b.item_id = a.item_id
+         |) x ON i.id = x.item_id""".stripMargin,
+      Seq(Row(1L, 1L), Row(2L, 2L), Row(3L, 3L)),
+      expectedShuffles = 1)
+    val broadcast = collect(plan) { case j: BroadcastHashJoinExec => j }.head
+    assert(broadcast.buildSide == BuildLeft, plan)
+    assert(collect(broadcast.right) {
+      case s: ShuffleQueryStageExec
+          if s.shuffle.outputPartitioning.isInstanceOf[KeyedPartitioning] => s
+    }.nonEmpty, plan)
+    assert(isPushedDown(plan), plan)
+  }
+
+  test("a window without a partition spec keeps both shuffles") {
+    loadData()
+    // Empty window keys ask for all tuples in one partition, which a keyed 
layout cannot serve.
+    check(
+      s"""SELECT i.id, p.rn FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT item_id, row_number() OVER (ORDER BY price) AS rn
+         |  FROM testcat.ns.$purchases
+         |) p ON i.id = p.item_id""".stripMargin,
+      Seq(Row(1L, 4L), Row(1L, 4L), Row(2L, 1L), Row(3L, 3L)),
+      expectedShuffles = 2)
+  }
+
+  test("outer joins") {
+    loadData()
+    check(
+      s"""SELECT i.id, p.total FROM testcat.ns.$items i
+         |LEFT JOIN (
+         |  SELECT item_id, sum(price) AS total
+         |  FROM testcat.ns.$purchases GROUP BY item_id
+         |) p ON i.id = p.item_id""".stripMargin,
+      aggregateJoinAnswer,
+      expectedShuffles = 1)
+    check(
+      s"""SELECT i.id, p.total FROM (
+         |  SELECT item_id, sum(price) AS total
+         |  FROM testcat.ns.$purchases GROUP BY item_id
+         |) p LEFT JOIN testcat.ns.$items i ON i.id = p.item_id""".stripMargin,
+      aggregateJoinAnswer :+ Row(null, 20.0),
+      expectedShuffles = 1)
+    check(
+      s"""SELECT i.id, p.total FROM testcat.ns.$items i
+         |FULL OUTER JOIN (
+         |  SELECT item_id, sum(price) AS total
+         |  FROM testcat.ns.$purchases GROUP BY item_id
+         |) p ON i.id = p.item_id""".stripMargin,
+      aggregateJoinAnswer :+ Row(null, 20.0),
+      expectedShuffles = 1)
+  }
+
+  test("join key order differs from the group key order") {
+    val cols = Array(
+      Column.create("a", LongType),
+      Column.create("b", LongType),
+      Column.create("v", LongType))
+    createTable("pairs", cols, Array(identity("a"), identity("b")))
+    sql("INSERT INTO testcat.ns.pairs VALUES (1, 1, 0), (1, 2, 0), (2, 1, 0), 
(2, 2, 0)")
+    createTable("facts", cols, Array.empty)
+    sql("INSERT INTO testcat.ns.facts VALUES " +
+      "(1, 1, 10), (1, 2, 20), (2, 1, 30), (2, 2, 40), (3, 3, 50)")
+    val expected =
+      Seq(Row(1L, 1L, 10L), Row(1L, 2L, 20L), Row(2L, 1L, 30L), Row(2L, 2L, 
40L))
+    check(
+      """SELECT p.a, p.b, f.total FROM testcat.ns.pairs p
+        |JOIN (
+        |  SELECT b, a, sum(v) AS total FROM testcat.ns.facts GROUP BY b, a
+        |) f ON p.a = f.a AND p.b = f.b""".stripMargin,
+      expected,
+      expectedShuffles = 1)
+    check(
+      """SELECT p.a, p.b, f.total FROM testcat.ns.pairs p
+        |JOIN (
+        |  SELECT b, a, sum(v) AS total FROM testcat.ns.facts GROUP BY a, b
+        |) f ON p.b = f.b AND p.a = f.a""".stripMargin,
+      expected,
+      expectedShuffles = 1)
+  }
+
+  /** A keyed side whose layout is a `bucket` transform, so the layout's 
expressions are too. */
+  private def loadBucketed(): Unit = {
+    val cols = Array(Column.create("id", LongType), Column.create("data", 
StringType))
+    createTable("bucketed", cols, Array(bucket(4, "id")))
+    sql("INSERT INTO testcat.ns.bucketed VALUES (0, 'a'), (1, 'b'), (2, 'c'), 
(3, 'd')")
+    createTable(purchases, purchasesColumns, Array.empty)
+    sql(s"INSERT INTO testcat.ns.$purchases VALUES " +
+      "(0, 10.0, cast('2020-01-01' as timestamp)), " +
+      "(1, 20.0, cast('2020-01-02' as timestamp)), " +
+      "(2, 30.0, cast('2020-01-03' as timestamp)), " +
+      "(3, 40.0, cast('2020-01-04' as timestamp)), " +
+      "(5, 50.0, cast('2020-01-05' as timestamp))")
+  }
+
+  private val bucketedJoin =
+    s"""SELECT b.id, p.total, b.data FROM testcat.ns.bucketed b
+       |JOIN (
+       |  SELECT item_id, sum(price) AS total
+       |  FROM testcat.ns.$purchases GROUP BY item_id
+       |) p ON b.id = p.item_id""".stripMargin
+
+  test("bucketed keyed side") {
+    loadBucketed()
+    check(bucketedJoin,
+      Seq(Row(0L, 10.0, "a"), Row(1L, 20.0, "b"), Row(2L, 30.0, "c"), Row(3L, 
40.0, "d")),
+      expectedShuffles = 1)
+  }
+
+  test("a layout that cannot serve as a shuffle template is not pushed down") {
+    loadBucketed()
+    withSQLConf(
+        SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
+        SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> "false",
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
+        SQLConf.SHUFFLE_PARTITIONS.key -> "2") {
+      // The prepared non-adaptive plan places the keyed shuffle above the 
aggregate and the hash
+      // shuffle under it; the rule is what AQE preparation runs on that shape.
+      val plan = sql(bucketedJoin).queryExecution.executedPlan
+      val rule = PushDownKeyedShuffleExchange(EnsureRequirements(), 
queryContainsSubqueries = false)
+
+      def exchanges(plan: SparkPlan): Seq[ShuffleExchangeExec] =
+        collect(plan) { case s: ShuffleExchangeExec => s }
+      def keyed(plan: SparkPlan): Seq[ShuffleExchangeExec] =
+        
exchanges(plan).filter(_.outputPartitioning.isInstanceOf[KeyedPartitioning])
+      // The planned keyed layout with one clause of `canTemplateShuffle` made 
to fail.
+      def withKeyedLayout(f: KeyedPartitioning => KeyedPartitioning): 
SparkPlan =
+        plan.transformUp {
+          case exchange @ ShuffleExchangeExec(k: KeyedPartitioning, _, _, _, 
_) =>
+            exchange.copy(outputPartitioning = f(k))
+        }
+      def assertDeclined(mutated: SparkPlan, clause: String): Unit = {
+        
assert(keyed(mutated).exists(!_.outputPartitioning.asInstanceOf[KeyedPartitioning]
+          .canTemplateShuffle), s"$clause did not flip:\n$mutated")
+        assert(rule.apply(mutated) eq mutated, s"$clause must stop the 
push-down:\n$mutated")
+      }
+
+      assert(exchanges(plan).size == 2 && keyed(plan).size == 1, plan)
+      val pushed = rule.apply(plan)
+      assert(pushed ne plan, s"the layout has to be a template:\n$plan")
+      assert(exchanges(pushed).size == 1, pushed)
+
+      assertDeclined(
+        withKeyedLayout(_.withLayout(_.copy(isGrouped = false))), "isGrouped")
+      assertDeclined(
+        withKeyedLayout(_.withLayout(_.copy(unknownKeysOrigin = 
Some(ROUTING_LOST)))),
+        "unknownKeysRouted")
+      // The reduced-keys clause keeps the guard one predicate with the 
producer, but a plan-level
+      // case cannot separate it: a layout that does not describe its keys 
fails the requirement
+      // check as well, so the rewrite is refused either way.
+      val reduced = withKeyedLayout { k =>
+        k.copy(expressions = k.expressions.map {
+          case t: TransformExpression => t.reducedTogetherWith(t)
+          case e => e
+        })
+      }
+      val reducedLayout =
+        keyed(reduced).head.outputPartitioning.asInstanceOf[KeyedPartitioning]
+      assert(reducedLayout.isGrouped && reducedLayout.unknownKeysRouted, 
reduced)
+      assert(!reducedLayout.canTemplateShuffle, reduced)
+      assert(!ValidateRequirements.validateWithOrigins(reduced, None), reduced)
+      assert(rule.apply(reduced) eq reduced, reduced)
+
+      // A hash shuffle feeding the operator with more partitions than the 
keyed layout offers:
+      // retargeting would cut the operator's parallelism. Both join sides 
still pair, since the
+      // keyed layout is the one the storage side reports, so only this guard 
refuses.
+      val keyedPartitions = keyed(plan).head.outputPartitioning.numPartitions
+      val wider = plan.transformUp {
+        case e @ ShuffleExchangeExec(h: HashPartitioning, _, _, _, _) =>
+          e.copy(outputPartitioning = h.copy(numPartitions = keyedPartitions + 
1))
+      }
+      assert(keyedPartitions < exchanges(wider)
+        .filterNot(_.outputPartitioning.isInstanceOf[KeyedPartitioning])
+        .head.outputPartitioning.numPartitions, wider)
+      assert(rule.apply(wider) eq wider, wider)
+    }
+  }
+
+  test("a shuffle that cannot evaluate the layout is not retargeted") {
+    val a = AttributeReference("a", LongType)()
+    val b = AttributeReference("b", LongType)()
+    // A third-party rule can put an `ENSURE_REQUIREMENTS` shuffle under a 
projection, with no
+    // clustered consumer between them.
+    def plan(layoutOn: Expression): SparkPlan = {
+      val scan = new LocalTableScanExec(Seq(a), Seq(InternalRow(1L)), None, 
false)
+      val hash = ShuffleExchangeExec(HashPartitioning(Seq(a), 2), scan, 
ENSURE_REQUIREMENTS)
+      val project = ProjectExec(Seq(a, Alias(Add(a, Literal(1L)), "b")()), 
hash)

Review Comment:
   **Nit (P3):** With the layout on `b`, which this projection computes, 
`rebind` (PushDownKeyedShuffleExchange.scala:187-207) finds no plain rename and 
returns `None` at the `ProjectExec`, so the walk never reaches the hash-shuffle 
arm whose evaluability clause (line 130 of that file) the test is named for; 
deleting the clause keeps the test green. The clause is the only refusal when a 
`GenerateExec` whose generator output carries the layout sits directly over an 
`ENSURE_REQUIREMENTS` hash shuffle: `GenerateExec` reports its child's 
partitioning, so without the clause the rewrite passes the final layout check 
and `validateWithOrigins`, and the shuffle then fails at execution when it 
binds an attribute its input lacks. Keeping this projection pair and adding a 
generate pair, with a control whose layout is on a column of the generate's 
child, would pin the clause.
   
   **Verification:**
   - **Regression:** With the rewrite enabled, a plan with a generate operator 
directly over an EnsureRequirements hash shuffle and the keyed layout on the 
generator's output is left unchanged, while the same plan with the layout on a 
column of the generate's child is rewritten.



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/PushDownKeyedShuffleExchangeSuite.scala:
##########
@@ -0,0 +1,853 @@
+/*
+ * 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.connector
+
+import org.apache.spark.SparkConf
+import org.apache.spark.sql.Row
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Add, Alias, 
AttributeReference, Expression, Literal, TransformExpression}
+import org.apache.spark.sql.catalyst.expressions.aggregate.Partial
+import org.apache.spark.sql.catalyst.optimizer.BuildLeft
+import org.apache.spark.sql.catalyst.plans.physical.{HashPartitioning, 
KeyedPartitioning, ROUTING_LOST}
+import org.apache.spark.sql.connector.catalog.{Column, Identifier}
+import org.apache.spark.sql.connector.catalog.functions._
+import org.apache.spark.sql.connector.expressions.Expressions._
+import org.apache.spark.sql.execution.{FilterExec, GenerateExec, 
LocalTableScanExec, ProjectExec, SortExec, SparkPlan}
+import org.apache.spark.sql.execution.adaptive.{PushDownKeyedShuffleExchange, 
ShuffleQueryStageExec}
+import org.apache.spark.sql.execution.aggregate.{BaseAggregateExec, 
MergingSessionsExec, ObjectHashAggregateExec}
+import org.apache.spark.sql.execution.exchange.{ENSURE_REQUIREMENTS, 
EnsureRequirements, ReusedExchangeExec, ShuffleExchangeExec, 
ShuffleExchangeLike, ValidateRequirements}
+import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec, 
BroadcastNestedLoopJoinExec}
+import org.apache.spark.sql.execution.window.{Final, Partial => WGLPartial, 
WindowExec, WindowGroupLimitExec}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{LongType, StringType}
+
+class PushDownKeyedShuffleExchangeSuite extends 
KeyGroupedPartitioningSuiteBase {
+
+  private val functions = Seq(
+    UnboundYearsFunction,
+    UnboundDaysFunction,
+    UnboundBucketFunction,
+    UnboundTruncateFunction)
+
+  override def sparkConf: SparkConf = super.sparkConf
+    .set(SQLConf.V2_BUCKETING_ENABLED, true)
+    .set(SQLConf.AUTO_BROADCASTJOIN_THRESHOLD, -1L)
+
+  before {
+    functions.foreach { f =>
+      catalog.createFunction(Identifier.of(Array.empty, f.name()), f)
+    }
+  }
+
+  after {
+    catalog.clearTables()
+    catalog.clearFunctions()
+  }
+
+  private def shuffles(plan: SparkPlan): Seq[ShuffleExchangeLike] =
+    collect(plan) { case s: ShuffleExchangeLike => s }
+
+  /** Whether a keyed shuffle sits below the final aggregate, i.e. right above 
a partial one. */
+  private def isPushedDown(plan: SparkPlan): Boolean = shuffles(plan).exists { 
s =>
+    s.outputPartitioning.isInstanceOf[KeyedPartitioning] &&
+      s.child.collectFirst { case a: BaseAggregateExec => a }
+        .exists(_.aggregateExpressions.forall(_.mode == Partial))
+  }
+
+  // Dynamic partition pruning injects a pruning subquery on a filtered join 
side, and the rule's
+  // query-wide subquery gate then keeps both shuffles; "disabled for a query 
with subqueries"
+  // covers that gate directly.
+  private def withPushDownConf[T](confs: (String, String)*)(f: => T): T = {
+    withSQLConf(Seq(
+        SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
+        SQLConf.DYNAMIC_PARTITION_PRUNING_ENABLED.key -> "false",
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.SHUFFLE_PARTITIONS.key -> "2") ++ confs: _*)(f)
+  }
+
+  /** Runs `query`, checks its answer and returns its final adaptive plan. */
+  private def run(query: String, expected: Seq[Row]): SparkPlan = {
+    val df = sql(query)
+    checkAnswer(df, expected)
+    // `checkAnswer` runs a copy; execute `df` itself so its adaptive plan is 
final.
+    df.collect()
+    val plan = df.queryExecution.executedPlan
+    assert(ValidateRequirements.validate(stripAQEPlan(plan)), s"plan does not 
validate:\n$plan")
+    plan
+  }
+
+  private def check(
+      query: String,
+      expected: Seq[Row],
+      expectedShuffles: Int,
+      confs: (String, String)*): SparkPlan = withPushDownConf(confs: _*) {
+    val plan = run(query, expected)
+    assert(shuffles(plan).size == expectedShuffles,
+      s"expected $expectedShuffles shuffles, got 
${shuffles(plan).size}:\n$plan")
+    plan
+  }
+
+  private def loadData(): Unit = {
+    createTable(items, itemsColumns, Array(identity("id")))
+    sql(s"INSERT INTO testcat.ns.$items VALUES " +
+      "(1, 'aa', 40.0, cast('2020-01-01' as timestamp)), " +
+      "(1, 'aa', 41.0, cast('2020-01-02' as timestamp)), " +
+      "(2, 'bb', 10.0, cast('2020-01-01' as timestamp)), " +
+      "(3, 'cc', 15.5, cast('2020-02-01' as timestamp))")
+    createTable(purchases, purchasesColumns, Array.empty)
+    sql(s"INSERT INTO testcat.ns.$purchases VALUES " +
+      "(1, 40.0, cast('2020-01-01' as timestamp)), " +
+      "(2, 10.0, cast('2020-01-02' as timestamp)), " +
+      "(3, 25.5, cast('2020-01-03' as timestamp)), " +
+      "(4, 20.0, cast('2020-01-04' as timestamp))")
+  }
+
+  private val aggregateJoin =
+    s"""SELECT i.id, p.total FROM testcat.ns.$items i
+       |JOIN (
+       |  SELECT item_id, sum(price) AS total
+       |  FROM testcat.ns.$purchases GROUP BY item_id
+       |) p ON i.id = p.item_id""".stripMargin
+  private val aggregateJoinAnswer =
+    Seq(Row(1L, 40.0), Row(1L, 40.0), Row(2L, 10.0), Row(3L, 25.5))
+
+  test("aggregate runs on the keyed shuffle") {
+    loadData()
+    val plan = check(aggregateJoin, aggregateJoinAnswer, expectedShuffles = 1)
+    val stages = collect(plan) { case s: ShuffleQueryStageExec => s }
+    assert(stages.size == 1, plan)
+    
assert(stages.head.shuffle.outputPartitioning.isInstanceOf[KeyedPartitioning], 
plan)
+    assert(isPushedDown(plan), plan)
+    // With more shuffle partitions than the keyed side's 3, 
`EnsureRequirements` shuffles both
+    // sides on hash, so there is no keyed shuffle to push down.
+    check(aggregateJoin, aggregateJoinAnswer, expectedShuffles = 2,
+      SQLConf.SHUFFLE_PARTITIONS.key -> "8")
+  }
+
+  test("disabled by config, without the one-side shuffle or under partial 
clustering") {
+    loadData()
+    check(aggregateJoin, aggregateJoinAnswer, expectedShuffles = 2,
+      SQLConf.PUSH_DOWN_KEYED_SHUFFLE_ENABLED.key -> "false")
+    check(aggregateJoin, aggregateJoinAnswer, expectedShuffles = 2,
+      SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "false")
+    // `KeyedShuffleSpec.canCreatePartitioning` plans no keyed shuffle here, 
so both sides take a
+    // hash shuffle with or without the rule's own gate.
+    check(aggregateJoin, aggregateJoinAnswer, expectedShuffles = 2,
+      SQLConf.V2_BUCKETING_PARTIALLY_CLUSTERED_DISTRIBUTION_ENABLED.key -> 
"true")
+  }
+
+  test("disabled for a query with subqueries") {
+    loadData()
+    val query =
+      s"""SELECT i.id, p.total FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT item_id, sum(price) AS total
+         |  FROM testcat.ns.$purchases GROUP BY item_id
+         |) p ON i.id = p.item_id
+         |WHERE p.total > (SELECT avg(price) FROM 
testcat.ns.$purchases)""".stripMargin
+    val expected = Seq(Row(1L, 40.0), Row(1L, 40.0), Row(3L, 25.5))
+    check(query, expected, expectedShuffles = 2)
+    check(query, expected, expectedShuffles = 1,
+      SQLConf.PUSH_DOWN_KEYED_SHUFFLE_ALLOW_WITH_SUBQUERIES_ENABLED.key -> 
"true")
+  }
+
+  test("non-adaptive plans keep both shuffles") {
+    loadData()
+    withSQLConf(
+        SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.SHUFFLE_PARTITIONS.key -> "2") {
+      val df = sql(aggregateJoin)
+      checkAnswer(df, aggregateJoinAnswer)
+      assert(shuffles(df.queryExecution.executedPlan).size == 2)
+    }
+  }
+
+  test("session window aggregate") {
+    createTable(items, itemsColumns, Array(identity("id")))
+    sql(s"INSERT INTO testcat.ns.$items VALUES " +
+      "(1, 'aa', 40.0, cast('2020-01-01' as timestamp)), " +
+      "(2, 'bb', 10.0, cast('2020-01-01' as timestamp)), " +
+      "(3, 'cc', 15.5, cast('2020-02-01' as timestamp))")
+    createTable(purchases, purchasesColumns, Array.empty)
+    sql(s"INSERT INTO testcat.ns.$purchases VALUES " +
+      "(1, 10.0, cast('2020-01-01 00:00:00' as timestamp)), " +
+      "(1, 20.0, cast('2020-01-01 12:00:00' as timestamp)), " +
+      "(1, 30.0, cast('2020-01-20 00:00:00' as timestamp)), " +
+      "(2, 40.0, cast('2020-01-01 00:00:00' as timestamp)), " +
+      "(2, 50.0, cast('2020-01-01 06:00:00' as timestamp)), " +
+      "(4, 60.0, cast('2020-01-01 00:00:00' as timestamp))")
+    val query =
+      s"""SELECT i.id, p.cnt FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT item_id, count(*) AS cnt
+         |  FROM testcat.ns.$purchases
+         |  GROUP BY item_id, session_window(time, '1 day')
+         |) p ON i.id = p.item_id""".stripMargin
+    // Item 1 has two sessions (two rows within a day, one 19 days later), 
item 2 has one.
+    val expected = Seq(Row(1L, 2L), Row(1L, 1L), Row(2L, 2L))
+    val plan = check(query, expected, expectedShuffles = 1)
+    assert(collect(plan) { case m: MergingSessionsExec => m }.nonEmpty, plan)
+    // Only the merge step's input sort: `MergingSessionsExec` reports it, so 
the final
+    // aggregate above needs none of its own.
+    assert(collect(plan) { case s: SortExec => s }.size == 1, plan)
+    assert(isPushedDown(plan), plan)
+    // The same rows come from a hash shuffle over the whole grouping.
+    check(query, expected, expectedShuffles = 2,
+      SQLConf.PUSH_DOWN_KEYED_SHUFFLE_ENABLED.key -> "false")
+  }
+
+  test("a filter between the aggregate and the keyed shuffle") {
+    loadData()
+    val plan = check(
+      s"""SELECT i.id, p.total FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT item_id, sum(price) AS total
+         |  FROM testcat.ns.$purchases GROUP BY item_id HAVING sum(price) > 15
+         |) p ON i.id = p.item_id""".stripMargin,
+      Seq(Row(1L, 40.0), Row(1L, 40.0), Row(3L, 25.5)),
+      expectedShuffles = 1)
+    assert(collect(plan) {
+      case f: FilterExec if f.child.isInstanceOf[BaseAggregateExec] => f
+    }.nonEmpty, plan)
+    assert(isPushedDown(plan), plan)
+  }
+
+  test("rows of one key stay together, declared by the keyed side or not") {
+    createTable(items, itemsColumns, Array(identity("id")))
+    sql(s"INSERT INTO testcat.ns.$items VALUES " +
+      "(1, 'aa', 40.0, cast('2020-01-01' as timestamp)), " +
+      "(1, 'aa', 41.0, cast('2020-01-02' as timestamp)), " +
+      "(2, 'bb', 10.0, cast('2020-01-01' as timestamp)), " +
+      "(3, 'cc', 15.5, cast('2020-02-01' as timestamp))")
+    createTable(purchases, purchasesColumns, Array.empty)
+    // One row per split. Keys 1, 4 and 5 repeat across splits, and the keyed 
side does not declare
+    // 4 or 5, so the keyed shuffle routes those by hash.
+    val rows = Seq(1 -> 1.0, 1 -> 2.0, 1 -> 4.0, 2 -> 8.0, 4 -> 16.0, 4 -> 
32.0, 4 -> 64.0,
+      5 -> 128.0, 5 -> 256.0, 3 -> 512.0)
+    sql(s"INSERT INTO testcat.ns.$purchases VALUES " + rows.zipWithIndex.map {
+      case ((k, p), i) => s"($k, $p, cast('2020-01-0${i % 9 + 1}' as 
timestamp))"
+    }.mkString(", "))
+    Seq(
+      s"""SELECT p.item_id, p.total, p.c, i.id FROM (
+         |  SELECT item_id, sum(price) AS total, count(*) AS c
+         |  FROM testcat.ns.$purchases GROUP BY item_id
+         |) p LEFT JOIN testcat.ns.$items i ON i.id = p.item_id""".stripMargin,
+      s"""SELECT p.item_id, p.c, i.id FROM (
+         |  SELECT item_id, count(DISTINCT price) AS c
+         |  FROM testcat.ns.$purchases GROUP BY item_id
+         |) p FULL OUTER JOIN testcat.ns.$items i ON i.id = 
p.item_id""".stripMargin,
+      s"""SELECT p.item_id, p.rn, i.id FROM (
+         |  SELECT item_id, row_number() OVER (PARTITION BY item_id ORDER BY 
price) AS rn
+         |  FROM testcat.ns.$purchases
+         |) p LEFT JOIN testcat.ns.$items i ON i.id = p.item_id""".stripMargin
+    ).foreach { query =>
+      val (expected, base) =
+        withPushDownConf(SQLConf.PUSH_DOWN_KEYED_SHUFFLE_ENABLED.key -> 
"false") {
+          val df = sql(query)
+          val rows = df.collect().toSeq
+          (rows, shuffles(df.queryExecution.executedPlan).size)
+        }
+      val plan = withPushDownConf() { run(query, expected) }
+      assert(shuffles(plan).size == base - 1, plan)
+    }
+  }
+
+  test("a non-deterministic operator ends the walk") {
+    loadData()
+    def query(column: String): String =
+      s"""SELECT i.id, p.total FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT item_id, total, $column AS r FROM (
+         |    SELECT item_id, sum(price) AS total
+         |    FROM testcat.ns.$purchases GROUP BY item_id)
+         |) p ON i.id = p.item_id AND p.r >= 0""".stripMargin
+    check(query("total * 2"), aggregateJoinAnswer, expectedShuffles = 1)
+    check(query("rand(1)"), aggregateJoinAnswer, expectedShuffles = 2)
+  }
+
+  test("aliased group key") {
+    loadData()
+    check(
+      s"""SELECT i.id, p.k FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT item_id AS k, sum(price) AS total
+         |  FROM testcat.ns.$purchases GROUP BY item_id
+         |) p ON i.id = p.k""".stripMargin,
+      Seq(Row(1L, 1L), Row(1L, 1L), Row(2L, 2L), Row(3L, 3L)),
+      expectedShuffles = 1)
+  }
+
+  test("a join key computed by the aggregate keeps both shuffles") {
+    loadData()
+    check(
+      s"""SELECT i.id, p.cnt FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT item_id, count(*) AS cnt
+         |  FROM testcat.ns.$purchases GROUP BY item_id
+         |) p ON i.id = p.cnt""".stripMargin,
+      Seq.fill(8)(Row(1L, 1L)),
+      expectedShuffles = 2)
+  }
+
+  test("a layout on a subset of the group keys is admitted") {
+    loadData()
+    // The keyed layout on `item_id` alone covers only part of the aggregate's 
keys. Groups are
+    // still co-located, in coarser partitions, as they are for a source 
reporting this layout.
+    check(
+      s"""SELECT i.id, p.cnt FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT item_id, price, count(*) AS cnt
+         |  FROM testcat.ns.$purchases GROUP BY item_id, price
+         |) p ON i.id = p.item_id""".stripMargin,
+      Seq(Row(1L, 1L), Row(1L, 1L), Row(2L, 1L), Row(3L, 1L)),
+      expectedShuffles = 1)
+  }
+
+  test("window runs on the keyed shuffle") {
+    loadData()
+    val plan = check(
+      s"""SELECT i.id, p.item_id, p.rn FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT item_id, row_number() OVER (PARTITION BY item_id ORDER BY 
price) AS rn
+         |  FROM testcat.ns.$purchases
+         |) p ON i.id = p.item_id""".stripMargin,
+      Seq(Row(1L, 1L, 1), Row(1L, 1L, 1), Row(2L, 2L, 1), Row(3L, 3L, 1)),
+      expectedShuffles = 1,
+      SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> "false")
+    // The window's input sort also serves the join, so it is the only one.
+    val sorts = collect(plan) { case s: SortExec => s }
+    assert(sorts.size == 1, plan)
+    val window = collect(plan) { case w: WindowExec => w }.head
+    assert(window.child.fastEquals(sorts.head), plan)
+    // The keyed shuffle is below that sort, so the window reads the storage 
layout.
+    assert(collect(sorts.head) {
+      case s: ShuffleQueryStageExec
+          if s.shuffle.outputPartitioning.isInstanceOf[KeyedPartitioning] => s
+    }.nonEmpty, plan)
+    check(
+      s"""SELECT i.id, p.k, p.rn FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT item_id AS k,
+         |    row_number() OVER (PARTITION BY item_id ORDER BY price) AS rn
+         |  FROM testcat.ns.$purchases
+         |) p ON i.id = p.k""".stripMargin,
+      Seq(Row(1L, 1L, 1), Row(1L, 1L, 1), Row(2L, 2L, 1), Row(3L, 3L, 1)),
+      expectedShuffles = 1)
+  }
+
+  test("window group limit runs on the keyed shuffle") {
+    loadData()
+    val plan = check(
+      s"""SELECT i.id, p.price FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT item_id, price FROM (
+         |    SELECT item_id, price,
+         |      rank() OVER (PARTITION BY item_id ORDER BY price) AS rk
+         |    FROM testcat.ns.$purchases)
+         |  WHERE rk = 1
+         |) p ON i.id = p.item_id""".stripMargin,
+      Seq(Row(1L, 40.0f), Row(1L, 40.0f), Row(2L, 10.0f), Row(3L, 25.5f)),
+      expectedShuffles = 1)
+    assert(collect(plan) {
+      case l: WindowGroupLimitExec if l.mode == Final => l
+    }.nonEmpty, plan)
+    assert(shuffles(plan).exists { s =>
+      s.outputPartitioning.isInstanceOf[KeyedPartitioning] &&
+        s.child.collectFirst { case l: WindowGroupLimitExec => l 
}.exists(_.mode == WGLPartial)
+    }, plan)
+  }
+
+  test("a non-deterministic filter ends the walk") {
+    loadData()
+    def query(having: String): String =
+      s"""SELECT i.id, p.total FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT item_id, sum(price) AS total
+         |  FROM testcat.ns.$purchases GROUP BY item_id HAVING $having
+         |) p ON i.id = p.item_id""".stripMargin
+    check(query("sum(price) > 15"),
+      Seq(Row(1L, 40.0), Row(1L, 40.0), Row(3L, 25.5)), expectedShuffles = 1)
+    // A partition-seeded condition keeps a different set of rows under 
another partitioning.
+    withPushDownConf() {
+      val df = sql(query("rand(1) < 0.5"))
+      df.collect()
+      assert(shuffles(df.queryExecution.executedPlan).size == 2,
+        df.queryExecution.executedPlan)
+    }
+  }
+
+  test("a window expression mentioning a non-deterministic seed is pulled 
below the window") {
+    loadData()
+    withPushDownConf() {
+      val df = sql(
+        s"""SELECT i.id, p.f FROM testcat.ns.$items i
+           |JOIN (
+           |  SELECT item_id, first_value(rand()) OVER (PARTITION BY item_id 
ORDER BY price) AS f
+           |  FROM testcat.ns.$purchases
+           |) p ON i.id = p.item_id""".stripMargin)
+      df.collect()
+      val plan = df.queryExecution.executedPlan
+      assert(collect(plan) { case w: WindowExec => w }
+        .forall(_.expressions.forall(_.deterministic)), plan)
+      assert(shuffles(plan).size == 1, plan)
+    }
+  }
+
+  test("window on other keys keeps both shuffles") {
+    loadData()
+    check(
+      s"""SELECT i.id, p.item_id, p.rn FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT item_id, row_number() OVER (PARTITION BY price ORDER BY 
item_id) AS rn
+         |  FROM testcat.ns.$purchases
+         |) p ON i.id = p.item_id""".stripMargin,
+      Seq(Row(1L, 1L, 1), Row(1L, 1L, 1), Row(2L, 2L, 1), Row(3L, 3L, 1)),
+      expectedShuffles = 2)
+    check(
+      s"""SELECT i.id, p.item_id FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT item_id, sum(item_id) OVER (PARTITION BY item_id) AS total
+         |  FROM testcat.ns.$purchases
+         |) p ON i.id = p.total""".stripMargin,
+      Seq(Row(1L, 1L), Row(1L, 1L), Row(2L, 2L), Row(3L, 3L)),
+      expectedShuffles = 2)
+  }
+
+  test("aggregate under a window over the same keys") {
+    loadData()
+    check(
+      s"""SELECT i.id, p.total, p.rn FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT item_id, total, row_number() OVER (PARTITION BY item_id 
ORDER BY total) AS rn
+         |  FROM (
+         |    SELECT item_id, sum(price) AS total FROM testcat.ns.$purchases 
GROUP BY item_id)
+         |) p ON i.id = p.item_id""".stripMargin,
+      Seq(Row(1L, 40.0, 1), Row(1L, 40.0, 1), Row(2L, 10.0, 1), Row(3L, 25.5, 
1)),
+      expectedShuffles = 1)
+  }
+
+  test("object hash aggregate runs on the keyed shuffle") {
+    loadData()
+    val plan = check(
+      s"""SELECT i.id, p.prices FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT item_id, collect_list(price) AS prices
+         |  FROM testcat.ns.$purchases GROUP BY item_id
+         |) p ON i.id = p.item_id""".stripMargin,
+      Seq(Row(1L, Seq(40.0f)), Row(1L, Seq(40.0f)), Row(2L, Seq(10.0f)),
+        Row(3L, Seq(25.5f))),
+      expectedShuffles = 1)
+    assert(collect(plan) { case a: ObjectHashAggregateExec => a }.nonEmpty, 
plan)
+    // The aggregate reports no ordering, so the join keeps its own sort above 
it.
+    assert(collect(plan) { case s: SortExec => s }.size == 1, plan)
+    assert(isPushedDown(plan), plan)
+  }
+
+  test("sort aggregate drops the join's sort") {
+    loadData()
+    val plan = check(
+      s"""SELECT i.id, p.total FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT item_id, max(cast(price as string)) AS total
+         |  FROM testcat.ns.$purchases GROUP BY item_id
+         |) p ON i.id = p.item_id""".stripMargin,
+      Seq(Row(1L, "40.0"), Row(1L, "40.0"), Row(2L, "10.0"), Row(3L, "25.5")),
+      expectedShuffles = 1,
+      SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> "false")
+    // The aggregate's output is ordered on the join key, so the join needs no 
sort above it.
+    val sortsOverAggregate = collect(plan) {
+      case s: SortExec if s.child.isInstanceOf[BaseAggregateExec] => s
+    }
+    assert(sortsOverAggregate.isEmpty, plan)
+    // One sort for the final aggregate and one for the partial one; nothing 
else.
+    assert(collect(plan) { case s: SortExec => s }.size == 2, plan)
+    assert(isPushedDown(plan), plan)
+  }
+
+  test("broadcast join is crossed through its streamed side") {
+    loadData()
+    val plan = check(
+      s"""SELECT i.id, p.total FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT /*+ BROADCAST(b) */ a.item_id, a.total
+         |  FROM (
+         |    SELECT item_id, sum(price) AS total
+         |    FROM testcat.ns.$purchases GROUP BY item_id) a
+         |  JOIN (
+         |    SELECT item_id FROM testcat.ns.$purchases WHERE price >= 0) b
+         |  ON a.item_id = b.item_id
+         |) p ON i.id = p.item_id""".stripMargin,
+      Seq(Row(1L, 40.0), Row(1L, 40.0), Row(2L, 10.0), Row(3L, 25.5)),
+      expectedShuffles = 1)
+    val broadcast = collect(plan) { case j: BroadcastHashJoinExec => j }.head
+    // The keyed shuffle now feeds the streamed side's aggregate, under the 
broadcast join.
+    val streamed = if (broadcast.buildSide == BuildLeft) broadcast.right else 
broadcast.left
+    assert(collect(streamed) {
+      case s: ShuffleQueryStageExec
+          if s.shuffle.outputPartitioning.isInstanceOf[KeyedPartitioning] => s
+    }.nonEmpty, plan)
+    assert(isPushedDown(plan), plan)
+  }
+
+  test("generate is crossed") {
+    loadData()
+    val plan = check(
+      s"""SELECT i.id, g.x FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT item_id, explode(array(total, total)) AS x
+         |  FROM (
+         |    SELECT item_id, sum(price) AS total
+         |    FROM testcat.ns.$purchases GROUP BY item_id)
+         |) g ON i.id = g.item_id""".stripMargin,
+      Seq(Row(1L, 40.0), Row(1L, 40.0), Row(1L, 40.0), Row(1L, 40.0),
+        Row(2L, 10.0), Row(2L, 10.0), Row(3L, 25.5), Row(3L, 25.5)),
+      expectedShuffles = 1)
+    val generate = collect(plan) { case g: GenerateExec => g }.head
+    assert(collect(generate) {
+      case s: ShuffleQueryStageExec
+          if s.shuffle.outputPartitioning.isInstanceOf[KeyedPartitioning] => s
+    }.nonEmpty, plan)
+    assert(isPushedDown(plan), plan)
+  }
+
+  test("a broadcast join's build-side column as the join key keeps both 
shuffles") {
+    createTable(items, itemsColumns, Array(identity("id")))
+    sql(s"INSERT INTO testcat.ns.$items VALUES " +
+      "(1, 'aa', 40.0, cast('2020-01-01' as timestamp)), " +
+      "(2, 'bb', 10.0, cast('2020-01-01' as timestamp)), " +
+      "(3, 'cc', 15.5, cast('2020-02-01' as timestamp))")
+    createTable(purchases, purchasesColumns, Array.empty)
+    sql(s"INSERT INTO testcat.ns.$purchases VALUES " +
+      "(1, 1.0, cast('2020-01-01' as timestamp)), " +
+      "(2, 2.0, cast('2020-01-02' as timestamp)), " +
+      "(3, 3.0, cast('2020-01-03' as timestamp))")
+    // Only the build side provides `k`, so the streamed side's shuffle cannot 
be laid out on it.
+    check(
+      s"""SELECT i.id, p.total FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT /*+ BROADCAST(b) */ a.item_id, a.total, b.k
+         |  FROM (
+         |    SELECT item_id, sum(price) AS total
+         |    FROM testcat.ns.$purchases GROUP BY item_id) a
+         |  JOIN (
+         |    SELECT item_id, item_id AS k FROM testcat.ns.$purchases WHERE 
price >= 0) b
+         |  ON a.item_id = b.item_id
+         |) p ON i.id = p.k""".stripMargin,
+      Seq(Row(1L, 1.0), Row(2L, 2.0), Row(3L, 3.0)),
+      expectedShuffles = 2)
+  }
+
+  test("a user repartition below the operator keeps both shuffles") {
+    createTable(items, itemsColumns, Array(identity("id")))
+    sql(s"INSERT INTO testcat.ns.$items VALUES " +
+      "(1, 'aa', 40.0, cast('2020-01-01' as timestamp)), " +
+      "(2, 'bb', 10.0, cast('2020-01-01' as timestamp)), " +
+      "(3, 'cc', 15.5, cast('2020-02-01' as timestamp))")
+    createTable(purchases, purchasesColumns, Array.empty)
+    sql(s"INSERT INTO testcat.ns.$purchases VALUES " +
+      "(1, 40.0, cast('2020-01-01' as timestamp)), " +
+      "(2, 10.0, cast('2020-01-02' as timestamp)), " +
+      "(3, 25.5, cast('2020-01-03' as timestamp)), " +
+      "(4, 20.0, cast('2020-01-04' as timestamp))")
+    // The aggregate's input is the user's own repartition, which the rule 
does not retarget.
+    check(
+      s"""SELECT i.id, p.total FROM testcat.ns.$items i
+         |JOIN (
+         |  SELECT item_id, sum(price) AS total
+         |  FROM (SELECT /*+ REPARTITION(2, item_id) */ * FROM 
testcat.ns.$purchases)

Review Comment:
   **Nit (P3):** With this hint the aggregate is planned as final over partial 
over the user shuffle, with no `EnsureRequirements` shuffle between them, and 
the walk stops at the partial aggregate because its 
`requiredChildDistributionExpressions` is `None` 
(PushDownKeyedShuffleExchange.scala:154). It never reaches the 
`ENSURE_REQUIREMENTS` field of the retarget pattern (line 128 of that file), 
the only check that keeps a user repartition on the walk in place, so widening 
that pattern to any shuffle origin keeps every test green. A window partitioned 
by `item_id` directly over `/*+ REPARTITION(2, item_id) */` reaches the user 
shuffle through the window and local-sort arms, and there only the origin field 
refuses.
   
   **Verification:**
   - **Regression:** With the rewrite enabled, a window partitioned by the join 
key directly over a user repartition by that key keeps the user's two-partition 
shuffle and the keyed shuffle.



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