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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -9001,26 +9001,44 @@ 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. Eligible " +
+        "children already reporting the target keep their layouts; every other 
child, " +

Review Comment:
   **Nit (P3):** Now that this sentence covers V2 keyed targets, 'every other 
child ... is retargeted or given a new exchange' no longer holds for them: 
under a keyed target `rebuildUnion` keeps every child that `reportsDomain(kept 
= true)` accepts, which includes an unmarked child whose keys are a subset of 
the target's, in any order, and a marked child that declares the target's key 
list in the same order and still routes by hash. Neither reports the target. 
For example, in a union of `identity(id)` scans with keys {1, 2, 3} and {1, 2} 
plus a `VALUES` leg, the {1, 2} scan keeps its layout, as 'a child whose keys 
are a subset of the domain keeps its layout' asserts. Saying that under a keyed 
target the eligible children on its domain keep their layouts too, as the 
`allowV2Bucketing` doc describes, and keeping 'every other child' for the rest, 
would match the rule.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60553#discussion_r4600231301).
   
   **Verification:**
   - **Inspection:** The enable doc's keep rule, read for a V2 keyed target, 
keeps exactly the children the rule keeps: those reporting the target, unmarked 
children holding a subset of its keys, and marked children that declare its key 
list in the same order and still route by hash.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/PushDownShuffleExchangeThroughUnion.scala:
##########
@@ -65,27 +68,48 @@ import org.apache.spark.sql.internal.SQLConf
  * gate exists: the child is then shuffled before the reduction, which can 
send more data than the
  * one shuffle it replaces.
  *
- * Targets are hash layouts reported by the union's children, ranked by how 
many children offer
- * them when size estimates are unavailable; otherwise estimated bytes kept 
decide first. The
- * count must be between the smaller and the larger of the replaced exchange's 
count and the
- * effective initial shuffle partition count 
(`coalescePartitions.initialPartitionNum` when set);
- * the larger side is scaled by `maxTargetPartitionNumFactor`. A branch that 
is already a query
- * stage pins the target to the layout it reports, unless its stage wraps an 
unmarked user
+ * Targets are eligible hash or keyed layouts reported by the union's 
children, ranked by how many
+ * children offer them when size estimates are unavailable; otherwise 
estimated bytes kept decide
+ * first. The count must be between the smaller and the larger of the replaced 
exchange's count
+ * and the effective initial shuffle partition count 
(`coalescePartitions.initialPartitionNum`
+ * when set); the larger side is scaled by `maxTargetPartitionNumFactor`. A 
branch that is already
+ * a query stage pins the target to the layout it reports, unless its stage 
wraps an unmarked user
  * repartition: the rewrite could only stack on such a branch, and a re-plan 
must be able to
  * repeat that. At least one child keeps its layout; others are retargeted or 
shuffled without
  * changing child order.
  * `spark.sql.adaptive.pushDownShuffleThroughUnion.maxMovedBranches` limits 
moved children, and
  * `maxUnionChildren` limits all branches whose tails run within each consumer 
task.
- * The rebuilt child must satisfy its consumer's distribution and pair with 
fixed siblings.
+ * The rebuilt child must satisfy its consumer's distribution and pair with 
the siblings.
+ *
+ * A V2 keyed target additionally requires
+ * `spark.sql.adaptive.pushDownShuffleThroughUnion.allowV2Bucketing.enabled`, 
which the V2
+ * bucketing configs further gate, and `spark.sql.unionOutputPartitioning`, 
since the union has

Review Comment:
   **Nit (P3):** This sentence presents `spark.sql.unionOutputPartitioning` as 
something only a keyed target needs, but the setting gates the whole rule: 
`AdaptiveSparkPlanExec` computes the rule's enablement as 
`unionConf.outputPartitioning && conf.pushDownShuffleThroughUnionEnabled && 
...` (AdaptiveSparkPlanExec.scala:120-124), and `apply` returns its input when 
that is false, whatever the target. A maintainer reading the class doc would 
conclude that hash push-down works with the setting off. The comment in 
'SPARK-61785: regroup V2 union domains instead of shuffling all rows' 
(KeyGroupedPartitioningSuite.scala:800-802) repeats this: it explains the 
setting by what the rebuilt union reports with it off, although with it off the 
rule never runs. The enable config's doc already states the requirement for the 
whole rule; saying it the same way here, keeping only `allowV2Bucketing` and 
the V2 bucketing settings as what a keyed target adds, and saying in that test 
comment that the rule 
 does not run with the setting off, would make them agree.
   
   **Verification:**
   - **Inspection:** The class doc states spark.sql.unionOutputPartitioning as 
a requirement of the whole rule, matching the enablement AdaptiveSparkPlanExec 
computes, and the end-to-end comment says the rule does not run with it off.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/adaptive/PushDownShuffleExchangeThroughUnionSuite.scala:
##########
@@ -201,6 +214,41 @@ class PushDownShuffleExchangeThroughUnionSuite extends 
QueryTest with SharedSpar
       spark.sql(sql).collect().toSeq
     }
 
