Skip to content

Deduplicate the final DISTINCT in parallel - #114550

Merged
nihalzp merged 107 commits into
masterfrom
parallel-distinct
Oct 20, 2026
Merged

nihalzp merged 107 commits into
masterfrom
parallel-distinct

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 12, 2026 •

Copy link
Copy Markdown
Member

The final DISTINCT merged all of its input streams into one and deduplicated them on a single thread, so SELECT DISTINCT did not scale with max_threads while the equivalent GROUP BY did - aggregation parallelizes its merge over two-level hash tables, DISTINCT had nothing of the sort.

This repartitions the input streams by the hash of the DISTINCT columns instead of merging them: equal values then land in the same stream, so every stream can be deduplicated on its own, and what is left to merge is already deduplicated. The repartitioning uses scatterByPartition, which SortingStep and ShuffleSendStep already use.

The decision is taken in the applyStreamDisjointness plan optimization. An input-order requirement set by applyOrder keeps the final DISTINCT on one merged stream, because hash partitioning would reorder its rows.

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

  • the input is already globally sorted, or a consumer requires the input order, because then DISTINCT keeps the order of its input and the repartitioning would break it;
  • the final DISTINCT deduplicates sorted input (optimize_distinct_in_order), or follows a preliminary DISTINCT in input order, because sorted deduplication needs equal prefix values to stay contiguous;
  • the streams are already disjoint - allow_distinct_partitions_independently covers that case and skips the merge entirely.

It is applied under LIMIT, OFFSET and LIMIT BY over unordered input: a DISTINCT without ORDER BY has no defined row order, so any subset of the distinct values is a valid result (05212_parallel_distinct_order_requirements pins this).

max_rows_in_distinct and max_bytes_in_distinct keep their global meaning: the streams hold disjoint parts of one DISTINCT set, so the transforms add up the sizes of their sets in a shared counter and check the limits against the total. Enforcing them in the single final transform instead would have disabled the optimization for everyone who sets them - including all of CI, where the test profile sets both to 10G.

Every input chunk is split across all partitions, so the number of partitions is capped rather than following max_threads. On SELECT DISTINCT number FROM numbers_mt(4e7) the total CPU time the scatter adds grows by 8% at 4 partitions, 20% at 16 and 96% at 96; without the cap that turned into a wall-clock regression at high max_threads.

Wall clock, minimum of 3 runs, aarch64:

workload max_threads before after speedup
20M distinct UInt64, MergeTree 4 0.442 s 0.205 s 2.16x
16 0.458 s 0.148 s 3.09x
96 0.502 s 0.165 s 3.04x
40M distinct UInt64, numbers_mt 4 0.965 s 0.545 s 1.77x
16 0.929 s 0.360 s 2.58x
96 0.886 s 0.299 s 2.96x
8M distinct String, numbers_mt 4 0.515 s 0.288 s 1.79x
16 0.517 s 0.093 s 5.56x
96 0.518 s 0.083 s 6.24x

The measurements were taken on a busy machine, hence the minimum of several runs; the existing distinct_in_order, distinct_high_cardinality and sorted_distinct performance tests cover these shapes, so the performance comparison job is the authoritative check.

DISTINCT without ORDER BY has no defined row order, and the repartitioning changes the order it happens to produce. Two existing tests relied on it: 04109_sort_propagation_apply_order asserts that per-stream sortedness reaches DISTINCT, so it pins the setting off, and 00585_union_all_subquery_aggregation_column_removal gets the explicit ORDER BY it was missing. Other tests that depend on the incidental order of a DISTINCT may surface in CI and should be fixed the same way.

Closes: #114532
Related: #48988

Changelog category (leave one):

  • Performance Improvement

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

Evaluate the final DISTINCT on several threads by repartitioning its input by the hash of the DISTINCT columns, instead of merging everything into a single stream and deduplicating it on one thread. Up to 6x faster on high-cardinality DISTINCT. Controlled by the new setting allow_parallel_distinct, enabled by default. Note that this changes the order in which a DISTINCT without ORDER BY returns rows, which was never defined.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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

Version info

  • Merged into: 26.11.1.284-master (included in 26.11 and later)

