dongjoon-hyun commented on code in PR #60658:
URL: https://github.com/apache/spark/pull/60658#discussion_r4620905962


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/PushDownKeyedShuffleExchange.scala:
##########
@@ -0,0 +1,210 @@
+/*
+ * 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 either shuffle. 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
+        // marks it `HASH_ROUTING`, and this shuffle routes undeclared rows by 
hash, as marked.
+        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. 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.
+        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) =>

Review Comment:
   **[1] A failable join key is now evaluated on rows that a crossed filter or 
join removes.**
   
   The layout's partition expressions are this side's join keys 
(`KeyedShuffleSpec.createPartitioning` builds them over the clustering), so 
they can be computed and can fail. Without this rule, the keyed shuffle 
evaluates them only on the rows that reach it, after every filter and join 
below it. The retargeted shuffle evaluates them below the operators the walk 
crosses, and some of those remove rows: this `FilterExec` (e.g. a `HAVING`), an 
inner, semi or anti broadcast hash join, a broadcast nested loop join with a 
condition, and a `GenerateExec` that is not outer. The walk checks that those 
operators are deterministic, but nothing checks that the layout can be 
evaluated on the rows they would have removed.
   
   For example, with the suite's `withPushDownConf` settings and ANSI mode on 
(the default), `items` keyed by `identity(id)`, and a `purchases.code STRING` 
column that holds `'n/a'` in a group whose total is 1:
   
   ```sql
   SELECT i.id, p.total FROM testcat.ns.items i
   JOIN (
     SELECT code, sum(price) AS total FROM testcat.ns.purchases
     GROUP BY code HAVING sum(price) > 10
   ) p ON i.id = CAST(p.code AS BIGINT)
   ```
   
   The keyed shuffle is on `cast(code as bigint)`. Without the rule, the 
`HAVING` filter removes the `'n/a'` group before anything casts it. With the 
rule, the walk crosses the filter and the final aggregate, and the partitioner 
of the retargeted shuffle casts `'n/a'` on the partial aggregate's row, so the 
query fails with `CAST_INVALID_INPUT`.
   
   Could the walk refuse to cross an operator that removes rows unless every 
layout expression passes `ExprUtils.canEvaluateUnconditionally`? An identity 
layout over a column, as in `a filter between the aggregate and the keyed 
shuffle`, would still be crossed.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/PushDownKeyedShuffleExchange.scala:
##########
@@ -0,0 +1,210 @@
+/*
+ * 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) ||

Review Comment:
   **[2] One refused candidate reverts every push-down in the plan.**
   
   `apply` rewrites every keyed shuffle in one `transformUp` and validates the 
whole result once. When one candidate fails `validateWithOrigins`, the plan 
falls back to the original, and the other, independent candidates are dropped 
with it. For example, in a `UNION ALL` of two storage-partitioned joins, or a 
chain of joins with two keyed shuffles, a refusal on one branch keeps the 
redundant shuffle on the other. `PushDownShuffleExchangeThroughUnion` retries 
per child for the same reason. Could this validate per keyed shuffle, and keep 
each rewrite that passes on its own?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/PushDownKeyedShuffleExchange.scala:
##########
@@ -0,0 +1,210 @@
+/*
+ * 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 either shuffle. 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
+        // marks it `HASH_ROUTING`, and this shuffle routes undeclared rows by 
hash, as marked.
+        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. 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.
+        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 if 
window.expressions.forall(_.deterministic) =>
+        retargetChild(window, layout,
+          childLayout => servesClustering(childLayout, window.partitionSpec))
+      case wgl: WindowGroupLimitExec if wgl.mode == FinalWindowGroupLimit =>
+        retargetChild(wgl, layout, childLayout => 
servesClustering(childLayout, wgl.partitionSpec))
+
+      case join: BroadcastHashJoinExec if 
join.condition.forall(_.deterministic) =>
+        retargetStreamed(join, join.buildSide, layout)
+      case join: BroadcastNestedLoopJoinExec if 
join.condition.forall(_.deterministic) =>
+        retargetStreamed(join, join.buildSide, layout)
+
+      case _ => None
+    }
+
+    retarget(keyedExchange.child, layout).filter { moved =>
+      PartitioningCollection.representativeOf(moved.outputPartitioning)

Review Comment:
   **[3] The final layout check reads only the first keyed member.**
   
   `representativeOf` returns the first keyed member of a 
`PartitioningCollection`, and `semanticEquals` also compares the expressions, 
so a subtree that reports the layout as a later member is refused. As far as I 
can trace, `AliasAwareOutputExpression` lists the aliases of a column before 
the column itself, so this happens when the operator also outputs an alias of 
the join key:
   
   ```sql
   SELECT i.id, p.k, p.total FROM testcat.ns.items i
   JOIN (
     SELECT item_id, item_id AS k, sum(price) AS total
     FROM testcat.ns.purchases GROUP BY item_id
   ) p ON i.id = p.item_id
   ```
   
   The layout is on `item_id`, and the rebuilt final aggregate reports 
`[keyed(k), keyed(item_id)]`, so both shuffles stay, although the join would 
pair with the second member. Checking every member, e.g. 
`PartitioningCollection.flatten(moved.outputPartitioning).exists(_.semanticEquals(layout))`,
 would admit it.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/PushDownKeyedShuffleExchange.scala:
##########
@@ -0,0 +1,210 @@
+/*
+ * 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 either shuffle. 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
+        // marks it `HASH_ROUTING`, and this shuffle routes undeclared rows by 
hash, as marked.
+        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. 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.
+        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 if 
window.expressions.forall(_.deterministic) =>
+        retargetChild(window, layout,
+          childLayout => servesClustering(childLayout, window.partitionSpec))
+      case wgl: WindowGroupLimitExec if wgl.mode == FinalWindowGroupLimit =>
+        retargetChild(wgl, layout, childLayout => 
servesClustering(childLayout, wgl.partitionSpec))
+
+      case join: BroadcastHashJoinExec if 
join.condition.forall(_.deterministic) =>
+        retargetStreamed(join, join.buildSide, layout)
+      case join: BroadcastNestedLoopJoinExec if 
join.condition.forall(_.deterministic) =>
+        retargetStreamed(join, join.buildSide, layout)
+
+      case _ => None
+    }
+
+    retarget(keyedExchange.child, layout).filter { moved =>
+      PartitioningCollection.representativeOf(moved.outputPartitioning)
+        .exists(_.semanticEquals(layout))
+    }
+  }
+
+  /**
+   * Whether `layout` can serve an operator clustered on `keys`. Empty keys 
ask for all tuples in
+   * one partition, which a keyed layout does not give.
+   */
+  private def servesClustering(layout: KeyedPartitioning, keys: 
Seq[Expression]): Boolean =
+    keys.nonEmpty && layout.satisfies(ClusteredDistribution(keys))

