Skip to content

Parallelize final DISTINCT through aggregation - #119012

Draft
nihalzp wants to merge 15 commits into
ClickHouse:masterfrom
nihalzp:distinct-to-aggregation
Draft

nihalzp wants to merge 15 commits into
ClickHouse:masterfrom
nihalzp:distinct-to-aggregation

Conversation

@nihalzp

@nihalzp nihalzp commented Sep 9, 2026 •

Copy link
Copy Markdown
Member

Closes: #114532
Related: #114550
Related: #48988

The final DISTINCT deduplicates on a single thread. DistinctStep::transformPipeline resizes the pipeline to one stream for the non-preliminary step and runs a single DistinctTransform over it, with one hash set holding every distinct value. The preliminary DISTINCT is parallel, but it only removes duplicates within its own stream, so everything that survives it still goes through that one set. As a result SELECT DISTINCT a FROM t stops getting faster past a few threads, while the equivalent SELECT a FROM t GROUP BY a scales: aggregation fills a hash table per thread, switches to two-level tables when they grow, and merges the buckets in parallel.

This replaces the final unordered DISTINCT with the AggregatingStep that SELECT a FROM t GROUP BY a would produce. Deduplication then gets everything aggregation already has: per-thread hash tables, two-level conversion, the parallel bucket merge, packed string keys, prefetching, and the adaptive aggregator when enable_adaptive_aggregator is on. Constant columns take no part in the deduplication: they are left out of the keys and put back by an expression step after the aggregation.

The new setting query_plan_convert_distinct_to_aggregation, enabled by default, controls it. It is not applied when:

  • the input is globally sorted, because then DISTINCT keeps the order of its input and aggregation would not.
  • a LIMIT, OFFSET, or LIMIT BY (or one of their negative and fractional variants) is above the DISTINCT, in the same query or an enclosing one: the streaming DISTINCT stops as soon as the limit is satisfied and returns the first values of its input, while an aggregation would consume the whole input first and return an arbitrary subset;
  • the source is unbounded or streaming: an aggregation would wait for an input that never ends;
  • the plan carries totals or extremes, which DISTINCT forwards and aggregation discards;
  • all DISTINCT columns are constant, because the step then stops after its first non-empty chunk;
  • the streams are already disjoint: when the table is partitioned by a function of the DISTINCT keys, allow_distinct_partitions_independently lets the final DISTINCT deduplicate each partition's stream without merging them.

max_rows_in_distinct and max_bytes_in_distinct keep their meaning. The row limit maps onto max_rows_to_group_by, the byte limit onto a new internal Aggregator::Params::max_bytes_to_group_by.

Release build on a 64-core AMD (x86_64). Times average the last three of five runs.

SELECT DISTINCT a FROM t versus SELECT a FROM t GROUP BY a on a MergeTree table with ORDER BY tuple(), merged into one part, holding 20M distinct UInt64 values (a = 0 through 19999999).

max_threads DISTINCT (master) DISTINCT (PR) GROUP BY
1 0.467 s 0.359 s 0.489 s
4 0.453 s 0.112 s 0.108 s
16 0.519 s 0.040 s 0.036 s
64 0.534 s 0.031 s 0.022 s

Wall-clock time with query_plan_convert_distinct_to_aggregation = 0 (before) and 1 (after):

workload max_threads before after speedup
20M distinct UInt64, MergeTree 1 0.467 s 0.359 s 1.30x
4 0.453 s 0.112 s 4.04x
16 0.519 s 0.040 s 12.88x
64 0.534 s 0.031 s 17.05x
40M distinct UInt64, numbers_mt 1 0.761 s 0.514 s 1.48x
4 0.767 s 0.158 s 4.86x
16 0.817 s 0.054 s 15.14x
64 0.815 s 0.051 s 15.97x
8M distinct String, numbers_mt 1 0.436 s 0.402 s 1.09x
4 0.437 s 0.106 s 4.13x
16 0.454 s 0.041 s 10.98x
64 0.466 s 0.036 s 12.83x

An explicit GROUP BY is still slightly faster in the multithreaded runs because unlike it, the rewritten query keeps the preliminary DISTINCT pass over its input.

Changelog category (leave one):

  • Performance Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Unordered SELECT DISTINCT queries with many distinct values are now several times faster: the final DISTINCT step is executed as an aggregation, so deduplication and merging run in parallel like GROUP BY instead of in a single thread. Up to 17 times faster high-cardinality DISTINCT. The optimization is controlled by the new setting query_plan_convert_distinct_to_aggregation, enabled by default.


Workflow [PR]
Sync PR [sync-upstream/pr/119012]

@nihalzp nihalzp changed the title Parallelize final DISTINCT Parallelize final DISTINCT through aggregation Sep 9, 2026
@yariks5s yariks5s self-assigned this Sep 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [46a5c41]

Summary: ❌

job_name test_name status info comment
Fast test FAIL
Build ClickHouse FAIL
Build (arm_tidy) FAIL
Build ClickHouse FAIL cidb
Code Review DROPPED
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 9, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Sep 9, 2026
@nihalzp

nihalzp commented Sep 9, 2026

Copy link
Copy Markdown
Member Author

Need streaming GROUP BY without aggregate functions first.

…tion

Resolve the conflict with the move of the settings changes history into the setting declarations
(ee6b44f): the history records this PR added to `SettingsChangesHistory.cpp` now live as
trailing arguments of the `DECLARE` of each setting.

- retargeted PR record [email protected] to 26.10 (settings-history check rule)

Also resolved conflicts in:
- `src/Core/ProtocolDefines.h`
- `src/Interpreters/executeQuery.cpp`
- `src/Processors/QueryPlan/Optimizations/QueryPlanOptimizationSettings.cpp`
- `src/Processors/QueryPlan/Optimizations/applyOrder.cpp`
- `src/Processors/QueryPlan/ReadFromRemote.cpp`

Master took query plan serialization versions 16 to 20, so this PR's aggregation limits now use version 21.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

This branch has not been deployed

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

Labels

comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Final DISTINCT pass is single-threaded and does not scale with max_threads

3 participants