cloud-fan commented on code in PR #59630:
URL: https://github.com/apache/spark/pull/59630#discussion_r4489291663


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -8728,6 +8730,137 @@ object SQLConf {
       .booleanConf
       .createWithDefault(true)
 
+  val PUSH_DOWN_SHUFFLE_THROUGH_UNION_ENABLED =
+    buildConf("spark.sql.optimizer.pushDownShuffleThroughUnion.enabled")
+      .internal()
+      .doc("When set to true, during AQE query stage preparation a 
ShuffleExchangeExec with " +
+        "hash partitioning added by EnsureRequirements on top of a UnionExec 
is pushed down " +
+        "below the union, shuffling only the children that do not already 
report the picked " +

Review Comment:
   **Nit (P3):** This sentence and the class scaladoc ("only the union's 
children that are not already laid out on the target take one", 
`PushDownShuffleExchangeThroughUnion.scala:42`) both say a child that already 
reports the picked layout is never shuffled. That is not how the rule behaves. 
`childLayouts` returns no layouts for a child that `keepableLayout` rejects, 
and `rebuildUnion` keeps a child only when its own list contains the target, so 
an excluded child already on the target is moved anyway.
   
   For example, take coalescing on, `keepNonCoalescibleBranches` off and 5 
shuffle partitions, with a window `PARTITION BY a` over three branches: 
`REPARTITION(5, a)`, `DISTRIBUTE BY a` and a plain scan. The target `hash(a, 
5)` comes from the `DISTRIBUTE BY` branch. The `REPARTITION(5, a)` branch 
already reports `hash(a, 5)`, but it still gets a new requirement exchange 
stacked on its fixed-count one. Cached children are moved the same way, and so 
are shuffled-join branches when `keepJoinBranches` is off. That extra shuffle 
costs no more than the base branch's union exchange, so only the description 
misleads.
   
   Could both texts say that eligible children already on the picked layout 
keep it, and that every other child is retargeted or gets a new exchange?
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/59630#discussion_r4339854107).
   
   **Verification:**
   - **Inspection:** Both texts describe the kept children as eligible children 
that report the picked layout, and agree with how the rule treats a child the 
eligibility settings exclude even though it already reports that layout.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/PartitioningOrigin.scala:
##########
@@ -0,0 +1,79 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.exchange
+
+import 
org.apache.spark.sql.catalyst.plans.physical.{CoalescedHashPartitioning, 
HashPartitioning, PartitioningCollection}
+import org.apache.spark.sql.catalyst.trees.TreeNodeTag
+import org.apache.spark.sql.execution.SparkPlan
+
+/**
+ * Records the hash layout and shuffle origin of a user repartition removed by 
EnsureRequirements.
+ * The retained plan node carries this requirement as a tag, outside its 
canonical form, so a
+ * physical rewrite can preserve it when rebuilding or replacing the node and 
validate it later.
+ * Each node retains the outermost elided repartition; requirements at 
different nodes stay local.
+ *
+ * Validation accepts a matching hash layout or a matching member of a 
partitioning collection.
+ * Coalesced layouts preserve the keys in order, and REPARTITION_BY_NUM also 
requires the explicit
+ * output partition count. A node without an origin imposes no additional 
requirement.
+ * Push-down validates these records on its proposals; recording them does not 
constrain other
+ * adaptive rules automatically.
+ */
+private[execution] case class PartitioningOrigin(
+    partitioning: HashPartitioning,
+    shuffleOrigin: ShuffleOrigin)
+
+private[execution] object PartitioningOrigin {
+  private val ORIGIN = 
TreeNodeTag[PartitioningOrigin]("outputPartitioningOrigin")
+
+  /**
+   * Record the user layout that justified removing an exchange. 
EnsureRequirements visits
+   * bottom-up, so an outer repartition replaces the origin already recorded 
at this node.
+   */
+  def record(
+      plan: SparkPlan,
+      partitioning: HashPartitioning,
+      shuffleOrigin: ShuffleOrigin): Unit = {
+    plan.setTagValue(ORIGIN, PartitioningOrigin(partitioning, shuffleOrigin))
+  }
+
+  def inherit(original: SparkPlan, rebuilt: SparkPlan): SparkPlan = {
+    if (original ne rebuilt) {
+      original.getTagValue(ORIGIN).foreach(rebuilt.setTagValue(ORIGIN, _))
+    }
+    rebuilt
+  }
+
+  /**
+   * Preserve the hash layout that justified elision. Coalesced layouts retain 
the same keys
+   * in order without requiring the original reducer count; explicit output 
counts still hold.
+   */
+  def validateNode(plan: SparkPlan): Boolean = {
+    plan.getTagValue(ORIGIN).forall { origin =>
+      PartitioningCollection.flatten(plan.outputPartitioning).exists {

Review Comment:
   **Nit (P3):** `EnsureRequirements.hasSemanticEqualPartitioning` matches 
`PartitioningCollection` members, so line 1459 there also records an origin on 
a child that reports a collection. Examples are an inner sort-merge join, or a 
broadcast hash join with an expanded output partitioning, under an elided 
`repartition(k)`. This flatten-and-match is what validates such a node. Yet 
every `PartitioningOrigin.record` call in the suite tags a node reporting a 
plain `HashPartitioning` or `CoalescedHashPartitioning`, and no end-to-end test 
elides a user repartition above a join.
   
   Two regressions would pass the suite. If the flatten were dropped, every 
proposal in such plans would roll back. If members were compared too loosely, a 
push-down that moves the join onto `hash(k, 8)` would be accepted, and the 
user's partition count would be lost under `mapPartitions` or a planned write.
   
   Could the origin-validation test add two tagged nodes that report a 
collection, one containing the recorded layout and one lacking it?
   
   **Verification:**
   - **Regression:** Origin validation accepts a tagged node whose partitioning 
collection contains the recorded layout and rejects one whose collection lacks 
it, so that no longer flattening the collection, or comparing its members more 
loosely, fails a test.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/adaptive/PushDownShuffleExchangeThroughUnionSuite.scala:
##########
@@ -0,0 +1,2913 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.adaptive
+
+import scala.collection.mutable.ArrayBuffer
+
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{DataFrame, QueryTest, Row}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{
+  Alias, Ascending, Attribute, AttributeReference, ExprId, GreaterThan, 
IsNotNull, Literal, Rand,
+  RowNumber, SortOrder}
+import org.apache.spark.sql.catalyst.optimizer.BuildLeft
+import org.apache.spark.sql.catalyst.plans.physical.{
+  ClusteredDistribution, CoalescedBoundary, CoalescedHashPartitioning, 
Distribution,
+  HashPartitioning, NullAwareHashPartitioning, Partitioning, 
PartitioningCollection,
+  RoundRobinPartitioning,
+  UnknownPartitioning}
+import org.apache.spark.sql.execution.{
+  FilterExec, InputAdapter, LocalLimitExec, ProjectExec, QueryExecution, 
ScalarSubquery, SortExec,
+  SparkPlan, StampUnionDecisions, SubqueryExec, UnaryExecNode, 
UnionConfSnapshot, UnionExec,
+  WholeStageCodegenExec}
+import org.apache.spark.sql.execution.exchange.{
+  ENSURE_REQUIREMENTS, EnsureRequirements, REPARTITION_BY_COL, 
REPARTITION_BY_NUM,
+  ShuffleExchangeExec, ShuffleExchangeLike, ValidateRequirements}
+import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec, 
ShuffledHashJoinExec, SortMergeJoinExec}
+import org.apache.spark.sql.execution.window.{Final => FinalWindowGroupLimit, 
Partial => PartialWindowGroupLimit, WindowGroupLimitExec}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.test.SharedSparkSession
+import org.apache.spark.sql.types.IntegerType
+
+class PushDownShuffleExchangeThroughUnionSuite extends QueryTest with 
SharedSparkSession {
+  import testImplicits._
+
+  // The suite exercises the rule itself, so it is on for every test whatever 
the default is.
+  override protected def sparkConf =
+    super.sparkConf
+      .set(SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ENABLED.key, "true")
+      
.set(SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ALLOW_JOIN_INPUTS_ENABLED.key, 
"true")
+      
.set(SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_KEEP_JOIN_BRANCHES_ENABLED.key, 
"true")
+      
.set(SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ALLOW_WITH_SUBQUERIES_ENABLED.key, 
"true")
+      .set(SQLConf
+        
.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ALLOW_PARTITION_KEYS_SUBSET_OF_CLUSTER_KEYS_ENABLED.key,

Review Comment:
   **Nit (P3):** With `allowPartitionKeysSubsetOfClusterKeys` set to true here 
and `requireAllClusterKeysForCoPartition` off two lines below, the `||` in 
`rebuildChild`'s spec check 
(`PushDownShuffleExchangeThroughUnion.scala:325-327`) short-circuits before 
`required.areAllClusterKeysMatched(...)` in every positive test. That full-key 
arm is the one every accepted target goes through for a user who sets only 
`spark.sql.optimizer.pushDownShuffleThroughUnion.enabled`.
   
   Three tests restore the subset default, and all of them expect rejection: 
"full-key policy protects a join above relaxed windows", "two-key joins between 
unions respect both subset permissions" and "subset targets require both 
permissions". No other suite runs a positive push-down. So if that arm 
regressed to reject every target, the whole suite would stay green while the 
rule never fired under the shipped defaults.
   
   Could one positive case, such as the suite's base window query, run with 
both settings at their defaults?
   
   **Verification:**
   - **Regression:** With only the main push-down flag enabled and every 
sub-setting at its default, a window over a union whose child is already 
partitioned on all the window's keys has no exchange above the union, and the 
check fails if the full-key acceptance arm rejects that target.
   - **Behavior:** The same query returns the rows it returns with the 
push-down disabled.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/adaptive/PushDownShuffleExchangeThroughUnionSuite.scala:
##########
@@ -0,0 +1,2913 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.adaptive
+
+import scala.collection.mutable.ArrayBuffer
+
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{DataFrame, QueryTest, Row}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{
+  Alias, Ascending, Attribute, AttributeReference, ExprId, GreaterThan, 
IsNotNull, Literal, Rand,
+  RowNumber, SortOrder}
+import org.apache.spark.sql.catalyst.optimizer.BuildLeft
+import org.apache.spark.sql.catalyst.plans.physical.{
+  ClusteredDistribution, CoalescedBoundary, CoalescedHashPartitioning, 
Distribution,
+  HashPartitioning, NullAwareHashPartitioning, Partitioning, 
PartitioningCollection,
+  RoundRobinPartitioning,
+  UnknownPartitioning}
+import org.apache.spark.sql.execution.{
+  FilterExec, InputAdapter, LocalLimitExec, ProjectExec, QueryExecution, 
ScalarSubquery, SortExec,
+  SparkPlan, StampUnionDecisions, SubqueryExec, UnaryExecNode, 
UnionConfSnapshot, UnionExec,
+  WholeStageCodegenExec}
+import org.apache.spark.sql.execution.exchange.{
+  ENSURE_REQUIREMENTS, EnsureRequirements, REPARTITION_BY_COL, 
REPARTITION_BY_NUM,
+  ShuffleExchangeExec, ShuffleExchangeLike, ValidateRequirements}
+import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec, 
ShuffledHashJoinExec, SortMergeJoinExec}
+import org.apache.spark.sql.execution.window.{Final => FinalWindowGroupLimit, 
Partial => PartialWindowGroupLimit, WindowGroupLimitExec}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.test.SharedSparkSession
+import org.apache.spark.sql.types.IntegerType
+
+class PushDownShuffleExchangeThroughUnionSuite extends QueryTest with 
SharedSparkSession {
+  import testImplicits._
+
+  // The suite exercises the rule itself, so it is on for every test whatever 
the default is.
+  override protected def sparkConf =
+    super.sparkConf
+      .set(SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ENABLED.key, "true")
+      
.set(SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ALLOW_JOIN_INPUTS_ENABLED.key, 
"true")
+      
.set(SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_KEEP_JOIN_BRANCHES_ENABLED.key, 
"true")
+      
.set(SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ALLOW_WITH_SUBQUERIES_ENABLED.key, 
"true")
+      .set(SQLConf
+        
.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ALLOW_PARTITION_KEYS_SUBSET_OF_CLUSTER_KEYS_ENABLED.key,
+        "true")
+      .set(SQLConf.REQUIRE_ALL_CLUSTER_KEYS_FOR_CO_PARTITION.key, "false")
+
+  private val query: String =
+    """
+      |SELECT id, v, row_number() OVER (PARTITION BY id ORDER BY v) AS rn
+      |FROM (
+      |  SELECT id, sum(v) AS v FROM t1 GROUP BY id
+      |  UNION ALL
+      |  SELECT id, v FROM t2
+      |)
+      |""".stripMargin
+
+  // A shuffle that moves a union as a whole, not one the rewrite puts under 
one of its children to
+  // lay that child out on the target.
+  private def numShufflesOnUnion(plan: SparkPlan): Int =
+    plan.collect { case s: ShuffleExchangeExec if isUnionPlan(s.child) => s 
}.size
+
+  // The union may be wrapped in a `WholeStageCodegenExec` by 
`CollapseCodegenStages`, or in an
+  // `InputAdapter` when it feeds a codegen'd parent, so look through both 
when checking whether
+  // a shuffle's child is (effectively) a union.
+  private def isUnionPlan(plan: SparkPlan): Boolean = plan match {
+    case _: UnionExec => true
+    case w: WholeStageCodegenExec => isUnionPlan(w.child)
+    case i: InputAdapter => isUnionPlan(i.child)
+    case _ => false
+  }
+
+  // A shuffle with a union anywhere below it, through the operators this rule 
can cross and the
+  // codegen wrappers `CollapseCodegenStages` may have added.
+  private def numShufflesOverUnion(plan: SparkPlan): Int =
+    countShuffles(plan, underUnion = false) { s => reachesUnion(s.child) }
+
+  private def countShuffles(
+      plan: SparkPlan,
+      underUnion: Boolean)(matches: ShuffleExchangeExec => Boolean): Int = {
+    val here = plan match {
+      case s: ShuffleExchangeExec if !underUnion && matches(s) => 1
+      case _ => 0
+    }
+    here + plan.children.map(countShuffles(_, underUnion || 
plan.isInstanceOf[UnionExec])(matches))
+      .sum
+  }
+
+  private def reachesUnion(plan: SparkPlan): Boolean = plan match {
+    case _: UnionExec => true
+    case unary: UnaryExecNode => reachesUnion(unary.child)
+    case _ => false
+  }
+
+  private def withLookThrough(f: => Unit): Unit = withSQLConf(
+    SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_LOOK_THROUGH_OPERATORS_ENABLED.key 
-> "true")(f)
+
+  private def aqeInitialPlan(df: DataFrame): SparkPlan = 
df.queryExecution.executedPlan match {
+    case a: AdaptiveSparkPlanExec => a.initialPlan
+    case other => fail(s"expected an adaptive plan:\n$other")
+  }
+
+  private def pushDown(plan: SparkPlan, required: Option[Distribution] = 
None): SparkPlan = {
+    val snapshot = UnionConfSnapshot(spark.sessionState.conf)
+    PushDownShuffleExchangeThroughUnion(
+      snapshot, EnsureRequirements(requiredDistribution = required),
+      queryContainsSubqueries = false)(plan)
+  }
+
+  private def withPushDown(f: => Unit): Unit = withSQLConf(
+      SQLConf.UNION_OUTPUT_PARTITIONING.key -> "true",
+      SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ENABLED.key -> "true",
+      
SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_KEEP_NON_COALESCIBLE_BRANCHES_ENABLED.key
 ->
+        "true")(f)
+
+  private def attr(name: String): AttributeReference = 
AttributeReference(name, IntegerType)()
+
+  private def leaf(
+      output: Attribute,
+      partitioning: Partitioning = UnknownPartitioning(0)): 
TestPartitioningPlan =
+    TestPartitioningPlan(outputPartitioning = partitioning, output = 
Seq(output))
+
+  private def hash(a: Attribute, n: Int): HashPartitioning = 
HashPartitioning(Seq(a), n)
+
+  private def clustered(a: Attribute): ClusteredDistribution = 
ClusteredDistribution(Seq(a))
+
+  private def ensureShuffle(partitioning: Partitioning, child: SparkPlan): 
ShuffleExchangeExec =
+    ShuffleExchangeExec(partitioning, child, ENSURE_REQUIREMENTS)
+
+  private def assertReshuffled(plan: SparkPlan, expected: Partitioning, child: 
SparkPlan): Unit = {
+    plan match {
+      case s: ShuffleExchangeExec =>
+        assert(s.shuffleOrigin === ENSURE_REQUIREMENTS)
+        assert(s.outputPartitioning === expected, s"unexpected target:\n$plan")
+        assert(s.child.fastEquals(child), s"the shuffled child should be 
unchanged:\n$plan")
+      case other => fail(s"expected a shuffle into $expected:\n$other")
+    }
+  }
+
+  private def createTables(): Unit = {
+    Seq((1, 10), (1, 20), (2, 5), (3, 7)).toDF("id", 
"v").createOrReplaceTempView("t1")
+    Seq((1, 40), (2, 8)).toDF("id", "v").createOrReplaceTempView("t2")
+  }
+
+  private def expectedResult(sql: String): Seq[Row] =
+    withSQLConf(SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ENABLED.key -> 
"false") {
+      spark.sql(sql).collect().toSeq
+    }
+
+  Seq("MERGE", "SHUFFLE_HASH").foreach { hint =>
+    Seq("INNER", "FULL OUTER").foreach { joinType =>
+      test(s"SPARK-60379: push down through union for $hint $joinType join") {
+        withSQLConf(
+            SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
+            SQLConf.COALESCE_PARTITIONS_ENABLED.key -> "false",
+            SQLConf.SHUFFLE_PARTITIONS.key -> "4",
+            SQLConf.SHUFFLE_SPREAD_NULL_JOIN_KEYS_ENABLED.key -> "false",
+            SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1") {
+          withTempView("t1", "t2") {
+            Seq((Option(1), 10), (Option(1), 20), (None, 30)).toDF("id", "v")
+              .createOrReplaceTempView("t1")
+            Seq((Option(2), 40), (None, 50)).toDF("id", 
"v").createOrReplaceTempView("t2")
+            val query = s"""SELECT /*+ $hint(u, r) */ u.id, u.v, r.v FROM (
+               |SELECT /*+ REPARTITION(4, id) */ id, v FROM t1
+               |UNION ALL SELECT id, v FROM t2) u
+               |$joinType JOIN t1 r ON u.id = r.id""".stripMargin
+            val expected = expectedResult(query)
+            Seq(false, true).foreach { enabled =>
+              withSQLConf(SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ENABLED.key 
-> enabled.toString) {
+                val df = spark.sql(query)
+                checkAnswer(df, expected)
+                val initial = aqeInitialPlan(df)
+                assert(numShufflesOnUnion(initial) === (if (enabled) 0 else 1),
+                  s"unexpected shuffle over the union:\n$initial")
+                if (hint == "MERGE") {
+                  assert(initial.exists(_.isInstanceOf[SortMergeJoinExec]),
+                    s"expected a sort-merge join:\n$initial")
+                } else {
+                  assert(initial.exists(_.isInstanceOf[ShuffledHashJoinExec]),
+                    s"expected a shuffled hash join:\n$initial")
+                }
+                assert(ValidateRequirements.validate(initial))
+              }
+            }
+          }
+        }
+      }
+    }
+  }
+
+  Seq(2, 8, 64).foreach { partitions =>
+    test(s"SPARK-60379: the rebuilt union carries its own count with a " +
+      s"$partitions-partition child") {
+      withSQLConf(
+          SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
+          SQLConf.COALESCE_PARTITIONS_ENABLED.key -> "false",
+          SQLConf.SHUFFLE_PARTITIONS.key -> "8") {
+        withTempView("t1", "t2") {
+          createTables()
+          val query = s"""SELECT id, v,
+             |row_number() OVER (PARTITION BY id ORDER BY v) AS rn FROM (
+             |SELECT /*+ REPARTITION($partitions, id) */ id, v FROM t1
+             |UNION ALL SELECT id, v FROM t2)""".stripMargin
+          val expected = expectedResult(query)
+          Seq(false, true).foreach { enabled =>
+            withSQLConf(SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ENABLED.key -> 
enabled.toString) {
+              val df = spark.sql(query)
+              checkAnswer(df, expected)
+              val initial = aqeInitialPlan(df)
+              // A target below what the replaced exchange carried is not 
picked, since the
+              // operator above would then run with fewer partitions than 
before.
+              val pushedDown = enabled && partitions >= 8
+              assert(numShufflesOnUnion(initial) === (if (pushedDown) 0 else 
1),
+                s"unexpected shuffle over the union:\n$initial")
+              // The window runs with the child's count once the layout is 
pushed down, and with
+              // `spark.sql.shuffle.partitions` while the exchange above the 
union is kept.
+              val expectedPartitions = if (pushedDown) partitions else 8
+              assert(initial.outputPartitioning.numPartitions === 
expectedPartitions,
+                s"unexpected count:\n$initial")
+              assert(df.rdd.getNumPartitions === expectedPartitions)
+            }
+          }
+        }
+      }
+    }
+  }
+
+  test("SPARK-60379: do not push down a null-aware shuffle") {
+    withSQLConf(
+        SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
+        SQLConf.COALESCE_PARTITIONS_ENABLED.key -> "false",
+        SQLConf.SHUFFLE_PARTITIONS.key -> "4",
+        SQLConf.SHUFFLE_SPREAD_NULL_JOIN_KEYS_ENABLED.key -> "true",
+        SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1") {
+      withTempView("t1", "t2") {
+        Seq((Option(1), 10), (Option(1), 20), (None, 30)).toDF("id", "v")
+          .createOrReplaceTempView("t1")
+        Seq((Option(2), 40), (None, 50)).toDF("id", 
"v").createOrReplaceTempView("t2")
+        // A full outer join on nullable keys lets null keys spread, so its 
exchange is a
+        // `NullAwareHashPartitioning`, which a child laid out on a plain 
layout cannot report.
+        val query =
+          """SELECT /*+ MERGE(u, r) */ u.id, u.v, r.v FROM (
+            |SELECT /*+ REPARTITION(4, id) */ id, v FROM t1
+            |UNION ALL SELECT id, v FROM t2) u
+            |FULL OUTER JOIN t1 r ON u.id = r.id""".stripMargin
+        val df = spark.sql(query)
+        checkAnswer(df, expectedResult(query))
+
+        val initial = aqeInitialPlan(df)
+        assert(initial.collect {
+          case s: ShuffleExchangeExec
+            if s.outputPartitioning.isInstanceOf[NullAwareHashPartitioning] => 
s
+        }.nonEmpty, s"the join should spread null keys:\n$initial")
+        assert(numShufflesOnUnion(initial) === 1, s"the union shuffle must 
stay:\n$initial")
+      }
+    }
+  }
+
+  test("SPARK-60379: select compatible targets for two union sides") {
+    withPushDown {
+      val a = attr("a")
+      val b = attr("b")
+      val a1 = attr("a1")
+      val b1 = attr("b1")
+      val left = UnionExec(Seq(leaf(a, hash(a, 4)), leaf(a1)))
+      val right = UnionExec(Seq(leaf(b, hash(b, 4)), leaf(b1)))
+      val parent = TestPartitioningPlan(
+        children = Seq(ensureShuffle(hash(a, 4), left), ensureShuffle(hash(b, 
4), right)),
+        required = Seq(clustered(a), clustered(b)))
+      val result = pushDown(parent)
+      assert(result.children.forall(_.isInstanceOf[UnionExec]))
+      assert(ValidateRequirements.validate(result))
+    }
+  }
+
+  test("SPARK-60379: shuffle push-down is not registered in classic 
preparations") {
+    withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false") {
+      assert(!QueryExecution.preparations(spark, subquery = false)
+        .exists(_.isInstanceOf[PushDownShuffleExchangeThroughUnion]))
+      withTempView("t1", "t2") {
+        createTables()
+        val df = spark.sql(query)
+        checkAnswer(df, expectedResult(query))
+        assert(numShufflesOnUnion(df.queryExecution.executedPlan) === 1)
+      }
+    }
+  }
+
+  test("SPARK-60379: push down shuffle through union") {
+    withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true") {
+      withTempView("t1", "t2") {
+        createTables()
+        val df = spark.sql(query)
+
+        // The rule only rewrites the physical plan, so the result must be 
unchanged.
+        checkAnswer(df, expectedResult(query))
+
+        val plan = aqeInitialPlan(df)
+        assert(numShufflesOnUnion(plan) === 0,
+          s"shuffle should be pushed down below the union:\n$plan")
+      }
+    }
+  }
+
+  test("SPARK-60379: duplicate union output exprIds retain the requirement 
exchange") {
+    withSQLConf(
+        SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
+        SQLConf.COALESCE_PARTITIONS_ENABLED.key -> "false",
+        SQLConf.SHUFFLE_PARTITIONS.key -> "5",
+        SQLConf.UNION_IS_RESOLVED_WHEN_DUPLICATES_PER_CHILD_RESOLVED.key -> 
"false",
+        SQLConf.ENFORCE_TYPE_COERCION_BEFORE_UNION_DEDUPLICATION.key -> 
"false") {
+      val first = spark.range(1000).selectExpr("id a", "id 
v").repartition($"a")
+      val second = spark.range(1000, 11000)
+        .selectExpr("id % 1000 b", "id c", "id v")
+      Seq(false, true).foreach { duplicate =>
+        val left = if (duplicate) {
+          first.select($"a", $"a", $"v")
+        } else {
+          first.select($"a", $"a".as("other"), $"v")
+        }
+        def result(enabled: Boolean): DataFrame = {
+          withSQLConf(SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_ENABLED.key -> 
enabled.toString) {
+            val union = left.union(second)
+            val df = union.withColumn("rn", 
org.apache.spark.sql.functions.row_number().over(
+              
org.apache.spark.sql.expressions.Window.partitionBy(first.col("a")).orderBy("v")))
+            df.queryExecution.executedPlan
+            df
+          }
+        }
+        val baseline = result(enabled = false).collect().toSeq
+        val df = result(enabled = true)
+        val initial = aqeInitialPlan(df)
+        val union = initial.collectFirst { case u: UnionExec => u }.get
+        assert((union.output.map(_.exprId).distinct.size != union.output.size) 
=== duplicate,
+          s"the fixture must retain the requested output 
identities:\n$initial")
+        val actual = df.collect().toSeq
+        assert(actual.count(_.getInt(3) == 1) === 1000)
+        checkAnswer(df, baseline)
+        assert(numShufflesOnUnion(initial) === (if (duplicate) 1 else 0),
+          s"only ambiguous union outputs should block push-down:\n$initial")
+      }
+    }
+  }
+
+  test("SPARK-60379: do not push down when no child is co-located with the 
target") {
+    withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true") {
+      withTempView("t1", "t2") {
+        Seq((1, 10), (2, 5)).toDF("id", "v").createOrReplaceTempView("t1")
+        Seq((1, 40), (2, 8)).toDF("id", "v").createOrReplaceTempView("t2")
+
+        val df = spark.sql(
+          """
+            |SELECT id, v, row_number() OVER (PARTITION BY id ORDER BY v) AS rn
+            |FROM (
+            |  SELECT id, v FROM t1
+            |  UNION ALL
+            |  SELECT id, v FROM t2
+            |)
+            |""".stripMargin)
+
+        // Pushing the shuffle down would turn one shuffle into two with no 
child saved.
+        val plan = aqeInitialPlan(df)
+        assert(numShufflesOnUnion(plan) === 1,
+          s"shuffle on top of union should be kept when no child is 
co-located:\n$plan")
+      }
+    }
+  }
+
+  test("SPARK-60379: push down shuffle through union with AQE enabled") {
+    withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true") {
+      withTempView("t1", "t2") {
+        createTables()
+        val df = spark.sql(query)
+        checkAnswer(df, expectedResult(query))
+
+        val initial = aqeInitialPlan(df)
+        assert(numShufflesOnUnion(initial) === 0,
+          s"shuffle should be pushed below the union in the initial 
plan:\n$initial")
+        val union = initial.collectFirst { case u: UnionExec => u }.get
+        assert(union.children.count(_.isInstanceOf[ShuffleExchangeExec]) === 1,
+          s"only the scan child should be re-shuffled:\n$initial")
+      }
+    }
+  }
+
+  Seq(false, true).foreach { adaptive =>
+    test(s"SPARK-60379: retain the user-requested root partition count with 
AQE=$adaptive") {
+      withSQLConf(
+          SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString,
+          SQLConf.COALESCE_PARTITIONS_ENABLED.key -> "false",
+          SQLConf.SHUFFLE_PARTITIONS.key -> "5") {
+        withTempView("t1", "t2") {
+          createTables()
+          val df = spark.table("t1").repartition(8, $"id")
+            .union(spark.table("t2"))
+            .withColumn("rn", org.apache.spark.sql.functions.row_number().over(
+              
org.apache.spark.sql.expressions.Window.partitionBy("id").orderBy("v")))
+            .repartition(5, $"id").select("id", "v", "rn")
+          checkAnswer(df, Seq(
+            Row(1, 10, 1), Row(1, 20, 2), Row(1, 40, 3), Row(2, 5, 1), Row(2, 
8, 2),
+            Row(3, 7, 1)))
+
+          val plan = if (adaptive) {
+            aqeInitialPlan(df)
+          } else {
+            df.queryExecution.executedPlan
+          }
+          if (adaptive) {
+            // The 8-partition target passes the floor of 5, but not the 
elided root repartition's
+            // explicit count of 5. Only the root check rejects this rewrite.

Review Comment:
   **Nit (P3):** When `EnsureRequirements` elides the root `repartition(5, 
$"id")` here, it also records `hash(id, 5)` with a `REPARTITION_BY_NUM` origin 
on the node it keeps (`EnsureRequirements.scala:1459`). That tag survives 
`withNewChildren`, so `PartitioningOrigin.validateNode` rejects the rebuilt 
`hash(id, 8)` layout at `PushDownShuffleExchangeThroughUnion.scala:173`, 
alongside the root check. "retain the keys of a root repartition" is rejected 
the same way.
   
   The synthetic root test uses single-key distributions, so nothing isolates 
the `requireAllClusterKeys = true` override at line 167. Dropping it would keep 
every test green.
   
   Could this comment name both checks? A synthetic two-key root case without a 
recorded origin would then pin the override.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/59630#discussion_r4339854072).
   
   **Verification:**
   - **Regression:** A synthetic plan whose root requires clustering on two 
keys, with a union child laid out on only one of them and no recorded origin, 
is rolled back, and the check fails if the root distribution stops being held 
to all its keys.
   - **Inspection:** The root-count test comment matches the checks its fixture 
actually triggers.



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