Review Comment:
   **[4] A layout on a subset of the operator's keys can skew the operator's 
input.**
   
   `servesClustering` admits a layout that covers only some of the operator's 
keys, as `a layout on a subset of the group keys is admitted` shows. So an 
aggregate on `(item_id, price)` joined on `item_id` now receives all partial 
rows of an `item_id` in one task. Before the rewrite, only the aggregated 
output was laid out that way, and the aggregate's own input was spread over 
`hash(item_id, price)`. With a hot `item_id`, the aggregate stage becomes a 
straggler, and AQE can neither coalesce nor split the keyed stage. On the join 
side, 
`spark.sql.sources.v2.bucketing.requireAllClusterKeysForCoPartition.enabled` 
(true by default) guards the same trade-off. Could the rule follow that config, 
or admit only a layout that covers every key of the operator?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/PushDownKeyedShuffleExchange.scala:
##########
@@ -0,0 +1,210 @@
+/*
+ * 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 either shuffle. 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
+        // marks it `HASH_ROUTING`, and this shuffle routes undeclared rows by 
hash, as marked.
+        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. 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.
+        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 if 
window.expressions.forall(_.deterministic) =>
+        retargetChild(window, layout,
+          childLayout => servesClustering(childLayout, window.partitionSpec))
+      case wgl: WindowGroupLimitExec if wgl.mode == FinalWindowGroupLimit =>
+        retargetChild(wgl, layout, childLayout => 
servesClustering(childLayout, wgl.partitionSpec))
+
+      case join: BroadcastHashJoinExec if 
join.condition.forall(_.deterministic) =>
+        retargetStreamed(join, join.buildSide, layout)
+      case join: BroadcastNestedLoopJoinExec if 
join.condition.forall(_.deterministic) =>
+        retargetStreamed(join, join.buildSide, layout)
+
+      case _ => None
+    }
+
+    retarget(keyedExchange.child, layout).filter { moved =>
+      PartitioningCollection.representativeOf(moved.outputPartitioning)
+        .exists(_.semanticEquals(layout))
+    }
+  }
+
+  /**
+   * Whether `layout` can serve an operator clustered on `keys`. Empty keys 
ask for all tuples in
+   * one partition, which a keyed layout does not give.
+   */
+  private def servesClustering(layout: KeyedPartitioning, keys: 
Seq[Expression]): Boolean =
+    keys.nonEmpty && layout.satisfies(ClusteredDistribution(keys))
+
+  /**
+   * `layout` rewritten from `operator`'s output attributes into its child's, 
or `None` when one of
+   * its expressions references an attribute the operator computes, which the 
child does not have.
+   * Only a plain rename is followed (`c1 AS x` becomes `c1`), as in 
`PushDownLocalSort`.
+   */
+  private def rebind(
+      layout: KeyedPartitioning,
+      operator: UnaryExecNode): Option[KeyedPartitioning] = {
+    val outputExprs: Seq[Expression] = operator match {
+      case project: ProjectExec => project.projectList
+      case aggregate: BaseAggregateExec => aggregate.resultExpressions
+      case _ => Nil
+    }
+    val aliases = AttributeMap(outputExprs.collect {

Review Comment:
   **[7] nit: `rebind` repeats the rename map of `PushDownLocalSort`.**
   
   This alias map is the one in `PushDownLocalSort.scala:112-117`, as the doc 
says. A small shared helper, or `AliasHelper.getAliasMap` with `replaceAlias` 
followed by the same `subsetOf` check, would keep the two rules from drifting 
apart, e.g. when one of them starts to follow an `Alias` of a `Cast`.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/PushDownKeyedShuffleExchange.scala:
##########
@@ -0,0 +1,210 @@
+/*
+ * 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 either shuffle. 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 &&

Review Comment:
   **[5] The PR description states the partition-count condition the other way 
round.**
   
   The admission list in the description says "the lower one is a hash shuffle 
with at least the keyed layout's partition count", but this guard requires the 
opposite: the keyed layout has at least the hash shuffle's partition count. The 
class doc, the commit message and `a layout that cannot serve as a shuffle 
template is not pushed down` say so too. Could you fix the description, so that 
it does not read as if the rewrite may cut the operator's parallelism?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/PushDownKeyedShuffleExchange.scala:
##########
@@ -0,0 +1,210 @@
+/*
+ * 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 either shuffle. 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
+        // marks it `HASH_ROUTING`, and this shuffle routes undeclared rows by 
hash, as marked.
+        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. 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.
+        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 =>

Review Comment:
   **[8] nit: the `layout` lambda parameter shadows two other `layout`s.**
   
   On this line `layout` is the rebound child layout, while `pushDown` has a 
`layout` of the keyed shuffle and `retarget` takes one too, as does 
`retargetStreamed`. The window arms below call it `childLayout`; the same name 
here would make clear which layout `servesClustering` checks. Also, `case _ => 
Nil` in `rebind` (L195) is unreachable, since `rebind` is only called with a 
`ProjectExec` or a `BaseAggregateExec`.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/PushDownKeyedShuffleExchange.scala:
##########
@@ -0,0 +1,210 @@
+/*
+ * 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(

Review Comment:
   **[6] Could this live in `EnsureRequirements` instead of an AQE-only rule?**
   
   `EnsureRequirements` already retargets a shuffle in place when the 
co-partitioned child is that shuffle (`s.copy(outputPartitioning = 
newPartitioning)` at `EnsureRequirements.scala:329`). This rule extends that 
case to a shuffle below clustered operators, but only in AQE preparation and 
only after both shuffles were planned, so it has to revalidate the whole plan. 
Non-AQE plans keep both shuffles, although they have no adaptive statistics to 
lose. Looking through the same operators from that case of `EnsureRequirements` 
would cover both paths. If the AQE-only placement is deliberate, a sentence on 
why in the class doc would help.



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