HyukjinKwon commented on code in PR #56777:
URL: https://github.com/apache/spark/pull/56777#discussion_r3479415128


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/AggUtils.scala:
##########
@@ -127,11 +127,34 @@ object AggUtils {
       aggregateExpressions: Seq[AggregateExpression],
       resultExpressions: Seq[NamedExpression],
       child: SparkPlan): Seq[SparkPlan] = {
-    // Check if we can use HashAggregate.
+
+    val groupingAttributes = groupingExpressions.map(_.toAttribute)
+
+    // When partial aggregation is disabled, skip the pre-shuffle partial 
aggregation and run a
+    // single Complete-mode aggregation after the shuffle. This can improve 
performance when the
+    // group cardinality is high and the pre-shuffle reduction ratio is low.
+    //
+    // session_window requires MergingSessionsExec (inserted below via 
mayAppendMergingSessionExec)
+    // to sort and merge overlapping sessions before the final aggregation. 
The bypass is skipped
+    // when a session_window grouping key is present so that the normal 
Partial+Merge+Final path
+    // runs and MergingSessionsExec is correctly inserted.
+    val hasSessionWindow = 
groupingExpressions.exists(_.metadata.contains(SessionWindow.marker))
+    if (child.conf.bypassPartialAggregation && !hasSessionWindow) {

Review Comment:
   Non-blocking (perf): this gate also fires for **global aggregation** 
(`groupingExpressions.isEmpty`). There `requiredChildDistributionExpressions = 
Some(groupingAttributes)` is `Some(Nil)` → `AllTuples`, so all raw rows shuffle 
to a single partition with no pre-aggregation. For a cardinality-1 global agg 
that's a pure regression with zero upside, and a user who enables this 
session-wide for high-cardinality grouped queries silently pessimizes any 
global aggs in the same session. Consider also requiring grouping keys:
   ```suggestion
       if (child.conf.bypassPartialAggregation && groupingExpressions.nonEmpty 
&& !hasSessionWindow) {
   ```



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/aggregate/PartialAggregationBypassSuite.scala:
##########
@@ -0,0 +1,131 @@
+/*
+ * 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.aggregate
+
+import org.apache.spark.sql.{functions => F, QueryTest}
+import org.apache.spark.sql.catalyst.expressions.aggregate.{Complete, Final, 
Partial}
+import org.apache.spark.sql.execution.SparkPlan
+import org.apache.spark.sql.execution.adaptive.AdaptiveSparkPlanHelper
+import org.apache.spark.sql.functions.{count, session_window, sum}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.test.SharedSparkSession
+
+class PartialAggregationBypassSuite
+    extends QueryTest
+    with SharedSparkSession
+    with AdaptiveSparkPlanHelper {
+
+  private def aggNodes(plan: SparkPlan): Seq[BaseAggregateExec] =
+    collectWithSubqueries(plan) { case a: BaseAggregateExec => a }
+
+  test("bypassPartialAggregation=true produces no Partial-mode node and one 
Complete-mode node") {
+    withSQLConf(SQLConf.BYPASS_PARTIAL_AGGREGATION.key -> "true") {
+      val df = spark.range(100).toDF("v")
+        .groupBy((F.col("v") % 10).as("k"))
+        .agg(F.sum("v"), F.count("v"))
+      val aggs = aggNodes(df.queryExecution.executedPlan)
+      assert(aggs.forall(_.aggregateExpressions.forall(_.mode != Partial)),
+        "expected no Partial-mode aggregation nodes")
+      assert(aggs.exists(_.aggregateExpressions.exists(_.mode == Complete)),
+        "expected at least one Complete-mode aggregation node")
+      assert(!aggs.exists(_.aggregateExpressions.exists(_.mode == Final)),
+        "expected no Final-mode aggregation nodes")
+    }
+  }
+
+  test("bypassPartialAggregation=false (default) produces Partial+Final plan") 
{
+    val df = spark.range(100).toDF("v")
+      .groupBy((F.col("v") % 10).as("k"))
+      .agg(F.sum("v"))
+    val aggs = aggNodes(df.queryExecution.executedPlan)
+    assert(aggs.exists(_.aggregateExpressions.exists(_.mode == Partial)),
+      "expected a Partial-mode aggregation node")
+    assert(aggs.exists(_.aggregateExpressions.exists(_.mode == Final)),
+      "expected a Final-mode aggregation node")
+  }
+
+  test("results are identical with and without partial aggregation — SUM") {
+    val data = spark.range(1000).selectExpr("id % 7 as k", "id as v")
+    val expected = data.groupBy("k").sum("v").orderBy("k").collect()
+    withSQLConf(SQLConf.BYPASS_PARTIAL_AGGREGATION.key -> "true") {
+      val actual = data.groupBy("k").sum("v").orderBy("k").collect()
+      assert(actual.toSeq == expected.toSeq)
+    }
+  }
+
+  test("results are identical with and without partial aggregation — COUNT") {
+    val data = spark.range(1000).selectExpr("id % 13 as k")
+    val expected = data.groupBy("k").count().orderBy("k").collect()
+    withSQLConf(SQLConf.BYPASS_PARTIAL_AGGREGATION.key -> "true") {
+      val actual = data.groupBy("k").count().orderBy("k").collect()
+      assert(actual.toSeq == expected.toSeq)
+    }
+  }
+
+  test("results are identical with and without partial aggregation — AVG") {
+    val data = spark.range(1000).selectExpr("id % 5 as k", "id as v")
+    val expected = data.groupBy("k").avg("v").orderBy("k").collect()
+    withSQLConf(SQLConf.BYPASS_PARTIAL_AGGREGATION.key -> "true") {
+      val actual = data.groupBy("k").avg("v").orderBy("k").collect()
+      assert(actual.toSeq == expected.toSeq)
+    }
+  }
+
+  test("session_window with bypassPartialAggregation=true merges overlapping 
sessions correctly") {
+    // Regression test: when bypassPartialAggregation=true, the early-return 
path in
+    // planAggregateWithoutDistinct skipped mayAppendMergingSessionExec, so 
overlapping
+    // sessions were never merged and the aggregation produced wrong row 
counts / sums.
+    import testImplicits._
+    // Two events for key "a" fall within 10s of each other and must merge 
into one session.
+    // One event for key "b" stands alone.
+    val df = Seq(
+      ("2016-03-27 19:39:34", 1, "a"),
+      ("2016-03-27 19:39:39", 2, "a"), // within 10s of the first "a" — same 
session
+      ("2016-03-27 19:39:56", 3, "a"), // > 10s gap — separate session

Review Comment:
   Nit: em-dash (non-ASCII) in a `//` comment.
   ```suggestion
         ("2016-03-27 19:39:56", 3, "a"), // > 10s gap - separate session
   ```



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/aggregate/PartialAggregationBypassSuite.scala:
##########
@@ -0,0 +1,131 @@
+/*
+ * 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.aggregate
+
+import org.apache.spark.sql.{functions => F, QueryTest}
+import org.apache.spark.sql.catalyst.expressions.aggregate.{Complete, Final, 
Partial}
+import org.apache.spark.sql.execution.SparkPlan
+import org.apache.spark.sql.execution.adaptive.AdaptiveSparkPlanHelper
+import org.apache.spark.sql.functions.{count, session_window, sum}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.test.SharedSparkSession
+
+class PartialAggregationBypassSuite
+    extends QueryTest
+    with SharedSparkSession
+    with AdaptiveSparkPlanHelper {
+
+  private def aggNodes(plan: SparkPlan): Seq[BaseAggregateExec] =
+    collectWithSubqueries(plan) { case a: BaseAggregateExec => a }
+
+  test("bypassPartialAggregation=true produces no Partial-mode node and one 
Complete-mode node") {
+    withSQLConf(SQLConf.BYPASS_PARTIAL_AGGREGATION.key -> "true") {
+      val df = spark.range(100).toDF("v")
+        .groupBy((F.col("v") % 10).as("k"))
+        .agg(F.sum("v"), F.count("v"))
+      val aggs = aggNodes(df.queryExecution.executedPlan)
+      assert(aggs.forall(_.aggregateExpressions.forall(_.mode != Partial)),
+        "expected no Partial-mode aggregation nodes")
+      assert(aggs.exists(_.aggregateExpressions.exists(_.mode == Complete)),
+        "expected at least one Complete-mode aggregation node")
+      assert(!aggs.exists(_.aggregateExpressions.exists(_.mode == Final)),
+        "expected no Final-mode aggregation nodes")
+    }
+  }
+
+  test("bypassPartialAggregation=false (default) produces Partial+Final plan") 
{
+    val df = spark.range(100).toDF("v")
+      .groupBy((F.col("v") % 10).as("k"))
+      .agg(F.sum("v"))
+    val aggs = aggNodes(df.queryExecution.executedPlan)
+    assert(aggs.exists(_.aggregateExpressions.exists(_.mode == Partial)),
+      "expected a Partial-mode aggregation node")
+    assert(aggs.exists(_.aggregateExpressions.exists(_.mode == Final)),
+      "expected a Final-mode aggregation node")
+  }
+
+  test("results are identical with and without partial aggregation — SUM") {
+    val data = spark.range(1000).selectExpr("id % 7 as k", "id as v")
+    val expected = data.groupBy("k").sum("v").orderBy("k").collect()
+    withSQLConf(SQLConf.BYPASS_PARTIAL_AGGREGATION.key -> "true") {
+      val actual = data.groupBy("k").sum("v").orderBy("k").collect()
+      assert(actual.toSeq == expected.toSeq)
+    }
+  }
+
+  test("results are identical with and without partial aggregation — COUNT") {
+    val data = spark.range(1000).selectExpr("id % 13 as k")
+    val expected = data.groupBy("k").count().orderBy("k").collect()
+    withSQLConf(SQLConf.BYPASS_PARTIAL_AGGREGATION.key -> "true") {
+      val actual = data.groupBy("k").count().orderBy("k").collect()
+      assert(actual.toSeq == expected.toSeq)
+    }
+  }
+
+  test("results are identical with and without partial aggregation — AVG") {
+    val data = spark.range(1000).selectExpr("id % 5 as k", "id as v")
+    val expected = data.groupBy("k").avg("v").orderBy("k").collect()
+    withSQLConf(SQLConf.BYPASS_PARTIAL_AGGREGATION.key -> "true") {
+      val actual = data.groupBy("k").avg("v").orderBy("k").collect()
+      assert(actual.toSeq == expected.toSeq)
+    }
+  }
+
+  test("session_window with bypassPartialAggregation=true merges overlapping 
sessions correctly") {
+    // Regression test: when bypassPartialAggregation=true, the early-return 
path in
+    // planAggregateWithoutDistinct skipped mayAppendMergingSessionExec, so 
overlapping
+    // sessions were never merged and the aggregation produced wrong row 
counts / sums.
+    import testImplicits._
+    // Two events for key "a" fall within 10s of each other and must merge 
into one session.
+    // One event for key "b" stands alone.
+    val df = Seq(
+      ("2016-03-27 19:39:34", 1, "a"),
+      ("2016-03-27 19:39:39", 2, "a"), // within 10s of the first "a" — same 
session

Review Comment:
   Nit: em-dash (non-ASCII) in a `//` comment — CLAUDE.md/scalastyle flag 
non-ASCII in comments.
   ```suggestion
         ("2016-03-27 19:39:39", 2, "a"), // within 10s of the first "a" - same 
session
   ```



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