The final `DISTINCT` merged all of its input streams into one and deduplicated
them on a single thread, so `SELECT DISTINCT` did not scale with `max_threads`
while the equivalent `GROUP BY` did - aggregation parallelizes its merge over
two-level hash tables, `DISTINCT` had nothing of the sort.

Repartition the input streams by the hash of the `DISTINCT` columns instead of
merging them: equal values then land in the same stream, so every stream can be
deduplicated on its own, and what is left to merge is already deduplicated. The
repartitioning uses `scatterByPartition`, which `SortingStep` and
`ShuffleSendStep` already use.

The new setting `allow_parallel_distinct`, on by default, controls it. Whether
the order of the step's output is free is only known where the sorting
properties are, so the decision is taken in `applyOrder`. It is not applied
when the input is globally sorted, when `max_rows_in_distinct` or
`max_bytes_in_distinct` is set, when there is a `LIMIT`, or when the streams
are already disjoint - `allow_distinct_partitions_independently` covers that
case and skips the merge entirely.

Every input chunk is split across all partitions, so the number of partitions
is capped rather than following `max_threads`: on `SELECT DISTINCT number FROM
numbers_mt(4e7)` the total CPU time the scatter adds grows by 8% at 4
partitions, 20% at 16 and 96% at 96.

Wall clock, minimum of 3 runs, aarch64:

    workload                     threads    before     after   speedup
    20M distinct UInt64                4   0.442 s   0.205 s     2.16x
    (MergeTree)                       16   0.458 s   0.148 s     3.09x
                                      96   0.502 s   0.165 s     3.04x
    40M distinct UInt64                4   0.965 s   0.545 s     1.77x
    (numbers_mt)                      16   0.929 s   0.360 s     2.58x
                                      96   0.886 s   0.299 s     2.96x
    8M distinct String                 4   0.515 s   0.288 s     1.79x
    (numbers_mt)                      16   0.517 s   0.093 s     5.56x
                                      96   0.518 s   0.083 s     6.24x

`DISTINCT` without `ORDER BY` has no defined row order, and the repartitioning
changes the order it happens to produce. Two tests relied on it:
`04109_sort_propagation_apply_order` asserts that per-stream sortedness reaches
`DISTINCT`, so it pins the setting off, and
`00585_union_all_subquery_aggregation_column_removal` gets the explicit
`ORDER BY` it was missing.

Closes: #114532
Related: #48988

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4323f08]

Summary: ✅


AI Review

Summary

PR #114550 parallelizes final DISTINCT through hash partitioning, retains required input ordering, and enforces combined size limits across disjoint streams. Reviewed head 4323f088baa1614e8a1cec68ec8bb67f60782ac9, including the current code, regression coverage, and all prior discussion. No unresolved actionable findings remain.

Missing context / blind spots
  • ⚠️ Local execution and independent extraction of CI performance metrics were unavailable because no clickhouse binary is installed. Performance evidence comes from the PR's before/after measurements; the current CI report reports green. Running the performance-report tool with a binary available would close this verification gap.
Final Verdict

Status: ✅ Approve. No new inline findings or thread updates are warranted.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 12, 2026
alexey-milovidov and others added 2 commits August 13, 2026 23:08
…ation

`max_rows_in_distinct` and `max_bytes_in_distinct` were enforced by the single
`DistinctTransform` that saw the whole merged input, so the parallel path simply
gave up whenever either limit was set. That is how the `Fast test` failed: the CI
profile sets both limits to `10G` in `tests/config/users.d/limits.yaml`, so the
optimization was off in every stateless test, including its own.

The scattered streams hold disjoint parts of one `DISTINCT` set - equal values
meet in the same stream - so the sizes of their sets add up to the size of the
whole set. The transforms now accumulate them in a shared counter and check the
limits against the total, which keeps the limits global and lets the
optimization run under them.

The test gains the two cases that tell a global limit from a per-stream one: a
limit of 500 on a set of 1000 values scattered over 4 streams, which a
per-stream limit would let pass, and a `max_bytes_in_distinct` case.

