dongjoon-hyun opened a new pull request, #60260:
URL: https://github.com/apache/spark/pull/60260

   ### What changes were proposed in this pull request?
   
   This PR removes work proportional to the number of input columns from the 
per-column loop of `RelationalGroupedDataset.toDF` in Spark Classic. `toDF` 
builds the result of `groupBy`, `cube`, `rollup`, `groupingSets` and `pivot` 
aggregations and of `Dataset.agg`.
   
   - `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?
   
   For each aggregate column, `toDF` did two things that take time proportional 
to the number of input columns `N`.
   
   - It evaluated `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` created 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: _*)
   ```
   
   Local measurements on an Apple M3 Max with JDK 21. Time to create the 
`DataFrame` (Best Time) with `N` input columns `c_i` and `sum` of each of them:
   
   | Columns (N) | `cube(...).agg(...)` before | after | 
`groupBy(...).agg(...)` before | after |
   |---:|---:|---:|---:|---:|
   | 100 | 4 ms | 4 ms | 3 ms | 3 ms |
   | 1,000 | 55 ms | 31 ms | 49 ms | 25 ms |
   | 10,000 | 2,690 ms | 355 ms | 2,668 ms | 320 ms |
   
   At 10,000 columns, the analysis phase takes about 0.3 s both before and 
after. The rest of the `cube` case went from 2,356 ms to 22 ms. Computing 
`output` once without the lazy deserializer left 243 ms outside the analysis. 
The `cube` case with `queryExecution.optimizedPlan` went from 4,703 ms to 2,534 
ms.
   
   This is a regression in Apache Spark 4.0.0 from SPARK-49421 (#47918), which 
made `toDF` call `withInputType` for every aggregate column. Before, 
`RelationalGroupedDataset.agg` called it only for a `TypedColumn`.
   
   ### 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` takes less time.
   
   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"))` and `select($"x".as[Long])` on it 
failed with `java.lang.IllegalArgumentException: requirement failed: Input 
attributes must all be resolved.`, because `withInputType` built the 
deserializer for them too. Now both return `1`. A typed aggregate on it still 
fails in the same way, because it needs the deserializer.
   
   ### How was this patch tested?
   
   Pass the CIs with the existing tests. For example, `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
   


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