You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@spark.apache.org by ul...@apache.org on 2026/09/15 12:27:52 UTC

(spark) branch master updated: [SPARK-59492][SQL] Remove partial window group limit below a GroupPartitionsExec

This is an automated email from the ASF dual-hosted git repository.

ulysses-you pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark.git


The following commit(s) were added to refs/heads/master by this push:
     new 89067b646f15 [SPARK-59492][SQL] Remove partial window group limit below a GroupPartitionsExec
89067b646f15 is described below

commit 89067b646f1584dc4326de83b016d6a9d3a5d98d
Author: Xiduo You <ul...@gmail.com>
AuthorDate: Tue Sep 15 20:27:38 2026 +0800

    [SPARK-59492][SQL] Remove partial window group limit below a GroupPartitionsExec
    
    ### What changes were proposed in this pull request?
    
    `RemoveRedundantWindowGroupLimits` now looks through the `GroupPartitionsExec` and the local sort that `EnsureRequirements` may put between the two `WindowGroupLimitExec` nodes, and removes the partial node below them together with the local sort that only fed it. Both go only where a sort between the two nodes already orders the rows the final node ranks as a whole; where the partial node holds no local sort of its own and a sort above the grouping does order them, it stays, being th [...]
    
    ### Why are the changes needed?
    
    A partial `WindowGroupLimitExec` below a `GroupPartitionsExec` cannot change the result: a partition of the final node is a union of partitions of the partial node, so every row the final node keeps is one the partial node kept too, and the grouping is there to satisfy the final node's distribution. Removing it, together with the local sort that only fed it when a sort above already orders the final node's rows, drops an operator and a sort pass from the plan.
    
    Where the partial node holds no local sort of its own, it is the only cardinality reducer between its child and the sort above the grouping, so removing it there would leave that sort with the whole scan instead of the partial node's output - the trade `spark.sql.execution.pushDownLocalSort.throughCardinalityReducer` declines by default. Keeping the reducer is the cheap answer in that shape: reclaiming `GroupPartitionsExec`'s sorted merge instead of sorting above the grouping measured [...]
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, the plan changes for a window top-k whose child needs a `GroupPartitionsExec`, e.g.
    
    Before:
    
    ```
    WindowGroupLimit (Final)
    +- Sort
       +- GroupPartitions
          +- WindowGroupLimit (Partial)
             +- Sort
                +- BatchScan
    ```
    
    After:
    
    ```
    WindowGroupLimit (Final)
    +- Sort
       +- GroupPartitions
          +- BatchScan
    ```
    
    Where no sort lands between the final node and the grouping, the partial node goes on its own and the sort it fed stays where the partial node was. Where the source reports the ordering the window needs, the partial node holds no sort of its own and the sort above the grouping is the only one either way, so both nodes stay and the plan is unchanged. Results are unchanged.
    
    ### How was this patch tested?
    
    New tests in `KeyGroupedPartitioningSuite` for a window top-k over a v2 table whose partition keys are not grouped, so `EnsureRequirements` coalesces them with a `GroupPartitionsExec`: one where the ranked column is a partition key, so no sort sits between the two limit nodes and the partial node's own sort is the one that stays; one where it is not a partition key, so a sort sits between them and goes away with the partial node; and one where the source reports the ordering the windo [...]
    
    `RemoveRedundantWindowGroupLimitsSuite` asserts, for the plan whose child already satisfies the final node's distribution, that the sort that fed the partial node stays where the partial node was.
    
    Also ran `PushDownLocalSortSuite`, `EnsureRequirementsSuite`, `GroupPartitionsExecSuite` and `InferWindowGroupLimitSuite`, 321 tests in total with the two suites above, on `74f2edb0e91`.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Code (deepseek-v4.1-flash)
    
    Closes #58775 from ulysses-you/SPARK-59492.
    
    Authored-by: Xiduo You <ul...@gmail.com>
    Signed-off-by: Xiduo You <ul...@apache.org>
