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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/PushDownShuffleExchangeThroughUnion.scala:
##########
@@ -131,6 +154,10 @@ case class PushDownShuffleExchangeThroughUnion(
         
SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_MAX_TARGET_PARTITION_NUM_FACTOR),
       keepJoinBranches =
         
conf.getConf(SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_KEEP_JOIN_BRANCHES_ENABLED),
+      allowV2Bucketing = conf.getConf(

Review Comment:
   **Blocking (P1):** `allowV2Bucketing` is fixed for both rewrite passes, and 
when the first pass fails `accepted()`, the only fallback is the existing 
retry, which restricts every site in the plan to its removed exchange's layout. 
So a keyed target that passes its own site's checks but breaks an ancestor also 
costs other union sites their hash push-downs.
   
   By my reading of the code: with the rule and V2 bucketing shuffles on, 
partition coalescing off, the subset permission on, 
`spark.sql.requireAllClusterKeysForCoPartition` off and 8 shuffle partitions, 
take a plan with two unions. The first is a V2 table partitioned by 
`identity(id)` with ids 1 to 8 plus a `VALUES` leg, under a window that is 
joined with a hash-shuffled table. The second is a V1 table bucketed by `id` 
into 8 buckets plus an unbucketed table, under a window clustered on `(id, 
data)`. On the base branch the first union has no hash candidate and keeps its 
exchange, while the second keeps the bucketed leg's `hashpartitioning(id, 8)` 
and shuffles only the other leg. On this branch the first union adopts the 
keyed target, the join can no longer pair it with the hash side, and the 
whole-plan check fails. The retry then keeps only `hashpartitioning(id, 8)` at 
the first site and `hashpartitioning((id, data), 8)` at the second, neither 
union offers its removed layout, and `a
 pply` returns the input plan. AQE stages both union exchanges in its first 
round, since they read scans directly, so no re-plan recovers the second 
push-down and that union shuffles every row of both legs.
   
   A target larger than the removed exchange under 
`maxTargetPartitionNumFactor` above 1 is lost the same way, and so is the 
shared hash target of a join with two union inputs, through the non-joint 
fallback. Results stay correct, but the extra shuffle grows with the second 
union's rows, and no test covers a second site or join input with such a target.
   
   **Recommended change:** When keyed targets are on and a rewrite fails, fall 
back to the base branch's hash-only attempt at the level that failed before 
using the existing fallbacks. If the whole-plan check rejects a pass in which a 
site adopted a keyed target, rerun the pass with keyed targets off and keep its 
result when it changes the plan and the check accepts it; otherwise run the 
retry on each site's removed layout as today. If an operator's joint attempt 
fails after one of its inputs adopted a keyed target, run the hash-only joint 
attempt before the non-joint fallback. Update the class doc's sentence on the 
retry to describe this order. Add union push-down tests, at plan level and end 
to end, for a union with no keyed child beside a keyed site that breaks an 
ancestor, and for a join with two union inputs that share a hash target other 
than their removed layout.
   
   **Why this works:** The hash-only attempt runs with the policy the base 
branch uses, allowV2Bucketing off and every other setting unchanged, so its 
result is the base branch's result. Trying it right after a keyed failure means 
no site or join input ends with less than the base branch gives it whenever 
that result changes the plan and passes the whole-plan check. When it changes 
nothing, the base branch pushes nothing either, so the existing removed-layout 
retry runs as it does today and can still keep a keyed removed layout; that 
retry also still handles a hash-only result that fails the check. The joint 
fallback does the same per operator, where the base branch's joint attempt can 
adopt a shared hash target that the non-joint attempt cannot. Plans whose keyed 
attempts succeed never reach either fallback.
   
   **Scope:** Rework the rule's failure fallbacks so a failed keyed attempt 
falls back to the base branch's hash-only attempt, and add tests for the two 
shapes that lose push-downs today.
   
   **Compatibility:** Keyed targets that pass the whole-plan check are still 
adopted, and with allowV2Bucketing off the rule behaves exactly as on the base 
branch.
   
   **Risks:** A failed keyed attempt now costs one more rewrite pass and 
whole-plan check in each AQE planning round, on top of the existing retry. A 
keyed requirement exchange that only the removed-layout retry would push keeps 
its exchange when the hash-only pass changes the plan and passes the check; 
such sites are new in this PR, so the plan is no worse than on the base branch, 
and setting allowV2Bucketing to false still removes all keyed behavior.
   
   **Constraints:** The hash-only attempt must run with exactly the base 
branch's policy, so per-pass state, such as whether an earlier site pushed and 
whether every site used its removed layout, has to be reset for it. Plans whose 
keyed attempts pass the whole-plan check, and every plan with allowV2Bucketing 
off, must keep their current plans.
   
   **Exclusions:**
   - Attributing a whole-plan failure to the site that caused it, so that other 
sites keep their keyed targets, is left out, because the whole-plan check does 
not report which site failed.
   
   **Success:** When the whole-plan check rejects a pass in which a site 
adopted a keyed target, the rule returns the base branch's hash-only result 
whenever that result changes the plan and passes the check, so a union with no 
keyed child keeps the push-down the base branch gives it. When an operator's 
joint attempt fails after one of its inputs adopted a keyed target, the base 
branch's hash-only joint attempt is tried before the non-joint fallback, so two 
union inputs that share a hash target other than their removed layout both keep 
it. Plans in which every keyed attempt passes, and all plans with 
allowV2Bucketing off, are unchanged.
   
   **Verification:**
   - **Regression:** A plan with a keyed union site whose target breaks an 
ancestor, such as a window joined with a hash-partitioned side, and a second 
union with no keyed child whose accepted target is not its removed layout, such 
as a subset-key target with the subset permission on and 
spark.sql.requireAllClusterKeysForCoPartition off, pushes the second union down 
as the base branch does, while the keyed site keeps its exchange or takes its 
removed layout and the query results are unchanged.
   - **Regression:** A shuffled join with two union inputs under 
allowJoinInputs, one of them with a keyed leg ranked first, whose base-branch 
joint attempt adopts a shared hash target other than the removed layout, gives 
both inputs that shared target, with unchanged results.
   - **Compatibility:** Plans whose keyed attempts pass the whole-plan check, 
including the PR's end-to-end keyed shapes, and plans with allowV2Bucketing off 
keep their current plans and shuffle counts.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/PushDownShuffleExchangeThroughUnion.scala:
##########
@@ -240,56 +267,76 @@ case class PushDownShuffleExchangeThroughUnion(
       maxUnionChildren: Int,
       maxTargetPartitionNumFactor: Double,
       keepJoinBranches: Boolean,
+      allowV2Bucketing: Boolean,
       allowSubsetTargets: Boolean,
       preferRemovedLayout: Boolean = false)
 
-  /** Lazily discover and rank layouts once per site for both joint and 
fallback attempts. */
-  private class PreparedChild(val pushable: PushableChild, policy: 
LayoutPolicy) {
+  /** Lazily discover the reported layouts and rank the targets once per site 
for both attempts. */
+  private class PreparedChild(
+      val pushable: PushableChild,
+      required: ClusteredDistribution,
+      policy: LayoutPolicy) {
     /**
-     * Eligible child layouts in child order, expressed in the union's output 
attributes.
-     * Collections offer their hash members; a child offering nothing takes a 
shuffle.
-     * Equality follows UnionExec's comparison after prepareOutputPartitioning 
rebinding.
+     * The hash or keyed layouts each child reports, in child order, expressed 
in the union's output
+     * attributes. A collection offers its hash members; a keyed layout offers 
itself when it is
+     * grouped and its grouped form when it is not, the form 
`EnsureRequirements` plans. A child
+     * offering nothing takes a shuffle.
+     *
+     * A kept marked leg is still subject to the union's concatenation: beside 
another marked leg,
+     * it has to declare the same key list in the same order and still route 
by hash. One that
+     * fails those makes the candidate fail its final check, and the plan is 
left as it was.

Review Comment:
   **Nit (P3):** This contradicts `reportsDomain`. With `kept = true` a marked 
leg is kept only when it still routes by hash and declares the target's key 
list in the same order, so a leg that fails either is not in `offeredBy`, 
`rebuildUnion` lays it out on the target, and the site is rewritten rather than 
left as it was. `reportsDomain`'s own doc says so, and 'a marked child whose 
key order differs is laid out' and 'a marked leg that lost its routing is laid 
out beside a marked target' assert it. The kept-leg summaries in the 
`rebuildUnion` doc ('keeps the children whose layouts lie on the domain or on 
part of it') and the `candidateTargets` doc also leave out the marked-leg 
exception. Please replace this sentence with what `reportsDomain` does, and add 
the exception to those two summaries or point them at `reportsDomain`.
   
   **Verification:**
   - **Inspection:** The layouts, rebuildUnion and candidateTargets docs 
describe a non-conforming marked leg as laid out on the target, as 
reportsDomain's doc says and as the plan-level tests for a reordered marked leg 
and a lost-routing leg assert.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/physical/partitioning.scala:
##########
@@ -579,6 +579,41 @@ case class KeyLayout(
    */
   def describesSameKeys(other: KeyLayout): Boolean =
     dataTypes == other.dataTypes && partitionKeys == other.partitionKeys
+
+  /**
+   * Whether every key of this layout is one of `other`'s. The types are 
asked; the order and how
+   * often a key repeats are not. Callers ask this beside 
`describesSameLayoutState`, and only
+   * where a later node merges the key lists: the rows are already in the 
partitions `other` names
+   * for their keys, and the layouts declaring the remaining keys supply the 
rest.
+   */
+  def describesSubsetOfKeys(other: KeyLayout): Boolean =
+    dataTypes == other.dataTypes && {
+      val declared = other.partitionKeys.toSet
+      partitionKeys.forall(declared.contains)
+    }
+
+  /**
+   * Whether `other` describes the same keys as this layout as a set: the same 
key values at the
+   * same types, whatever their order and how often each repeats. The types 
are asked for the reason
+   * given on `describesSameKeys`.
+   *
+   * A call site may read a domain this way only when a merge and a sort have 
already settled the
+   * key order: the caller compares such a result against the layout it was 
built for. A pairing
+   * and a concatenation keep the order they are given, so they ask 
`describesSameKeys`. Callers ask
+   * this beside `describesSameLayoutState`, which makes the repeats harmless: 
equal grouping state
+   * means both lists hold unique keys, so the set says the same as the 
multiset.

Review Comment:
   **Nit (P3):** 'Equal grouping state means both lists hold unique keys' holds 
only when the layouts are grouped. `describesSameLayoutState` compares 
`isGrouped` for equality, so two ungrouped layouts such as `[1, 1, 2]` and `[1, 
2, 2]`, with the same collapse and ungrouping state, pass both it and 
`describesSameKeySet` while their key multisets differ. The only caller, 
`reportsDomain`, compares against a target that `PreparedChild.layouts` always 
offers grouped, so nothing goes wrong today, but a later caller relying on this 
sentence would treat two different ungrouped layouts as one domain. Please 
narrow the doc to a comparison against a grouped layout, and say that two 
ungrouped layouts can share a key set and a layout state while their keys 
repeat differently.
   
   **Verification:**
   - **Inspection:** The doc's guarantee holds for every pair it covers: it 
requires a grouped side and does not cover two ungrouped layouts such as [1, 1, 
2] and [1, 2, 2].



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/ShuffleSpecSuite.scala:
##########
@@ -1206,6 +1206,40 @@ class ShuffleSpecSuite extends SparkFunSuite with 
SQLHelper {
     }
   }
 
+  test("KeyLayout: the key set ignores order and the layout state does not") {

Review Comment:
   **Nit (P3):** The name says the layout state does not ignore order, but the 
third assertion requires `ascending.describesSameLayoutState(descending)`: 
`describesSameLayoutState` compares only `isGrouped`, `isCollapsed` and 
`ungroupingOrigin`, and what this test shows it refuses is a repeated key and a 
collapse. Something like:
   
   ```suggestion
     test("KeyLayout: key set and layout state ignore order; only the state 
refuses repeats") {
   ```
   
   **Verification:**
   - **Inspection:** The test name agrees with its assertions, including that 
two key lists in different orders share a layout state.



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/KeyGroupedPartitioningSuite.scala:
##########
@@ -721,6 +746,670 @@ class KeyGroupedPartitioningSuite
     }
   }
 
+  test("SPARK-61785: regroup V2 union domains instead of shuffling all rows") {
+    withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
+        SQLConf.UNION_OUTPUT_PARTITIONING.key -> "true",
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_PARTIALLY_CLUSTERED_DISTRIBUTION_ENABLED.key -> 
"false",
+        SQLConf.SHUFFLE_PARTITIONS.key -> "2",
+        SQLConf.COALESCE_PARTITIONS_ENABLED.key -> "false",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ENABLED.key -> "true") {
+      createTable("keyed_left", columns, Array(Expressions.identity("id")))
+      createTable("keyed_right", columns, Array(Expressions.identity("id")))
+      sql("INSERT INTO testcat.ns.keyed_left VALUES " +
+        "(1, 'a', timestamp'2022-01-01'), (1, 'b', timestamp'2022-01-02'), " +
+        "(2, 'c', timestamp'2022-01-03')")
+      sql("INSERT INTO testcat.ns.keyed_right VALUES " +
+        "(1, 'd', timestamp'2022-01-04'), (2, 'e', timestamp'2022-01-05')")
+      val previous = spark.experimental.extraStrategies
+      // Reach the rule with the exchange in place. The stock planner groups 
this all-keyed union
+      // before the rule sees it, and with `unionOutputPartitioning` off the 
rebuilt union reports
+      // the default partitioning, which no keyed target answers. An extension 
can introduce such
+      // an exchange as well, which this strategy stands in for.
+      spark.experimental.extraStrategies = Seq(new SparkStrategy {
+        override def apply(plan: LogicalPlan): Seq[SparkPlan] = plan match {
+          case union: org.apache.spark.sql.catalyst.plans.logical.Union =>
+            val child = UnionExec(union.children.map(planLater))
+            
Seq(ShuffleExchangeExec(physical.HashPartitioning(Seq(union.output.head), 2),
+              child, 
org.apache.spark.sql.execution.exchange.ENSURE_REQUIREMENTS))
+          case _ => Nil
+        }
+      }) ++ previous
+      try {
+        Seq(false, true).foreach { enabled =>
+          
withSQLConf(SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ALLOW_V2_BUCKETING_ENABLED.key
 ->
+              enabled.toString) {
+            val df = sql("SELECT id, data, row_number() OVER (PARTITION BY id 
ORDER BY data) rn " +
+              "FROM (SELECT id, data FROM testcat.ns.keyed_left UNION ALL " +
+              "SELECT id, data FROM testcat.ns.keyed_right)")
+            checkAnswer(df, Seq(Row(1, "a", 1), Row(1, "b", 2), Row(1, "d", 3),
+              Row(2, "c", 1), Row(2, "e", 2)))
+            val plan = df.queryExecution.executedPlan
+            assert(satisfiesRequirements(plan))
+            // The exchange only survives while the keyed permission is off.
+            assert(allExchanges(plan).size === (if (enabled) { 0 } else { 1 }),
+              s"unexpected shuffles:\n$plan")
+            if (enabled) {
+              assert(hasGroupedUnion(plan), s"expected a grouped 
union:\n$plan")
+              assert(exchangesOverUnion(plan).isEmpty,
+                s"the union's scans keep their layouts:\n$plan")
+              val union = collect(plan) { case u: UnionExec => u }.head
+              
assert(union.children.forall(!_.exists(_.isInstanceOf[ShuffleExchangeExec])),
+                s"the union's scans keep their layouts:\n$plan")
+              
assert(union.outputPartitioning.isInstanceOf[physical.KeyedPartitioning],
+                s"expected a keyed layout:\n$plan")
+            } else {
+              assert(exchangesOverUnion(plan).size === 1,
+                s"expected the union to be shuffled:\n$plan")
+            }
+          }
+        }
+      } finally {
+        spark.experimental.extraStrategies = previous
+      }
+    }
+  }
+
+  test("SPARK-61785: lay a union's other children out on a V2 keyed domain") {
+    withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_PARTIALLY_CLUSTERED_DISTRIBUTION_ENABLED.key -> 
"false",
+        SQLConf.SHUFFLE_PARTITIONS.key -> "2",
+        SQLConf.COALESCE_PARTITIONS_ENABLED.key -> "false",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ENABLED.key -> "true") {
+      createTable("keyed_domain", columns, Array(Expressions.identity("id")))
+      sql("INSERT INTO testcat.ns.keyed_domain VALUES " +
+        "(1, 'a', timestamp'2022-01-01'), (2, 'c', timestamp'2022-01-03')")
+      Seq(false, true).foreach { enabled =>
+        
withSQLConf(SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ALLOW_V2_BUCKETING_ENABLED.key
 ->
+            enabled.toString) {
+          // A union over a keyed table and a scan with no layout of its own: 
the planner puts the
+          // requirement exchange above the union, and the rule keeps the 
keyed leg and lays the
+          // other one out on its domain. The value side has a key (3) the 
domain does not
+          // declare, which the grouped union routes by hash and keeps whole.
+          val df = sql("SELECT id, data, row_number() OVER (PARTITION BY id 
ORDER BY data) rn " +
+            "FROM (SELECT id, data FROM testcat.ns.keyed_domain UNION ALL " +
+            "SELECT * FROM VALUES (1, 'b'), (3, 'f'), (3, 'g') AS v(id, 
data))")
+          checkAnswer(df, Seq(Row(1, "a", 1), Row(1, "b", 2), Row(2, "c", 1), 
Row(3, "f", 1),
+            Row(3, "g", 2)))
+          val plan = df.queryExecution.executedPlan
+          assert(satisfiesRequirements(plan))
+          // The keyed scan keeps its partitions and the leg without a layout 
is laid out on its
+          // domain, so the only shuffle is that leg's.
+          assert(allExchanges(plan).size === 1, s"expected one 
shuffle:\n$plan")
+          if (enabled) {
+            assert(hasGroupedUnion(plan), s"expected a grouped union:\n$plan")
+            val union = collect(plan) { case u: UnionExec => u }.head
+            assert(union.children.head.exists(_.isInstanceOf[BatchScanExec]),
+              s"expected the keyed scan to keep its layout:\n$plan")
+            assert(collect(union.children(1)) {
+              case shuffle: ShuffleExchangeExec => shuffle
+            }.nonEmpty, s"expected the other leg to be laid out:\n$plan")
+            
assert(union.outputPartitioning.isInstanceOf[physical.KeyedPartitioning],
+              s"expected a keyed layout:\n$plan")
+          } else {
+            assert(exchangesOverUnion(plan).size === 1,
+              s"expected the union to be shuffled:\n$plan")
+          }
+        }
+      }
+    }
+  }
+
+  test("SPARK-61785: keep a leg whose layout the planner marked as 
hash-routed") {
+    withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
+        SQLConf.UNION_OUTPUT_PARTITIONING.key -> "true",
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_PARTIALLY_CLUSTERED_DISTRIBUTION_ENABLED.key -> 
"false",
+        SQLConf.SHUFFLE_PARTITIONS.key -> "2",
+        SQLConf.COALESCE_PARTITIONS_ENABLED.key -> "false",
+        SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ENABLED.key -> "true",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_KEEP_JOIN_BRANCHES_ENABLED.key 
-> "true",
+        
SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_KEEP_NON_COALESCIBLE_BRANCHES_ENABLED.key
 ->
+          "true") {
+      createTable("marked_left", columns, Array(Expressions.identity("id")))
+      createTable("marked_right", columns, Array(Expressions.bucket(2, "id")))
+      sql("INSERT INTO testcat.ns.marked_left VALUES " +
+        "(1, 'a', timestamp'2022-01-01'), (2, 'c', timestamp'2022-01-02')")
+      sql("INSERT INTO testcat.ns.marked_right VALUES " +
+        "(1, 'b', timestamp'2022-01-03'), (2, 'd', timestamp'2022-01-04'), " +
+        "(3, 'e', timestamp'2022-01-05')")
+      // The join lays its left side out on the right's keyed domain, which 
marks the layout: rows
+      // of a key the domain does not declare were routed by hash. A right 
outer join reports the
+      // right side's layout, so the union's join leg carries the marker, and 
the rule keeps it
+      // beside an unmarked scan on the same domain.
+      val df = sql("SELECT id, data, row_number() OVER (PARTITION BY id ORDER 
BY data) rn " +
+        "FROM (SELECT id, data FROM testcat.ns.marked_left UNION ALL " +
+        "SELECT b.id, b.data FROM testcat.ns.marked_left a " +
+        "RIGHT OUTER JOIN testcat.ns.marked_right b ON a.id = b.id UNION ALL " 
+
+        "SELECT * FROM VALUES (1, 'z') AS v(id, data))")
+      checkAnswer(df, Seq(Row(1, "a", 1), Row(1, "b", 2), Row(1, "z", 3), 
Row(2, "c", 1),
+        Row(2, "d", 2), Row(3, "e", 1)))
+      val plan = df.queryExecution.executedPlan
+      assert(satisfiesRequirements(plan))
+      val union = collect(plan) { case u: UnionExec => u }.head
+      assert(union.children.head.exists(_.isInstanceOf[BatchScanExec]),
+        s"the scan keeps its layout:\n$plan")
+      union.children(1).outputPartitioning match {
+        case keyed: physical.KeyedPartitioning =>
+          assert(keyed.mayContainUnknownPartitionKeys && 
keyed.unknownKeysRouted,
+            s"expected a hash-routed marked leg:\n$plan")
+        case other => fail(s"expected a keyed join leg, got $other:\n$plan")
+      }
+      assert(collect(union.children(1)) { case s: ShuffleExchangeExec => s 
}.size === 1,
+        s"the leg keeps its layout, so only the join's own side 
shuffles:\n$plan")
+      // The join's own alignment and the values leg take one shuffle each; 
the exchange the
+      // planner put above the union is gone.
+      assert(allExchanges(plan).size === 2, s"expected two shuffles:\n$plan")
+      assert(exchangesOverUnion(plan).isEmpty, s"the target is pushed 
down:\n$plan")
+      assert(hasGroupedUnion(plan), s"expected a grouped union:\n$plan")
+    }
+  }
+
+  test("SPARK-61785: a child whose keys are a subset of the domain keeps its 
layout") {
+    withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
+        SQLConf.UNION_OUTPUT_PARTITIONING.key -> "true",
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_PARTIALLY_CLUSTERED_DISTRIBUTION_ENABLED.key -> 
"false",
+        SQLConf.SHUFFLE_PARTITIONS.key -> "3",
+        SQLConf.COALESCE_PARTITIONS_ENABLED.key -> "false",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ENABLED.key -> "true",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ALLOW_V2_BUCKETING_ENABLED.key 
-> "true") {
+      createTable("keyed_small", columns, Array(Expressions.identity("id")))
+      createTable("keyed_big", columns, Array(Expressions.identity("id")))
+      sql("INSERT INTO testcat.ns.keyed_small VALUES " +
+        "(1, 'a', timestamp'2022-01-01'), (2, 'c', timestamp'2022-01-02')")
+      sql("INSERT INTO testcat.ns.keyed_big VALUES " +
+        "(1, 'b', timestamp'2022-01-03'), (2, 'd', timestamp'2022-01-04'), " +
+        "(3, 'e', timestamp'2022-01-05')")
+      // The domain is {1, 2, 3}, declared by keyed_big; keyed_small holds 
keys {1, 2}, a subset of
+      // it, so that leg keeps its layout and only the leg without one is laid 
out.
+      val df = sql("SELECT id, data, row_number() OVER (PARTITION BY id ORDER 
BY data) rn FROM (" +
+        "SELECT id, data FROM testcat.ns.keyed_small UNION ALL " +
+        "SELECT id, data FROM testcat.ns.keyed_big UNION ALL " +
+        "SELECT * FROM VALUES (1, 'v') AS v(id, data))")
+      checkAnswer(df, Seq(Row(1, "a", 1), Row(1, "b", 2), Row(1, "v", 3), 
Row(2, "c", 1),
+        Row(2, "d", 2), Row(3, "e", 1)))
+      val plan = df.queryExecution.executedPlan
+      assert(satisfiesRequirements(plan))
+      assert(allExchanges(plan).size === 1, s"expected one shuffle:\n$plan")
+      assert(hasGroupedUnion(plan), s"expected a grouped union:\n$plan")
+      val union = collect(plan) { case union: UnionExec => union }.head
+      
assert(union.children.take(2).forall(_.exists(_.isInstanceOf[BatchScanExec])),
+        s"both keyed legs keep their layouts:\n$plan")
+      assert(collect(union.children(2)) {
+        case shuffle: ShuffleExchangeExec => shuffle
+      }.nonEmpty, s"the leg without a layout is laid out:\n$plan")
+    }
+  }
+
+  test("SPARK-61785: regroup an out-of-order subset leg beside a bigger keyed 
domain") {
+    withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
+        SQLConf.UNION_OUTPUT_PARTITIONING.key -> "true",
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_PARTIALLY_CLUSTERED_DISTRIBUTION_ENABLED.key -> 
"false",
+        SQLConf.SHUFFLE_PARTITIONS.key -> "3",
+        SQLConf.COALESCE_PARTITIONS_ENABLED.key -> "false",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ENABLED.key -> "true") {
+      Seq(1, 2, 3).foreach { id =>
+        createTable(s"ordered_$id", columns, Array(Expressions.identity("id")))
+        sql(s"INSERT INTO testcat.ns.ordered_$id VALUES " +
+          s"($id, 'v$id', timestamp'2022-01-0$id')")
+      }
+      // Each leg is an aggregate over an inner union, so `CombineUnions` 
cannot flatten it and
+      // each leg reports its children's order: [1, 2, 3] for the first, the 
only domain whose
+      // partition count fits the bounds, and [2, 1] for the second, a subset 
in another order.
+      val df = sql(
+        """SELECT id, data, row_number() OVER (PARTITION BY id ORDER BY data) 
rn FROM (
+          |  SELECT id, max(data) AS data FROM (
+          |    SELECT id, data FROM testcat.ns.ordered_1
+          |    UNION ALL SELECT id, data FROM testcat.ns.ordered_2
+          |    UNION ALL SELECT id, data FROM testcat.ns.ordered_3) GROUP BY id
+          |  UNION ALL
+          |  SELECT id, max(data) AS data FROM (
+          |    SELECT id, data FROM testcat.ns.ordered_2
+          |    UNION ALL SELECT id, data FROM testcat.ns.ordered_1) GROUP BY id
+          |  UNION ALL SELECT * FROM VALUES (1, 'v0') AS v(id, 
data))""".stripMargin)
+      checkAnswer(df, Seq(Row(1, "v0", 1), Row(1, "v1", 2), Row(1, "v1", 3), 
Row(2, "v2", 1),
+        Row(2, "v2", 2), Row(3, "v3", 1)))
+      val plan = df.queryExecution.executedPlan
+      assert(satisfiesRequirements(plan))
+      assert(allExchanges(plan).size === 1, s"only the leg without a layout 
shuffles:\n$plan")
+      assert(hasGroupedUnion(plan), s"expected a grouped union:\n$plan")
+      // The first leg's inner union has three children too, so the outer 
union is the one the
+      // grouping above the site reads.
+      val union = collect(plan) { case group: GroupPartitionsExec => group }
+        .flatMap { group =>
+          unwrap(group.child) match {
+            case u: UnionExec => Some(u)
+            case _ => None
+          }
+        }.head
+      assert(collect(union.children(1)) { case s: ShuffleExchangeExec => s 
}.isEmpty,
+        s"the out-of-order subset leg keeps its layout:\n$plan")
+      union.children(1).outputPartitioning match {
+        case keyed: physical.KeyedPartitioning =>
+          assert(keyed.partitionKeys.map(_.row.getInt(0)) === Seq(2, 1),
+            s"expected the leg's own order [2, 1]:\n$plan")
+        case other => fail(s"expected a kept keyed leg, got $other:\n$plan")
+      }
+    }
+  }
+
+  test("SPARK-61785: a keyed union side pairs with a keyed table") {
+    withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_PARTIALLY_CLUSTERED_DISTRIBUTION_ENABLED.key -> 
"false",
+        SQLConf.SHUFFLE_PARTITIONS.key -> "2",
+        SQLConf.COALESCE_PARTITIONS_ENABLED.key -> "false",
+        SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ENABLED.key -> "true",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ALLOW_JOIN_INPUTS_ENABLED.key 
-> "true") {
+      createTable("keyed_union", columns, Array(Expressions.identity("id")))
+      createTable("keyed_probe", columns, Array(Expressions.identity("id")))
+      sql("INSERT INTO testcat.ns.keyed_union VALUES " +
+        "(1, 'a', timestamp'2022-01-01'), (2, 'c', timestamp'2022-01-03')")
+      sql("INSERT INTO testcat.ns.keyed_probe VALUES " +
+        "(1, 'x', timestamp'2022-01-06'), (2, 'y', timestamp'2022-01-07')")
+      Seq(false, true).foreach { enabled =>
+        
withSQLConf(SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ALLOW_V2_BUCKETING_ENABLED.key
 ->
+            enabled.toString) {
+          // The planner lines the union up on the probe's keyed domain by 
shuffling the union,
+          // and the rule keeps the union's keyed leg instead, laying only the 
leg without a
+          // layout. The pair then holds with the probe as it stands.
+          val df = sql(
+            """SELECT /*+ MERGE(u, p) */ u.id, u.data, p.data
+              |FROM (SELECT id, data FROM testcat.ns.keyed_union UNION ALL
+              |      SELECT * FROM VALUES (1, 'b'), (3, 'f') AS v(id, data)) u
+              |JOIN testcat.ns.keyed_probe p ON u.id = p.id""".stripMargin)
+          checkAnswer(df, Seq(Row(1, "a", "x"), Row(1, "b", "x"), Row(2, "c", 
"y")))
+          val plan = df.queryExecution.executedPlan
+          assert(satisfiesRequirements(plan))
+          assert(allExchanges(plan).size === 1, s"expected one 
shuffle:\n$plan")
+          if (enabled) {
+            assert(hasGroupedUnion(plan), s"expected a grouped union:\n$plan")
+            val union = collect(plan) { case u: UnionExec => u }.head
+            assert(union.children.head.exists(_.isInstanceOf[BatchScanExec]),
+              s"expected the keyed leg to keep its layout:\n$plan")
+            assert(collect(union.children(1)) {
+              case shuffle: ShuffleExchangeExec => shuffle
+            }.nonEmpty, s"expected the leg without a layout to be 
shuffled:\n$plan")
+          } else {
+            assert(exchangesOverUnion(plan).size === 1,
+              s"expected the union to be shuffled:\n$plan")
+          }
+        }
+      }
+    }
+  }
+
+  test("SPARK-61785: an unsorted keyed side is not paired with") {
+    withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
+        SQLConf.UNION_OUTPUT_PARTITIONING.key -> "true",
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_PARTIALLY_CLUSTERED_DISTRIBUTION_ENABLED.key -> 
"false",
+        SQLConf.SHUFFLE_PARTITIONS.key -> "2",
+        SQLConf.COALESCE_PARTITIONS_ENABLED.key -> "false",
+        SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ENABLED.key -> "true",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ALLOW_V2_BUCKETING_ENABLED.key 
-> "true",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ALLOW_JOIN_INPUTS_ENABLED.key 
-> "true") {
+      createTable("keyed_union", columns, Array(Expressions.identity("id")))
+      createTable("keyed_two", columns, Array(Expressions.identity("id")))
+      createTable("keyed_one", columns, Array(Expressions.identity("id")))
+      sql("INSERT INTO testcat.ns.keyed_union VALUES " +
+        "(1, 'a', timestamp'2022-01-01'), (2, 'c', timestamp'2022-01-03')")
+      sql("INSERT INTO testcat.ns.keyed_two VALUES (2, 'y', 
timestamp'2022-01-07')")
+      sql("INSERT INTO testcat.ns.keyed_one VALUES (1, 'x', 
timestamp'2022-01-06')")
+      // The inner union reports its grouped domain in child order, [2, 1], 
and the planner
+      // shuffles the outer union onto it. Keeping the outer union's keyed leg 
would group it on
+      // the sorted [1, 2], which cannot pair with [2, 1], so the rewrite 
declines and the union
+      // keeps the exchange it was given.
+      val df = sql(
+        """SELECT /*+ MERGE(u, p) */ u.id, u.data, p.data
+          |FROM (SELECT id, data FROM testcat.ns.keyed_union UNION ALL
+          |      SELECT * FROM VALUES (1, 'b') AS v(id, data)) u
+          |JOIN (SELECT id, data FROM testcat.ns.keyed_two UNION ALL
+          |      SELECT id, data FROM testcat.ns.keyed_one) p ON u.id = 
p.id""".stripMargin)
+      checkAnswer(df, Seq(Row(1, "a", "x"), Row(1, "b", "x"), Row(2, "c", 
"y")))
+      val plan = df.queryExecution.executedPlan
+      assert(satisfiesRequirements(plan))
+      assert(allExchanges(plan).size === 1, s"expected one shuffle:\n$plan")
+      assert(!hasGroupedUnion(plan), s"the keyed target must not pair:\n$plan")
+      assert(exchangesOverUnion(plan).size === 1,
+        s"expected one exchange over a union:\n$plan")
+      exchangesOverUnion(plan).head.outputPartitioning match {
+        case keyed: physical.KeyedPartitioning =>
+          assert(keyed.partitionKeys.map(_.row.getInt(0)) === Seq(2, 1),
+            s"expected the sibling's unsorted order:\n$plan")
+        case other =>
+          fail(s"expected a keyed exchange over the union, got $other:\n$plan")
+      }
+    }
+  }
+
+  test("SPARK-61785: a keyed target that breaks an upper join is retried on 
the removed layout") {
+    withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
+        SQLConf.UNION_OUTPUT_PARTITIONING.key -> "true",
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_PARTIALLY_CLUSTERED_DISTRIBUTION_ENABLED.key -> 
"false",
+        SQLConf.SHUFFLE_PARTITIONS.key -> "2",
+        SQLConf.COALESCE_PARTITIONS_ENABLED.key -> "false",
+        SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ENABLED.key -> "true",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ALLOW_V2_BUCKETING_ENABLED.key 
-> "true") {
+      createTable("keyed_union", columns, Array(Expressions.identity("id")))
+      createTable("plain_hash", columns, Array.empty[Transform])
+      createTable("plain_probe", columns, Array.empty[Transform])
+      sql("INSERT INTO testcat.ns.keyed_union VALUES " +
+        "(1, 'a', timestamp'2022-01-01'), (1, 'b', timestamp'2022-01-02'), " +
+        "(2, 'c', timestamp'2022-01-03'), (2, 'd', timestamp'2022-01-04')")
+      sql("INSERT INTO testcat.ns.plain_hash VALUES (3, 'x', 
timestamp'2022-01-05')")
+      sql("INSERT INTO testcat.ns.plain_probe VALUES " +
+        "(1, 'p', timestamp'2022-01-06'), (2, 'q', timestamp'2022-01-07')")
+      // The keyed leg is the first child and the biggest, so the first 
attempt takes its domain.
+      // The REPARTITION leg offers the hash layout of the exchange above the 
union, which is what
+      // the retry falls back to.
+      val core =
+        """SELECT id, data, row_number() OVER (PARTITION BY id ORDER BY data) 
rn FROM (
+          |  SELECT id, data FROM testcat.ns.keyed_union
+          |  UNION ALL SELECT 3 AS id, 'y' AS data
+          |  UNION ALL SELECT /*+ REPARTITION(2, id) */ id, data
+          |    FROM testcat.ns.plain_hash)""".stripMargin
+      // Without the join the keyed target is taken, which is what makes the 
join the deciding
+      // factor below.
+      val keyed = sql(core)
+      checkAnswer(keyed, Seq(Row(1, "a", 1), Row(1, "b", 2), Row(2, "c", 1), 
Row(2, "d", 2),
+        Row(3, "x", 1), Row(3, "y", 2)))
+      val keyedPlan = keyed.queryExecution.executedPlan
+      assert(satisfiesRequirements(keyedPlan))
+      // The values leg is laid out, and the user repartition legs keeps its 
exchange and takes
+      // the keyed one on top.
+      assert(allExchanges(keyedPlan).size === 3, s"expected three 
shuffles:\n$keyedPlan")
+      assert(hasGroupedUnion(keyedPlan), s"expected the keyed 
target:\n$keyedPlan")
+      assert(exchangesOverUnion(keyedPlan).isEmpty,
+        s"the keyed target keeps the union's exchange down:\n$keyedPlan")
+      // With the join, the keyed layout cannot pair with the other side's 
hash layout; the retry
+      // pushes the removed hash layout down instead.
+      val joined = sql(s"SELECT w.id, w.rn, p.data FROM ($core) w " +
+        "JOIN testcat.ns.plain_probe p ON w.id = p.id")
+      checkAnswer(joined, Seq(Row(1, 1, "p"), Row(1, 2, "p"), Row(2, 1, "q"), 
Row(2, 2, "q")))
+      // AQE re-plans around the stages it creates, so the retried layout has 
to hold there.
+      val plan = joined.queryExecution.executedPlan
+      assert(satisfiesRequirements(plan))
+      assert(!hasGroupedUnion(plan),
+        s"the keyed target must not survive the join's pairing:\n$plan")
+      assert(collect(plan) { case u: UnionExec => u }.head.outputPartitioning
+        .isInstanceOf[physical.HashPartitioning],
+        s"the retry should rebuild the union on the removed layout:\n$plan")
+      assert(exchangesOverUnion(plan).isEmpty,
+        s"the retry should push the removed layout down:\n$plan")
+      // The two legs laid out on the removed layout and the probe side take 
one each; the user
+      // repartition leg already reports it.
+      assert(allExchanges(plan).size === 4, s"expected four shuffles:\n$plan")
+    }
+  }
+
+  test("SPARK-61785: a keyed target Spark cannot evaluate is not laid out") {
+    withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
+        SQLConf.UNION_OUTPUT_PARTITIONING.key -> "true",
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_PARTIALLY_CLUSTERED_DISTRIBUTION_ENABLED.key -> 
"false",
+        SQLConf.SHUFFLE_PARTITIONS.key -> "4",
+        SQLConf.COALESCE_PARTITIONS_ENABLED.key -> "false",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ENABLED.key -> "true",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ALLOW_V2_BUCKETING_ENABLED.key 
-> "true",
+        
SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ALLOW_PARTITION_KEYS_SUBSET_OF_CLUSTER_KEYS_ENABLED
+          .key -> "true") {
+      // Laying the plain leg out on `bucket(4, id)` evaluates the transform 
for each row. With a
+      // function Spark cannot call, the rule must leave that leg to the hash 
shuffle the planner
+      // planned; the evaluable function shows the target is otherwise 
admissible.
+      val expected = (0L until 8L).flatMap { i =>
+        if (i == 1L) {
+          Seq(Row(1L, "a", 1), Row(1L, "v1", 2))
+        } else if (i == 2L) {
+          Seq(Row(2L, "b", 1), Row(2L, "v2", 2))
+        } else {
+          Seq(Row(i, s"v$i", 1))
+        }
+      }
+      Seq(UnboundNonScalarBucketFunction -> false, UnboundBucketFunction -> 
true).foreach {
+        case (fn, pushed) =>
+          withFunction(fn) {
+            createBucketedIdTable("bucket4", 4, numIds = 8)
+            val df = sql(
+              """SELECT id, data, row_number() OVER (PARTITION BY id ORDER BY 
data) rn FROM (
+                |  SELECT id, data FROM testcat.ns.bucket4
+                |  UNION ALL SELECT * FROM VALUES (1L, 'a'), (2L, 'b') AS 
v(id, data)
+                |)""".stripMargin)
+            checkAnswer(df, expected)
+            val plan = df.queryExecution.executedPlan
+            assert(hasGroupedUnion(plan) === pushed,
+              s"expected the keyed target to be laid out == $pushed:\n$plan")
+            assert(allExchanges(plan).size === 1, s"expected one 
shuffle:\n$plan")
+            catalog.clearTables()
+          }
+      }
+    }
+  }
+
+  test("SPARK-61785: a grouped but unsorted union leg supplies a sorted 
target") {
+    withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
+        SQLConf.UNION_OUTPUT_PARTITIONING.key -> "true",
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_PARTIALLY_CLUSTERED_DISTRIBUTION_ENABLED.key -> 
"false",
+        SQLConf.SHUFFLE_PARTITIONS.key -> "4",
+        SQLConf.COALESCE_PARTITIONS_ENABLED.key -> "false",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ENABLED.key -> "true",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ALLOW_V2_BUCKETING_ENABLED.key 
-> "true") {
+      createTable("keyed_13", columns, Array(Expressions.identity("id")))
+      createTable("keyed_24", columns, Array(Expressions.identity("id")))
+      sql("INSERT INTO testcat.ns.keyed_13 VALUES (1, 'a', 
timestamp'2022-01-01'), " +
+        "(3, 'b', timestamp'2022-01-02')")
+      sql("INSERT INTO testcat.ns.keyed_24 VALUES (2, 'c', 
timestamp'2022-01-03'), " +
+        "(4, 'd', timestamp'2022-01-04')")
+      // The aggregate between the two unions blocks `CombineUnions`, so the 
inner union stays a
+      // node: it reports a grouped domain in child order, [1, 3, 2, 4], and 
the aggregate keeps
+      // that layout. The grouping above the outer union sorts it, so a target 
taken as it stands
+      // could not match the output.
+      val df = sql("SELECT id, data, row_number() OVER (PARTITION BY id ORDER 
BY data) rn FROM (" +
+        "SELECT id, max(data) AS data FROM (" +
+        "SELECT id, data FROM testcat.ns.keyed_13 UNION ALL " +
+        "SELECT id, data FROM testcat.ns.keyed_24) GROUP BY id UNION ALL " +
+        "SELECT * FROM VALUES (5, 'e') AS v(id, data))")
+      checkAnswer(df, Seq(Row(1, "a", 1), Row(2, "c", 1), Row(3, "b", 1), 
Row(4, "d", 1),
+        Row(5, "e", 1)))
+      val plan = df.queryExecution.executedPlan
+      assert(satisfiesRequirements(plan))
+      assert(hasGroupedUnion(plan), s"expected the sorted domain to be 
picked:\n$plan")
+      assert(exchangesOverUnion(plan).isEmpty, s"the target must be pushed 
down:\n$plan")
+      assert(allExchanges(plan).size === 1, s"expected one shuffle:\n$plan")
+    }
+  }
+
+  test("SPARK-61785: a kept keyed leg keeps its layout while AQE coalesces") {
+    withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
+        SQLConf.UNION_OUTPUT_PARTITIONING.key -> "true",
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_PARTIALLY_CLUSTERED_DISTRIBUTION_ENABLED.key -> 
"false",
+        SQLConf.SHUFFLE_PARTITIONS.key -> "2",
+        SQLConf.COALESCE_PARTITIONS_ENABLED.key -> "true",
+        SQLConf.COALESCE_PARTITIONS_MIN_PARTITION_NUM.key -> "1",
+        SQLConf.ADVISORY_PARTITION_SIZE_IN_BYTES.key -> "10g",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ENABLED.key -> "true",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ALLOW_V2_BUCKETING_ENABLED.key 
-> "true",
+        
SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_KEEP_NON_COALESCIBLE_BRANCHES_ENABLED.key
 ->
+          "true") {
+      createTable("keyed_coalesced", columns, 
Array(Expressions.identity("id")))
+      sql("INSERT INTO testcat.ns.keyed_coalesced VALUES " +
+        "(1, 'a', timestamp'2022-01-01'), (1, 'b', timestamp'2022-01-02'), " +
+        "(2, 'c', timestamp'2022-01-03')")
+      val df = sql("SELECT id, data, row_number() OVER (PARTITION BY id ORDER 
BY data) rn FROM (" +
+        "SELECT id, data FROM testcat.ns.keyed_coalesced UNION ALL " +
+        "SELECT * FROM VALUES (1, 'd'), (3, 'e') AS v(id, data))")
+      checkAnswer(df, Seq(Row(1, "a", 1), Row(1, "b", 2), Row(1, "d", 3), 
Row(2, "c", 1),
+        Row(3, "e", 1)))
+      val plan = df.queryExecution.executedPlan
+      // The kept scan leaves the union's coalesce group ineligible, so the 
keyed layout survives
+      // the coalescing the opt-in allows.
+      assert(collect(plan) { case r: AQEShuffleReadExec => r }.isEmpty,
+        s"expected no coalesced read over the keyed stage:\n$plan")
+      assert(hasGroupedUnion(plan), s"expected a grouped union:\n$plan")
+      assert(allExchanges(plan).size === 1, s"expected one shuffle:\n$plan")
+    }
+  }
+
+  test("SPARK-61785: keep the bigger keyed domain when children declare 
different ones") {
+    withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_PARTIALLY_CLUSTERED_DISTRIBUTION_ENABLED.key -> 
"false",
+        SQLConf.SHUFFLE_PARTITIONS.key -> "2",
+        SQLConf.COALESCE_PARTITIONS_ENABLED.key -> "false",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ENABLED.key -> "true",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ALLOW_V2_BUCKETING_ENABLED.key 
-> "true") {
+      createTable("keyed_big", columns, Array(Expressions.identity("id")))
+      createTable("keyed_small", columns, Array(Expressions.identity("id")))
+      sql("INSERT INTO testcat.ns.keyed_big VALUES " +
+        "(1, 'a', timestamp'2022-01-01'), (1, 'b', timestamp'2022-01-02'), " +
+        "(2, 'c', timestamp'2022-01-03')")
+      sql("INSERT INTO testcat.ns.keyed_small VALUES " +
+        "(1, 'd', timestamp'2022-01-04'), (3, 'e', timestamp'2022-01-05')")
+      // Two keyed domains, {1,2} and {1,3}, and a leg with no layout: one 
domain is picked and
+      // the two children that do not declare it are laid out on it.
+      val df = sql("SELECT id, data, row_number() OVER (PARTITION BY id ORDER 
BY data) rn " +
+        "FROM (SELECT id, data FROM testcat.ns.keyed_big UNION ALL " +
+        "SELECT id, data FROM testcat.ns.keyed_small UNION ALL " +
+        "SELECT * FROM VALUES (2, 'f') AS v(id, data))")
+      checkAnswer(df, Seq(Row(1, "a", 1), Row(1, "b", 2), Row(1, "d", 3), 
Row(2, "c", 1),
+        Row(2, "f", 2), Row(3, "e", 1)))
+      val plan = df.queryExecution.executedPlan
+      assert(satisfiesRequirements(plan))
+      // The two legs that do not declare the picked domain are laid out on it.
+      assert(allExchanges(plan).size === 2, s"expected two shuffles:\n$plan")
+      assert(exchangesOverUnion(plan).isEmpty, s"unexpected shuffles over the 
union:\n$plan")
+      val union = collect(plan) { case u: UnionExec => u }.head
+      assert(union.children.head.exists(_.isInstanceOf[BatchScanExec]),
+        s"expected the bigger domain to keep its layout:\n$plan")
+      assert(collect(union.children(1)) {
+        case shuffle: ShuffleExchangeExec => shuffle
+      }.nonEmpty, s"expected the other keyed leg to be laid out:\n$plan")
+      assert(collect(union.children(2)) {
+        case shuffle: ShuffleExchangeExec => shuffle
+      }.nonEmpty, s"expected the leg without a layout to be laid out:\n$plan")
+      assert(hasGroupedUnion(plan), s"expected a grouped union:\n$plan")
+    }
+  }
+
+  test("SPARK-61785: a keyed domain covering part of the cluster keys needs 
permission") {
+    withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_PARTIALLY_CLUSTERED_DISTRIBUTION_ENABLED.key -> 
"false",
+        // Both locks have to be open: the rule's own subset permission below, 
and the V2
+        // requirement that the partition keys cover every cluster key.
+        SQLConf.V2_BUCKETING_REQUIRE_ALL_CLUSTER_KEYS_FOR_CO_PARTITION.key -> 
"false",
+        SQLConf.SHUFFLE_PARTITIONS.key -> "2",
+        SQLConf.COALESCE_PARTITIONS_ENABLED.key -> "false",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ENABLED.key -> "true",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ALLOW_V2_BUCKETING_ENABLED.key 
-> "true") {
+      createTable("keyed_part", columns, Array(Expressions.identity("id")))
+      sql("INSERT INTO testcat.ns.keyed_part VALUES " +
+        "(1, 'a', timestamp'2022-01-01'), (1, 'a', timestamp'2022-01-02'), " +
+        "(2, 'c', timestamp'2022-01-03')")
+      // The domain is partitioned by `id`, the window clusters on `(id, 
data)`: the layout names
+      // part of the cluster keys only.
+      val df = sql("SELECT id, data, row_number() OVER (PARTITION BY id, data 
ORDER BY ts) rn " +
+        "FROM (SELECT id, data, ts FROM testcat.ns.keyed_part UNION ALL " +
+        "SELECT * FROM VALUES (1, 'b', timestamp'2022-01-04') AS v(id, data, 
ts))")
+      checkAnswer(df, Seq(Row(1, "a", 1), Row(1, "a", 2), Row(1, "b", 1), 
Row(2, "c", 1)))

Review Comment:
   **Nit (P3):** This `checkAnswer` runs on `df`, which is built under the 
outer conf where `allowPartitionKeysSubsetOfClusterKeys` is still at its 
default `false`, so it executes the plan in which the union keeps its exchange. 
Inside the loop, the `allowed = true` plan, which lays the `VALUES` leg out on 
the `id` domain under the `(id, data)` window, gets only requirement and 
exchange-count assertions, so its rows are never compared. The comment above 
also says both locks have to be open, yet 
`spark.sql.sources.v2.bucketing.requireAllClusterKeysForCoPartition.enabled` 
stays `false` throughout, and no test runs a partial-key target with the 
permission on and that setting on. For a single-input consumer like this 
window, the `KeyedShuffleSpec` admission in `candidateTargets` is the only 
place that setting is enforced. Please compare the answer inside the loop for 
each permission value, and add a case with both the permission and the V2 
co-partition setting on that asserts the union ke
 eps its exchange.
   
   **Verification:**
   - **Behavior:** With the subset permission on and the V2 co-partition 
setting off, the window over a domain on part of its cluster keys is pushed 
down and returns the expected rows.
   - **Regression:** With the subset permission on and the V2 co-partition 
setting on, the same query keeps the union's exchange.



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/KeyGroupedPartitioningSuite.scala:
##########
@@ -721,6 +746,670 @@ class KeyGroupedPartitioningSuite
     }
   }
 
+  test("SPARK-61785: regroup V2 union domains instead of shuffling all rows") {
+    withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
+        SQLConf.UNION_OUTPUT_PARTITIONING.key -> "true",
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_PARTIALLY_CLUSTERED_DISTRIBUTION_ENABLED.key -> 
"false",
+        SQLConf.SHUFFLE_PARTITIONS.key -> "2",
+        SQLConf.COALESCE_PARTITIONS_ENABLED.key -> "false",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ENABLED.key -> "true") {
+      createTable("keyed_left", columns, Array(Expressions.identity("id")))
+      createTable("keyed_right", columns, Array(Expressions.identity("id")))
+      sql("INSERT INTO testcat.ns.keyed_left VALUES " +
+        "(1, 'a', timestamp'2022-01-01'), (1, 'b', timestamp'2022-01-02'), " +
+        "(2, 'c', timestamp'2022-01-03')")
+      sql("INSERT INTO testcat.ns.keyed_right VALUES " +
+        "(1, 'd', timestamp'2022-01-04'), (2, 'e', timestamp'2022-01-05')")
+      val previous = spark.experimental.extraStrategies
+      // Reach the rule with the exchange in place. The stock planner groups 
this all-keyed union
+      // before the rule sees it, and with `unionOutputPartitioning` off the 
rebuilt union reports
+      // the default partitioning, which no keyed target answers. An extension 
can introduce such
+      // an exchange as well, which this strategy stands in for.
+      spark.experimental.extraStrategies = Seq(new SparkStrategy {
+        override def apply(plan: LogicalPlan): Seq[SparkPlan] = plan match {
+          case union: org.apache.spark.sql.catalyst.plans.logical.Union =>
+            val child = UnionExec(union.children.map(planLater))
+            
Seq(ShuffleExchangeExec(physical.HashPartitioning(Seq(union.output.head), 2),
+              child, 
org.apache.spark.sql.execution.exchange.ENSURE_REQUIREMENTS))
+          case _ => Nil
+        }
+      }) ++ previous
+      try {
+        Seq(false, true).foreach { enabled =>
+          
withSQLConf(SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ALLOW_V2_BUCKETING_ENABLED.key
 ->
+              enabled.toString) {
+            val df = sql("SELECT id, data, row_number() OVER (PARTITION BY id 
ORDER BY data) rn " +
+              "FROM (SELECT id, data FROM testcat.ns.keyed_left UNION ALL " +
+              "SELECT id, data FROM testcat.ns.keyed_right)")
+            checkAnswer(df, Seq(Row(1, "a", 1), Row(1, "b", 2), Row(1, "d", 3),
+              Row(2, "c", 1), Row(2, "e", 2)))
+            val plan = df.queryExecution.executedPlan
+            assert(satisfiesRequirements(plan))
+            // The exchange only survives while the keyed permission is off.
+            assert(allExchanges(plan).size === (if (enabled) { 0 } else { 1 }),
+              s"unexpected shuffles:\n$plan")
+            if (enabled) {
+              assert(hasGroupedUnion(plan), s"expected a grouped 
union:\n$plan")
+              assert(exchangesOverUnion(plan).isEmpty,
+                s"the union's scans keep their layouts:\n$plan")
+              val union = collect(plan) { case u: UnionExec => u }.head
+              
assert(union.children.forall(!_.exists(_.isInstanceOf[ShuffleExchangeExec])),
+                s"the union's scans keep their layouts:\n$plan")
+              
assert(union.outputPartitioning.isInstanceOf[physical.KeyedPartitioning],
+                s"expected a keyed layout:\n$plan")
+            } else {
+              assert(exchangesOverUnion(plan).size === 1,
+                s"expected the union to be shuffled:\n$plan")
+            }
+          }
+        }
+      } finally {
+        spark.experimental.extraStrategies = previous
+      }
+    }
+  }
+
+  test("SPARK-61785: lay a union's other children out on a V2 keyed domain") {
+    withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_PARTIALLY_CLUSTERED_DISTRIBUTION_ENABLED.key -> 
"false",
+        SQLConf.SHUFFLE_PARTITIONS.key -> "2",
+        SQLConf.COALESCE_PARTITIONS_ENABLED.key -> "false",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ENABLED.key -> "true") {
+      createTable("keyed_domain", columns, Array(Expressions.identity("id")))
+      sql("INSERT INTO testcat.ns.keyed_domain VALUES " +
+        "(1, 'a', timestamp'2022-01-01'), (2, 'c', timestamp'2022-01-03')")
+      Seq(false, true).foreach { enabled =>
+        
withSQLConf(SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ALLOW_V2_BUCKETING_ENABLED.key
 ->
+            enabled.toString) {
+          // A union over a keyed table and a scan with no layout of its own: 
the planner puts the
+          // requirement exchange above the union, and the rule keeps the 
keyed leg and lays the
+          // other one out on its domain. The value side has a key (3) the 
domain does not
+          // declare, which the grouped union routes by hash and keeps whole.
+          val df = sql("SELECT id, data, row_number() OVER (PARTITION BY id 
ORDER BY data) rn " +
+            "FROM (SELECT id, data FROM testcat.ns.keyed_domain UNION ALL " +
+            "SELECT * FROM VALUES (1, 'b'), (3, 'f'), (3, 'g') AS v(id, 
data))")
+          checkAnswer(df, Seq(Row(1, "a", 1), Row(1, "b", 2), Row(2, "c", 1), 
Row(3, "f", 1),
+            Row(3, "g", 2)))
+          val plan = df.queryExecution.executedPlan
+          assert(satisfiesRequirements(plan))
+          // The keyed scan keeps its partitions and the leg without a layout 
is laid out on its
+          // domain, so the only shuffle is that leg's.
+          assert(allExchanges(plan).size === 1, s"expected one 
shuffle:\n$plan")
+          if (enabled) {
+            assert(hasGroupedUnion(plan), s"expected a grouped union:\n$plan")
+            val union = collect(plan) { case u: UnionExec => u }.head
+            assert(union.children.head.exists(_.isInstanceOf[BatchScanExec]),
+              s"expected the keyed scan to keep its layout:\n$plan")
+            assert(collect(union.children(1)) {
+              case shuffle: ShuffleExchangeExec => shuffle
+            }.nonEmpty, s"expected the other leg to be laid out:\n$plan")
+            
assert(union.outputPartitioning.isInstanceOf[physical.KeyedPartitioning],
+              s"expected a keyed layout:\n$plan")
+          } else {
+            assert(exchangesOverUnion(plan).size === 1,
+              s"expected the union to be shuffled:\n$plan")
+          }
+        }
+      }
+    }
+  }
+
+  test("SPARK-61785: keep a leg whose layout the planner marked as 
hash-routed") {
+    withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
+        SQLConf.UNION_OUTPUT_PARTITIONING.key -> "true",
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_PARTIALLY_CLUSTERED_DISTRIBUTION_ENABLED.key -> 
"false",
+        SQLConf.SHUFFLE_PARTITIONS.key -> "2",
+        SQLConf.COALESCE_PARTITIONS_ENABLED.key -> "false",
+        SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ENABLED.key -> "true",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_KEEP_JOIN_BRANCHES_ENABLED.key 
-> "true",
+        
SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_KEEP_NON_COALESCIBLE_BRANCHES_ENABLED.key
 ->
+          "true") {
+      createTable("marked_left", columns, Array(Expressions.identity("id")))
+      createTable("marked_right", columns, Array(Expressions.bucket(2, "id")))
+      sql("INSERT INTO testcat.ns.marked_left VALUES " +
+        "(1, 'a', timestamp'2022-01-01'), (2, 'c', timestamp'2022-01-02')")
+      sql("INSERT INTO testcat.ns.marked_right VALUES " +
+        "(1, 'b', timestamp'2022-01-03'), (2, 'd', timestamp'2022-01-04'), " +
+        "(3, 'e', timestamp'2022-01-05')")
+      // The join lays its left side out on the right's keyed domain, which 
marks the layout: rows
+      // of a key the domain does not declare were routed by hash. A right 
outer join reports the
+      // right side's layout, so the union's join leg carries the marker, and 
the rule keeps it
+      // beside an unmarked scan on the same domain.
+      val df = sql("SELECT id, data, row_number() OVER (PARTITION BY id ORDER 
BY data) rn " +
+        "FROM (SELECT id, data FROM testcat.ns.marked_left UNION ALL " +
+        "SELECT b.id, b.data FROM testcat.ns.marked_left a " +
+        "RIGHT OUTER JOIN testcat.ns.marked_right b ON a.id = b.id UNION ALL " 
+
+        "SELECT * FROM VALUES (1, 'z') AS v(id, data))")
+      checkAnswer(df, Seq(Row(1, "a", 1), Row(1, "b", 2), Row(1, "z", 3), 
Row(2, "c", 1),
+        Row(2, "d", 2), Row(3, "e", 1)))
+      val plan = df.queryExecution.executedPlan
+      assert(satisfiesRequirements(plan))
+      val union = collect(plan) { case u: UnionExec => u }.head
+      assert(union.children.head.exists(_.isInstanceOf[BatchScanExec]),
+        s"the scan keeps its layout:\n$plan")
+      union.children(1).outputPartitioning match {
+        case keyed: physical.KeyedPartitioning =>
+          assert(keyed.mayContainUnknownPartitionKeys && 
keyed.unknownKeysRouted,
+            s"expected a hash-routed marked leg:\n$plan")
+        case other => fail(s"expected a keyed join leg, got $other:\n$plan")
+      }
+      assert(collect(union.children(1)) { case s: ShuffleExchangeExec => s 
}.size === 1,
+        s"the leg keeps its layout, so only the join's own side 
shuffles:\n$plan")
+      // The join's own alignment and the values leg take one shuffle each; 
the exchange the
+      // planner put above the union is gone.
+      assert(allExchanges(plan).size === 2, s"expected two shuffles:\n$plan")
+      assert(exchangesOverUnion(plan).isEmpty, s"the target is pushed 
down:\n$plan")
+      assert(hasGroupedUnion(plan), s"expected a grouped union:\n$plan")
+    }
+  }
+
+  test("SPARK-61785: a child whose keys are a subset of the domain keeps its 
layout") {
+    withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
+        SQLConf.UNION_OUTPUT_PARTITIONING.key -> "true",
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_PARTIALLY_CLUSTERED_DISTRIBUTION_ENABLED.key -> 
"false",
+        SQLConf.SHUFFLE_PARTITIONS.key -> "3",
+        SQLConf.COALESCE_PARTITIONS_ENABLED.key -> "false",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ENABLED.key -> "true",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ALLOW_V2_BUCKETING_ENABLED.key 
-> "true") {
+      createTable("keyed_small", columns, Array(Expressions.identity("id")))
+      createTable("keyed_big", columns, Array(Expressions.identity("id")))
+      sql("INSERT INTO testcat.ns.keyed_small VALUES " +
+        "(1, 'a', timestamp'2022-01-01'), (2, 'c', timestamp'2022-01-02')")
+      sql("INSERT INTO testcat.ns.keyed_big VALUES " +
+        "(1, 'b', timestamp'2022-01-03'), (2, 'd', timestamp'2022-01-04'), " +
+        "(3, 'e', timestamp'2022-01-05')")
+      // The domain is {1, 2, 3}, declared by keyed_big; keyed_small holds 
keys {1, 2}, a subset of
+      // it, so that leg keeps its layout and only the leg without one is laid 
out.
+      val df = sql("SELECT id, data, row_number() OVER (PARTITION BY id ORDER 
BY data) rn FROM (" +
+        "SELECT id, data FROM testcat.ns.keyed_small UNION ALL " +
+        "SELECT id, data FROM testcat.ns.keyed_big UNION ALL " +
+        "SELECT * FROM VALUES (1, 'v') AS v(id, data))")
+      checkAnswer(df, Seq(Row(1, "a", 1), Row(1, "b", 2), Row(1, "v", 3), 
Row(2, "c", 1),
+        Row(2, "d", 2), Row(3, "e", 1)))
+      val plan = df.queryExecution.executedPlan
+      assert(satisfiesRequirements(plan))
+      assert(allExchanges(plan).size === 1, s"expected one shuffle:\n$plan")
+      assert(hasGroupedUnion(plan), s"expected a grouped union:\n$plan")
+      val union = collect(plan) { case union: UnionExec => union }.head
+      
assert(union.children.take(2).forall(_.exists(_.isInstanceOf[BatchScanExec])),
+        s"both keyed legs keep their layouts:\n$plan")
+      assert(collect(union.children(2)) {
+        case shuffle: ShuffleExchangeExec => shuffle
+      }.nonEmpty, s"the leg without a layout is laid out:\n$plan")
+    }
+  }
+
+  test("SPARK-61785: regroup an out-of-order subset leg beside a bigger keyed 
domain") {
+    withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
+        SQLConf.UNION_OUTPUT_PARTITIONING.key -> "true",
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_PARTIALLY_CLUSTERED_DISTRIBUTION_ENABLED.key -> 
"false",
+        SQLConf.SHUFFLE_PARTITIONS.key -> "3",
+        SQLConf.COALESCE_PARTITIONS_ENABLED.key -> "false",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ENABLED.key -> "true") {
+      Seq(1, 2, 3).foreach { id =>
+        createTable(s"ordered_$id", columns, Array(Expressions.identity("id")))
+        sql(s"INSERT INTO testcat.ns.ordered_$id VALUES " +
+          s"($id, 'v$id', timestamp'2022-01-0$id')")
+      }
+      // Each leg is an aggregate over an inner union, so `CombineUnions` 
cannot flatten it and
+      // each leg reports its children's order: [1, 2, 3] for the first, the 
only domain whose
+      // partition count fits the bounds, and [2, 1] for the second, a subset 
in another order.
+      val df = sql(
+        """SELECT id, data, row_number() OVER (PARTITION BY id ORDER BY data) 
rn FROM (
+          |  SELECT id, max(data) AS data FROM (
+          |    SELECT id, data FROM testcat.ns.ordered_1
+          |    UNION ALL SELECT id, data FROM testcat.ns.ordered_2
+          |    UNION ALL SELECT id, data FROM testcat.ns.ordered_3) GROUP BY id
+          |  UNION ALL
+          |  SELECT id, max(data) AS data FROM (
+          |    SELECT id, data FROM testcat.ns.ordered_2
+          |    UNION ALL SELECT id, data FROM testcat.ns.ordered_1) GROUP BY id
+          |  UNION ALL SELECT * FROM VALUES (1, 'v0') AS v(id, 
data))""".stripMargin)
+      checkAnswer(df, Seq(Row(1, "v0", 1), Row(1, "v1", 2), Row(1, "v1", 3), 
Row(2, "v2", 1),
+        Row(2, "v2", 2), Row(3, "v3", 1)))
+      val plan = df.queryExecution.executedPlan
+      assert(satisfiesRequirements(plan))
+      assert(allExchanges(plan).size === 1, s"only the leg without a layout 
shuffles:\n$plan")
+      assert(hasGroupedUnion(plan), s"expected a grouped union:\n$plan")
+      // The first leg's inner union has three children too, so the outer 
union is the one the
+      // grouping above the site reads.
+      val union = collect(plan) { case group: GroupPartitionsExec => group }
+        .flatMap { group =>
+          unwrap(group.child) match {
+            case u: UnionExec => Some(u)
+            case _ => None
+          }
+        }.head
+      assert(collect(union.children(1)) { case s: ShuffleExchangeExec => s 
}.isEmpty,
+        s"the out-of-order subset leg keeps its layout:\n$plan")
+      union.children(1).outputPartitioning match {
+        case keyed: physical.KeyedPartitioning =>
+          assert(keyed.partitionKeys.map(_.row.getInt(0)) === Seq(2, 1),
+            s"expected the leg's own order [2, 1]:\n$plan")
+        case other => fail(s"expected a kept keyed leg, got $other:\n$plan")
+      }
+    }
+  }
+
+  test("SPARK-61785: a keyed union side pairs with a keyed table") {
+    withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_PARTIALLY_CLUSTERED_DISTRIBUTION_ENABLED.key -> 
"false",
+        SQLConf.SHUFFLE_PARTITIONS.key -> "2",
+        SQLConf.COALESCE_PARTITIONS_ENABLED.key -> "false",
+        SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ENABLED.key -> "true",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ALLOW_JOIN_INPUTS_ENABLED.key 
-> "true") {
+      createTable("keyed_union", columns, Array(Expressions.identity("id")))
+      createTable("keyed_probe", columns, Array(Expressions.identity("id")))
+      sql("INSERT INTO testcat.ns.keyed_union VALUES " +
+        "(1, 'a', timestamp'2022-01-01'), (2, 'c', timestamp'2022-01-03')")
+      sql("INSERT INTO testcat.ns.keyed_probe VALUES " +
+        "(1, 'x', timestamp'2022-01-06'), (2, 'y', timestamp'2022-01-07')")
+      Seq(false, true).foreach { enabled =>
+        
withSQLConf(SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ALLOW_V2_BUCKETING_ENABLED.key
 ->
+            enabled.toString) {
+          // The planner lines the union up on the probe's keyed domain by 
shuffling the union,
+          // and the rule keeps the union's keyed leg instead, laying only the 
leg without a
+          // layout. The pair then holds with the probe as it stands.
+          val df = sql(
+            """SELECT /*+ MERGE(u, p) */ u.id, u.data, p.data
+              |FROM (SELECT id, data FROM testcat.ns.keyed_union UNION ALL
+              |      SELECT * FROM VALUES (1, 'b'), (3, 'f') AS v(id, data)) u
+              |JOIN testcat.ns.keyed_probe p ON u.id = p.id""".stripMargin)
+          checkAnswer(df, Seq(Row(1, "a", "x"), Row(1, "b", "x"), Row(2, "c", 
"y")))
+          val plan = df.queryExecution.executedPlan
+          assert(satisfiesRequirements(plan))
+          assert(allExchanges(plan).size === 1, s"expected one 
shuffle:\n$plan")
+          if (enabled) {
+            assert(hasGroupedUnion(plan), s"expected a grouped union:\n$plan")
+            val union = collect(plan) { case u: UnionExec => u }.head
+            assert(union.children.head.exists(_.isInstanceOf[BatchScanExec]),
+              s"expected the keyed leg to keep its layout:\n$plan")
+            assert(collect(union.children(1)) {
+              case shuffle: ShuffleExchangeExec => shuffle
+            }.nonEmpty, s"expected the leg without a layout to be 
shuffled:\n$plan")
+          } else {
+            assert(exchangesOverUnion(plan).size === 1,
+              s"expected the union to be shuffled:\n$plan")
+          }
+        }
+      }
+    }
+  }
+
+  test("SPARK-61785: an unsorted keyed side is not paired with") {
+    withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
+        SQLConf.UNION_OUTPUT_PARTITIONING.key -> "true",
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_PARTIALLY_CLUSTERED_DISTRIBUTION_ENABLED.key -> 
"false",
+        SQLConf.SHUFFLE_PARTITIONS.key -> "2",
+        SQLConf.COALESCE_PARTITIONS_ENABLED.key -> "false",
+        SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ENABLED.key -> "true",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ALLOW_V2_BUCKETING_ENABLED.key 
-> "true",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ALLOW_JOIN_INPUTS_ENABLED.key 
-> "true") {
+      createTable("keyed_union", columns, Array(Expressions.identity("id")))
+      createTable("keyed_two", columns, Array(Expressions.identity("id")))
+      createTable("keyed_one", columns, Array(Expressions.identity("id")))
+      sql("INSERT INTO testcat.ns.keyed_union VALUES " +
+        "(1, 'a', timestamp'2022-01-01'), (2, 'c', timestamp'2022-01-03')")
+      sql("INSERT INTO testcat.ns.keyed_two VALUES (2, 'y', 
timestamp'2022-01-07')")
+      sql("INSERT INTO testcat.ns.keyed_one VALUES (1, 'x', 
timestamp'2022-01-06')")
+      // The inner union reports its grouped domain in child order, [2, 1], 
and the planner
+      // shuffles the outer union onto it. Keeping the outer union's keyed leg 
would group it on
+      // the sorted [1, 2], which cannot pair with [2, 1], so the rewrite 
declines and the union
+      // keeps the exchange it was given.
+      val df = sql(
+        """SELECT /*+ MERGE(u, p) */ u.id, u.data, p.data
+          |FROM (SELECT id, data FROM testcat.ns.keyed_union UNION ALL
+          |      SELECT * FROM VALUES (1, 'b') AS v(id, data)) u
+          |JOIN (SELECT id, data FROM testcat.ns.keyed_two UNION ALL
+          |      SELECT id, data FROM testcat.ns.keyed_one) p ON u.id = 
p.id""".stripMargin)
+      checkAnswer(df, Seq(Row(1, "a", "x"), Row(1, "b", "x"), Row(2, "c", 
"y")))
+      val plan = df.queryExecution.executedPlan
+      assert(satisfiesRequirements(plan))
+      assert(allExchanges(plan).size === 1, s"expected one shuffle:\n$plan")
+      assert(!hasGroupedUnion(plan), s"the keyed target must not pair:\n$plan")
+      assert(exchangesOverUnion(plan).size === 1,
+        s"expected one exchange over a union:\n$plan")
+      exchangesOverUnion(plan).head.outputPartitioning match {
+        case keyed: physical.KeyedPartitioning =>
+          assert(keyed.partitionKeys.map(_.row.getInt(0)) === Seq(2, 1),
+            s"expected the sibling's unsorted order:\n$plan")
+        case other =>
+          fail(s"expected a keyed exchange over the union, got $other:\n$plan")
+      }
+    }
+  }
+
+  test("SPARK-61785: a keyed target that breaks an upper join is retried on 
the removed layout") {
+    withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
+        SQLConf.UNION_OUTPUT_PARTITIONING.key -> "true",
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_PARTIALLY_CLUSTERED_DISTRIBUTION_ENABLED.key -> 
"false",
+        SQLConf.SHUFFLE_PARTITIONS.key -> "2",
+        SQLConf.COALESCE_PARTITIONS_ENABLED.key -> "false",
+        SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ENABLED.key -> "true",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ALLOW_V2_BUCKETING_ENABLED.key 
-> "true") {
+      createTable("keyed_union", columns, Array(Expressions.identity("id")))
+      createTable("plain_hash", columns, Array.empty[Transform])
+      createTable("plain_probe", columns, Array.empty[Transform])
+      sql("INSERT INTO testcat.ns.keyed_union VALUES " +
+        "(1, 'a', timestamp'2022-01-01'), (1, 'b', timestamp'2022-01-02'), " +
+        "(2, 'c', timestamp'2022-01-03'), (2, 'd', timestamp'2022-01-04')")
+      sql("INSERT INTO testcat.ns.plain_hash VALUES (3, 'x', 
timestamp'2022-01-05')")
+      sql("INSERT INTO testcat.ns.plain_probe VALUES " +
+        "(1, 'p', timestamp'2022-01-06'), (2, 'q', timestamp'2022-01-07')")
+      // The keyed leg is the first child and the biggest, so the first 
attempt takes its domain.
+      // The REPARTITION leg offers the hash layout of the exchange above the 
union, which is what
+      // the retry falls back to.
+      val core =
+        """SELECT id, data, row_number() OVER (PARTITION BY id ORDER BY data) 
rn FROM (
+          |  SELECT id, data FROM testcat.ns.keyed_union
+          |  UNION ALL SELECT 3 AS id, 'y' AS data
+          |  UNION ALL SELECT /*+ REPARTITION(2, id) */ id, data
+          |    FROM testcat.ns.plain_hash)""".stripMargin
+      // Without the join the keyed target is taken, which is what makes the 
join the deciding
+      // factor below.
+      val keyed = sql(core)
+      checkAnswer(keyed, Seq(Row(1, "a", 1), Row(1, "b", 2), Row(2, "c", 1), 
Row(2, "d", 2),
+        Row(3, "x", 1), Row(3, "y", 2)))
+      val keyedPlan = keyed.queryExecution.executedPlan
+      assert(satisfiesRequirements(keyedPlan))
+      // The values leg is laid out, and the user repartition legs keeps its 
exchange and takes
+      // the keyed one on top.
+      assert(allExchanges(keyedPlan).size === 3, s"expected three 
shuffles:\n$keyedPlan")
+      assert(hasGroupedUnion(keyedPlan), s"expected the keyed 
target:\n$keyedPlan")
+      assert(exchangesOverUnion(keyedPlan).isEmpty,
+        s"the keyed target keeps the union's exchange down:\n$keyedPlan")
+      // With the join, the keyed layout cannot pair with the other side's 
hash layout; the retry
+      // pushes the removed hash layout down instead.
+      val joined = sql(s"SELECT w.id, w.rn, p.data FROM ($core) w " +
+        "JOIN testcat.ns.plain_probe p ON w.id = p.id")
+      checkAnswer(joined, Seq(Row(1, 1, "p"), Row(1, 2, "p"), Row(2, 1, "q"), 
Row(2, 2, "q")))
+      // AQE re-plans around the stages it creates, so the retried layout has 
to hold there.
+      val plan = joined.queryExecution.executedPlan
+      assert(satisfiesRequirements(plan))
+      assert(!hasGroupedUnion(plan),
+        s"the keyed target must not survive the join's pairing:\n$plan")
+      assert(collect(plan) { case u: UnionExec => u }.head.outputPartitioning
+        .isInstanceOf[physical.HashPartitioning],
+        s"the retry should rebuild the union on the removed layout:\n$plan")
+      assert(exchangesOverUnion(plan).isEmpty,
+        s"the retry should push the removed layout down:\n$plan")
+      // The two legs laid out on the removed layout and the probe side take 
one each; the user
+      // repartition leg already reports it.
+      assert(allExchanges(plan).size === 4, s"expected four shuffles:\n$plan")
+    }
+  }
+
+  test("SPARK-61785: a keyed target Spark cannot evaluate is not laid out") {
+    withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
+        SQLConf.UNION_OUTPUT_PARTITIONING.key -> "true",
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_PARTIALLY_CLUSTERED_DISTRIBUTION_ENABLED.key -> 
"false",
+        SQLConf.SHUFFLE_PARTITIONS.key -> "4",
+        SQLConf.COALESCE_PARTITIONS_ENABLED.key -> "false",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ENABLED.key -> "true",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ALLOW_V2_BUCKETING_ENABLED.key 
-> "true",
+        
SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ALLOW_PARTITION_KEYS_SUBSET_OF_CLUSTER_KEYS_ENABLED
+          .key -> "true") {
+      // Laying the plain leg out on `bucket(4, id)` evaluates the transform 
for each row. With a
+      // function Spark cannot call, the rule must leave that leg to the hash 
shuffle the planner
+      // planned; the evaluable function shows the target is otherwise 
admissible.
+      val expected = (0L until 8L).flatMap { i =>
+        if (i == 1L) {
+          Seq(Row(1L, "a", 1), Row(1L, "v1", 2))
+        } else if (i == 2L) {
+          Seq(Row(2L, "b", 1), Row(2L, "v2", 2))
+        } else {
+          Seq(Row(i, s"v$i", 1))
+        }
+      }
+      Seq(UnboundNonScalarBucketFunction -> false, UnboundBucketFunction -> 
true).foreach {
+        case (fn, pushed) =>
+          withFunction(fn) {
+            createBucketedIdTable("bucket4", 4, numIds = 8)
+            val df = sql(
+              """SELECT id, data, row_number() OVER (PARTITION BY id ORDER BY 
data) rn FROM (
+                |  SELECT id, data FROM testcat.ns.bucket4
+                |  UNION ALL SELECT * FROM VALUES (1L, 'a'), (2L, 'b') AS 
v(id, data)
+                |)""".stripMargin)
+            checkAnswer(df, expected)
+            val plan = df.queryExecution.executedPlan
+            assert(hasGroupedUnion(plan) === pushed,
+              s"expected the keyed target to be laid out == $pushed:\n$plan")
+            assert(allExchanges(plan).size === 1, s"expected one 
shuffle:\n$plan")
+            catalog.clearTables()
+          }
+      }
+    }
+  }
+
+  test("SPARK-61785: a grouped but unsorted union leg supplies a sorted 
target") {
+    withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
+        SQLConf.UNION_OUTPUT_PARTITIONING.key -> "true",
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_PARTIALLY_CLUSTERED_DISTRIBUTION_ENABLED.key -> 
"false",
+        SQLConf.SHUFFLE_PARTITIONS.key -> "4",
+        SQLConf.COALESCE_PARTITIONS_ENABLED.key -> "false",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ENABLED.key -> "true",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ALLOW_V2_BUCKETING_ENABLED.key 
-> "true") {
+      createTable("keyed_13", columns, Array(Expressions.identity("id")))
+      createTable("keyed_24", columns, Array(Expressions.identity("id")))
+      sql("INSERT INTO testcat.ns.keyed_13 VALUES (1, 'a', 
timestamp'2022-01-01'), " +
+        "(3, 'b', timestamp'2022-01-02')")
+      sql("INSERT INTO testcat.ns.keyed_24 VALUES (2, 'c', 
timestamp'2022-01-03'), " +
+        "(4, 'd', timestamp'2022-01-04')")
+      // The aggregate between the two unions blocks `CombineUnions`, so the 
inner union stays a
+      // node: it reports a grouped domain in child order, [1, 3, 2, 4], and 
the aggregate keeps
+      // that layout. The grouping above the outer union sorts it, so a target 
taken as it stands
+      // could not match the output.
+      val df = sql("SELECT id, data, row_number() OVER (PARTITION BY id ORDER 
BY data) rn FROM (" +
+        "SELECT id, max(data) AS data FROM (" +
+        "SELECT id, data FROM testcat.ns.keyed_13 UNION ALL " +
+        "SELECT id, data FROM testcat.ns.keyed_24) GROUP BY id UNION ALL " +
+        "SELECT * FROM VALUES (5, 'e') AS v(id, data))")
+      checkAnswer(df, Seq(Row(1, "a", 1), Row(2, "c", 1), Row(3, "b", 1), 
Row(4, "d", 1),
+        Row(5, "e", 1)))
+      val plan = df.queryExecution.executedPlan
+      assert(satisfiesRequirements(plan))
+      assert(hasGroupedUnion(plan), s"expected the sorted domain to be 
picked:\n$plan")
+      assert(exchangesOverUnion(plan).isEmpty, s"the target must be pushed 
down:\n$plan")
+      assert(allExchanges(plan).size === 1, s"expected one shuffle:\n$plan")
+    }
+  }
+
+  test("SPARK-61785: a kept keyed leg keeps its layout while AQE coalesces") {
+    withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
+        SQLConf.UNION_OUTPUT_PARTITIONING.key -> "true",
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_PARTIALLY_CLUSTERED_DISTRIBUTION_ENABLED.key -> 
"false",
+        SQLConf.SHUFFLE_PARTITIONS.key -> "2",
+        SQLConf.COALESCE_PARTITIONS_ENABLED.key -> "true",
+        SQLConf.COALESCE_PARTITIONS_MIN_PARTITION_NUM.key -> "1",
+        SQLConf.ADVISORY_PARTITION_SIZE_IN_BYTES.key -> "10g",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ENABLED.key -> "true",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ALLOW_V2_BUCKETING_ENABLED.key 
-> "true",
+        
SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_KEEP_NON_COALESCIBLE_BRANCHES_ENABLED.key
 ->
+          "true") {
+      createTable("keyed_coalesced", columns, 
Array(Expressions.identity("id")))
+      sql("INSERT INTO testcat.ns.keyed_coalesced VALUES " +
+        "(1, 'a', timestamp'2022-01-01'), (1, 'b', timestamp'2022-01-02'), " +
+        "(2, 'c', timestamp'2022-01-03')")
+      val df = sql("SELECT id, data, row_number() OVER (PARTITION BY id ORDER 
BY data) rn FROM (" +
+        "SELECT id, data FROM testcat.ns.keyed_coalesced UNION ALL " +
+        "SELECT * FROM VALUES (1, 'd'), (3, 'e') AS v(id, data))")
+      checkAnswer(df, Seq(Row(1, "a", 1), Row(1, "b", 2), Row(1, "d", 3), 
Row(2, "c", 1),
+        Row(3, "e", 1)))
+      val plan = df.queryExecution.executedPlan
+      // The kept scan leaves the union's coalesce group ineligible, so the 
keyed layout survives
+      // the coalescing the opt-in allows.
+      assert(collect(plan) { case r: AQEShuffleReadExec => r }.isEmpty,
+        s"expected no coalesced read over the keyed stage:\n$plan")
+      assert(hasGroupedUnion(plan), s"expected a grouped union:\n$plan")
+      assert(allExchanges(plan).size === 1, s"expected one shuffle:\n$plan")
+    }
+  }
+
+  test("SPARK-61785: keep the bigger keyed domain when children declare 
different ones") {
+    withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_PARTIALLY_CLUSTERED_DISTRIBUTION_ENABLED.key -> 
"false",
+        SQLConf.SHUFFLE_PARTITIONS.key -> "2",
+        SQLConf.COALESCE_PARTITIONS_ENABLED.key -> "false",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ENABLED.key -> "true",
+        SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ALLOW_V2_BUCKETING_ENABLED.key 
-> "true") {
+      createTable("keyed_big", columns, Array(Expressions.identity("id")))
+      createTable("keyed_small", columns, Array(Expressions.identity("id")))
+      sql("INSERT INTO testcat.ns.keyed_big VALUES " +
+        "(1, 'a', timestamp'2022-01-01'), (1, 'b', timestamp'2022-01-02'), " +
+        "(2, 'c', timestamp'2022-01-03')")
+      sql("INSERT INTO testcat.ns.keyed_small VALUES " +
+        "(1, 'd', timestamp'2022-01-04'), (3, 'e', timestamp'2022-01-05')")
+      // Two keyed domains, {1,2} and {1,3}, and a leg with no layout: one 
domain is picked and
+      // the two children that do not declare it are laid out on it.
+      val df = sql("SELECT id, data, row_number() OVER (PARTITION BY id ORDER 
BY data) rn " +
+        "FROM (SELECT id, data FROM testcat.ns.keyed_big UNION ALL " +
+        "SELECT id, data FROM testcat.ns.keyed_small UNION ALL " +
+        "SELECT * FROM VALUES (2, 'f') AS v(id, data))")
+      checkAnswer(df, Seq(Row(1, "a", 1), Row(1, "b", 2), Row(1, "d", 3), 
Row(2, "c", 1),
+        Row(2, "f", 2), Row(3, "e", 1)))
+      val plan = df.queryExecution.executedPlan
+      assert(satisfiesRequirements(plan))
+      // The two legs that do not declare the picked domain are laid out on it.
+      assert(allExchanges(plan).size === 2, s"expected two shuffles:\n$plan")
+      assert(exchangesOverUnion(plan).isEmpty, s"unexpected shuffles over the 
union:\n$plan")
+      val union = collect(plan) { case u: UnionExec => u }.head
+      assert(union.children.head.exists(_.isInstanceOf[BatchScanExec]),

Review Comment:
   **Nit (P3):** `keyed_big` is both the largest leg and the union's first 
child, and each domain has one offer and two partitions, so the 
first-occurrence tie-break picks the same leg as the byte ranking, and this 
assertion would still pass if keyed targets were ranked without bytes. The hash 
precedent, 'SPARK-60379: prefer the layout that keeps the most bytes', puts the 
largest child last for exactly this reason; listing the bigger domain after the 
smaller one would leave only the byte ranking able to pick it. Separately, no 
test shows a subset leg's bytes counting toward the domain that keeps it, which 
`candidateTargets` now does by summing `keptBytes` over `offeredBy`. A second 
case would cover that: list first a domain whose own leg is bigger, and give 
the other domain a subset leg large enough that only counting its bytes lets 
that domain win.
   
   **Verification:**
   - **Regression:** With the smaller keyed domain listed first, the bigger 
domain still keeps its layout and the smaller one is laid out, so ranking by 
first occurrence fails the assertion.
   - **Regression:** In the subset case the domain whose own leg is smaller 
keeps its layout because its subset leg's bytes count, so a ranking that left 
subset legs out of the bytes kept fails the assertion.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/adaptive/PushDownShuffleExchangeThroughUnionSuite.scala:
##########
@@ -201,6 +213,36 @@ class PushDownShuffleExchangeThroughUnionSuite extends 
QueryTest with SharedSpar
       spark.sql(sql).collect().toSeq
     }
 
+  test("SPARK-61785: a query on the defaults keeps its shuffle") {

Review Comment:
   **Nit (P3):** This test does not run the defaults its comment describes. The 
suite's `sparkConf` keeps 
`spark.sql.adaptive.pushDownShuffleThroughUnion.enabled` on (default false) and 
`maxTargetPartitionNumFactor` at 2.0 (default 1.0), and the test pins 
`allowJoinInputs` and the other opt-ins to explicit `false` values instead of 
unsetting them. Flipping one of those defaults therefore leaves the test 
passing, and its assertion only repeats the `allowJoinInputs = false` case that 
'SPARK-60379: join inputs require explicit permission' already covers. Because 
the query is a shuffled-join input, it would also keep its shuffle under the 
join-input default even if the rule's own default turned on. To make it a real 
defaults check, unset the push-down settings for the test (the rule's flag, its 
opt-ins and the factor) and restore them afterwards, as 'SPARK-60379: push-down 
is disabled by default and requires explicit enablement' does, and use a query 
the rule rewrites once enabled, such 
 as the suite's window over a union with an aggregate leg.
   
   **Verification:**
   - **Regression:** With every push-down setting unset the query keeps its 
union shuffle, and setting only the rule's own flag to true removes that 
shuffle, so the test fails if the rule's default changes to on.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -9099,6 +9098,31 @@ object SQLConf {
       .checkValue(_ >= 0, "The maximum number of union children must be 
non-negative.")
       .createWithDefault(10)
 
+  val PUSH_DOWN_SHUFFLE_THROUGH_UNION_ALLOW_V2_BUCKETING_ENABLED =
+    
buildConf("spark.sql.adaptive.pushDownShuffleThroughUnion.allowV2Bucketing.enabled")
+      .internal()
+      .doc("When true, union shuffle push-down may use a V2 keyed layout as 
the union's " +
+        "output, whether the shuffle it replaces was keyed or hash. Children 
already reporting " +
+        "the picked domain keep their layouts, and an unmarked child reporting 
a subset of its " +
+        "keys keeps it too; a marked child has to declare the domain's list in 
the same order. " +
+        "The others are shuffled onto it, which creates keyed shuffles, and 
rows of a key the " +
+        "domain does not declare are routed by hash, which the layout records. 
The grouping " +
+        "above the rebuilt union then holds the full-key claim only. Set to 
false to restrict " +
+        s"the rule to hash layouts. Requires 
${PUSH_DOWN_SHUFFLE_THROUGH_UNION_ENABLED.key} and " +
+        s"${V2_BUCKETING_ENABLED.key}, ${V2_BUCKETING_SHUFFLE_ENABLED.key} 
since a child may be " +
+        s"shuffled onto the domain, and " +
+        s"${V2_BUCKETING_PARTIALLY_CLUSTERED_DISTRIBUTION_ENABLED.key} to be 
disabled. A target " +
+        s"naming only part of the consumer's cluster keys further needs " +
+        s"${V2_BUCKETING_REQUIRE_ALL_CLUSTER_KEYS_FOR_CO_PARTITION.key} off 
and " +
+        
"spark.sql.adaptive.pushDownShuffleThroughUnion.allowPartitionKeysSubsetOfClusterKeys."
 +
+        "enabled on. A source-reported keyed layout is kept only when the 
consumer's shuffle " +
+        s"group cannot coalesce, so ${COALESCE_PARTITIONS_ENABLED.key} must be 
off or " +

Review Comment:
   **Nit (P3):** The first half of this sentence is right, but the 'so ... must 
be off or ... on' part is not: `apply` widens each site's policy to 
`allowNonCoalescible || !allExchangeInputs(operator)`, and `keepableLayout` 
keeps any leaf while that holds. So a consumer with a non-exchange input, such 
as the class doc's own merge-join example whose other side is a keyed 
`BatchScan`, keeps the keyed scan with coalescing on and 
`keepNonCoalescibleBranches` off. That is the exception the 
`keepNonCoalescibleBranches` doc already states ('A non-exchange input already 
prevents the compatible group from coalescing'). As written, this doc can lead 
users to turn session-wide coalescing off for a rewrite that already happens 
without it.
   
   Please make the requirement conditional on every consumer input path 
reaching an exchange, as the `keepNonCoalescibleBranches` doc does, here and in 
the two code comments that say the same thing: the class doc ('keeping it needs 
that opt-in or coalescing off') and the comment above `LayoutPolicy`.
   
   **Verification:**
   - **Inspection:** The allowV2Bucketing doc, the class doc and the 
LayoutPolicy comment make the coalescing requirement conditional on every 
consumer input path reaching an exchange, consistent with the per-operator 
widening the rule applies and with the keepNonCoalescibleBranches doc.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/PushDownShuffleExchangeThroughUnion.scala:
##########
@@ -639,8 +793,22 @@ case class PushDownShuffleExchangeThroughUnion(
     // Origin inheritance can tag a zero-move candidate, so it must not reuse 
the input union.
     val rebuilt = union.copy(children = newChildren)
     rebuilt.copyTagsFrom(union)
-    Option.when(
-      
PartitioningCollection.flatten(rebuilt.outputPartitioning).contains(target))(rebuilt)
+    val grouped = rebuilt.outputPartitioning match {
+      case keyed: KeyedPartitioning if !keyed.isGrouped =>
+        // Grouping merges the partitions that share a key. That loses 
granularity only for a
+        // collapsed layout, which the planner gates behind the V2 subset 
permission; ask the same
+        // question here. Every kept child shares the target's collapse state, 
so the concatenation
+        // gives the same answer as the target.
+        if (!keyed.mayGroupToSatisfy(required)) {
+          return None
+        }
+        GroupPartitionsExec(rebuilt)
+      case _ => rebuilt
+    }
+    // The last word on a candidate: the union has to report the target's key 
domain. The grouping
+    // above sorts the keys, so the order of the target is not part of that 
check.
+    Option.when(PartitioningCollection.flatten(grouped.outputPartitioning)

Review Comment:
   **Nit (P3):** For a hash target no `GroupPartitionsExec` is added, so 
`grouped` is `rebuilt`, and this line derives the union's partitioning a second 
time: `UnionExec.outputPartitioning` re-derives it from every child on each 
call. The base branch's hash path did this once per evaluated candidate, so 
every hash-only site now pays one extra derivation per candidate and per AQE 
re-plan, for the same plan. Keeping the value read in the `match` above and 
reusing it here when no grouping node is added, and reading the grouping node's 
partitioning only when one is, restores the base cost.
   
   **Verification:**
   - **Inspection:** When rebuildUnion adds no grouping node it reads the 
rebuilt union's output partitioning once, and its final check compares that 
same value with the target; with a grouping node it reads the grouping node's 
partitioning.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -9099,6 +9098,31 @@ object SQLConf {
       .checkValue(_ >= 0, "The maximum number of union children must be 
non-negative.")
       .createWithDefault(10)
 
+  val PUSH_DOWN_SHUFFLE_THROUGH_UNION_ALLOW_V2_BUCKETING_ENABLED =
+    
buildConf("spark.sql.adaptive.pushDownShuffleThroughUnion.allowV2Bucketing.enabled")
+      .internal()
+      .doc("When true, union shuffle push-down may use a V2 keyed layout as 
the union's " +
+        "output, whether the shuffle it replaces was keyed or hash. Children 
already reporting " +
+        "the picked domain keep their layouts, and an unmarked child reporting 
a subset of its " +
+        "keys keeps it too; a marked child has to declare the domain's list in 
the same order. " +
+        "The others are shuffled onto it, which creates keyed shuffles, and 
rows of a key the " +
+        "domain does not declare are routed by hash, which the layout records. 
The grouping " +
+        "above the rebuilt union then holds the full-key claim only. Set to 
false to restrict " +
+        s"the rule to hash layouts. Requires 
${PUSH_DOWN_SHUFFLE_THROUGH_UNION_ENABLED.key} and " +
+        s"${V2_BUCKETING_ENABLED.key}, ${V2_BUCKETING_SHUFFLE_ENABLED.key} 
since a child may be " +
+        s"shuffled onto the domain, and " +
+        s"${V2_BUCKETING_PARTIALLY_CLUSTERED_DISTRIBUTION_ENABLED.key} to be 
disabled. A target " +
+        s"naming only part of the consumer's cluster keys further needs " +

Review Comment:
   **Non-blocking (P2):** This sentence asks for 
`allowPartitionKeysSubsetOfClusterKeys` only for a target that names part of 
the cluster keys, but `rebuildChild` also needs it for any transform domain. 
Without the permission it keeps a keyed target only when 
`required.allClusterKeysAmong(keyed.partitioning.expressions)` holds, which 
compares expressions with `semanticEquals`, so `bucket(n, id)` never matches 
the cluster key `id`. Admission reads the transform's reference instead, so the 
V2 co-partition setting does not block such a target. As a result, a user who 
follows this doc for a table bucketed by `bucket(8, id)` under `PARTITION BY 
id` keeps the union's exchange, and turning the V2 co-partition setting off, as 
this sentence suggests, changes nothing. The PR's tests pin this behavior: 'a 
transform domain that coarsens its key needs permission', and 'a keyed target 
Spark cannot evaluate is not laid out', which turns the permission on for its 
`bucket(4, id)` target.
   
   Please say here, and in the `allowPartitionKeysSubsetOfClusterKeys` doc, 
which now governs keyed targets too, that a keyed target whose partition 
expressions are transforms, such as `bucket(n, id)` or `days(ts)`, needs that 
permission even when it covers every cluster key, and that the V2 co-partition 
setting does not block it. The current sentence can stay for targets that name 
part of the cluster keys.
   
   **Verification:**
   - **Inspection:** Both config docs state that a transform domain covering 
every cluster key, such as bucket(n, id) under a clustering on id, needs the 
subset permission and not the V2 co-partition setting off, matching the rule's 
keyed subset gate and the plan-level test that requires the permission for such 
a domain.



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