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

dongjoon-hyun pushed a commit to branch branch-4.3
in repository https://gitbox.apache.org/repos/asf/spark.git


The following commit(s) were added to refs/heads/branch-4.3 by this push:
     new 031f890e5732 [SPARK-61295][SQL] Fix a performance regression in 
`RelationalGroupedDataset` when aggregating many columns of a wide DataFrame
031f890e5732 is described below

commit 031f890e5732435bd6195ff9bc3df79461ddeacd
Author: Dongjoon Hyun <[email protected]>
AuthorDate: Mon Nov 9 17:05:58 2026 -0800

    [SPARK-61295][SQL] Fix a performance regression in 
`RelationalGroupedDataset` when aggregating many columns of a wide DataFrame
    
    ### What changes were proposed in this pull request?
    
    This PR fixes a performance regression since Apache Spark 4.0.0 in 
`RelationalGroupedDataset.toDF` of Spark Classic, which builds the result of 
`groupBy`, `cube`, `rollup`, `groupingSets` and `pivot` aggregations and of 
`Dataset.agg`. It removes work proportional to the number of input columns from 
the per-column loop of `toDF`.
    
    - `toDF` computes `df.logicalPlan.output` at most once instead of once per 
aggregate column.
    - `TypedAggUtils.withInputType` builds its `UnresolvedDeserializer` only 
when the expression has a `TypedAggregateExpression` that needs input 
information.
    
    ```scala
    // Before
    val aggExprs = aggCols.map(_.expr).map { e =>
      withInputType(e, df.exprEnc, df.logicalPlan.output)
    }
    ...
    val unresolvedDeserializer = 
UnresolvedDeserializer(inputEncoder.deserializer, inputAttributes)
    ```
    
    ```scala
    // After
    lazy val inputAttributes = df.logicalPlan.output
    val aggExprs = aggCols.map(_.expr).map { e =>
      withInputType(e, df.exprEnc, inputAttributes)
    }
    ...
    lazy val unresolvedDeserializer =
      UnresolvedDeserializer(inputEncoder.deserializer, inputAttributes)
    ```
    
    `inputAttributes` is lazy, so `output` is still evaluated after 
`df.exprEnc` in the first `withInputType` call, and not at all when there is no 
aggregate column. For a lazily analyzed `DataFrame`, such as one with 
`Column.outer()`, `logicalPlan` is not analyzed yet and its `output` can fail.
    
    Typed aggregates, such as `Aggregator.toColumn`, get the same deserializer 