+  test("SPARK-61785: the rule's default keeps the union's shuffle") {
+    // The suite opens every opt-in for the rest of its tests. Here the rule 
goes back to its
+    // declared default, which keeps the union's shuffle. The query needs no 
other opt-in: the
+    // second leg takes a column repartition hint, so turning only the rule on 
removes the
+    // shuffle, and flipping the rule's own default fails this test.

Review Comment:
   **Nit (P3):** The query puts `/*+ REPARTITION(id) */` on the first leg, the 
one reading `t1`; the second leg, `SELECT id, v FROM t2`, has no hint, so the 
comment points at the wrong child as the one whose layout supplies the target.
   
   ```suggestion
       // declared default, which keeps the union's shuffle. The query needs no 
other opt-in: the
       // first leg takes a column repartition hint, so turning only the rule 
on removes the
   ```
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60553#discussion_r4600231289).
   
   **Verification:**
   - **Inspection:** The defaults test's comment names the leg reading t1 as 
the one with the column repartition hint, matching its query.



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/KeyGroupedPartitioningSuite.scala:
##########
@@ -721,6 +781,1136 @@ 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 planner lays the right side's bucket(2, id) layout out on the 
left side's
+      // identity(id) domain {1, 2}, which marks the laid-out layout: rows of 
a key the domain
+      // does not declare, such as key 3, were routed by hash. A right outer 
join reports its
+      // right side, 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: one pass keeps a keyed site beside a hash site") {
+    withReplay {
+      createTable("one_pass_keyed", columns, Array(Expressions.identity("id")))
+      createTable("one_pass_plain", columns, Array.empty[Transform])
+      sql("INSERT INTO testcat.ns.one_pass_keyed VALUES " +
+        "(1, 'a', timestamp'2022-01-01'), (2, 'c', timestamp'2022-01-02')")
+      sql("INSERT INTO testcat.ns.one_pass_plain VALUES " +
+        "(1, 'b', timestamp'2022-01-03'), (2, 'd', timestamp'2022-01-04')")
+      // Two independent sites: the first keeps its keyed scan, the second 
keeps a repartition
+      // and lays its values leg out on that layout.
+      val query =
+        """SELECT id, data, rn FROM (
+          |  SELECT id, data, row_number() OVER (PARTITION BY id ORDER BY 
data) rn FROM (
+          |    SELECT id, data FROM testcat.ns.one_pass_keyed
+          |    UNION ALL SELECT * FROM VALUES (1, 'v') AS v(id, data))
+          |  UNION ALL
+          |  SELECT id, data, row_number() OVER (PARTITION BY id ORDER BY 
data) rn FROM (
+          |    SELECT /*+ REPARTITION(2, id) */ id, data FROM 
testcat.ns.one_pass_plain
+          |    UNION ALL SELECT * FROM VALUES (2, 'w') AS w(id, data))
+          |)""".stripMargin
+      val expected = Seq(Row(1, "a", 1), Row(1, "v", 2), Row(2, "c", 1), 
Row(1, "b", 1),
+        Row(2, "d", 1), Row(2, "w", 2))
+      def check(plan: SparkPlan): Unit = {
+        assert(satisfiesRequirements(plan), s"invalid plan:\n$plan")
+        // The keyed site lays its values leg out; the hash site keeps its 
repartition and lays
+        // the other leg out.
+        assert(exchangeKinds(plan) === (1, 1, 1), s"unexpected shuffle 
kinds:\n$plan")
+        assert(hasGroupedUnion(plan), s"expected a grouped keyed 
union:\n$plan")
+        val unions = collect(plan) { case u: UnionExec => u }
+        
assert(unions.exists(_.outputPartitioning.isInstanceOf[physical.KeyedPartitioning]),
+          s"expected a keyed union:\n$plan")
+        
assert(unions.exists(_.outputPartitioning.isInstanceOf[physical.HashPartitioning]),
+          s"expected a hash union:\n$plan")
+      }
+      val df = sql(query)
+      checkAnswer(df, expected)
+      check(df.queryExecution.executedPlan)
+      // The proposal holds, so no fallback runs and the replay switch cannot 
apply.
+      
withSQLConf(SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_PARTIAL_REPLAY_ENABLED.key 
-> "false") {
+        val unreplayed = sql(query)
+        checkAnswer(unreplayed, expected)
+        check(unreplayed.queryExecution.executedPlan)
+      }
+    }
+  }
+
+  test("SPARK-61785: the replay keeps a keyed site beside a hash site") {
+    withReplay {
+      createTable("replay_a", columns, Array(Expressions.identity("id")))
+      createTable("replay_pa", columns, Array.empty[Transform])
+      createTable("replay_b", columns, Array(Expressions.identity("id")))
+      createTable("replay_pc", columns, Array.empty[Transform])
+      sql("INSERT INTO testcat.ns.replay_a VALUES " +
+        "(1, 'a', timestamp'2022-01-01'), (2, 'c', timestamp'2022-01-02')")
+      sql("INSERT INTO testcat.ns.replay_pa VALUES (1, 'p', 
timestamp'2022-01-03')")
+      sql("INSERT INTO testcat.ns.replay_b VALUES " +
+        "(2, 'b', timestamp'2022-01-04'), (3, 'e', timestamp'2022-01-05')")
+      sql("INSERT INTO testcat.ns.replay_pc VALUES (1, 'q', 
timestamp'2022-01-06')")
+      // The first site's keyed target cannot pair with its join partner, so 
the whole plan
+      // rejects the first pass. The replay keeps the other two sites: one 
keyed, one hash.
+      val df = sql(
+        """SELECT id, data, rn FROM (
+          |  SELECT /*+ MERGE(u, p) */ u.id, u.data, u.rn FROM (
+          |    SELECT id, data, row_number() OVER (PARTITION BY id ORDER BY 
data) rn FROM (
+          |      SELECT id, data FROM testcat.ns.replay_a
+          |      UNION ALL SELECT * FROM VALUES (1, 'x') AS v(id, data))) u
+          |  JOIN (SELECT /*+ REPARTITION(2, id) */ id, data FROM 
testcat.ns.replay_pa) p
+          |    ON u.id = p.id
+          |  UNION ALL
+          |  SELECT id, data, row_number() OVER (PARTITION BY id ORDER BY 
data) rn FROM (
+          |    SELECT id, data FROM testcat.ns.replay_b
+          |    UNION ALL SELECT * FROM VALUES (2, 'y') AS w(id, data))
+          |  UNION ALL
+          |  SELECT id, data, row_number() OVER (PARTITION BY id ORDER BY 
data) rn FROM (
+          |    SELECT /*+ REPARTITION(2, id) */ id, data FROM 
testcat.ns.replay_pc
+          |    UNION ALL SELECT * FROM VALUES (1, 'z') AS q(id, data))
+          |)""".stripMargin)
+      checkAnswer(df, Seq(Row(1, "a", 1), Row(1, "x", 2), Row(2, "b", 1), 
Row(2, "y", 2),
+        Row(3, "e", 1), Row(1, "q", 1), Row(1, "z", 2)))
+      val plan = df.queryExecution.executedPlan
+      assert(satisfiesRequirements(plan), s"invalid plan:\n$plan")
+      // The rejected site keeps the exchange it came with; the other two keep 
their layouts.
+      assert(exchangesOverUnion(plan).size === 1, s"expected the rejected 
site's exchange:\n$plan")
+      assert(exchangeKinds(plan) === (1, 2, 2), s"unexpected shuffle 
kinds:\n$plan")
+      assert(hasGroupedUnion(plan), s"expected the kept keyed site:\n$plan")
+      val unions = collect(plan) { case u: UnionExec => u }
+      
assert(unions.exists(_.outputPartitioning.isInstanceOf[physical.HashPartitioning]),
+        s"expected the kept hash site:\n$plan")
+    }
+  }
+
+  test("SPARK-61785: the replay falls a site back to the layout it removes") {
+    withReplay {
+      createTable("fallback_a", columns, Array(Expressions.identity("id")))
+      createTable("fallback_pa", columns, Array.empty[Transform])
+      createTable("fallback_b", columns, Array(Expressions.identity("id")))
+      sql("INSERT INTO testcat.ns.fallback_a VALUES " +
+        "(1, 'a1', timestamp'2022-01-01'), (1, 'a2', timestamp'2022-01-02'), " 
+
+        "(2, 'c1', timestamp'2022-01-03'), (2, 'c2', timestamp'2022-01-04')")
+      sql("INSERT INTO testcat.ns.fallback_pa VALUES (1, 'p', 
timestamp'2022-01-05')")
+      sql("INSERT INTO testcat.ns.fallback_b VALUES " +
+        "(2, 'b', timestamp'2022-01-06'), (3, 'e', timestamp'2022-01-07')")
+      // The first site's keyed target outranks its repartition leg but cannot 
pair with the join
+      // partner, so the replay takes the layout of the exchange that site 
removes, which the
+      // repartition leg reports. The other site keeps its keyed target.
+      val df = sql(
+        """SELECT id, data, rn FROM (
+          |  SELECT /*+ MERGE(u, p) */ u.id, u.data, u.rn FROM (
+          |    SELECT id, data, row_number() OVER (PARTITION BY id ORDER BY 
data) rn FROM (
+          |      SELECT id, data FROM testcat.ns.fallback_a
+          |      UNION ALL SELECT /*+ REPARTITION(2, id) */ id, data FROM 
testcat.ns.fallback_pa
+          |      UNION ALL SELECT * FROM VALUES (1, 'x') AS v(id, data))) u
+          |  JOIN (SELECT /*+ REPARTITION(2, id) */ id, data FROM 
testcat.ns.fallback_pa) p
+          |    ON u.id = p.id
+          |  UNION ALL
+          |  SELECT id, data, row_number() OVER (PARTITION BY id ORDER BY 
data) rn FROM (
+          |    SELECT id, data FROM testcat.ns.fallback_b
+          |    UNION ALL SELECT * FROM VALUES (2, 'y') AS w(id, data))
+          |)""".stripMargin)
+      checkAnswer(df, Seq(Row(1, "a1", 1), Row(1, "a2", 2), Row(1, "p", 3), 
Row(1, "x", 4),
+        Row(2, "b", 1), Row(2, "y", 2), Row(3, "e", 1)))
+      val plan = df.queryExecution.executedPlan
+      assert(satisfiesRequirements(plan), s"invalid plan:\n$plan")
+      // Both sites are pushed down: neither keeps an exchange above its union.
+      assert(exchangesOverUnion(plan).isEmpty, s"expected both sites 
pushed:\n$plan")
+      assert(exchangeKinds(plan) === (1, 2, 2), s"unexpected shuffle 
kinds:\n$plan")
+      assert(hasGroupedUnion(plan), s"expected the keyed site:\n$plan")
+      val unions = collect(plan) { case u: UnionExec => u }
+      
assert(unions.exists(_.outputPartitioning.isInstanceOf[physical.HashPartitioning]),
+        s"expected the site on the layout it removes:\n$plan")
+    }
+  }
+
+  test("SPARK-61785: the replay leaves the rejected site alone") {
+    withReplay {
+      createTable("partial_a", columns, Array(Expressions.identity("id")))
+      createTable("partial_pa", columns, Array.empty[Transform])
+      createTable("partial_b", columns, Array(Expressions.identity("id")))
+      sql("INSERT INTO testcat.ns.partial_a VALUES " +
+        "(1, 'a', timestamp'2022-01-01'), (2, 'c', timestamp'2022-01-02')")
+      sql("INSERT INTO testcat.ns.partial_pa VALUES (1, 'p', 
timestamp'2022-01-03')")
+      sql("INSERT INTO testcat.ns.partial_b VALUES " +
+        "(2, 'b', timestamp'2022-01-04'), (3, 'e', timestamp'2022-01-05')")
+      // The first site's keyed target cannot pair with its join partner and 
has no other target,
+      // so the replay leaves it as it came; the second site keeps its keyed 
target.
+      val df = sql(
+        """SELECT id, data, rn FROM (
+          |  SELECT /*+ MERGE(u, p) */ u.id, u.data, u.rn FROM (
+          |    SELECT id, data, row_number() OVER (PARTITION BY id ORDER BY 
data) rn FROM (
+          |      SELECT id, data FROM testcat.ns.partial_a
+          |      UNION ALL SELECT * FROM VALUES (1, 'x') AS v(id, data))) u
+          |  JOIN (SELECT /*+ REPARTITION(2, id) */ id, data FROM 
testcat.ns.partial_pa) p
+          |    ON u.id = p.id
+          |  UNION ALL
+          |  SELECT id, data, row_number() OVER (PARTITION BY id ORDER BY 
data) rn FROM (
+          |    SELECT id, data FROM testcat.ns.partial_b
+          |    UNION ALL SELECT * FROM VALUES (2, 'y') AS w(id, data))
+          |)""".stripMargin)
+      checkAnswer(df, Seq(Row(1, "a", 1), Row(1, "x", 2), Row(2, "b", 1), 
Row(2, "y", 2),
+        Row(3, "e", 1)))
+      val plan = df.queryExecution.executedPlan
+      assert(satisfiesRequirements(plan), s"invalid plan:\n$plan")
+      // Only the rejected site keeps an exchange above its union; the other 
site is pushed down.
+      assert(exchangesOverUnion(plan).size === 1, s"expected one rejected 
site:\n$plan")
+      assert(exchangeKinds(plan) === (1, 1, 1), s"unexpected shuffle 
kinds:\n$plan")
+      assert(hasGroupedUnion(plan), s"expected the kept site:\n$plan")
+    }
+  }
+
+  test("SPARK-61785: two keyed sites that cannot pair keep the layouts they 
remove") {
+    withSQLConf(
+        
SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_MAX_TARGET_PARTITION_NUM_FACTOR.key -> 
"2.0") {
+      withReplay {
+        createTable("retry_a", columns, Array(Expressions.identity("id")))
+        createTable("retry_b", columns, Array(Expressions.identity("id")))
+        createTable("retry_plain", columns, Array.empty[Transform])
+        sql("INSERT INTO testcat.ns.retry_a VALUES " +
+          "(1, 'a1', timestamp'2022-01-01'), (1, 'a2', timestamp'2022-01-02'), 
" +
+          "(2, 'c1', timestamp'2022-01-03'), (2, 'c2', timestamp'2022-01-04')")
+        sql("INSERT INTO testcat.ns.retry_b VALUES " +
+          "(1, 'b1', timestamp'2022-01-05'), (2, 'd1', timestamp'2022-01-06'), 
" +
+          "(3, 'e1', timestamp'2022-01-07')")
+        sql("INSERT INTO testcat.ns.retry_plain VALUES (1, 'p1', 
timestamp'2022-01-08')")
+        // Both sides of the join are sites, with keyed targets of 2 and 3 
partitions: neither
+        // target pairs with the other side, so the whole plan rejects the 
first pass. The
+        // repartition legs report the layout of the exchange each site 
removes, so the replay
+        // pushes both unions down on it.
+        val query = """SELECT l.id, l.rn, r.rn FROM (
+          |  SELECT id, data, row_number() OVER (PARTITION BY id ORDER BY 
data) rn FROM (
+          |    SELECT id, data FROM testcat.ns.retry_a
+          |    UNION ALL SELECT /*+ REPARTITION(2, id) */ id, data FROM 
testcat.ns.retry_plain
+          |    UNION ALL SELECT * FROM VALUES (1, 'x') AS v(id, data))) l
+          |  JOIN (SELECT id, data, row_number() OVER (PARTITION BY id ORDER 
BY data) rn FROM (
+          |    SELECT id, data FROM testcat.ns.retry_b
+          |    UNION ALL SELECT /*+ REPARTITION(2, id) */ id, data FROM 
testcat.ns.retry_plain
+          |    UNION ALL SELECT * FROM VALUES (2, 'y') AS w(id, data))) r
+          |    ON l.id = r.id""".stripMargin
+        val expected = Seq(
+          Row(1, 1, 1), Row(1, 1, 2), Row(1, 2, 1), Row(1, 2, 2),
+          Row(1, 3, 1), Row(1, 3, 2), Row(1, 4, 1), Row(1, 4, 2),
+          Row(2, 1, 1), Row(2, 1, 2), Row(2, 2, 1), Row(2, 2, 2))
+        def check(plan: SparkPlan): Unit = {
+          assert(satisfiesRequirements(plan))
+          assert(!hasGroupedUnion(plan), s"no keyed target survives:\n$plan")
+          assert(exchangesOverUnion(plan).isEmpty, s"both sites are pushed 
down:\n$plan")
+          val unions = collect(plan) { case union: UnionExec => union }
+          assert(unions.length === 2)
+          assert(unions.forall(union =>
+            union.outputPartitioning.isInstanceOf[physical.HashPartitioning] &&
+              union.outputPartitioning.numPartitions === 2),
+            s"both unions take the layout they remove:\n$plan")
+          assert(exchangeKinds(plan) === (0, 4, 1), s"unexpected shuffle 
kinds:\n$plan")
+        }
+        val df = sql(query)
+        checkAnswer(df, expected)
+        check(df.queryExecution.executedPlan)
+        // With the replay off, the whole plan falls back to the retry on the 
layouts it removes,

Review Comment:
   **Nit (P3):** With the replay off, this query never reaches the whole-plan 
retry: the scans report `KeyedPartitioning`, so the rejected first pass goes to 
`hashOnlyPass`, which puts each union on the `hash(id, 2)` layout its 
`REPARTITION(2, id)` leg reports, the layout of the exchange it removes, and 
that plan is accepted and returned. With the replay on, `partialReplayKeyed` 
only retries the two keyed targets, which the join rejects, so the comment at 
lines 1131-1132 crediting the replay is off as well. The same holds for 'the 
replay falls a site back to the layout it removes' (lines 1048-1050, and its 
name): the hash-only pass lands its first site on `hash(id, 2)`, and the replay 
only adds the second site's keyed target. Separately, in 'paired sites keep the 
hash target they share' (lines 1184-1185) the left union has one leg that 
offers `hash(id, 3)`, the `REPARTITION(3, id)` one; the `VALUES` leg reports no 
layout. Crediting the hash-only pass in these comments, renaming the s
 econd test, and counting one leg would make them describe what the assertions 
exercise.
   
   **Verification:**
   - **Inspection:** Each of the three tests' comments, and the renamed test's 
name, attributes its asserted plan to the step that produces it, the hash-only 
pass for the sites on their removed layouts and the keyed replay for the other 
site's keyed target, and the paired-sites comment counts the legs that offer 
hash(id, 3) correctly.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/PushDownShuffleExchangeThroughUnion.scala:
##########
@@ -201,26 +272,130 @@ case class PushDownShuffleExchangeThroughUnion(
       satisfied && !candidate.exists(node => 
!PartitioningOrigin.validateNode(node))
     }
 
-    val pushed = rewrite(preferRemovedLayout = false)
+    val (pushed, usedRemovedLayout, candidateSites, _) =
+      rewrite(removedLayoutSites = Set.empty, rewriteSites = None, keyedSites 
= None)
+
+    /**
+     * The whole-plan retry on the layouts of the exchanges it removes, which 
every ancestor was
+     * planned against. The retry cannot help while every target a proposal 
adopted is such a
+     * layout already.
+     */
+    def retryOnRemovedLayouts(): SparkPlan = {
+      if (usedRemovedLayout) {
+        plan
+      } else {
+        val (retried, _, _, _) =
+          rewrite(removedLayoutSites = candidateSites, rewriteSites = None, 
keyedSites = None)
+        if (retried.fastEquals(plan) || !accepted(retried)) plan else retried
+      }
+    }
+
+    /**
+     * The plan of the base policy: keyed targets off, every other setting 
unchanged. A rejected
+     * keyed proposal falls back to it, so it keeps the push-down that policy 
gives every site,
+     * including ones that have to take one layout together, which a 
single-site replay cannot
+     * re-derive. `None` when keyed targets were never available, when the 
plan reports no keyed
+     * layout (so the first pass already is this pass), when the pass changes 
nothing, or when the
+     * whole plan rejects it too.
+     */
+    def hashOnlyPass(): Option[(SparkPlan, Set[Int])] = {
+      if (!policy.allowV2Bucketing ||
+          !plan.exists(_.outputPartitioning.isInstanceOf[KeyedPartitioning])) {

Review Comment:
   **Nit (P3):** This check skips the hash-only pass only when no node reports 
a keyed layout, but the pass can differ from the first pass only where a keyed 
choice changed a site's result: a site that matched a keyed requirement 
exchange, was offered a keyed child layout, or ran the in-pass joint retry. 
When the keyed layout belongs to, say, a V2 bucketed scan under an unrelated 
storage-partitioned join elsewhere in the plan, and a hash-only union site's 
top target breaks an ancestor join, every site sees the same children and 
targets: the pass rebuilds the rejected plan, which differs from the input, and 
`accepted()` rejects it again before `retryOnRemovedLayouts()` runs. That is 
one extra whole-plan rewrite and validation in each AQE round that rejects 
again, growing with the plan's size while changing no plan. The PR description 
gives the reason for the skip as the pass otherwise repeating the first pass, 
which applies here too, and the earlier suggestion this change implements r
 an the pass only after a site took a keyed target. Having the first pass 
report whether a site took a keyed target or rebuilt a child whose removed 
exchange is keyed, and running the pass only then, keeps the same plans; at 
minimum, skipping `accepted()` when the hash-only plan equals the rejected one 
removes the second validation.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60553#discussion_r4600231260).
   
   See **Shared repair plan 1** in the review body.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/PushDownShuffleExchangeThroughUnion.scala:
##########
@@ -390,51 +593,65 @@ case class PushDownShuffleExchangeThroughUnion(
       (if (movable) child else None, required)
     }
 
-    val newChildren = new ArrayBuffer[SparkPlan](children.length)
-    // Whether every target adopted by the attempt whose result is used is the 
layout of the
-    // exchange this rewrite removes. The retry cannot help while this holds.
+    // The plan at each child position as the attempt runs. A rewritten child 
replaces its own
+    // entry; a child not reached yet keeps the one it came with.
+    val newChildren = new Array[SparkPlan](children.length)
+    // Whether every target adopted by the attempt whose children are used is 
the layout of the
+    // exchange this site removes.
     var usedRemovedLayout = true
-    def rebuildChildren(joint: Boolean): Boolean = {
+    def rebuildChildren(
+        joint: Boolean,
+        sites: Seq[(Option[PreparedChild], ClusteredDistribution)],
+        sitePolicy: LayoutPolicy): Boolean = {
       // The joint attempt may have adopted another layout before failing on a 
sibling; only the
       // attempt whose children are used counts.
       usedRemovedLayout = true
-      newChildren.clear()
+      children.indices.foreach { position => newChildren(position) = 
children(position) }
       children.indices.forall { index =>
-        val (pushableChild, required) = movableSites(index)
-        val rebuilt = pushableChild.flatMap { child =>
+        val (preparedChild, required) = sites(index)
+        val rebuilt = preparedChild.flatMap { child =>
           val fixed = children.indices.flatMap { position =>
-            val (sibling, distribution) = movableSites(position)
+            val (sibling, distribution) = sites(position)
             Option.when(position != index && (!joint || position < index || 
sibling.isEmpty)) {
-              val fixedChild = if (position < index) {
-                newChildren(position)
-              } else {
-                children(position)
-              }
-              (fixedChild, distribution)
+              (newChildren(position), distribution)
             }
           }
-          rebuildChild(child, required, fixed, sharedExchanges, policy).map {
+          rebuildChild(child, required, fixed, sharedExchanges, 
sitePolicy).map {
             case (candidate, usesRemovedLayout) =>
               usedRemovedLayout = usedRemovedLayout && usesRemovedLayout
               candidate
           }
         }
-        if (joint && pushableChild.isDefined && rebuilt.isEmpty) {
-          false
-        } else {
-          newChildren += rebuilt.getOrElse(children(index))
-          true
+        rebuilt match {
+          case Some(candidate) =>
+            newChildren(index) = candidate
+            true
+          case None =>
+            !joint || preparedChild.isEmpty
         }
       }
     }
 
     // Joint selection lets later pushable siblings follow; the fallback fixes 
every sibling. A
     // single pushable child makes both attempts identical, so a failed joint 
attempt stays as is.
-    if (!rebuildChildren(joint = true)) {
+    if (!rebuildChildren(joint = true, movableSites, policy)) {
       if (movableSites.count(_._1.isDefined) <= 1) {
         return (operator, usedRemovedLayout)
       }
-      rebuildChildren(joint = false)
+      // Retry the joint attempt with keyed targets off. Without keyed targets 
the retry
+      // repeats the attempt that failed, so it only runs when keyed targets 
are available.
+      val recovered = policy.allowV2Bucketing && {

Review Comment:
   **Nit (P3):** This gate is broader than the comment above it says the retry 
needs. With keyed targets off, `PreparedChild.layouts` drops only the keyed 
child layouts, the hash targets keep their order (a keyed layout never counts 
as an offer for a hash target), and `keepableLayout`, `stagedIndices`, 
`rebuildChild` and `rebuildUnion` never read `allowV2Bucketing`. So the retry 
can differ from the failed attempt only when that attempt adopted a keyed 
target for an earlier input, or when a movable input removes a keyed exchange, 
which line 646 drops. Otherwise, as for a sort-merge join with join inputs 
allowed whose two inputs are hash exchanges over unions with no keyed child, 
the retry builds new `PreparedChild` instances, reruns `rebuildChild` over the 
same targets and fails at the same input before the per-input attempt runs. 
That duplicate planning work happens in every pass that allows keyed targets, 
including plans the whole-plan check accepts and pure-hash plans in sessions w
 ith V2 bucketing shuffles on, while the plans stay the same. Recording in 
`rebuildChildren` whether the failed attempt took a keyed target, and running 
the retry only then or when a movable input removes a keyed exchange, keeps the 
same plans; the earlier suggestion this change implements gated the retry that 
way.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60553#discussion_r4600231260).
   
   See **Shared repair plan 1** in the review body.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/PushDownShuffleExchangeThroughUnion.scala:
##########
@@ -201,26 +272,130 @@ case class PushDownShuffleExchangeThroughUnion(
       satisfied && !candidate.exists(node => 
!PartitioningOrigin.validateNode(node))
     }
 
-    val pushed = rewrite(preferRemovedLayout = false)
+    val (pushed, usedRemovedLayout, candidateSites, _) =
+      rewrite(removedLayoutSites = Set.empty, rewriteSites = None, keyedSites 
= None)
+
+    /**
+     * The whole-plan retry on the layouts of the exchanges it removes, which 
every ancestor was
+     * planned against. The retry cannot help while every target a proposal 
adopted is such a
+     * layout already.
+     */
+    def retryOnRemovedLayouts(): SparkPlan = {
+      if (usedRemovedLayout) {
+        plan
+      } else {
+        val (retried, _, _, _) =
+          rewrite(removedLayoutSites = candidateSites, rewriteSites = None, 
keyedSites = None)
+        if (retried.fastEquals(plan) || !accepted(retried)) plan else retried
+      }
+    }
+
+    /**
+     * The plan of the base policy: keyed targets off, every other setting 
unchanged. A rejected
+     * keyed proposal falls back to it, so it keeps the push-down that policy 
gives every site,
+     * including ones that have to take one layout together, which a 
single-site replay cannot
+     * re-derive. `None` when keyed targets were never available, when the 
plan reports no keyed
+     * layout (so the first pass already is this pass), when the pass changes 
nothing, or when the
+     * whole plan rejects it too.
+     */
+    def hashOnlyPass(): Option[(SparkPlan, Set[Int])] = {
+      if (!policy.allowV2Bucketing ||
+          !plan.exists(_.outputPartitioning.isInstanceOf[KeyedPartitioning])) {
+        None
+      } else {
+        val (hashOnly, _, _, hashOnlyPushed) =
+          rewrite(removedLayoutSites = Set.empty, rewriteSites = None,
+            keyedSites = Some(Set.empty))
+        Option.when(!hashOnly.fastEquals(plan) && accepted(hashOnly))(
+          (hashOnly, hashOnlyPushed))
+      }
+    }
+
+    /**
+     * Partially replay keyed targets one site at a time over the accepted 
hash-only plan. Every
+     * site is re-derived on each attempt, with keyed targets off outside 
`adopted` and the site
+     * being tried, so the other sites keep the base policy's choice. A site 
keeps a keyed target
+     * only while the whole plan holds; a site the hash-only pass left on its 
exchange may also
+     * take that exchange's layout, which the hash-only pass had no target 
for, and keeps it in
+     * the later attempts.
+     */
+    def partialReplayKeyed(hashOnly: SparkPlan, hashOnlySites: Set[Int]): 
SparkPlan = {
+      var adopted = Set.empty[Int]
+      var onRemovedLayout = Set.empty[Int]
+      var bestPlan = hashOnly
+      def adopt(index: Int, removedLayoutSites: Set[Int]): Boolean = {
+        val (candidate, _, _, _) = rewrite(
+          removedLayoutSites = removedLayoutSites,
+          rewriteSites = None,
+          keyedSites = Some(adopted + index))
+        if (!candidate.fastEquals(bestPlan) && accepted(candidate)) {
+          adopted += index
+          onRemovedLayout = removedLayoutSites
+          bestPlan = candidate
+          true
+        } else {
+          false
+        }
+      }
+      candidateSites.toSeq.sorted.foreach { index =>
+        adopt(index, onRemovedLayout) ||
+          (!hashOnlySites.contains(index) && adopt(index, onRemovedLayout + 
index))
+      }
+      bestPlan
+    }
+
+    /**
+     * Partially replay the proposal, with hash and keyed targets, over the 
input plan, for a
+     * hash-only pass that is unavailable, changes nothing, or fails: a site 
the whole plan
+     * rejects takes the layout of the exchange it removes, and a site no 
child can lay out keeps
+     * the exchange it came with.
+     */
+    def partialReplayHashAndKeyed(): SparkPlan = {
+      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,
+          rewriteSites = Some(adopted + index),
+          keyedSites = Some(adopted + index))
+        if (!candidate.fastEquals(bestPlan) && accepted(candidate)) {
+          adopted += index
+          onRemovedLayout = removedLayoutSites
+          bestPlan = candidate
+          true
+        } else {
+          false
+        }
+      }
+      candidateSites.toSeq.sorted.foreach { index =>
+        adopt(index, onRemovedLayout) || adopt(index, onRemovedLayout + index)

Review Comment:
   **Nit (P3):** By my reading of both suites, no test fails if this 
`adopt(index, onRemovedLayout + index)` attempt is dropped. The only replay-on 
tests that reach `partialReplayHashAndKeyed`, 'the replay visits a site the 
first pass skipped' and 'the replay leaves the rejected site alone', have no 
child offering the removed layout and settle by adopting another site. The 
tests written for this fallback offer the removed hash layout on a hash leg in 
a plan with a keyed layout, so the hash-only pass already puts the site there 
and the replay over the input plan never runs.
   
   Two neighboring steps have the same gap. With the replay off, nothing 
reaches `retryOnRemovedLayouts()` at line 398 after a hash-only pass that ran 
and left the retry something to adopt: 'a recorded repartition origin rejects a 
keyed target' reaches it with nothing to adopt, and the SPARK-60379 retry tests 
run with V2 bucketing shuffles off, where the hash-only pass never runs. In 
`partialReplayKeyed`, passing `Set.empty` instead of `onRemovedLayout` to later 
attempts (lines 333 and 341) changes no outcome either, because in 'the replay 
takes a keyed site's removed layout' the later site has no keyed option. A 
regression in any of these would silently lose push-downs the documented 
fallbacks give.
   
   Plan-level cases in which the hash-only pass cannot settle the plan would 
close the gap: the replay over a plan with no keyed layout putting a rejected 
site on its removed layout beside an unrelated site it keeps on another target; 
the replay off, with a keyed site and a hash site whose targets both break an 
ancestor, so only the retry lands the hash site on its removed layout; and, 
after a site takes its removed layout over an accepted hash-only plan, a later 
unrelated keyed site that keeps its target only because its attempt holds the 
earlier site there.
   
   **Verification:**
   - **Behavior:** With the replay on and no keyed layout in the plan, a site 
whose proposal breaks an ancestor ends on the layout of the exchange it removes 
while an unrelated site keeps its own target, and the rewritten plan satisfies 
every requirement.
   - **Regression:** With the replay off, a plan in which a keyed site's target 
and a hash site's top target both break an ancestor lands the hash site on its 
removed layout through the whole-plan retry after the hash-only pass is 
rejected.
   - **Regression:** With the replay on over an accepted hash-only plan, a 
later unrelated site keeps its keyed target after an earlier site took the 
layout of the exchange it removes, so passing an empty set of removed-layout 
sites to the later attempt fails the test.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/PushDownShuffleExchangeThroughUnion.scala:
##########
@@ -390,51 +593,65 @@ case class PushDownShuffleExchangeThroughUnion(
       (if (movable) child else None, required)
     }
 
-    val newChildren = new ArrayBuffer[SparkPlan](children.length)
-    // Whether every target adopted by the attempt whose result is used is the 
layout of the
-    // exchange this rewrite removes. The retry cannot help while this holds.
+    // The plan at each child position as the attempt runs. A rewritten child 
replaces its own
+    // entry; a child not reached yet keeps the one it came with.
+    val newChildren = new Array[SparkPlan](children.length)
+    // Whether every target adopted by the attempt whose children are used is 
the layout of the
+    // exchange this site removes.
     var usedRemovedLayout = true
-    def rebuildChildren(joint: Boolean): Boolean = {
+    def rebuildChildren(
+        joint: Boolean,
+        sites: Seq[(Option[PreparedChild], ClusteredDistribution)],
+        sitePolicy: LayoutPolicy): Boolean = {
       // The joint attempt may have adopted another layout before failing on a 
sibling; only the
       // attempt whose children are used counts.
       usedRemovedLayout = true
-      newChildren.clear()
+      children.indices.foreach { position => newChildren(position) = 
children(position) }
       children.indices.forall { index =>
-        val (pushableChild, required) = movableSites(index)
-        val rebuilt = pushableChild.flatMap { child =>
+        val (preparedChild, required) = sites(index)
+        val rebuilt = preparedChild.flatMap { child =>
           val fixed = children.indices.flatMap { position =>
-            val (sibling, distribution) = movableSites(position)
+            val (sibling, distribution) = sites(position)
             Option.when(position != index && (!joint || position < index || 
sibling.isEmpty)) {
-              val fixedChild = if (position < index) {
-                newChildren(position)
-              } else {
-                children(position)
-              }
-              (fixedChild, distribution)
+              (newChildren(position), distribution)
             }
           }
-          rebuildChild(child, required, fixed, sharedExchanges, policy).map {
+          rebuildChild(child, required, fixed, sharedExchanges, 
sitePolicy).map {
             case (candidate, usesRemovedLayout) =>
               usedRemovedLayout = usedRemovedLayout && usesRemovedLayout
               candidate
           }
         }
-        if (joint && pushableChild.isDefined && rebuilt.isEmpty) {
-          false
-        } else {
-          newChildren += rebuilt.getOrElse(children(index))
-          true
+        rebuilt match {
+          case Some(candidate) =>
+            newChildren(index) = candidate
+            true
+          case None =>
+            !joint || preparedChild.isEmpty
         }
       }
     }
 
     // Joint selection lets later pushable siblings follow; the fallback fixes 
every sibling. A
     // single pushable child makes both attempts identical, so a failed joint 
attempt stays as is.
-    if (!rebuildChildren(joint = true)) {
+    if (!rebuildChildren(joint = true, movableSites, policy)) {
       if (movableSites.count(_._1.isDefined) <= 1) {
         return (operator, usedRemovedLayout)
       }
-      rebuildChildren(joint = false)
+      // Retry the joint attempt with keyed targets off. Without keyed targets 
the retry

Review Comment:
   **Nit (P3):** The method's Scaladoc (lines 561-563) still says that when a 
joint rewrite fails, individual children are retried against their siblings, 
but this new block first runs a joint attempt with keyed targets off, and when 
that succeeds the per-child attempt never runs. For two union inputs that share 
a hash target, this retry is what settles the join. Listing the joint attempt, 
this hash-only joint retry with the condition the code checks, and the 
per-child attempt, in that order, would bring the doc in line with the body.
   
   **Verification:**
   - **Inspection:** The method doc lists the joint attempt, the hash-only 
joint retry with the condition the code checks before running it, and the 
per-child attempt, in the order the body runs them.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -9001,26 +9001,44 @@ 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. Eligible " +
+        "children already reporting the target keep their layouts; every other 
child, " +
+        "including an ineligible one that reports the target, is retargeted or 
given 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, and at most a " +
+        s"bounded multiple of the larger; the initial count includes " +
+        s"${COALESCE_PARTITIONS_INITIAL_PARTITION_NUM.key} when set. Requires 
" +
+        s"${UNION_OUTPUT_PARTITIONING.key}. Removing the union's exchange can 
reduce AQE skew " +
+        "handling and join conversion opportunities. Keeping a shuffled join 
child's layout " +
+        "can make skew optimization or local reads violate ancestor 
requirements; AQE then " +
+        "rejects the optimization or adds a shuffle when skew optimization is 
forced. Join " +
+        "inputs and join branches are opt-in. Only SimpleCostEvaluator 
compensates the added " +
+        "exchanges; custom evaluators should account for them, or AQE may 
reject the re-plan " +
+        "and its other runtime optimizations.")
       .version("4.4.0")
       .withBindingPolicy(ConfigBindingPolicy.SESSION)
       .booleanConf
       .createWithDefault(false)
 
+  val PUSH_DOWN_SHUFFLE_THROUGH_UNION_PARTIAL_REPLAY_ENABLED =
+    
buildConf("spark.sql.adaptive.pushDownShuffleThroughUnion.partialReplay.enabled")
+      .internal()
+      .doc("When the whole-plan check rejects a push-down proposal, the rule 
plans the same " +
+        "query with keyed targets off, which is the base policy, and keeps 
that plan when the " +
+        "whole plan holds; otherwise it falls back to the whole-plan retry on 
the removed " +
+        "layouts. When enabled, the rule also replays the proposal one site at 
a time: keyed " +
+        "targets on top of the hash-only plan, or the proposal itself over the 
input plan when " +
+        "that pass changes nothing or fails. A site the hash-only pass left on 
its exchange may " +
+        "also take that exchange's layout, and in the replay over the input 
plan a site the " +
+        "whole plan rejects takes it. A replayed site is kept only while the 
whole plan still " +
+        "holds. Each replayed site re-derives the whole plan, so a rejected 
proposal costs " +
+        "one rewrite per candidate site when enabled.")

Review Comment:
   **Nit (P3):** Both replays can make two attempts per site, not one: 
`partialReplayKeyed` runs `adopt(index, onRemovedLayout) || 
(!hashOnlySites.contains(index) && adopt(index, onRemovedLayout + index))` and 
`partialReplayHashAndKeyed` runs `adopt(index, onRemovedLayout) || adopt(index, 
onRemovedLayout + index)` (PushDownShuffleExchangeThroughUnion.scala:340-343 
and 371-373), and each `adopt` is a whole-plan rewrite followed, when it 
changes the plan, by a whole-plan `accepted()` check. A user sizing the opt-in 
from this sentence underestimates its planning cost by up to half per candidate 
site. Saying that enabling the replay costs up to two whole-plan rewrites and 
checks per candidate site would match the code; worded that way it also stays 
true beside anything added to this doc for the replay-order question under this 
review's Decision challenges.
   
   **Verification:**
   - **Inspection:** The partialReplay doc says that enabling the replay costs 
up to two whole-plan rewrites and checks per candidate site, matching the two 
attempts either replay can make at a site.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/PushDownShuffleExchangeThroughUnion.scala:
##########
@@ -240,56 +419,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.
+     *
+     * Every keepable keyed child offers its layout, marked or not, so any of 
them can supply the

Review Comment:
   **Nit (P3):** The 'so any of them can supply the target' part is too strong: 
`candidateTargets` drops every keyed layout whose routing is lost before 
admission (lines 834-836), and an ungrouped marked child is offered here in its 
grouped form, which `KeyedPartitioning.toGrouped` marks `ROUTING_LOST` 
(partitioning.scala:884-890). Such a layout, or an inner union site's grouped 
output, is offered but can never be the target, and `reportsDomain(kept = 
true)` does not keep it either, as 'a lost-routing leg is never a target, and 
is laid out' asserts. Limiting the claim to the offered layouts that still 
route by hash, and saying that a lost-routing one is laid out instead, would 
match `candidateTargets`.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60553#discussion_r4600231310).
   
   **Verification:**
   - **Inspection:** The layouts doc's statement of which offered layouts can 
supply the target matches candidateTargets, which drops a layout whose routing 
is lost, including the grouped form of an ungrouped marked child.



##########
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:
   Thanks, confirmed at 38fa3834c67: with the hash-only joint retry and the 
hash-only pass, paired union sites and the two union inputs of one join keep 
their shared hash target with the replay on or off, and the new plan-level and 
end-to-end tests pin both shapes. This review raises two narrower follow-ups: 
the hash-only pass runs whenever the plan holds a keyed layout, and the 
hash-only joint retry whenever keyed targets are allowed, rather than only 
after a keyed target was taken as this comment suggested, so each can repeat 
work that cannot change the plan.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4600231260","thread_id":"inline:4600231260","verdict_sha256":"e3e3ff7df2f6968227b8f3c34d068950a3def78393e36f5d5bf39b2c6e00bdeb"}
 -->



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