← Back to Pull requests

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

Open
unknown opened this pull request with 650 lines diff across 8 files
View on GitHub
unknown unknown commented on Dec 01, 2026 20:41 UTC
Author

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 (#6936). The fix, apache/datafusion#26154, is in DataFusion 56.0.0, which #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.

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: comphead Review duration: 1553m
    All Vouch review confidence checks passed
    Residual risk 0.28 = Change Risk (0.52) × (1 − Review Confidence (0.47)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.02 · 1 substantive comment(s)
    0.02
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    46%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.344
    Real PR Conversation Timeline
    1 comments
    "Review active on #7817"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 46.7% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 46.7% · Lower = rushed or shallow review
    46.7%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 27.7% · Safe to merge
    27.7%