Skip to content

feat: run native sort aggregates without the sort on their grouping keys - #7817

Open
warrenzhu25 wants to merge 3 commits into
apache:mainfrom
warrenzhu25:sort-aggregate-without-sort
Open

warrenzhu25 wants to merge 3 commits into
apache:mainfrom
warrenzhu25:sort-aggregate-without-sort

Conversation

@warrenzhu25

Copy link
Copy Markdown

Which issue does this PR close?

Closes #7146.

Rationale for this change

Spark plans a SortAggregateExec when an aggregation buffer cannot hold a value in an UnsafeRow, for example a string min/max, and EnsureRequirements puts a SortExec on 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 string min/max failed 39 of 40 map tasks with Additional allocation failed for OrderedPartialAggregateStream[0], and retries failed in ExternalSorterMerge[0].

What changes are included in this PR?

Behind a new config, spark.comet.exec.sortAggregate.dropInputSort.enabled (off by default), a pass in CometExecRule after the conversion pass removes that sort:

  • Partial aggregate under a shuffle: drops the sort and no longer reports an output ordering. The shuffle discards the order anyway, and Spark sorts again below the final aggregate.
  • Final or complete aggregate: drops the sort and keeps 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.
  • Aggregates whose result depends on input order (first, last, collect_list, listagg) keep the sort.
  • The pass runs after conversion, so it only removes a sort that converted together with its aggregate. CometSortAggregateExec records the dropped sort, and restoreSparkPlan, 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.
  • withoutAggregateInputSort splices the Sort out of the aggregate's native plan, under the result Projection when there is one.
  • A partial or partial-merge aggregate keeps its sort when its parent is not a shuffle. In a distinct aggregate, the partial-merge on (key, distinct column) feeds the next aggregate directly and keeps its sort; the first partial and the final drop theirs.

No native changes.

Why off by default

  1. DataFusion 55's hash aggregate under-reports the memory that string min/max retains (Native string and binary min/max under-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.
  2. It is not faster for every cardinality. CometSortAggregateBenchmark, string min/max over 8M rows, local[1]:
GROUP BY rows per group Spark Comet, input sort Comet, no input sort vs. input sort
int key, 1,000 groups ~8,400 3,845 ms 1,701 ms 576 ms 3.0x faster
int key, 10,000 groups ~840 3,918 ms 1,896 ms 677 ms 2.8x faster
int key, 100,000 groups ~84 4,026 ms 2,085 ms 2,392 ms 15% slower
int key, 1,000,000 groups ~8 5,912 ms 3,424 ms 4,105 ms 20% slower
string key, 10,000 groups ~840 8,815 ms 4,272 ms 751 ms 5.7x faster
three keys, 11,100 groups ~760 9,526 ms 4,920 ms 823 ms 6.0x faster

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/max accumulator 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/max over 4.2M rows, nearly one group per row, off-heap pool of 64 / 128 / 256 MB, local[1]:

off-heap pool input sort (today) no input sort
64 MB fails: Additional allocation failed for OrderedPartialAggregateStream[0] succeeds, 22.6 s, spilling
128 MB fails, same error succeeds, 18.3 s, spilling
256 MB fails, same error succeeds, 19.0 s, spilling

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; no CometSortExec remains under either aggregate; the partial reports no ordering and the final keeps it; restoreSparkPlan puts the sort back. A second query reorders the result to cover the Projection above 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, CometExecRuleSuite and CometInMemoryCacheSuite, 386 passed, 0 failed (1 canceled, Spark 4.2 only).

CometSortAggregateBenchmark is new and produces the table above.

Note: main now 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 current main.

@comphead comphead left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 =

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated in 0e5de7f to follow Rule T3 ("running in Comet" / "Rust-implemented") and shortened to describe the partial-under-shuffle behavior.

@warrenzhu25

Copy link
Copy Markdown
Author

Thanks for the thorough review @comphead! Addressed all comments in 0e5de7f:

  • Simplified to drop only the partial aggregate's input sort directly under a shuffle (removed the final/complete branch and orderedOutput).
  • Overrode CometExec.sparkFallback on CometSortAggregateExec instead of restoreSparkPlan, covering RevertNativeForTransitionHeavyStages and MakeDateEvaluation too.
  • Checked the Spark 4.1, JDK 17 [exec] failure: it was CometPlanEqualitySuite flagging droppedInputSort / orderedOutput missing from equals. Added droppedInputSort to CometBaseAggregateExec.equals / hashCode and verified CometPlanEqualitySuite + all SortAggregate tests pass locally (18/18).
  • Updated the CometConf doc for Rule T3 and tightened the tests (including checking nativeOp directly and asserting partials.nonEmpty).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Run SortAggregateExec as a native hash aggregate without its input sort

2 participants