Repository navigation
Deduplicate the final DISTINCT in parallel - #114550
Conversation
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]>
|
Workflow [PR], commit [4323f08] Summary: ✅
AI ReviewSummaryPR #114550 parallelizes final Missing context / blind spots
Final VerdictStatus: ✅ Approve. No new inline findings or thread updates are warranted. |
…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]>
|
📊 Cloud Performance Report ✅ AI verdict: 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
|
Add `ORDER BY` to the unordered DISTINCT queries in `01213_optimize_skip_unused_shards_DISTINCT`. Parallel DISTINCT may return otherwise valid rows in a different order. CI report: #114550
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes60 object files changed (+193.44 KiB total), 2 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units163 translation units recompiled, 1462 s compile time in total, 161 of them have a recent master baseline. |
|
@nihalzp, waiting for review. |
…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]>
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.
…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]>
…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]>
…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]>
The final
DISTINCTmerged all of its input streams into one and deduplicated them on a single thread, soSELECT DISTINCTdid not scale withmax_threadswhile the equivalentGROUP BYdid - aggregation parallelizes its merge over two-level hash tables,DISTINCThad nothing of the sort.This repartitions the input streams by the hash of the
DISTINCTcolumns 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 usesscatterByPartition, whichSortingStepandShuffleSendStepalready use.The decision is taken in the
applyStreamDisjointnessplan optimization. An input-order requirement set byapplyOrderkeeps the finalDISTINCTon 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:DISTINCTkeeps the order of its input and the repartitioning would break it;DISTINCTdeduplicates sorted input (optimize_distinct_in_order), or follows a preliminaryDISTINCTin input order, because sorted deduplication needs equal prefix values to stay contiguous;allow_distinct_partitions_independentlycovers that case and skips the merge entirely.It is applied under
LIMIT,OFFSETandLIMIT BYover unordered input: aDISTINCTwithoutORDER BYhas no defined row order, so any subset of the distinct values is a valid result (05212_parallel_distinct_order_requirementspins this).max_rows_in_distinctandmax_bytes_in_distinctkeep their global meaning: the streams hold disjoint parts of oneDISTINCTset, 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 to10G.Every input chunk is split across all partitions, so the number of partitions is capped rather than following
max_threads. OnSELECT 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 highmax_threads.Wall clock, minimum of 3 runs, aarch64:
max_threadsUInt64,MergeTreeUInt64,numbers_mtString,numbers_mtThe measurements were taken on a busy machine, hence the minimum of several runs; the existing
distinct_in_order,distinct_high_cardinalityandsorted_distinctperformance tests cover these shapes, so the performance comparison job is the authoritative check.DISTINCTwithoutORDER BYhas no defined row order, and the repartitioning changes the order it happens to produce. Two existing tests relied on it:04109_sort_propagation_apply_orderasserts that per-stream sortedness reachesDISTINCT, so it pins the setting off, and00585_union_all_subquery_aggregation_column_removalgets the explicitORDER BYit was missing. Other tests that depend on the incidental order of aDISTINCTmay surface in CI and should be fixed the same way.Closes: #114532
Related: #48988
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):
Evaluate the final
DISTINCTon several threads by repartitioning its input by the hash of theDISTINCTcolumns, instead of merging everything into a single stream and deduplicating it on one thread. Up to 6x faster on high-cardinalityDISTINCT. Controlled by the new settingallow_parallel_distinct, enabled by default. Note that this changes the order in which aDISTINCTwithoutORDER BYreturns rows, which was never defined.Documentation entry for user-facing changes
Workflow [PR]
Sync PR [sync-upstream/pr/114550]
Version info
26.11.1.284-master(included in26.11and later)