---
 .../RemoveRedundantWindowGroupLimits.scala         |  59 +++++++++--
 .../connector/KeyGroupedPartitioningSuite.scala    | 116 ++++++++++++++++++++-
 .../RemoveRedundantWindowGroupLimitsSuite.scala    |  17 +++
 3 files changed, 185 insertions(+), 7 deletions(-)

diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/RemoveRedundantWindowGroupLimits.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/RemoveRedundantWindowGroupLimits.scala
index 68b460f64e4f..c881ced6e4a7 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/execution/RemoveRedundantWindowGroupLimits.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/RemoveRedundantWindowGroupLimits.scala
@@ -18,20 +18,67 @@
 package org.apache.spark.sql.execution
 
 import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.execution.datasources.v2.GroupPartitionsExec
 import org.apache.spark.sql.execution.window.{Final, Partial, WindowGroupLimitExec}
 
 /**
  * Remove redundant partial WindowGroupLimitExec node from the spark plan. A partial
- * WindowGroupLimitExec node is redundant when its child satisfies its required child distribution.
+ * WindowGroupLimitExec node is redundant when the child left behind by removing it satisfies the
+ * final node's required child distribution: the partial node only pre-filters, keeping the rows
+ * whose rank within its own partition is within the limit, and a partition of the final node is a
+ * union of partitions of the partial node, so it drops no row the final node would keep. A
+ * [[GroupPartitionsExec]] between the two nodes, and a local sort, are looked through; the node is
+ * left in place where removing it would take no sort with it and leave the sort above the grouping
+ * with a bigger input.
  */
 object RemoveRedundantWindowGroupLimits extends Rule[SparkPlan] {
 
   def apply(plan: SparkPlan): SparkPlan = plan transform {
-    case outer @ WindowGroupLimitExec(
-    _, _, _, _, Final, WindowGroupLimitExec(_, _, _, _, Partial, child))
-      if child.outputPartitioning.satisfies(outer.requiredChildDistribution.head) =>
-      val newOuter = outer.withNewChildren(Seq(child))
-      newOuter
+    case outer @ WindowGroupLimitExec(_, _, _, _, Final, child) =>
+      val newChild = removePartialLimit(child, hasUpperSort = false)
+      if (newChild.outputPartitioning.satisfies(outer.requiredChildDistribution.head)) {
+        outer.withNewChildren(Seq(newChild))
+      } else {
+        outer
+      }
+  }
+
+  /**
+   * Removes the partial [[WindowGroupLimitExec]] at the top of `plan`, together with the local sort
+   * feeding it when `hasUpperSort` is set, or returns `plan` unchanged when it does not hold one.
+   *
+   * A [[GroupPartitionsExec]] and a local sort are looked through: `EnsureRequirements` adds the
+   * grouping between the two nodes when the child needs its partitions coalesced or its partition
+   * keys projected to satisfy the final node's distribution, and adds the sort between them to give
+   * the final node its ordering. That sort orders the rows the final node ranks as a whole, which
+   * is what makes the sort feeding the partial node dead; on its own that one is not redundant,
+   * having been added to give the partial node its required ordering.
+   *
+   * A partial node holding no local sort of its own stays where `hasUpperSort` is set: it is then
+   * the only cardinality reducer between its child and the sort above the grouping, and removing it
+   * hands that sort the whole input.
+   *
+   * @param hasUpperSort whether a local sort between the final node and `plan` orders the rows the
+   *                     final node ranks.
+   */
+  private def removePartialLimit(plan: SparkPlan, hasUpperSort: Boolean): SparkPlan = plan match {
+    case WindowGroupLimitExec(_, _, _, _, Partial, child) =>
+      if (hasUpperSort) {
+        child match {
+          case sort: SortExec if !sort.global => sort.child
+          // Nothing goes with the partial node here: it is the only cardinality reducer between
+          // its child and the sort above, which would then read the whole input -
+          // `PushDownLocalSort.isOrderPreserving` declines the same trade by default.
+          case _ => plan
+        }
+      } else {
+        child
+      }
+    case group: GroupPartitionsExec =>
+      group.withNewChildren(Seq(removePartialLimit(group.child, hasUpperSort)))
+    case sort: SortExec if !sort.global =>
+      sort.withNewChildren(Seq(removePartialLimit(sort.child, hasUpperSort = true)))
+    case other => other
   }
 
 }
