Skip to content

fix: Only apply SingleDistinctToGroupBy rewrite when it pays (closes #25932) - #26000

Open
mohitgurav20 wants to merge 1 commit into
apache:mainfrom
mohitgurav20:fix/single-distinct-groupby-memory-usage
Open

mohitgurav20 wants to merge 1 commit into
apache:mainfrom
mohitgurav20:fix/single-distinct-groupby-memory-usage

Conversation

@mohitgurav20

Copy link
Copy Markdown
Contributor

Which issue does this PR close?

Closes #25932

Rationale for this change

The SingleDistinctToGroupBy rule rewrites queries like SELECT g, sum(DISTINCT x) FROM t GROUP BY g into a two-step aggregation. While this rewrite can sometimes be faster, it can also consume over 2x more memory because the first step groups by both g and x.

DataFusion now has highly optimized GroupsAccumulator implementations for aggregates like sum, min, and max. If an aggregate natively supports GroupsAccumulator, the two-step rewrite is unnecessary and highly memory-inefficient.

Previously, the optimizer rule only checked if the rewrite was "worth it" if there was a count(*) in the query. If count(*) was absent, it blindly performed the memory-intensive rewrite.

What changes are included in this PR?

  • Renamed rewrite_pays_for_count to rewrite_pays.
  • Modified is_single_distinct_agg to apply the rewrite_pays check unconditionally for all queries, rather than gating it behind the presence of a count(*) rollup.
  • Updated optimizer snapshot tests using cargo insta accept. As expected, many single distinct aggregation tests now produce simpler, single-step aggregation plans since the rewrite correctly bails out when the underlying aggregate supports GroupsAccumulator.

Are these changes tested?

Yes, the existing optimizer test suite validates these changes (with snapshots updated to reflect the new, more efficient plans for natively supported distinct aggregates).

@github-actions github-actions Bot added the optimizer Optimizer rules label Oct 3, 2026
@mohitgurav20
mohitgurav20 force-pushed the fix/single-distinct-groupby-memory-usage branch from 527a544 to 9e8dfe6 Compare October 4, 2026 16:36
@github-actions github-actions Bot added the core Core DataFusion crate label Oct 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

core Core DataFusion crate optimizer Optimizer rules

Projects

None yet

Development

Successfully merging this pull request may close these issues.

sum(DISTINCT x) with GROUP BY uses twice the memory or more

1 participant