`allow_parallel_distinct` is added to `experimental_settings_ignore.txt`: it is
not an experimental feature, so it does not belong in
`enableAllExperimentalSettings`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 31 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 0073a68f-00c4-4a99-97a8-53fed18f3967
  • MIRAI run: 381f8c5f-aebc-40f7-85bd-a3ba505366ba
  • PR check IDs:
    • clickbench_1029293_1791801523
    • clickbench_1029299_1791801523
    • clickbench_1029305_1791801523
    • tpch_adapted_1_official_1029316_1791801523
    • tpch_adapted_1_official_1029327_1791801523
    • tpch_adapted_1_official_1029363_1791801523

@clickhouse-gh

clickhouse-gh Bot commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 4323f088b with master 0a3052562 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

60 object files changed (+193.44 KiB total), 2 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/Transforms/DistinctLimitsCheckingTransform.cpp.o new 92.88 KiB +92.88 KiB
src/CMakeFiles/dbms.dir/Processors/Transforms/DistinctSetMemoryTracker.cpp.o new 52.71 KiB +52.71 KiB
src/CMakeFiles/dbms.dir/Processors/Transforms/DistinctTransform.cpp.o 94.69 KiB 113.29 KiB +18.60 KiB (+19.64%)
src/CMakeFiles/dbms.dir/Processors/Transforms/DistinctSetFilter.cpp.o 439.31 KiB 455.72 KiB +16.41 KiB (+3.74%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/DistinctStep.cpp.o 174.58 KiB 190.89 KiB +16.31 KiB (+9.34%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

163 translation units recompiled, 1462 s compile time in total, 161 of them have a recent master baseline.

Job report

@CLAassistant

CLAassistant commented Aug 15, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

Comment thread src/Planner/Planner.cpp Resolved
Comment thread src/Processors/QueryPlan/DistinctStep.h Resolved
Comment thread src/Planner/Planner.cpp Resolved
@nihalzp nihalzp self-assigned this Oct 19, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

@nihalzp, waiting for review.

@nihalzp
nihalzp added this pull request to the merge queue Oct 20, 2026
Merged via the queue into master with commit 45dcd38 Oct 20, 2026
179 checks passed
@nihalzp
nihalzp deleted the parallel-distinct branch October 20, 2026 08:24
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 20, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 21, 2026
…eplicas

Same mechanism as 02317_distinct_in_order_optimization. Since ClickHouse#114550 the
final DISTINCT hash-partitions its input (DistinctStep::tryScatterStreams)
when it has more than one input stream and max_threads > 1. Under parallel
replicas the initiator's final DISTINCT has several input streams (local
plan plus remote replicas), so the two rows of `test_string` can land in
different partitions and reach the client in either order. CI's own rerun
with the failing run's settings reproduced it 19 of 446 times on PR ClickHouse#127095;
the test had 0 failures in 33352 runs before the merge.

The returned set is unchanged and a DISTINCT without ORDER BY has no
defined row order, so pin it with ORDER BY c1. The reference is unchanged.
With ORDER BY the final DISTINCT runs after the sort and keeps the input
order, which forbids the scatter.

The 49622 path stays covered (in-order DISTINCT with an empty-string
non-sorted column, preliminary and final): the preliminary DISTINCT is
still planned directly above the in-order read with the `c1` prefix, and
the final DISTINCT now also runs in order over `c1`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov added a commit to UnamedRus/ClickHouse that referenced this pull request Oct 21, 2026
Reconcile the bloom-filter `DISTINCT` with master's parallel `DISTINCT` (ClickHouse#114550):
- `DistinctTransform` takes master's `shared_set_bytes_` and `coalesce_rows_`
  before the bloom-filter parameters.
- The own-set path (bloom filter, parallel probing) is not used when the set
  memory is accounted globally across disjoint streams (`shared_set_bytes_`),
  because it does not report to `DistinctSetMemoryTracker`.
- Coalescing flushes when the own set is released, not merely when
  `distinct_set` is absent (which it always is on the own-set path).
- The thread budget of the final `DISTINCT` is shared among all its streams,
  including streams created by the scattered parallel `DISTINCT`.
- Plan serialization version 21 now covers both
  `min_bytes_before_external_group_by` and the bloom-filter settings.
alexey-milovidov pushed a commit to jayvenn21/ClickHouse that referenced this pull request Oct 21, 2026
…itions_*

Since ClickHouse#114550 the final DISTINCT hash-partitions a multi-stream input
(ScatterByPartitionTransform into several ExternalDistinctTransform), so
values from different partitions are emitted in scheduling order; a
DISTINCT without ORDER BY has no defined row order. The 13 SELECT DISTINCT
queries in each of the three twin tests had no ORDER BY while the
references expect 2 before 3 and 222 2 before 333 3.

On master the hash and partial_merge joins emit one stream, so the tests
pass there; a join that emits several streams (parallel_hash, or the
unified hash join of ClickHouse#115605) makes the hash test fail.

ORDER BY ALL sorts by every selected column; the references are already
ascending and stay unchanged.

Closes ClickHouse#127154

Co-Authored-By: Claude Opus 5.5 <[email protected]>
JTCunning pushed a commit to JTCunning/ClickHouse that referenced this pull request Oct 21, 2026
…s all-constant

The parallel final DISTINCT (ClickHouse#114550) hands its ScatterByPartitionTransform
lanes downstream as separate streams, and a scatter holds its input chunk
until every unfinished lane has accepted its piece, so the lanes are coupled.
A full sort normally decouples them, because MergeSortingTransform consumes
its whole input first. When every sort key is a constant, SortingTransform
strips them all and MergeSortingTransform::consume passes chunks through,
yet SortingStep::fullSort still merged the lanes with MergingSortedTransform.
With all keys equal the cursor tie-break is the source number, so the merge
asks for its first input only, until that input finishes. The first lane
finishes only after every scatter has finished, and a scatter cannot finish
while the lanes the merge does not read are full: Pipeline stuck (a logical
error, so debug and sanitizer servers abort).

Reachable without the fuzzer, e.g.
  SELECT * FROM (SELECT DISTINCT 'x' AS c, number FROM numbers_mt(100000))
  ORDER BY c SETTINGS max_threads = 4, max_block_size = 100
and with a window OVER (ORDER BY <constant>). DISTINCT and ORDER BY in the
same SELECT are not affected: preserveInputOrder() forbids the scatter there.

An all-constant description orders nothing, so any interleaving is a valid
result. fullSort now combines such streams with resize(1), whose
ResizeProcessor drains whichever input is ready. This is the remedy that
5e1ec58 (ClickHouse#114626) applied to GatherSendStep for the same wedge; its
helper sortDescriptionIsAllConstant moves to Core/SortDescription so both
sites share it (no behaviour change in GatherSendStep). The stage grouping
used by EXPLAIN PIPELINE is kept, virtual rows are still removed in the
shared non-merge branch, and the top-K threshold tracker is skipped because
it belongs to the merge. A limit on the sorting step is only a hint pushed
down from the LimitStep that stays above it, and the single-stream path
already relied on that, so LIMIT and WITH TIES stay correct.

Found by AST fuzzer (amd_debug, targeted) on
ClickHouse#125514

The new test fails with Pipeline stuck before this change and passes after
it, also 50/50 with randomized settings.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
JTCunning pushed a commit to JTCunning/ClickHouse that referenced this pull request Oct 21, 2026
…plicas

Since ClickHouse#114550 the final DISTINCT hash-partitions its input
(DistinctStep::tryScatterStreams) when it has more than one input stream
and max_threads > 1. Under parallel replicas the initiator's final DISTINCT
always has several input streams (local plan plus remote replicas, or only
remote replicas with parallel_replicas_local_plan = 0), so the single chunk
of `sorting_key_empty_tuple` is split into partitions whose outputs reach
the client in scheduling order: `0, 1` instead of `1, 0` in 4 of 198
ParallelReplicas runs since the merge, 0 of 2846 in the week before.

The returned set is unchanged and a DISTINCT without ORDER BY has no
defined row order (allow_parallel_distinct documents it), so pin the order
with ORDER BY, as ClickHouse#114550 did for 02733_distinct and
01213_optimize_skip_unused_shards_DISTINCT. The bug 42185 path stays
covered: the preliminary DISTINCT is still planned directly above the
in-order read with an empty sort description; ORDER BY only adds a sort
above it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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 pr-synced-to-cloud The PR is synced to the cloud repo

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

5 participants