diff --git a/sql/core/src/test/scala/org/apache/spark/sql/connector/KeyGroupedPartitioningSuite.scala b/sql/core/src/test/scala/org/apache/spark/sql/connector/KeyGroupedPartitioningSuite.scala
index 13e7cfdaca44..4d706a451a30 100644
--- a/sql/core/src/test/scala/org/apache/spark/sql/connector/KeyGroupedPartitioningSuite.scala
+++ b/sql/core/src/test/scala/org/apache/spark/sql/connector/KeyGroupedPartitioningSuite.scala
@@ -35,18 +35,21 @@ import org.apache.spark.sql.connector.expressions.Expressions._
 import org.apache.spark.sql.execution.{
   ExtendedMode,
   FormattedMode,
+  InputAdapter,
   LocalTableScanExec,
   ProjectExec,
   RDDScanExec,
   SimpleMode,
   SortExec,
   SparkPlan,
-  UnionExec}
+  UnionExec,
+  WholeStageCodegenExec}
 import org.apache.spark.sql.execution.datasources.v2.{BatchScanExec, DataSourceV2ScanRelation, GroupPartitionsExec}
 import org.apache.spark.sql.execution.exchange.{ReusedExchangeExec, ShuffleExchangeExec, ShuffleExchangeLike, ValidateRequirements}
 import org.apache.spark.sql.execution.joins.{ShuffledHashJoinExec, ShuffledJoin, SortMergeJoinExec}
 import org.apache.spark.sql.execution.metric.SQLMetricsTestUtils
 import org.apache.spark.sql.execution.ui.SparkPlanGraphNode
+import org.apache.spark.sql.execution.window.{Final, Partial, WindowGroupLimitExec, WindowGroupLimitMode}
 import org.apache.spark.sql.functions.{col, max}
 import org.apache.spark.sql.internal.SQLConf
 import org.apache.spark.sql.internal.SQLConf._
@@ -6349,6 +6352,117 @@ class KeyGroupedPartitioningSuite
     }
   }
 
