Skip to content

fix(optimizer): rewrite single distinct aggregates with Unsupported distinct handling - #27657

Open
mohitgurav20 wants to merge 1 commit into
apache:mainfrom
mohitgurav20:fix/rewrite-unsupported-distinct-aggregates
Open

mohitgurav20 wants to merge 1 commit into
apache:mainfrom
mohitgurav20:fix/rewrite-unsupported-distinct-aggregates

Conversation

@mohitgurav20

Copy link
Copy Markdown
Contributor

Which issue does this PR close?

Follow-up split from #26000 per review feedback from @jayzhan211.

Rationale for this change

On main, single-distinct queries combining a distinct aggregate with non-distinct companion aggregates (such as count(*)) check rewrite_pays_for_count to decide whether to rewrite to two-phase GROUP BY.

For aggregates declaring DistinctHandling::Unsupported (such as stddev), groups_accumulator_supported_for_types returns None rather than Some(false). As a result, rewrite_pays_for_count concludes the rewrite does not pay and leaves the query untouched. At execution time, the engine fails with an error because the accumulator cannot handle DISTINCT natively:

SELECT g, count(*), stddev(DISTINCT x) FROM t GROUP BY g;
-- Fails on main: STDDEV_POP(DISTINCT) aggregations are not available

SELECT count(*), stddev(DISTINCT x) FROM t;
-- Fails with same error

What changes are included in this PR?

  • Adds an early check in SingleDistinctToGroupBy::is_single_distinct_agg to ensure aggregates with DistinctHandling::Unsupported are always rewritten into the two-phase GROUP BY plan, where deduplication happens in the inner aggregation and the outer function runs non-distinct.
  • Adds an optimizer unit test covering the rewrite.
  • Adds regression tests for grouped and un-grouped stddev(DISTINCT) with companion count(*) in single_distinct_to_groupby.slt.

Are these changes tested?

Yes:

  • Unit test in datafusion/optimizer/src/single_distinct_to_groupby.rs.
  • End-to-end queries in single_distinct_to_groupby.slt.

@mohitgurav20

Copy link
Copy Markdown
Contributor Author

@mkleen @jayzhan211 sir pls free to reiview this PR as per requested.

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

Labels

optimizer Optimizer rules sqllogictest SQL Logic Tests (.slt)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant