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


##########
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:
   Thanks, the replay does keep union sites that the failed keyed target is not 
paired with, as 'a failed keyed target reverts only its own site' shows. It 
does not cover every case this comment raised, though. This review raises the 
remaining one as a new finding: when a keyed target ranked first fails to pair, 
union sites that an ancestor join pairs, and the two union inputs of one join, 
still lose the shared hash target the base branch gives them, so both unions 
keep their exchanges.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4595431977","thread_id":"inline:4595431977","verdict_sha256":"11ee99395c806c5ac28825825f0d70d6fa71dc6c7b46db5a0e7c329cfe1056cc"}
 -->



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/PushDownShuffleExchangeThroughUnion.scala:
##########
@@ -201,27 +251,59 @@ case class PushDownShuffleExchangeThroughUnion(
       satisfied && !candidate.exists(node => 
!PartitioningOrigin.validateNode(node))
     }
 
-    val pushed = rewrite(preferRemovedLayout = false)
+    val (pushed, sites, usedRemovedLayout) = rewrite(removedLayoutSites = 
Set.empty, sites = None)
+
+    /**
+     * The rule's fallback without keyed targets: retry the whole plan on the 
layouts of the
+     * exchanges it removes, which every ancestor was planned against. The 
retry cannot help while
+     * every target the proposal adopted is such a layout already.
+     */
+    def retryOnRemovedLayouts(): SparkPlan = {
+      if (usedRemovedLayout) {
+        plan
+      } else {
+        val (retried, _, _) = rewrite(removedLayoutSites = sites, sites = None)
+        if (retried.fastEquals(plan) || !accepted(retried)) plan else retried
+      }
+    }
+
     if (pushed.fastEquals(plan)) {
       plan
     } else if (accepted(pushed)) {
       pushed
-    } else if (usedRemovedLayout) {
-      // Every site already used the layout of the exchange this rewrite 
removes, so the retry
-      // would rebuild the same proposal and fail again.
-      plan
-    } else {
-      // A target can satisfy the consumer and the fixed siblings yet break an 
ancestor, such as
-      // a join that pairs this branch with a different partition count. Retry 
once on the removed
-      // exchange's own layout, which every ancestor was planned against.
-      val retried = rewrite(preferRemovedLayout = true)
-      if (retried.fastEquals(plan)) {
-        plan
-      } else if (accepted(retried)) {
-        retried
+    } else if 
(conf.getConf(SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_PARTIAL_REPLAY_ENABLED)) {
+      // The whole plan rejected the proposal, which a keyed target can cause 
without its own
+      // site, or the sites it was planned against, seeing it. Replay the 
proposal one site at a
+      // time over the input plan, keeping a site only while the whole plan 
still holds; a site
+      // the whole plan rejects takes the layout of the exchange it removes 
instead.
+      var adopted = Set.empty[Int]
+      var onRemovedLayout = Set.empty[Int]
+      var bestPlan = plan
+      def adopt(index: Int, removedLayoutSites: Set[Int]): Boolean = {
+        val (candidate, _, _) = rewrite(removedLayoutSites, sites = 
Some(adopted + index))
+        if (!candidate.fastEquals(bestPlan) && accepted(candidate)) {
+          adopted += index
+          onRemovedLayout = removedLayoutSites
+          bestPlan = candidate
+          true
+        } else {
+          false
+        }
+      }
+      sites.toSeq.sorted.foreach { index =>
+        adopt(index, onRemovedLayout) || adopt(index, onRemovedLayout + index)

Review Comment:
   **Blocking (P1):** The replay changes one site at a time while every other 
site stays on its exchange, and a rejected site then tries only the layout of 
the exchange it removes. So a shared hash target that two paired sites must 
adopt together is never tried once a keyed target ranked first fails to pair, 
and the non-joint attempt after a failed joint attempt has the same gap.
   
   By my reading of the code: use the settings of the 
KeyGroupedPartitioningSuite withReplay helper plus maxTargetPartitionNumFactor 
2.0, and take two windows joined by a merge join, each over a requirement 
exchange hash(id, 2). The left union is a table bucketed by identity(id) with 
keys {1, 2, 3}, a /*+ REPARTITION(3, id) */ leg and a VALUES leg; the right 
union is a /*+ REPARTITION(3, id) */ leg and a VALUES leg. On the base branch 
neither union has a keyed candidate, so both take hash(id, 3), which lies 
within [2, 4], and the merge join pairs them. On this branch the keyed domain 
ties with hash(id, 3) at the left site and comes first, or wins on bytes, so 
the merge join gets a keyed layout against a hash one and the whole plan is 
rejected. In the replay, the left site alone fails against the right exchange's 
hash(id, 2) and has no hash(id, 2) child to fall back to, and the right site 
alone fails on hash(id, 3) against the left exchange's hash(id, 2) and has none 
either. Nothing i
 s adopted, and the retry on removed layouts changes nothing, with 
partialReplay on or off. The two union inputs of one join under allowJoinInputs 
end the same way: the right input cannot pair with the keyed left input, and 
the non-joint attempt pairs each input only with the other's hash(id, 2) 
exchange.
   
   Both unions then keep their exchanges, so every row of both is shuffled 
again, including the repartition legs, where the base branch lays out only the 
legs that do not offer the shared target. The extra work grows with the unions' 
rows; results are unchanged. The earlier comment on the keyed fallback named 
the join shape; the replay covers neither.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60553#discussion_r4595431977).
   
   **Recommended change:** Let each rewrite pass choose per site whether keyed 
targets are allowed, defaulting to today's policy. In pushDownThroughUnion, 
when the joint attempt fails after one of the inputs took a keyed target, rerun 
the joint attempt with a hash-only policy (keyed targets off, so a keyed 
requirement exchange is not a site, and every other setting unchanged) before 
the non-joint attempt. In apply, when the whole-plan check rejects a first pass 
in which a site took a keyed target, build the hash-only pass over the input 
plan. When that pass changes the plan and the check accepts it, start from it. 
With partialReplay on, replay keyed choices on top of it one site at a time: a 
site the hash-only pass pushed down tries only its keyed target, if it has one, 
and a site it left on its exchange tries its own top target and then the layout 
of the exchange it removes; each is kept only while the whole plan still holds. 
With partialReplay off, return the accepted hash-only pas
 s, so the flag then turns off only the replays. When the hash-only pass 
changes nothing or is rejected, run the existing replay and retry over the 
input plan. Update the replay-off arm of the plan-level test 'a failed keyed 
target reverts only its own site', which today expects both exchanges to stay: 
the other site now keeps its own target there too. Rewrite the class doc's 
fallback paragraph and the partialReplay doc to describe this order, and add 
union push-down tests, at plan level and end to end over V2 bucketed tables, 
for two sites an ancestor join pairs on a shared hash target other than their 
removed exchanges and for a join with two union inputs that share one.
   
   **Why this works:** The hash-only attempt uses the base branch's policy, so 
at every site or join input it reproduces the base branch's choice. Running it 
where a keyed attempt failed means no site or join input ends with less 
push-down than the base branch gives it whenever that choice passes the check. 
The keyed replays on top of it still keep a keyed target wherever the whole 
plan accepts it, and never move a site the hash-only pass pushed down to the 
layout of the exchange it removes, which ranks below the target the base branch 
picks there. The exception is a nested shape: a keyed target kept at an inner 
site leaves a grouped layout that no longer routes by hash, which the enclosing 
site cannot take as its target, so that site can lose the push-down the 
hash-only pass gave it, as it does when the first proposal is accepted. When 
the hash-only pass changes nothing or is itself rejected, the base branch would 
also push nothing or fall to its retry, so the existing replay and re
 try run unchanged.
   
   **Scope:** Rework the union push-down's two failure fallbacks so that a 
failed keyed attempt falls back to the base branch's hash-only choice at the 
level that failed, keep keyed targets wherever the whole plan still accepts 
them, and cover the paired-site and two-input-join shapes with tests.
   
   **Compatibility:** Keyed targets that pass the whole-plan check are still 
adopted. With allowV2Bucketing off the rule plans as it does today, and with 
partialReplay off as well it plans exactly as on the base branch.
   
   **Risks:** A rejected keyed proposal now costs one more rewrite pass and 
whole-plan check, plus up to two keyed replay attempts per site, in every AQE 
planning round that rejects it; the work is planning-only and stays on the 
default-off push-down path. When the hash-only pass is accepted, a site whose 
keyed target the whole plan would accept only together with another site's 
keyed target keeps the hash-only choice, because the replay adds keyed choices 
one site at a time; outside nested shapes that plan is never worse than the 
base branch's. In a nested shape, a keyed target the replay keeps at an inner 
site leaves a grouped layout that an enclosing site cannot take as its target, 
so that enclosing site can lose the push-down the hash-only pass gave it, the 
same trade-off the first pass makes when it is accepted; whether to avoid it is 
the open question on nested union sites. With partialReplay off, a rejected 
keyed proposal now returns the accepted hash-only choice instead of go
 ing straight to the whole-plan retry, so that flag no longer brings back the 
loss of unrelated sites' push-downs. Turning both allowV2Bucketing and 
partialReplay off is what restores the base branch exactly, since with only 
allowV2Bucketing off a rejected hash-only proposal still goes to the replay.
   
   **Constraints:** The hash-only attempt must use exactly the base branch's 
policy, with every other setting unchanged and per-pass state such as hasPushed 
and usedRemovedLayout reset. Site indices must keep coming from the input 
plan's traversal, so a site's choice names the same operator in every pass. The 
rewritten fallback docs describe each step by what it does, without referring 
to the rule before this change.
   
   **Exclusions:**
   - Attributing a whole-plan failure to the site that caused it is left out, 
because the whole-plan check does not report which site failed.
   - The costs nested union sites pay, raised as separate questions to the 
author, are left to those answers; this repair adds no look-ahead across nested 
sites, including in the keyed replays it runs on top of the hash-only pass.
   
   **Success:** When the whole-plan check rejects a pass in which a site took a 
keyed target but accepts the base branch's hash-only choice, every site and 
join input keeps at least the push-down that choice gives it, with 
partialReplay on or off, except an enclosing site whose only target a keyed 
target kept at a site it contains removes, which the open question on nested 
union sites covers. When an operator's joint attempt fails after one of its 
inputs took a keyed target, two union inputs that share a hash target other 
than their removed layouts both keep it. Keyed targets at sites the failure 
does not involve are still kept when the whole plan accepts them, as in the 
PR's existing replay tests. With allowV2Bucketing off, and for plans whose 
keyed attempts pass the check, plans are unchanged.
   
   **Verification:**
   - **Regression:** Two windows over unions joined by a merge join, each with 
a fixed-count repartition leg that offers a shared hash target other than the 
layout of the exchange it removes, one of them also with a keyed table that 
ranks first, push both unions down on the shared target as the base branch 
does, with the replay on and off, and return the same rows.
   - **Regression:** A shuffled join with join inputs allowed and two union 
inputs, one of them with a keyed leg that ranks first, whose base-branch joint 
attempt adopts a shared hash target other than the removed layouts, gives both 
inputs that target and returns the same rows.
   - **Compatibility:** The PR's end-to-end keyed shapes and replay cases, 
including the keyed site kept beside a hash site and the rejected site that 
takes the layout it removes, keep their current plans and shuffle counts; plans 
with allowV2Bucketing off keep their current plans, and with partialReplay off 
as well they match the base branch. The one changed expectation is the 
replay-off arm of the plan-level case where a failed keyed target reverts only 
its own site, in which the other site now keeps its own target as it does with 
the replay on.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/adaptive/PushDownShuffleExchangeThroughUnionSuite.scala:
##########
@@ -201,6 +213,38 @@ class PushDownShuffleExchangeThroughUnionSuite extends 
QueryTest with SharedSpar
       spark.sql(sql).collect().toSeq
     }
 
+  test("SPARK-61785: a query on the defaults keeps its shuffle") {
+    // The suite opens every opt-in for the rest of its tests. Here each goes 
back to its declared
+    // default, with only AQE turned on, so flipping a default changes this 
plan and the answer.

Review Comment:
   **Nit (P3):** Three defaults each keep this query's union shuffle on their 
own, so no single flip changes the plan. The rule's flag at its default stops 
the rule. allowJoinInputs at its default leaves the MERGE-hinted join 
untouched. And with coalescing on, which this test leaves at its default, and 
keepNonCoalescibleBranches off, the fixed-count repartition leg cannot supply a 
target, because both join inputs reach an exchange. By my reading of the code, 
turning on the rule's flag, the join-input permission, or both still leaves 
numShufflesOnUnion(initial) at 1. The answer check cannot move either, since 
the push-down keeps results and expectedResult runs with it off. So the test 
pins none of the defaults it lists, including the rule's own default-off state.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60553#discussion_r4595432011).
   
   **Verification:**
   - **Regression:** Under the declared defaults the query keeps its union 
shuffle, and turning on only the rule's own flag removes it, so the test fails 
if that default flips.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/PushDownShuffleExchangeThroughUnion.scala:
##########
@@ -240,56 +322,77 @@ 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 marked leg is offered only when the union can merge it: it has to 
declare the target's

Review Comment:
   **Nit (P3):** This member has no target and filters nothing: every keepable 
keyed child offers its layout here, marked or not, so a marked leg whose key 
order differs from another marked leg's can itself become the target. The 
marked-leg check runs in reportsDomain(kept = true), when candidateTargets 
works out which legs each target keeps. reportsDomain's doc has a related 
problem: it justifies the allowed unknown-keys difference with 'the child the 
target came from declares every key it holds', which is false when a 
hash-routed child supplies the target, as 'a hash-routed keyed child supplies 
the target' shows and rebuildUnion's own comment says. A maintainer who trusts 
these docs looks for the rule in the wrong member and reads a reason that does 
not hold for every target.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60553#discussion_r4595432001).
   
   **Verification:**
   - **Inspection:** The layouts doc says every keepable keyed child offers its 
layout and that reportsDomain decides which legs are kept beside a target, and 
reportsDomain's reason for allowing a different unknown-keys state holds for a 
target that a hash-routed child supplies.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -9001,26 +9001,39 @@ object SQLConf {
   val PUSH_DOWN_SHUFFLE_THROUGH_UNION_ENABLED =
     buildConf("spark.sql.adaptive.pushDownShuffleThroughUnion.enabled")
       .internal()
-      .doc("When true, pushes an EnsureRequirements hash shuffle below a union 
during AQE " +
-        "query stage preparation. Eligible children already reporting the 
selected layout " +
-        "are retained; other children are retargeted or receive a new 
exchange. The target " +
-        "partition count must be at least the smaller of the replaced 
exchange's count and " +
-        "the effective initial shuffle count, including " +
-        s"${COALESCE_PARTITIONS_INITIAL_PARTITION_NUM.key} when set, and at 
most a bounded " +
-        "multiple of the larger of the two. Requires " +
-        s"${UNION_OUTPUT_PARTITIONING.key} to be enabled. Removing the union's 
direct shuffle " +
-        "stage can reduce AQE skew handling and join conversion opportunities. 
Retaining a " +
-        "shuffled join's layout can make skew optimization or local reads 
violate ancestor " +
-        "requirements; AQE may reject the optimization or add a shuffle when 
skew optimization " +
-        "is forced. Join inputs and join branches are opt-in. Cost 
compensation applies only " +
-        "to SimpleCostEvaluator. Custom evaluators should account for one 
union exchange " +
-        "becoming multiple branch exchanges; otherwise AQE may reject a 
re-plan and its other " +
-        "runtime optimizations due to the increased exchange count.")
+      .doc("When true, pushes an EnsureRequirements shuffle below a union 
during AQE query " +
+        "stage preparation. The shuffle and the target are hash or V2 keyed 
layouts. Children " +

Review Comment:
   **Nit (P3):** 'Children already reporting the target keep their layouts' 
drops the base doc's 'Eligible'. Only children that pass keepableLayout can 
keep a layout, and rebuildUnion gives every other child an exchange, even one 
that already reports the target. With coalescing on and 
keepNonCoalescibleBranches off, for example, a /*+ REPARTITION(n, id) */ leg 
beside an aggregate leg already reports hash(id, n), but as a fixed-count 
repartition it cannot be kept, so a second hash(id, n) shuffle is stacked on 
it. A shuffled-join branch without keepJoinBranches is laid out the same way. A 
user who reads this doc expects such a leg to keep its layout.
   
   **Verification:**
   - **Inspection:** The enabled config doc says that eligible children already 
reporting the target keep their layouts and that every other child, including 
an ineligible one that reports the target, is retargeted or given a new 
exchange.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/PushDownShuffleExchangeThroughUnion.scala:
##########
@@ -475,64 +582,154 @@ case class PushDownShuffleExchangeThroughUnion(
       }
 
     prepared.targets.view
-      .flatMap { target =>
-        rebuild(pushable.shuffle.child, target).map(child => (target, child))
+      .flatMap { case (target, offeredBy) =>
+        rebuild(pushable.shuffle.child, target, offeredBy).map(child => 
(target, child))
       }
       .map { case (target, child) =>
         (target, PartitioningOrigin.inherit(pushable.shuffle, child))
       }
-      .find { case (_, child) =>
+      // Keep a rebuilt child only if it answers the required distribution as 
rebuilt and pairs with
+      // the siblings. A keyed target's admission as a shuffle template was 
settled with the
+      // candidates; what remains is the rule's own subset permission, which 
reads the rebuilt
+      // layout's specs.
+      .filter { case (target, child) =>
         val partitioning = child.outputPartitioning
         partitioning.satisfies(required) &&
           PartitioningCollection.specsForPairing(partitioning, 
required).exists { spec =>
-            spec.canCreatePartitioning && (policy.allowSubsetTargets || (spec 
match {
-              case hash: HashShuffleSpec =>
-                
required.areAllClusterKeysMatched(hash.partitioning.expressions)
-              case _ => false
-            }))
+            // A keyed target was admitted as a template already; any other 
target asks its spec.
+            (target.isInstanceOf[KeyedPartitioning] || 
spec.canCreatePartitioning) &&
+              (policy.allowSubsetTargets || (spec match {
+                case hash: HashShuffleSpec =>
+                  
required.areAllClusterKeysMatched(hash.partitioning.expressions)
+                case keyed: KeyedShuffleSpec =>
+                  required.allClusterKeysAmong(keyed.partitioning.expressions)

Review Comment:
   **Nit (P3):** This arm extends allowPartitionKeysSubsetOfClusterKeys to 
keyed targets, but that config's doc, which this PR leaves unchanged, still 
describes hash targets only. allClusterKeysAmong compares by semanticEquals, so 
a transform domain such as bucket(n, id) needs the permission even when it 
covers every clustering key, while the doc says a target that matches all 
clustering keys needs nothing. A keyed target naming part of the clustering 
keys is admitted through 
spark.sql.sources.v2.bucketing.requireAllClusterKeysForCoPartition.enabled, 
which only defaults to spark.sql.requireAllClusterKeysForCoPartition, the one 
setting the doc names. Users who look this permission up for V2 bucketed tables 
are told neither; only the allowV2Bucketing doc gives the keyed conditions.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60553#discussion_r4595431983).
   
   **Verification:**
   - **Inspection:** The subset permission's doc states that a keyed transform 
target needs the permission even when it covers every clustering key and that a 
keyed target naming part of the clustering keys also needs the V2 co-partition 
setting off, consistent with the allowV2Bucketing doc and with the rule's keyed 
subset gate, while its hash-target wording stays as it is.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/PushDownShuffleExchangeThroughUnion.scala:
##########
@@ -201,27 +251,59 @@ case class PushDownShuffleExchangeThroughUnion(
       satisfied && !candidate.exists(node => 
!PartitioningOrigin.validateNode(node))
     }
 
-    val pushed = rewrite(preferRemovedLayout = false)
+    val (pushed, sites, usedRemovedLayout) = rewrite(removedLayoutSites = 
Set.empty, sites = None)
+
+    /**
+     * The rule's fallback without keyed targets: retry the whole plan on the 
layouts of the

Review Comment:
   **Nit (P3):** This retry is not limited to plans without keyed targets: it 
is the whole fallback when partialReplay is off, it runs after an empty replay 
in any plan, and its restriction also matches a keyed removed layout. The 
comment before its call ('stays as the fallback the rule has without keyed 
targets') says the same thing. In 'a failed keyed target reverts only its own 
site', a comment and an assertion message say the other site keeps 'the 
push-down the base branch gives it', which has no referent once this change 
lands. Describing each by what it does, such as the whole-plan retry on the 
layouts of the removed exchanges, or the other site keeping its own target 
hash(b1, 3), keeps them true after the merge.
   
   **Verification:**
   - **Inspection:** No comment or assertion message in the rule or its 
plan-level suite calls the whole-plan retry the fallback without keyed targets 
or refers to the base branch, and the retry's doc describes when it runs in 
terms that hold whichever fallbacks precede it.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/PushDownShuffleExchangeThroughUnion.scala:
##########
@@ -142,47 +173,66 @@ case class PushDownShuffleExchangeThroughUnion(
     lazy val sharedExchanges: Set[SparkPlan] =
       if (conf.exchangeReuseEnabled) AQEUtils.duplicatedShuffleForms(plan) 
else Set.empty
 
-    // Whether every adopted target is the layout of the exchange this rewrite 
removes. The retry
-    // cannot help while this holds.
-    var usedRemovedLayout = true
-    // Whether an earlier site in this pass has rewritten the plan. Until then 
its layouts are the
-    // ones preparation produced and can be read without checking.
-    var hasPushed = false
-    def rewrite(preferRemovedLayout: Boolean): SparkPlan = {
-      hasPushed = false
-      plan.transformUp {
+    /**
+     * One pass over the plan. `sites` restricts the rewrite to the operators 
it names, by their
+     * index in this pass's traversal; `None` rewrites every site. A site 
named by
+     * `removedLayoutSites` may adopt only the layout of the exchange it 
removes. Returns the
+     * rewritten plan, the indices of the sites the pass saw, including one it 
could not act on
+     * because an earlier change left its child invalid, and whether every 
target it adopted is
+     * the layout of the exchange it removes.
+     */
+    def rewrite(
+        removedLayoutSites: Set[Int],
+        sites: Option[Set[Int]]): (SparkPlan, Set[Int], Boolean) = {
+      // Whether an earlier site in this pass has rewritten the plan. Until 
then its layouts are
+      // the ones preparation produced and can be read without checking.
+      var hasPushed = false
+      // Whether every target this pass adopts is the layout of the exchange 
it removes.
+      var usedRemovedLayout = true
+      var index = -1
+      val candidateSites = mutable.Set.empty[Int]
+      val rewritten = plan.transformUp {
         case join: ShuffledJoin if !allowJoinInputs => join
         case operator: SparkPlan =>
-          val matched = operator.children.map { child =>
-            findPushableShuffle(child, lookThrough, policy)
-          }
+          index += 1
+          val matched =
+            if (sites.forall(_.contains(index))) {
+              operator.children.map(child => findPushableShuffle(child, 
lookThrough, policy))
+            } else {
+              Nil
+            }
           if (matched.forall(_.isEmpty)) {
             operator
           } else {
             // Read requirements only after finding a site; some operators log 
when asked.
             val required = operator.requiredChildDistribution
             if (!required.forall(_.isInstanceOf[ClusteredDistribution])) {
               operator
-            } else if (hasPushed && operator.children.exists(child =>
-                !ValidateRequirements.validate(child))) {
-              // An earlier site in this pass can leave a child invalid; its 
layout cannot be read.
-              operator
             } else {
-              val requirements = 
required.map(_.asInstanceOf[ClusteredDistribution])
-              val (candidate, operatorUsedRemovedLayout) = 
pushDownThroughUnion(
-                operator,
-                matched.zip(requirements),
-                sharedExchangesFunc = sharedExchanges,
-                policy = policy.copy(
-                  allowNonCoalescible =
-                    policy.allowNonCoalescible || !allExchangeInputs(operator),
-                  preferRemovedLayout = preferRemovedLayout))
-              usedRemovedLayout = usedRemovedLayout && 
operatorUsedRemovedLayout
-              hasPushed = hasPushed || (candidate ne operator)
-              candidate
+              candidateSites += index

Review Comment:
   **Nit (P3):** Recording the site here, before the invalid-child skip, is 
what lets the replay take a site the first pass could not act on, but no test 
fails if this line moves into the branch that calls pushDownThroughUnion. In 
'an invalid fixed sibling is not read during pairing' the replay adopts nothing 
else, so the whole-plan retry runs and pushes the outer site down anyway; in 
'an inner rewrite leaves no unreadable layout for an outer site' the outer site 
has no viable target either way. Adding an unrelated site that the replay 
adopts on a target other than its removed layout keeps the retry from running, 
so the skipped outer site is then pushed down only if the replay recorded it.
   
   **Verification:**
   - **Regression:** In a plan where an earlier push leaves a later site's 
child invalid and the replay adopts another site on a layout other than the one 
it removes, the skipped site is pushed down on its own, so recording only the 
sites a pass acts on fails the test.



##########
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:
   Thanks, the allowV2Bucketing doc now covers transform domains. The 
allowPartitionKeysSubsetOfClusterKeys doc, which this comment also asked about, 
is unchanged and still describes only hash targets, so this review raises that 
again as a small follow-up.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4595431983","thread_id":"inline:4595431983","verdict_sha256":"11ee99395c806c5ac28825825f0d70d6fa71dc6c7b46db5a0e7c329cfe1056cc"}
 -->



##########
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:
   Thanks, the allowV2Bucketing doc now states the condition correctly. The two 
code comments this comment also mentioned still say a keyed source is kept only 
with the coalescing opt-in or with coalescing off: the class doc ('keeping it 
needs that opt-in or coalescing off') and the comment above LayoutPolicy. Could 
you make those conditional on every consumer input reaching an exchange too, as 
the config docs now are?
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4595431988","thread_id":"inline:4595431988","verdict_sha256":"11ee99395c806c5ac28825825f0d70d6fa71dc6c7b46db5a0e7c329cfe1056cc"}
 -->



##########
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:
   Thanks, the doc now says a mismatched marked leg is laid out rather than 
left as it was. The new sentence still says such a leg is not offered, though: 
the layouts member offers every keepable keyed layout, marked or not, and 
reportsDomain only decides which legs are kept beside a given target, so a 
mismatched marked leg can still become the target itself. This review raises 
that, with a related misstatement in reportsDomain's doc, as a small follow-up.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4595432001","thread_id":"inline:4595432001","verdict_sha256":"11ee99395c806c5ac28825825f0d70d6fa71dc6c7b46db5a0e7c329cfe1056cc"}
 -->



##########
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:
   Thanks, the settings now go back to their declared defaults. The query is 
unchanged, though, and three defaults each keep the union's shuffle on their 
own: the rule's flag, the join-input permission, and partition coalescing, 
which stays on. So flipping the rule's own default would not change the plan, 
and the new comment's claim that a default flip changes the plan and the answer 
does not hold yet; this review raises that again with the details.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4595432011","thread_id":"inline:4595432011","verdict_sha256":"11ee99395c806c5ac28825825f0d70d6fa71dc6c7b46db5a0e7c329cfe1056cc"}
 -->



##########
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:
   Thanks, with keyed_big second only the byte ranking can pick it now. The 
second case this comment asked for is still missing: no test has a subset leg 
whose bytes decide which domain wins, so a ranking that stopped counting subset 
legs toward the domain that keeps them would pass every suite. Could you add 
one that lists first a domain whose own leg is bigger and gives the other 
domain a subset leg large enough that only its bytes let that domain win?
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4595432014","thread_id":"inline:4595432014","verdict_sha256":"11ee99395c806c5ac28825825f0d70d6fa71dc6c7b46db5a0e7c329cfe1056cc"}
 -->



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