+  test("SPARK-59492: remove the partial window group limit below a GroupPartitionsExec") {
+    // (1, 'aa') is stored in two splits, so the reported KeyedPartitioning is not grouped and
+    // EnsureRequirements coalesces the two splits with a GroupPartitionsExec to satisfy the final
+    // WindowGroupLimit's clustered distribution. The partial limit node is below that grouping, so
+    // it is not redundant in the work it saves and goes only where its own local sort goes with it:
+    // every partition the final node ranks is a union of partitions the partial node ranked, and
+    // the ordering the final node needs is re-established by a sort above the grouping.
+    val partitions = Array(identity("id"), identity("name"))
+    val orderedItems = "ordered_items"
+    createTable(items, itemsColumns, partitions)
+    // The same layout, with the source reporting the ordering the window below asks for.
+    createTable(orderedItems, itemsColumns, partitions,
+      ordering = Array(
+        sort(column("id"), SortDirection.ASCENDING, NullOrdering.NULLS_FIRST),
+        sort(column("name"), SortDirection.ASCENDING, NullOrdering.NULLS_FIRST),
+        sort(column("price"), SortDirection.ASCENDING, NullOrdering.NULLS_FIRST)))
+    Seq(items, orderedItems).foreach { table =>
+      sql(s"INSERT INTO testcat.ns.$table VALUES " +
+        s"(1, 'aa', 10.0, cast('2020-01-01' as timestamp)), " +
+        s"(1, 'aa', 20.0, cast('2020-01-01' as timestamp)), " +
+        s"(2, 'cc', 30.0, cast('2020-01-01' as timestamp))")
+    }
+
+    def limitModes(plan: SparkPlan): Seq[WindowGroupLimitMode] =
+      collect(plan) { case w: WindowGroupLimitExec => w.mode }
+
+    def finalChild(plan: SparkPlan): SparkPlan =
+      collectFirst(plan) { case w: WindowGroupLimitExec => w.child }.get
+
+    // A stage boundary below the sort shows up as codegen wrappers around the grouping, and the
+    // scan's projection sits between a limit node and the scan it reads.
+    def unwrap(plan: SparkPlan): SparkPlan = plan match {
+      case w: WholeStageCodegenExec => unwrap(w.child)
+      case i: InputAdapter => unwrap(i.child)
+      case p: ProjectExec => unwrap(p.child)
+      case other => other
+    }
+
+    // One limit node is left, with one local sort in the whole plan and no global one.
+    def assertFinalAloneWithOneLocalSort(plan: SparkPlan): Unit = {
+      val limits = limitModes(plan)
+      val sorts = collect(plan) { case s: SortExec => s }
+      assert(limits == Seq(Final), s"expected the final limit alone, got $limits:\n$plan")
+      assert(sorts.length == 1, s"expected one sort in total, got ${sorts.length}:\n$plan")
+      assert(!sorts.head.global, s"expected the sort to be local:\n$plan")
+    }
+
+    // How many sort orders the scan reports: the two of the partition keys, or the source's own.
+    def scanOrderingLength(plan: SparkPlan): Int =
+      collect(plan) { case s: BatchScanExec => s }.head.outputOrdering.length
+
+    // `price` is projected by both the window and the outer select: every row of a group shares its
+    // (id, name), and answers are compared as multisets, so a row ranked in the wrong order is only
+    // visible through the column that ranks it.
+    def topKQuery(table: String, orderCol: String): DataFrame = sql(
+      s"""SELECT id, name, price FROM (
+         |  SELECT id, name, price, RANK() OVER (PARTITION BY id, name ORDER BY $orderCol) rk
+         |  FROM testcat.ns.$table
+         |) t WHERE rk = 1
+         |""".stripMargin)
+
+    withSQLConf(
+        SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
+        SQLConf.V2_BUCKETING_PRESERVE_KEY_ORDERING_ON_COALESCE_ENABLED.key -> "true") {
+      // Ranking by a partition key leaves no sort between the two limit nodes: the coalesced
+      // partitions keep an ordering over the partition keys. With nothing above the grouping to
+      // order the rows the final node ranks, the sort that fed the partial node is the one carrying
+      // that ordering and stays where it is.
+      // Every row of a group ties on the key it is ranked by, so all of them rank first.
+      val byKey = topKQuery(items, "name")
+      checkAnswer(byKey,
+        Seq(Row(1L, "aa", 10.0f), Row(1L, "aa", 20.0f), Row(2L, "cc", 30.0f)))
+      val byKeyPlan = byKey.queryExecution.executedPlan
+      assertFinalAloneWithOneLocalSort(byKeyPlan)
+      finalChild(byKeyPlan) match {
+        case g: GroupPartitionsExec =>
+          assert(unwrap(g.child).isInstanceOf[SortExec],
+            s"expected the sort that fed the partial node below the grouping:\n$byKeyPlan")
+        case other =>
+          fail(s"expected the final limit to read the grouping, got $other:\n$byKeyPlan")
+      }
+
+      // Ranking by a non-key column loses the ordering when the splits are concatenated, so a sort
+      // sits between the two limit nodes. That one orders the rows the final node ranks, which
+      // makes the partial node's own sort dead: both the partial node and its sort go.
+      val byPrice = topKQuery(items, "price")
+      checkAnswer(byPrice, Seq(Row(1L, "aa", 10.0f), Row(2L, "cc", 30.0f)))
+      val byPricePlan = byPrice.queryExecution.executedPlan
+      assertFinalAloneWithOneLocalSort(byPricePlan)
+      assert(unwrap(finalChild(byPricePlan)).isInstanceOf[SortExec],
+        s"expected the sort above the grouping to be the one left:\n$byPricePlan")
+
+      // A source that reports the ordering the window needs leaves the partial node without a sort
+      // of its own. It is then the only cardinality reducer between the scan and the sort the
+      // grouping forces above it, so removing it would hand that sort the whole scan: it stays.
+      val reported = topKQuery(orderedItems, "price")
+      val reportedPlan = reported.queryExecution.executedPlan
+      checkAnswer(reported, Seq(Row(1L, "aa", 10.0f), Row(2L, "cc", 30.0f)))
+      assert(scanOrderingLength(reportedPlan) == 3,
+        s"expected the scan to report the source's own three sort orders:\n$reportedPlan")
+      assert(limitModes(reportedPlan) == Seq(Final, Partial),
+        s"expected both limit nodes, got ${limitModes(reportedPlan)}:\n$reportedPlan")
+      assert(collectFirst(reportedPlan) {
+        case w: WindowGroupLimitExec if w.mode == Partial => unwrap(w.child)
+      }.exists(_.isInstanceOf[BatchScanExec]),
+        s"expected the partial node to read the scan, with no sort of its own:\n$reportedPlan")
+      assert(unwrap(finalChild(reportedPlan)).isInstanceOf[SortExec],
+        s"expected the sort above the grouping to be the one left:\n$reportedPlan")
+    }
+  }
+
   test("SPARK-59022: keyed shuffle follows the declared partition key order") {
     val cols = Array(
       Column.create("id", LongType),
diff --git a/sql/core/src/test/scala/org/apache/spark/sql/execution/RemoveRedundantWindowGroupLimitsSuite.scala b/sql/core/src/test/scala/org/apache/spark/sql/execution/RemoveRedundantWindowGroupLimitsSuite.scala
index 03e2f4942ed4..2c0bf2e0d40d 100644
--- a/sql/core/src/test/scala/org/apache/spark/sql/execution/RemoveRedundantWindowGroupLimitsSuite.scala
+++ b/sql/core/src/test/scala/org/apache/spark/sql/execution/RemoveRedundantWindowGroupLimitsSuite.scala
@@ -39,6 +39,12 @@ abstract class RemoveRedundantWindowGroupLimitsSuiteBase
     checkAnswer(df, result)
   }
 
+  private def unwrapCodegen(plan: SparkPlan): SparkPlan = plan match {
+    case w: WholeStageCodegenExec => unwrapCodegen(w.child)
+    case i: InputAdapter => unwrapCodegen(i.child)
+    case other => other
+  }
+
   test("remove redundant WindowGroupLimits") {
     withTempView("t") {
       spark.range(0, 100).withColumn("value", lit(1)).createOrReplaceTempView("t")
@@ -54,6 +60,17 @@ abstract class RemoveRedundantWindowGroupLimitsSuiteBase
           |WHERE rn < 3
           |""".stripMargin
       checkWindowGroupLimits(query1, 1)
+      // The child is already clustered on the window's PARTITION BY, so no exchange lands between
+      // the two limit nodes and nothing above them orders the rows the final node ranks: the local
+      // sort that fed the partial node is the one carrying that ordering, and it stays where the
+      // partial node was.
+      val plan = sql(query1).queryExecution.executedPlan
+      val limits = collectWithSubqueries(plan) { case w: WindowGroupLimitExec => w }
+      assert(limits.length == 1, s"expected the final limit alone, got ${limits.length}:\n$plan")
+      val sorts = collectWithSubqueries(plan) { case s: SortExec => s }.filter(!_.global)
+      assert(sorts.length == 1, s"expected one local sort, got ${sorts.length}:\n$plan")
+      assert(unwrapCodegen(limits.head.child).isInstanceOf[SortExec],
+        s"expected the sort to stay where the partial node was:\n$plan")
 
       val query2 =
         """


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@spark.apache.org
For additional commands, e-mail: commits-help@spark.apache.org