ulysses-you commented on code in PR #60553:
URL: https://github.com/apache/spark/pull/60553#discussion_r4624036817


##########
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:
   Not adopted. The retry re-runs the same targets over the same children, so 
it is planning-only work, and it only runs when the keyed permission is on, 
which now defaults to false. Recording cross-pass state to skip it costs more 
than it saves.



##########
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:
   Not adopted. The plan.exists scan is over plan nodes, the pass already 
short-circuits accepted on fastEquals, and with the keyed permission off by 
default the pass does not run at all. A per-pass keyed flag is not worth the 
state.



##########
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:
   Fixed in d66c1e1b6fc: the test is now 'the hash-only pass falls a site back 
to the layout it removes', the comments credit the hash-only pass, and the 
paired-sites comment counts the one leg that offers hash(id, 3).



##########
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:
   Fixed in d66c1e1b6fc: only a keyed layout that still routes undeclared keys 
by hash can supply the target; one that lost its routing is laid out instead.



##########
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:
   Fixed in d66c1e1b6fc: the partialReplay doc states up to two rewrites and 
checks per candidate site for the input-plan replay (the keyed replay makes one 
attempt), and it also states the nested cost the replay over the input plan can 
add.



##########
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:
   Fixed in d66c1e1b6fc: the doc lists the joint attempt, the keyed-off joint 
retry (when keyed targets are available) and the per-child attempt, in that 
order.



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