as before. `withInputType` is also used by typed `Dataset.select`, 
`KeyValueGroupedDataset.agg` and the Spark Connect planner. For a typed 
aggregate, it builds the deserializer from the same arguments as before.
    
    ### Why are the changes needed?
    
    Since SPARK-49421 (#47918) in Apache Spark 4.0.0, `toDF` calls 
`withInputType` for every aggregate column. Before, 
`RelationalGroupedDataset.agg` called it only for a `TypedColumn`. As a result, 
for each aggregate column, `toDF` does two things that take time proportional 
to the number of input columns `N`.
    
    - It evaluates `df.logicalPlan.output`. `Project.output` is 
`projectList.map(_.toAttribute)`, and `Alias.toAttribute` creates a new 
`AttributeReference` on every call. So when the input `DataFrame` comes from 
`select` or `selectExpr` with `N` aliases, every evaluation creates `N` 
attributes.
    - `withInputType` creates an `UnresolvedDeserializer` even for an untyped 
aggregate, which does not use it. Its constructor checks 
`inputAttributes.forall(_.resolved)` over all `N` attributes.
    
    So `M` aggregate columns over `N` input columns take `O(N * M)` time before 
the analyzer starts. For example:
    
    ```scala
    val columns = (1 to 3).map(i => s"id as g_$i") ++ (1 to 10000).map(i => 
s"id as c_$i")
    val df = spark.range(1).selectExpr(columns: _*).cache()
    val sums = (1 to 10000).map(i => sum(s"c_$i"))
    df.cube("g_1", "g_2", "g_3").agg(sums.head, sums.tail: _*)
    ```
    
    The following is the time to create this `DataFrame`, and the same one with 
`groupBy("g_1")` instead of `cube`, in released versions. The same code runs in 
`spark-shell` on JDK 17 on an Apple M3 Max (Best Time of two runs). `4.3.0 + 
this PR` is the 4.3.0 distribution whose classes of the two changed files are 
compiled with this PR by the distribution's own Scala 2.13.18 compiler. 
Compiling the original files in the same way gives the classes of the 4.3.0 
release byte for byte.
    
    | Version | `cube`, 1,000 columns | `cube`, 10,000 columns | `groupBy`, 
1,000 columns | `groupBy`, 10,000 columns |
    |---|---:|---:|---:|---:|
    | 3.5.9 | 39 ms | 570 ms | 19 ms | 267 ms |
    | 4.0.5 | 57 ms | 2,253 ms | 34 ms | 2,053 ms |
    | 4.1.4 | 75 ms | 3,942 ms | 51 ms | 3,635 ms |
    | 4.2.1 | 65 ms | 3,163 ms | 45 ms | 3,057 ms |
    | 4.3.0 | 64 ms | 3,210 ms | 45 ms | 3,070 ms |
    | 4.3.0 + this PR | 38 ms | 481 ms | 19 ms | 252 ms |
    
    At 10,000 columns, the analysis phase takes 0.1-0.5 s in every version. The 
rest of the time is about 0.13 s in 3.5.9, about 2.9 s in 4.3.0 and about 0.05 
s in 4.3.0 with this PR.
    
    On `master` with JDK 21, this PR reduces the same `cube` case from 2,690 ms 
to 355 ms and the `groupBy` case from 2,668 ms to 320 ms. Computing `output` 
once without the lazy deserializer still left 243 ms outside the analysis of 
the `cube` case. The `cube` case with `queryExecution.optimizedPlan` went from 
4,703 ms to 2,534 ms.
    
    ### Does this PR introduce _any_ user-facing change?
    
    No, except that a corner case which failed before now works. The analyzed 
plans are the same, and creating such a `DataFrame` is as fast as in Apache 
Spark 3.5 again.
    
    The corner case is a lazily analyzed `DataFrame` whose `logicalPlan.output` 
has an unresolved attribute, such as `spark.range(1).select(($"id".outer() + 
1).as("x"))`. Before this PR, `agg(sum("x"))`, `select($"x".as[Long])` and 
`as[Long].groupByKey(v => v).count()` on it failed with 
`java.lang.IllegalArgumentException: requirement failed: Input attributes must 
all be resolved.`, because `withInputType` built the deserializer for them too. 
Now they return `1`, `1` and `(1, 1)`. A typed [...]
    
    ### How was this patch tested?
    
    Pass the CIs with a new test case in `DataFrameSubquerySuite` for the 
corner case above. It fails if `withInputType` builds the deserializer eagerly 
again. Among the existing tests, `DatasetAggregatorSuite` covers typed 
aggregates in `RelationalGroupedDataset` with `aggregator in 
DataFrame/Dataset[Row]` and `spark-15051 alias of aggregator in 
DataFrame/Dataset[Row]`. The following suites also pass locally.
    
    ```
    build/sbt "sql/testOnly org.apache.spark.sql.DatasetAggregatorSuite 
org.apache.spark.sql.DeprecatedDatasetAggregatorSuite 
org.apache.spark.sql.DataFrameAggregateSuite 
org.apache.spark.sql.DataFramePivotSuite 
org.apache.spark.sql.TypedImperativeAggregateSuite 
org.apache.spark.sql.DatasetSuite org.apache.spark.sql.DataFrameSubquerySuite"
    ```
    
    In addition, the analyzed plans of untyped and typed aggregates through 
`groupBy`, `cube`, `rollup`, `groupingSets`, `pivot`, `Dataset.agg` and typed 
`Dataset.select` are the same before and after this PR, including the input 
deserializers of the typed aggregates.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Opus 5.5
    
    Closes #60260 from dongjoon-hyun/SPARK-61295.
    
    Authored-by: Dongjoon Hyun <[email protected]>
    Signed-off-by: Dongjoon Hyun <[email protected]>
    
    (cherry picked from commit 06a62a35216175f5a49b33c035bd2132bdea4590)
    Signed-off-by: Dongjoon Hyun <[email protected]>
---
 .../org/apache/spark/sql/classic/RelationalGroupedDataset.scala  | 4 +++-
 .../main/scala/org/apache/spark/sql/classic/TypedAggUtils.scala  | 4 +++-
 .../test/scala/org/apache/spark/sql/DataFrameSubquerySuite.scala | 9 +++++++++
 3 files changed, 15 insertions(+), 2 deletions(-)

diff --git 
a/sql/core/src/main/scala/org/apache/spark/sql/classic/RelationalGroupedDataset.scala
 
b/sql/core/src/main/scala/org/apache/spark/sql/classic/RelationalGroupedDataset.scala
index bd7b3348b9f0..de8680852dfe 100644
--- 
a/sql/core/src/main/scala/org/apache/spark/sql/classic/RelationalGroupedDataset.scala
+++ 
b/sql/core/src/main/scala/org/apache/spark/sql/classic/RelationalGroupedDataset.scala
@@ -61,8 +61,10 @@ class RelationalGroupedDataset protected[sql](
   import df.sparkSession.toRichColumn
 
   override protected def toDF(aggCols: Seq[Column]): DataFrame = {
+    // Compute the output at most once. For a `Project`, it creates new 
attributes on every call.
+    lazy val inputAttributes = df.logicalPlan.output
     val aggExprs = aggCols.map(_.expr).map { e =>
-      withInputType(e, df.exprEnc, df.logicalPlan.output)
+      withInputType(e, df.exprEnc, inputAttributes)
     }
 
     @scala.annotation.nowarn("cat=deprecation")
diff --git 
a/sql/core/src/main/scala/org/apache/spark/sql/classic/TypedAggUtils.scala 
b/sql/core/src/main/scala/org/apache/spark/sql/classic/TypedAggUtils.scala
index d474522fe12f..b7994e99e143 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/classic/TypedAggUtils.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/classic/TypedAggUtils.scala
@@ -50,7 +50,9 @@ private[sql] object TypedAggUtils {
       expr: T,
       inputEncoder: ExpressionEncoder[_],
       inputAttributes: Seq[Attribute]): T = {
-    val unresolvedDeserializer = 
UnresolvedDeserializer(inputEncoder.deserializer, inputAttributes)
+    // Build it only for a typed aggregate. Its constructor checks every input 
attribute.
+    lazy val unresolvedDeserializer =
+      UnresolvedDeserializer(inputEncoder.deserializer, inputAttributes)
     val transformed = expr transform {
       case ta: TypedAggregateExpression if ta.inputDeserializer.isEmpty =>
         ta.withInputInfo(
diff --git 
a/sql/core/src/test/scala/org/apache/spark/sql/DataFrameSubquerySuite.scala 
b/sql/core/src/test/scala/org/apache/spark/sql/DataFrameSubquerySuite.scala
index af6745af361f..486ae528b043 100644
--- a/sql/core/src/test/scala/org/apache/spark/sql/DataFrameSubquerySuite.scala
+++ b/sql/core/src/test/scala/org/apache/spark/sql/DataFrameSubquerySuite.scala
@@ -68,6 +68,15 @@ class DataFrameSubquerySuite extends SharedSparkSession {
     )
   }
 
+  test("SPARK-61295: untyped aggregates and typed columns on a lazily analyzed 
DataFrame") {
+    // The output of the unanalyzed plan has an unresolved attribute `x`, but 
these need no
+    // input deserializer.
+    val df = spark.range(1).select(($"id".outer() + 1).as("x"))
+    checkAnswer(df.agg(sum("x")), Row(1))
+    checkDataset(df.select($"x".as[Long]), 1L)
+    checkDataset(df.as[Long].groupByKey(v => v).count(), (1L, 1L))
+  }
+
   test("simple uncorrelated scalar subquery") {
     checkAnswer(
       spark.range(1).select(


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to