Repository navigation
fix: skip SingleDistinctToGroupBy rewrite when single_distinct_prefer_native is set (closes #25932) - #26000
fix: skip SingleDistinctToGroupBy rewrite when single_distinct_prefer_native is set (closes #25932)#26000mohitgurav20 wants to merge 44 commits into
Conversation
527a544 to
9e8dfe6
Compare
There was a problem hiding this comment.
@mohitgurav20 Thanks for working on this.
Can you make sure all sql-logic tests pass, or correct them if invalid.
You can run them locally with:
cargo test --profile=ci --test sqllogictests
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #26000 +/- ##
========================================
Coverage 82.93% 82.94%
========================================
Files 1154 1154
Lines 458002 458300 +298
Branches 458002 458300 +298
========================================
+ Hits 379856 380130 +274
+ Misses 55123 55104 -19
- Partials 23023 23066 +43 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
63e9873 to
0c76607
Compare
|
@mkleen sir i have completed the work and addressed ur suggestion pls feel free to review and would like to work if any changes needed. |
|
run benchmarks |
|
🤖 Benchmark running (GKE) | trigger CPU Details (lscpu)Comparing fix/single-distinct-groupby-memory-usage (0923424) to 334f293 (merge-base) diff Run configurationrun benchmark clickbench_partitionedResults will be posted here when complete File an issue against this benchmark runner |
|
🤖 Benchmark running (GKE) | trigger CPU Details (lscpu)Comparing fix/single-distinct-groupby-memory-usage (0923424) to 334f293 (merge-base) diff Run configurationrun benchmark tpcdsResults will be posted here when complete File an issue against this benchmark runner |
|
🤖 Benchmark running (GKE) | trigger CPU Details (lscpu)Comparing fix/single-distinct-groupby-memory-usage (0923424) to 334f293 (merge-base) diff Run configurationrun benchmark tpchResults will be posted here when complete File an issue against this benchmark runner |
|
🤖 Benchmark completed (GKE) | trigger Instance: Comparing fix/single-distinct-groupby-memory-usage (0923424) to 334f293 (merge-base) diff Run configurationrun benchmark tpchCPU Details (lscpu)Details
Resource Usagetpch — base (merge-base)
tpch — branch
File an issue against this benchmark runner |
|
🤖 Benchmark completed (GKE) | trigger Instance: Comparing fix/single-distinct-groupby-memory-usage (0923424) to 334f293 (merge-base) diff Run configurationrun benchmark tpcdsCPU Details (lscpu)Details
Resource Usagetpcds — base (merge-base)
tpcds — branch
File an issue against this benchmark runner |
|
🤖 Benchmark completed (GKE) | trigger Instance: Comparing fix/single-distinct-groupby-memory-usage (0923424) to 334f293 (merge-base) diff Run configurationrun benchmark clickbench_partitionedCPU Details (lscpu)Details
Resource Usageclickbench_partitioned — base (merge-base)
clickbench_partitioned — branch
File an issue against this benchmark runner |
|
@mohitgurav20 There are serious performance regressions in the clickhouse benchmark. See #26000 (comment) for more details. |
|
Thanks for running the benchmark and flagging this @mkleen. I analyzed the benchmark run in detail: Because Without the two-phase rewrite to This confirms that the two-phase rewrite is a critical parallelization optimization for lone distinct queries, even when a specialized To address this cleanly: Does that direction sound good to you? If so, I'll update the rule accordingly so we preserve ClickBench performance. |
…pache#25932) SingleDistinctToGroupBy converts single DISTINCT aggregate expressions into a two-phase GROUP BY plan. This enables parallel deduplication via RepartitionExec hash partitioning, which is critical for lone-distinct queries like COUNT(DISTINCT x). However, when companion non-distinct aggregates are present alongside the distinct aggregate (e.g. SELECT sum(y), count(DISTINCT x)), the companion aggregates move to the inner group-by at a finer grain. When the distinct aggregate already has native GroupsAccumulator support, this inner grouping adds unnecessary memory and CPU overhead without benefiting from adapter offloading. This change: 1. Gates SingleDistinctToGroupBy with rewrite_pays() only when companion non-distinct aggregates are present. 2. Preserves the two-phase rewrite for pure lone-distinct queries so ClickBench and similar workloads maintain parallel deduplication without regression. 3. Consistently handles distinct aggregates with unsupported distinct handling. 4. Updates optimizer plan snapshots and sqllogictests.
287b932 to
ac76b0d
Compare
|
Hi @mkleen, just following up on this when you get a chance. I've rebased cleanly onto latest Could you trigger a benchmark run whenever convenient? Thanks! |
|
run benchmarks |
|
Benchmark for this request failed before finishing (Kubernetes reason: Benchmarks requested: Kubernetes messageFile an issue against this benchmark runner |
|
🤖 Benchmark running (GKE) | trigger CPU Details (lscpu)Comparing fix/single-distinct-groupby-memory-usage (bbf4ccb) to 484183d (merge-base) diff Run configurationrun benchmark tpchResults will be posted here when complete File an issue against this benchmark runner |
|
🤖 Benchmark running (GKE) | trigger CPU Details (lscpu)Comparing fix/single-distinct-groupby-memory-usage (bbf4ccb) to 484183d (merge-base) diff Run configurationrun benchmark tpcdsResults will be posted here when complete File an issue against this benchmark runner |
|
🤖 Benchmark completed (GKE) | trigger Instance: Comparing fix/single-distinct-groupby-memory-usage (bbf4ccb) to 484183d (merge-base) diff Run configurationrun benchmark tpchCPU Details (lscpu)Details
Resource Usagetpch — base (merge-base)
tpch — branch
File an issue against this benchmark runner |
|
🤖 Benchmark completed (GKE) | trigger Instance: Comparing fix/single-distinct-groupby-memory-usage (bbf4ccb) to 484183d (merge-base) diff Run configurationrun benchmark tpcdsCPU Details (lscpu)Details
Resource Usagetpcds — base (merge-base)
tpcds — branch
File an issue against this benchmark runner |
|
@mohitgurav20 Thanks! Looks good at first glance. I’ll go ahead and start the review. |
cf8fe84 to
678fe74
Compare
|
@jayzhan211 sir i have addressed the changes just go through it once whenever u are freee . |
jayzhan211
left a comment
There was a problem hiding this comment.
@mohitgurav20 thanks, everything from the last round is addressed. One optional doc fix inline.
| /// When `true`, the `SingleDistinctToGroupBy` optimizer rule keeps a grouped | ||
| /// DISTINCT aggregate native, instead of rewriting it into a two-phase `GROUP BY`, | ||
| /// when every DISTINCT argument is a fixed-width, non-float type. This lowers peak | ||
| /// memory when no memory limit is set, because the intermediate | ||
| /// `(group, distinct value)` result is never built. | ||
| /// | ||
| /// The native plan can avoid materializing distinct (group, value) pairs, | ||
| /// but can be slower for many groups with duplicate values. It must fit | ||
| /// each group's distinct values in memory, so queries that succeed by | ||
| /// spilling with the rewrite may fail with this option enabled. One target | ||
| /// partition can still have multiple input partitions and merge native states. | ||
| /// The native plan avoids materializing intermediate `(group, distinct value)` | ||
| /// pairs, which lowers peak memory when there are few groups with many | ||
| /// distinct values each. With many small groups it can use more memory and | ||
| /// run slower, because functions without a specialized DISTINCT | ||
| /// `GroupsAccumulator` (such as `sum`) keep one accumulator per group. | ||
| /// Native DISTINCT must also fit each group's distinct values in memory: | ||
| /// under a memory limit, the rewrite can spill those pairs, but the native | ||
| /// accumulator cannot, so queries that succeed by spilling with the rewrite | ||
| /// may fail with this option enabled. | ||
| /// | ||
| /// Queries without `GROUP BY`, and other argument types, keep the rewrite. |
There was a problem hiding this comment.
Optional cleanup: this doc no longer says the setting only applies at target_partitions = 1 with all-DISTINCT aggregates, so with default settings turning it on does nothing. Its first paragraph also says memory always goes down, while the second says many small groups need more. Last, "the native accumulator cannot" spill was my wording and it's wrong: at one partition with 50k groups it spilled 12 times and matched the rewrite. What it can't do is split one large group. This version fixes all three (I checked that dev/update_config_docs.sh and information_schema.slt pass with it):
| /// When `true`, the `SingleDistinctToGroupBy` optimizer rule keeps a grouped | |
| /// DISTINCT aggregate native, instead of rewriting it into a two-phase `GROUP BY`, | |
| /// when every DISTINCT argument is a fixed-width, non-float type. This lowers peak | |
| /// memory when no memory limit is set, because the intermediate | |
| /// `(group, distinct value)` result is never built. | |
| /// | |
| /// The native plan can avoid materializing distinct (group, value) pairs, | |
| /// but can be slower for many groups with duplicate values. It must fit | |
| /// each group's distinct values in memory, so queries that succeed by | |
| /// spilling with the rewrite may fail with this option enabled. One target | |
| /// partition can still have multiple input partitions and merge native states. | |
| /// The native plan avoids materializing intermediate `(group, distinct value)` | |
| /// pairs, which lowers peak memory when there are few groups with many | |
| /// distinct values each. With many small groups it can use more memory and | |
| /// run slower, because functions without a specialized DISTINCT | |
| /// `GroupsAccumulator` (such as `sum`) keep one accumulator per group. | |
| /// Native DISTINCT must also fit each group's distinct values in memory: | |
| /// under a memory limit, the rewrite can spill those pairs, but the native | |
| /// accumulator cannot, so queries that succeed by spilling with the rewrite | |
| /// may fail with this option enabled. | |
| /// | |
| /// Queries without `GROUP BY`, and other argument types, keep the rewrite. | |
| /// When `true` and `target_partitions` is 1, the `SingleDistinctToGroupBy` | |
| /// optimizer rule keeps a grouped aggregate whose aggregates are all DISTINCT | |
| /// native, instead of rewriting it into a two-phase `GROUP BY`, when every | |
| /// DISTINCT argument is an integer, boolean, decimal, date, time, timestamp | |
| /// or interval type. | |
| /// | |
| /// The native plan avoids materializing intermediate `(group, distinct value)` | |
| /// pairs, which lowers peak memory when there are few groups with many | |
| /// distinct values each. With many small groups it can use more memory and | |
| /// run slower, because functions without a specialized DISTINCT | |
| /// `GroupsAccumulator` (such as `sum`) keep one accumulator per group. | |
| /// Native DISTINCT must also fit each group's distinct values in memory: | |
| /// under a memory limit, it can spill whole groups but not split one group's | |
| /// distinct values, so a query with a few large groups that succeeds by | |
| /// spilling with the rewrite may fail with this option enabled. | |
| /// | |
| /// Queries without `GROUP BY`, and other argument types, keep the rewrite. |
There was a problem hiding this comment.
@jayzhan211 sirr i Applied the updated doc wording across config.rs, configs.md, and information_schema.slt. Verified information_schema.slt and the Prettier checks pass cleanly. Thanks for catching the spill distinction.
…group spill behavior
alamb
left a comment
There was a problem hiding this comment.
Thank you @mohitgurav20 and @jayzhan211 . I think this code looks ok, but I think we should clean up the tests and comments if possible before merging
cc @mkleen
| /// and every aggregate explicitly supports a specialized GroupsAccumulator | ||
| /// for its DISTINCT argument types. Defaults to false, preserving the | ||
| /// two-phase GROUP BY rewrite. | ||
| /// When `true` and `target_partitions` is 1, the `SingleDistinctToGroupBy` |
There was a problem hiding this comment.
Can we please rephrase this so it starts with the impact of this knob -- I think it is "queries with a single DISTINCT aggregate will take less memory but also run more slowly"?
i think all the background of the tradeoff is way too much detail for the config docs -- it probably belongs on the SingleDistinctToGroupBy docs, with perhaps a link from the config
|
|
||
| /// Check whether all aggregate exprs are eligible for the single-distinct-to-group-by rewrite. | ||
| /// | ||
| /// With `use_native_grouped_distinct` enabled (which requires one target partition, |
There was a problem hiding this comment.
can you please summarieze this paragraph -- it has too much irrelevant detail (eg. restating what use_native_grouped_distinct does in English)
| Ok(()) | ||
| } | ||
|
|
||
| fn unsupported_distinct(expr: Expr) -> Expr { |
There was a problem hiding this comment.
If these can be .slt tests, I think we should rewrite them to be slt -- the rust is far more verbose
|
thanks @alamb addressed all three points in the latest commit: Rephrased the config doc to lead with the memory vs performance impact, moving the deeper background into SingleDistinctToGroupBy docs. |
|
all checks are running green pls fell free to review this pr . |
|
Can someone remind me how we tested this and what the performance benefit is? I worry it just some hard to tune knob and we will break something for some other user / cause some queries to slow down and others to speed up Can we spend our attention trying to make everything faster somehow? |
|
@alamb fair question. The earlier numbers were for an older version. I re-ran the current pr using the #24929 method (target_partitions = 1, 4M rows, ~1M distinct x, smallest -m that finishes with -d 0 --mem-pool-type greedy). In the current state, we are trading performance for memory efficiency when we have few large groups and no memory limit. At the same time it hurts with many small groups. So it's complicated and as @asolimando suggested in #26000 (comment) this might be a cost-based-optimization (CBO) usecase. The current knob behaviour is tricky to figure out correctly. Anyway, your suggestion to makes things faster makes sense to me. So to improve the performance of |
That sounds like a better path to me -- it would improve for everyone |
|
@mohitgurav20 thanks for all the work on this. You went through several iterations, and now there's a new suggestion. Sorry about that. Would you like to continue? Shall we plan the native distinct group accumulator for sum together in a ticket before diving in? |
|
@mohitgurav20 sorry, I wasn't clear before. Our suggestion was to drop this pr, not continuing on it. The setting helps in some cases and hurts in others, so it's hard to get right. A native distinct sum accumulator is the right way forward. If you want to take that on, open a ticket with a rough plan first and we can figure it out together. Thanks for sticking with this! |
jayzhan211
left a comment
There was a problem hiding this comment.
@mohitgurav20 thanks for sticking with this. I agree with @mkleen that this PR should be closed, so I'm replacing my earlier approval. One part is worth keeping: the DistinctHandling::Unsupported early return fixes queries that fail on main at default settings. Could you open just that as its own small PR, with no config change?
SELECT g, count(*), stddev(DISTINCT x) FROM t GROUP BY g; -- main: STDDEV_POP(DISTINCT) aggregations are not available
SELECT count(*), stddev(DISTINCT x) FROM t; -- same error; not tested in this PROn the sum path: when I put main's check (groups_accumulator_supported_for_types == Some(true)) back in place of the type list, the only test that changes is sum(DISTINCT x) staying native, the case @mkleen measured 2–2.6x slower. So a native DISTINCT sum GroupsAccumulator that returns Some(true) there is picked up by the existing single_distinct_prefer_native with no change to this rule.
|
Good call sir i have closed this. Opened #27657 with just the DistinctHandling::Unsupported fix and the stddev tests as suggested. Thanks @mkleen and @jayzhan211! |
|
@mkleen @jayzhan211 sir i have closed this pr as per ur suggestion and worked on the DistinctHandling::Unsupported fix and the stddev tests and opened the pr #27657 pls feel free to review its open .thanks you |
|
Thanks for the efforts here |
|
@alamb thanks sir for ur guidance and help .. have a nice day |
Which issue does this PR close?
Closes #25932.
Rationale for this change
In queries with a single distinct aggregation,
SingleDistinctToGroupByrewrites the plan into a two-phaseGROUP BY. While this enables partition parallelism, it materializes intermediate(group, distinct_value)pairs, increasing peak memory when there are few groups with many distinct values each (~538–599 MiB vs ~306 MiB in unconstrained memory runs on #25932).PR #25988 previously introduced
datafusion.optimizer.single_distinct_prefer_nativeforCOUNT(DISTINCT int). Per review feedback from @mkleen and @jayzhan211, this PR consolidates both intodatafusion.optimizer.single_distinct_prefer_nativerather than adding a second knob.At
target_partitions = 1, nativeGroupsAccumulatorexecution avoids the two-phase grouping overhead and reduces peak memory for queries with few large groups on fixed-width types (e.g.sum(DISTINCT int)andcount(DISTINCT int)). Whentarget_partitions > 1, queries continue using the two-phase rewrite to maintain partition fan-out and support spilling under memory limits.Additionally, queries with unsupported distinct aggregates alongside non-distinct aggregates (such as
SELECT g, count(*), stddev(DISTINCT x) ... GROUP BY g) now rewrite correctly at default settings instead of erroring at runtime as on main.What changes are included in this PR?
Consolidated Configuration Knob:
datafusion.optimizer.single_distinct_prefer_native: bool(defaultfalse) to govern native single distinct execution.Opt-in Native Execution Gating:
single_distinct_prefer_native = trueandtarget_partitions == 1, skips the two-phase rewrite if all distinct aggregate arguments are fixed-width primitive types (integers, dates, decimals) supported natively.f32,f64) to preserve IEEE 754-0.0 == 0.0semantics.Durationtypes (sinceavglacks a native distinct accumulator for durations).target_partitions > 1, non-distinct companion aggregates are present, or distinct handling is unsupported (approx_median,stddev).Documentation & Schema Synchronization:
docs/source/user-guide/configs.mdandinformation_schema.slt.Are these changes tested?
Yes:
single_distinct_to_groupby.rscovering flag states, partition gating (target_partitions == 1vs> 1), float argument exclusions, and unsupported aggregate fallbacks.single_distinct_to_groupby.sltcovering plans, execution, duration distinct handling, andstddev(DISTINCT x)default execution.Are there any user-facing changes?
Yes:
datafusion.optimizer.single_distinct_prefer_nativeto cover other fixed-width distinct aggregates likesum(DISTINCT int).SELECT g, count(*), stddev(DISTINCT x) ... GROUP BY gthat previously errored on main now succeed at default settings.