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 3d63d89ec11e [SPARK-33744][SQL] Fix canonicalization of
SortAggregateExec
3d63d89ec11e is described below
commit 3d63d89ec11e2c3240592bfb238dded7cdb09ced
Author: Xiduo You <[email protected]>
AuthorDate: Fri Nov 13 09:03:13 2026 +0800
[SPARK-33744][SQL] Fix canonicalization of SortAggregateExec
### What changes were proposed in this pull request?
`SortAggregateExec` now overrides `allAttributes` with the same attributes
that
`HashAggregateExec` and `ObjectHashAggregateExec` already report: child
output, aggregate
buffer attributes, aggregate attributes, and input aggregate buffer
attributes.
`QueryPlan.doCanonicalize` normalizes attribute references against
`allAttributes`, which by
default only covers the children's output. A sort aggregate's result
expressions reference
aggregate attributes that are not in the child's output, so their exprIds
were left
unnormalized in `canonicalized`. Structurally identical `SortAggregateExec`
subtrees then
compared unequal, and exchange / subquery reuse silently stopped
deduplicating them.
Adds regression tests copied from SPARK-33744 (a `HashAggregateExec`
control and a
`SortAggregateExec` case) plus an end-to-end exchange reuse test over
identical sort-aggregate
branches, run with AQE off and on. The SPARK-33744 tests are adapted to
current defaults: AQE
is disabled so the physical plan can be inspected, and sort aggregation is
forced with
`spark.sql.execution.useHashAggregateExec=false` and
`spark.sql.execution.useObjectHashAggregateExec=false`.
### Why are the changes needed?
SPARK-33744 reports that the canonicalized plan of a simple aggregate query
differs between
planning runs for `SortAggregate`, but not for `HashAggregate`. Since
`spark.sql.execution.replaceHashWithSortAgg` is enabled by default in 4.3,
sort aggregates are
common in default plans, so duplicated subtrees that should share an
exchange no longer do.
Example, with hash aggregation disabled to force sort aggregates:
SELECT * FROM (SELECT k, count(*) AS c FROM t GROUP BY k) a
JOIN (SELECT k, count(*) AS c FROM t GROUP BY k) b ON a.k = b.k
AND a.c = b.c
Without the fix the plan keeps two join-side exchanges; with it, the second
becomes a reused
exchange.
### Does this PR introduce _any_ user-facing change?
No. Results are unchanged; affected queries may plan fewer exchanges by
reusing an existing
one.
### How was this patch tested?
Added to `ReuseExchangeAndSubquerySuite`:
- `SPARK-33744: HashAggregate canonicalization` (control, asserts a
`HashAggregateExec` is
planned)
- `SPARK-33744: SortAggregate canonicalization` (asserts a
`SortAggregateExec` is planned)
- `SPARK-33744: exchange reuse across identical sort aggregates`, with AQE
off and on
The `SortAggregate` canonicalization test and both exchange reuse variants
fail without the
`allAttributes` override and pass with it. The `HashAggregate` case is the
control from
SPARK-33744 and passes either way.
build/sbt 'sql/testOnly
org.apache.spark.sql.execution.ReuseExchangeAndSubquerySuite'
6 tests pass. Also ran `ReplaceHashWithSortAggSuite`,
`CombineAdjacentAggregationSuite`, and
the TPC-DS / TPCH plan stability suites with the same production change; no
plan changes.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: deepseek-flash
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Closes #60384 from ulysses-you/sortagg-canonicalization.
Authored-by: Xiduo You <[email protected]>
Signed-off-by: Xiduo You <[email protected]>
skip-checks: true
---
.../execution/aggregate/SortAggregateExec.scala | 4 ++
.../execution/ReuseExchangeAndSubquerySuite.scala | 74 +++++++++++++++++++++-
2 files changed, 76 insertions(+), 2 deletions(-)
diff --git
a/sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/SortAggregateExec.scala
b/sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/SortAggregateExec.scala
index 4d01e2e7a716..b1a662a73bab 100644
---
a/sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/SortAggregateExec.scala
+++
b/sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/SortAggregateExec.scala
@@ -45,6 +45,10 @@ case class SortAggregateExec(
extends AggregateCodegenSupport
with OrderPreservingUnaryExecNode {
+ override def allAttributes: AttributeSeq =
+ child.output ++ aggregateBufferAttributes ++ aggregateAttributes ++
+
aggregateExpressions.flatMap(_.aggregateFunction.inputAggBufferAttributes)
+
override lazy val metrics = Map(
"numOutputRows" -> SQLMetrics.createMetric(sparkContext, "number of output
rows"),
"aggTime" -> SQLMetrics.createTimingMetric(sparkContext, "time in
aggregation build"))
diff --git
a/sql/core/src/test/scala/org/apache/spark/sql/execution/ReuseExchangeAndSubquerySuite.scala
b/sql/core/src/test/scala/org/apache/spark/sql/execution/ReuseExchangeAndSubquerySuite.scala
index 16726547e324..bec13f43f18b 100644
---
a/sql/core/src/test/scala/org/apache/spark/sql/execution/ReuseExchangeAndSubquerySuite.scala
+++
b/sql/core/src/test/scala/org/apache/spark/sql/execution/ReuseExchangeAndSubquerySuite.scala
@@ -17,15 +17,85 @@
package org.apache.spark.sql.execution
+import org.apache.spark.sql.Row
+import org.apache.spark.sql.catalyst.expressions.aggregate.Final
+import org.apache.spark.sql.execution.adaptive.{AdaptiveSparkPlanHelper,
ShuffleQueryStageExec}
+import org.apache.spark.sql.execution.aggregate.{HashAggregateExec,
SortAggregateExec}
import org.apache.spark.sql.execution.exchange.{Exchange, ReusedExchangeExec}
-import org.apache.spark.sql.functions.col
+import org.apache.spark.sql.functions.{col, first}
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.test.SharedSparkSession
-class ReuseExchangeAndSubquerySuite extends SharedSparkSession {
+class ReuseExchangeAndSubquerySuite extends SharedSparkSession with
AdaptiveSparkPlanHelper {
val tableFormat: String = "parquet"
+ private def sortAggregateConf: Seq[(String, String)] = Seq(
+ SQLConf.USE_HASH_AGG.key -> "false",
+ SQLConf.USE_OBJECT_HASH_AGG.key -> "false")
+
+ Seq(false, true).foreach { aqeEnabled =>
+ test("SPARK-33744: exchange reuse across identical sort aggregates " +
+ s"(AQE: $aqeEnabled)") {
+ withSQLConf(sortAggregateConf ++ Seq(
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> aqeEnabled.toString,
+ SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
+ SQLConf.EXCHANGE_REUSE_ENABLED.key -> "true"): _*) {
+ withTable("sort_agg_reuse") {
+ spark.range(10).select(col("id").as("k"))
+ .write.format(tableFormat).saveAsTable("sort_agg_reuse")
+ val branch = "SELECT k, count(*) AS c FROM sort_agg_reuse GROUP BY k"
+ val df = sql(s"SELECT * FROM ($branch) a JOIN ($branch) b ON a.k =
b.k AND a.c = b.c")
+
+ checkAnswer(df, (0L until 10L).map(i => Row(i, 1L, i, 1L)))
+ val plan = stripAQEPlan(df.queryExecution.executedPlan)
+ // The join-side exchange sits above the final aggregate, whose
result expressions alias
+ // the aggregate attributes. Its reuse is what a sort aggregate's
canonicalization
+ // decides; the pre-shuffle exchange below the partial aggregate is
reused either way.
+ val reused = plan.collect {
+ case r: ReusedExchangeExec => r
+ case ShuffleQueryStageExec(_, r: ReusedExchangeExec, _) => r
+ }
+ val reusedOverFinalAgg = reused.exists { r =>
+ r.child.collect { case a: SortAggregateExec => a }
+ .exists(_.aggregateExpressions.exists(_.mode == Final))
+ }
+ assert(reusedOverFinalAgg,
+ s"expected the join-side exchange over a final sort aggregate to
be reused:\n$plan")
+ }
+ }
+ }
+ }
+
+ test("SPARK-33744: HashAggregate canonicalization") {
+ withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false") {
+ import testImplicits._
+ val data = Seq((1, 1)).toDF("c0", "c1")
+ val df1 = data.groupBy(col("c0")).agg(first("c1"))
+ val df2 = data.groupBy(col("c0")).agg(first("c1"))
+ assert(df1.queryExecution.executedPlan.collect {
+ case _: HashAggregateExec => true
+ }.nonEmpty, "setup: expected a hash aggregate")
+ assert(df1.queryExecution.executedPlan.canonicalized ==
+ df2.queryExecution.executedPlan.canonicalized)
+ }
+ }
+
+ test("SPARK-33744: SortAggregate canonicalization") {
+ withSQLConf(sortAggregateConf ++ Seq(
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false"): _*) {
+ import testImplicits._
+ val data = Seq(("a", "a")).toDF("c0", "c1")
+ val df1 = data.groupBy(col("c0")).agg(first("c1"))
+ val df2 = data.groupBy(col("c0")).agg(first("c1"))
+ assert(df1.queryExecution.executedPlan.collect {
+ case _: SortAggregateExec => true
+ }.nonEmpty, "setup: expected a sort aggregate")
+ assert(df1.queryExecution.executedPlan.canonicalized ==
+ df2.queryExecution.executedPlan.canonicalized)
+ }
+ }
+
test("SPARK-32041: No reuse interference inside ReuseExchange") {
withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false") {
withTable("df1", "df2") {
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]