Repository navigation
feat: run native sort aggregates without the sort on their grouping keys - #7817
warrenzhu25 wants to merge 3 commits into
Conversation
comphead
left a comment
There was a problem hiding this comment.
Keeping this off by default matches my comment on #7146 that it depends on DataFusion 56. The reported orderings are consistent: a dropped partial reports Nil and the final keeps its grouping-key order. Two things need fixing before this can land. The final-aggregate rewrite does not reach the native plan when the final has a native parent, and the Spark plan rebuilt by sparkFallback leaves out the dropped sort, which gives wrong results when spark.comet.exec.transitionRevert.enabled is also on. The fork run failed Spark 4.1, JDK 17 [exec], which runs CometAggregateSuite, along with the Celeborn reflection and one Iceberg build job. I could not read those logs. With the config off by default, only the new tests change behavior, so could you check whether one of them is the failure?
| .getOrElse(exchange) | ||
| case _ => exchange | ||
| } | ||
| case agg: CometSortAggregateExec if isFinal(agg) => |
There was a problem hiding this comment.
This rewrite does not reach the native plan when the final aggregate has a native parent. When a parent is converted, its nativeOp embeds its children's nativeOp (builder.addChildren(childOp) in the conversion around line 1466), and convertBlock serializes only the root's nativeOp. Take a final aggregate under CometSortMergeJoinExec, CometProjectExec or CometFilterExec. The Spark plan shows no CometSortExec and sets droppedInputSort, but the block still runs the old HashAgg over Sort. The comment at line 473 describes the same trap. The PR description says the gain and the loss both come from the partial, and a partial under a shuffle never has a native ancestor in its block. I suggest dropping only the partial's sort and removing the final branch, Complete and the orderedOutput parameter. A dropped sort would then always mean no output ordering. If the final branch stays, its ancestors need their nativeOp rebuilt, as refreshStaleShuffleScans does with withRefreshedNativeOp.
There was a problem hiding this comment.
Good catch — simplified in 0e5de7f to drop only the input sort of a partial aggregate directly under a shuffle exchange, and removed the final/complete branch and orderedOutput. Since the shuffle ends the native block, the partial never has a native ancestor whose embedded nativeOp could go stale.
| if (orderedOutput) super.outputOrdering else Nil | ||
|
|
||
| // Spark's sort aggregate reads its input in grouping-key order, so put the sort back. | ||
| override def restoreSparkPlan(children: Seq[SparkPlan]): SparkPlan = |
There was a problem hiding this comment.
CometExec.sparkFallback is the existing hook for this. Its doc says that operators which change the Spark plan shape must override it. RevertNativeForTransitionHeavyStages.revertToSpark (line 311) and MakeDateEvaluation (line 442) call sparkFallback, not restoreSparkPlan. So with spark.comet.exec.transitionRevert.enabled also on, a reverted stage gets a Spark SortAggregateExec in Final mode over unsorted shuffle output. That operator emits a row for each run of equal keys, so the result has duplicate groups. Overriding sparkFallback here and calling it from the three CometExecRule sites would cover every path and remove the second method. I did not run this.
There was a problem hiding this comment.
Fixed in 0e5de7f: removed restoreSparkPlan, overrode CometExec.sparkFallback on CometSortAggregateExec (calling super.sparkFallback with the re-wrapped SortExec child), and switched the three CometExecRule sites to sparkFallback. Also added a transitionRevert.enabled=true test.
| "SELECT a._1, a.m, b._2 FROM (SELECT _1, max(_2) AS m FROM sa GROUP BY _1) a " + | ||
| "JOIN sa_keys b ON a._1 = b._1") | ||
| val (_, plan) = checkSparkAnswer(df) | ||
| val finalAgg = sortAggregates(plan).find(_.modes == Seq(Final)) |
There was a problem hiding this comment.
This test passes whether or not the final aggregate's output sort runs. The final's parent is the join, and the join's native plan still holds the aggregate's input Sort (see my comment on dropSortAggregateInputSorts). I found this by reading the code and did not run it. An assertion on the serialized native plan, for example that no Sort is the child of the final HashAgg, would show which plan actually runs. The same applies to the join query in the null, float and multi-column key test.
There was a problem hiding this comment.
Updated in 0e5de7f: with only the partial under a shuffle dropping its sort, the tests now assert both on droppedInputSort.isDefined and directly on the partial's serialized nativeOp protobuf (!hasSortBelowHashAgg(partial.nativeOp)).
| withSortAggregateTables(dropInputSort = true) { | ||
| val (_, plan) = checkSparkAnswer( | ||
| sql("SELECT _1, max(_2) FROM (SELECT /*+ REPARTITION(_1) */ * FROM sa) GROUP BY _1")) | ||
| sortAggregates(plan).filter(_.modes == Seq(Partial)).foreach { partial => |
There was a problem hiding this comment.
If the filter is empty, the foreach does nothing and the test passes. That happens if the partial stops converting or Spark stops planning one. Assert that a Partial aggregate was found, as the other tests do with nonEmpty.
There was a problem hiding this comment.
Fixed in 0e5de7f — added assert(partials.nonEmpty, plan) before the foreach.
| .booleanConf | ||
| .createWithDefault(false) | ||
| val COMET_EXEC_SORT_AGGREGATE_DROP_INPUT_SORT_ENABLED: ConfigEntry[Boolean] = | ||
| conf("spark.comet.exec.sortAggregate.dropInputSort.enabled") |
There was a problem hiding this comment.
Rule T3 of the documentation style guide (docs/source/contributor-guide/style_guide.md) asks for "Rust-implemented" or "runs in Comet" instead of "native" on its own, as in "a native sort aggregate" and "The native aggregate hashes its groups". If only the partial keeps this behavior, the doc can also be shorter: say that a partial aggregate under a shuffle skips the sort, and that order-sensitive functions keep it.
There was a problem hiding this comment.
Updated in 0e5de7f to follow Rule T3 ("running in Comet" / "Rust-implemented") and shortened to describe the partial-under-shuffle behavior.
…de droppedInputSort in equals
|
Thanks for the thorough review @comphead! Addressed all comments in 0e5de7f:
|
Which issue does this PR close?
Closes #7146.
Rationale for this change
Spark plans a
SortAggregateExecwhen an aggregation buffer cannot hold a value in anUnsafeRow, for example a stringmin/max, andEnsureRequirementsputs aSortExecon the grouping keys under it. The sort exists only because of Spark's hash map limitation. Comet keeps it, so the native plan sorts the whole input before an aggregate that hashes its groups anyway. That sort is the expensive and fragile part: in #7146, a job grouping by 87 columns with stringmin/maxfailed 39 of 40 map tasks withAdditional allocation failed for OrderedPartialAggregateStream[0], and retries failed inExternalSorterMerge[0].What changes are included in this PR?
Behind a new config,
spark.comet.exec.sortAggregate.dropInputSort.enabled(off by default), a pass inCometExecRuleafter the conversion pass removes that sort:ordered_by_grouping_keys, so the native planner sorts the aggregated rows, one per group, instead of the input. The grouping-key order that Spark reports, and may have removed a sort above on the strength of (for example under a sort-merge join), still holds.first,last,collect_list,listagg) keep the sort.CometSortAggregateExecrecords the dropped sort, andrestoreSparkPlan, now used by every path that restores a Spark aggregate from a Comet one, puts it back, so a Spark sort aggregate never reads unsorted input after a fallback.withoutAggregateInputSortsplices theSortout of the aggregate's native plan, under the resultProjectionwhen there is one.No native changes.
Why off by default
min/maxretains (Native string and binarymin/maxunder-report memory in hash aggregates #6936). The fix, Fix retained-capacity accounting for grouped byte MIN/MAX datafusion#26154, is in DataFusion 56.0.0, which deps: upgrade to DataFusion 56.0.0 #7249 brings in. Until then, moving these aggregates from the ordered streams to the hash path could let native memory exceed its reservation.CometSortAggregateBenchmark, stringmin/maxover 8M rows,local[1]:String and multi-column keys cost more to sort, so dropping the sort gains more for them. The gain and the loss both come from the partial aggregate (dropping only the final's sort changes little either way). With few rows per group, the partial reduces little, and a hash aggregate over ~2M groups (3.58 s) is slower than sorting and streaming them (1.34 s sort + 0.78 s aggregate). Metrics show no spill. The cost is in DataFusion's grouped string
min/maxaccumulator at high cardinality, which apache/datafusion#27920 (for apache/datafusion#27914) makes 8% to 27% faster in micro-benchmarks; the rest is the cache miss of updating random groups, inherent to hashing.Reliability under memory pressure, which is what #7146 reports. A 12-column group-by with string
min/maxover 4.2M rows, nearly one group per row, off-heap pool of 64 / 128 / 256 MB,local[1]:Additional allocation failed for OrderedPartialAggregateStream[0]The ordered partial aggregate cannot spill on input sorted on every grouping key, as #7146 describes, while the hash partial emits early and spills. So in the issue's shape the change turns a failing query into one that completes, even where it is not faster.
So the config is documented as a win when each task sees many rows per group, and off for queries that pick one value per id. Turning it on by default needs DataFusion 56, and either the DataFusion improvement above or a runtime choice between hashing and sorting the partial; I'll open a follow-up for that.
How are these changes tested?
New tests in
CometAggregateSuite, with and without AQE:SortAggregate drops the sort on its grouping keys when enabled: results match Spark; noCometSortExecremains under either aggregate; the partial reports no ordering and the final keeps it;restoreSparkPlanputs the sort back. A second query reorders the result to cover theProjectionabove the native aggregate. With the config off, the sorts stay.SortAggregate keeps its input sort for an order-sensitive aggregate(first).SortAggregate without its input sort still feeds a sort-merge join in key order: the final aggregate feeds a sort-merge join with no sort between them, and the results match Spark.SortAggregate keeps a partial's input sort when no shuffle follows it: input already partitioned on the key, so the final reads the partial directly.SortAggregate without its input sort orders null, float and multi-column keys: null, NaN, -0.0/0.0, infinity and null string keys across three grouping columns, also feeding a sort-merge join.SortAggregate drops the input sorts of a distinct aggregate's first and last stages.SortAggregate without its input sort feeds a Spark final aggregate correctly: the final stays in Spark.SortAggregate keeps its input sort for every order-sensitive aggregate(last,collect_list).Also run locally with the config forced on:
CometAggregateSuite,CometExecRuleSuiteandCometInMemoryCacheSuite, 386 passed, 0 failed (1 canceled, Spark 4.2 only).CometSortAggregateBenchmarkis new and produces the table above.Note:
mainnow uses Arrow Java 20.0.0, which my build environment cannot fetch yet, so I built and ran the tests on the commit just before #7664 with this change cherry-picked; it applied without conflicts and touches nothing Arrow-specific. CI here covers currentmain.