fix: Only apply SingleDistinctToGroupBy rewrite when it pays (closes #25932) - #26000
Open
mohitgurav20 wants to merge 1 commit into
Open
mohitgurav20 wants to merge 1 commit into
mohitgurav20 wants to merge 1 commit into
Conversation
mohitgurav20
force-pushed
the
fix/single-distinct-groupby-memory-usage
branch
from
October 4, 2026 16:36
527a544 to
9e8dfe6
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Which issue does this PR close?
Closes #25932
Rationale for this change
The
SingleDistinctToGroupByrule rewrites queries likeSELECT g, sum(DISTINCT x) FROM t GROUP BY ginto 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 bothgandx.DataFusion now has highly optimized
GroupsAccumulatorimplementations for aggregates likesum,min, andmax. If an aggregate natively supportsGroupsAccumulator, 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. Ifcount(*)was absent, it blindly performed the memory-intensive rewrite.What changes are included in this PR?
rewrite_pays_for_counttorewrite_pays.is_single_distinct_aggto apply therewrite_payscheck unconditionally for all queries, rather than gating it behind the presence of acount(*)rollup.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 supportsGroupsAccumulator.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).