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


##########
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):** childLayouts returns no layouts for a child that 
keepableLayout rejects, so rebuildUnion gives that child an exchange even when 
it already reports the picked layout. For example, with coalescing on and 
keepNonCoalescibleBranches off, take a window over a union of an aggregate on 
hash(k, N), a REPARTITION(N, k) branch and a plain scan. The aggregate's layout 
is picked, and the REPARTITION(N, k) branch, already on hash(k, N), gets an 
ENSURE_REQUIREMENTS exchange stacked on its own shuffle. Rebalance shuffles, 
bucketed or cached leaves and protected join branches behave the same way. That 
costs no more than with the rule off, which reshuffles every child. Still, this 
sentence and the PushDownShuffleExchangeThroughUnion class doc both say such a 
child is not shuffled. Could both say that a child keeps its layout only when 
it reports the picked layout and that layout is eligible to keep?
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/59630#discussion_r4339854107).
   
   **Verification:**
   - **Inspection:** The enabled conf doc and the class doc describe kept 
children consistently with keepableLayout, including that an ineligible child 
already on the target is reshuffled.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -2857,8 +2857,10 @@ object SQLConf {
       .doc("Whether to forcibly enable some optimization rules that can change 
the output " +
         "partitioning of a cached query when executing it for caching. If it 
is set to true, " +
         "queries may need an extra shuffle to read the cached data. This 
configuration is " +
-        "disabled by default. The optimization rule enabled by this 
configuration " +
-        s"is 
${ADAPTIVE_EXECUTION_APPLY_FINAL_STAGE_SHUFFLE_OPTIMIZATIONS.key}.")
+        "disabled by default. When false, " +
+        s"${ADAPTIVE_EXECUTION_APPLY_FINAL_STAGE_SHUFFLE_OPTIMIZATIONS.key} 
and " +
+        "spark.sql.optimizer.pushDownShuffleThroughUnion.enabled are disabled 
for cached " +
+        "queries. When true, their configured enablement is retained.")

Review Comment:
   **Nit (P3):** This sentence matches the code: 
CacheManager.getOrCloneSessionWithConfigsOff only adds these confs to the 
disabled list when this conf is false and never turns one on. The unchanged 
opener still says the conf decides "whether to forcibly enable some 
optimization rules", so the doc now gives two opposite readings of true, and 
for the push-down, which defaults to false, true enables nothing. Could the 
opener say instead that the conf decides whether these rules may change a 
cached query's output partitioning when the query is executed for caching?
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/59630#discussion_r4420460708).
   
   **Verification:**
   - **Inspection:** Every statement in the conf doc about true and false 
matches CacheManager's behavior, including for the push-down, which defaults to 
false.



##########
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):** Two checks reject this rewrite, not one. EnsureRequirements 
elides the root repartition(5, id) onto the window and records it as the 
window's origin. The rebuilt window inherits that tag through withNewChildren, 
so PartitioningOrigin.validateNode rejects hash(id, 8) too. Removing the root 
requirement check would leave this test green. The test that isolates that 
check is 'roll back when the root required distribution is no longer 
satisfied'. Could the comment name both checks and point to that test for the 
root check?
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/59630#discussion_r4339854072).
   
   **Verification:**
   - **Inspection:** The comment matches the fixture: removing either the root 
requirement check or the recorded-origin validation alone leaves the assertion 
satisfied, and the comment says so or points to the synthetic test for the root 
check.



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