Skip to content

Speed up DISTINCT by running it independently per MergeTree partition - #108326

Merged
alexey-milovidov merged 33 commits into
ClickHouse:masterfrom
nihalzp:distinct-partitions-independently
Aug 1, 2026
Merged

alexey-milovidov merged 33 commits into
ClickHouse:masterfrom
nihalzp:distinct-partitions-independently

Conversation

@nihalzp

@nihalzp nihalzp commented Jun 23, 2026 •

Copy link
Copy Markdown
Member

Related: #105126

If the partition expression is a function of the DISTINCT columns, pre-DISTINCT will now request data to be emitted in each partition from a single port. This will significantly reduce data for the next steps because, unlike the base case where a single key may be present in all streams, here only one stream will have it.

Then, this PR adds applyStreamDisjointness, which works similarly to applyOrder but propagates data disjointness. And, for common shapes, this can reach the final DISTINCT, and the final DISTINCT will run in parallel instead of merging streams into one. applyStreamDisjointness is more broad in that it can propagate this property to downstream GROUP BY and LIMIT BY as well, making them run in parallel as well!

CREATE TABLE t (a UInt64) ENGINE = MergeTree ORDER BY tuple() PARTITION BY a % 8;
INSERT INTO t SELECT number % 1000000 FROM numbers(100000000);


OPTIMIZE TABLE t FINAL;

EXPLAIN PIPELINE
SELECT DISTINCT a FROM t
SETTINGS allow_distinct_partitions_independently = 1, max_threads = 8;
    ┌─explain─────────────────────────┐
 1. │ (Expression)                    │
 2. │ ExpressionTransform × 8         │
 3. │   (Distinct)                    │
 4. │   DistinctTransform × 8         │ <- final, now × 8 (was × 1, behind a `Resize 8 → 1`)
 5. │     (Distinct)                  │
 6. │     DistinctTransform × 8       │ <- preliminary, now on partition-disjoint streams
 7. │       (Expression)              │
 8. │       ExpressionTransform × 8   │
 9. │         (ReadFromMergeTree)     │
10. │         MergeTreeSelect(...) × 8│ <- per-partition reading (here 8 partitions → 8 streams)
    └─────────────────────────────────┘
image image

Changelog category (leave one):

  • Performance Improvement

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

Speed up and reduce the memory usage of DISTINCT queries on partitioned MergeTree tables by keeping each partition's rows within a single stream, so each stream's preliminary DISTINCT works on a disjoint set of keys, instead of the same set of keys appearing in multiple preliminary DISTINCTs. This applies when the partition expression is a deterministic function of the DISTINCT columns, and is gated by a cost heuristic on partition count and skew (which can be toggled by setting force_distinct_partitions_independently, disabled by default). The same per-partition disjointness is propagated through Expression, Filter and ARRAY JOIN steps to the final DISTINCT, LIMIT BY and GROUP BY consumers so they can skip their merge too. Controlled by the new settings allow_distinct_partitions_independently (enabled by default) and max_number_of_partitions_for_independent_distinct to tune the heuristic.

@clickhouse-gh

clickhouse-gh Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8c29cc5]

Summary: ✅


AI Review

Summary

This PR adds a per-partition DISTINCT optimization for MergeTree reads and a new applyStreamDisjointness pass so downstream DISTINCT, LIMIT BY, and GROUP BY steps can skip merge stages when the partition key is determined by their keys. The overall direction looks sound and CI is green, but there is still one planner path where size-limited DISTINCT queries half-enable the optimization even though the PR now documents that this mode is disabled.

Findings

⚠️ Majors

  • [src/Processors/QueryPlan/Optimizations/useDataParallelAggregation.cpp:218] The request-side pass still calls requestOutputEachPartitionThroughSeparatePortForDistinct before checking max_rows_in_distinct / max_bytes_in_distinct. The later guard in applyStreamDisjointness keeps the final merge global, but the read has already been rewired into per-partition ports, so the preliminary DistinctTransforms no longer see the legacy stream topology. That violates the new documented contract that the optimization is not applied when DISTINCT size limits are set, and it can still change distinct_overflow_mode = 'break', EXPLAIN, and sibling optimizer decisions that key off willOutputEachPartitionThroughSeparatePort().
    Suggested fix: short-circuit optimizeDistinctPerPartition when the preliminary step carries non-zero DISTINCT size limits, so the read-side request is suppressed as well.
Tests

⚠️ 04415_distinct_partitions_independently_size_limit proves only that the final query still throws. Add an EXPLAIN actions = 1 assertion (and ideally a distinct_overflow_mode = 'break' case) so the read-side request path cannot stay silently enabled when DISTINCT size limits are set.

Final Verdict

Needs changes before merge: the size-limit contract is still violated in the preliminary request pass.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jun 23, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR adds a default-on independent per-partition DISTINCT plan optimization plus a stream-disjointness propagation pass; it only activates when a table's partition key is a deterministic function of the DISTINCT/GROUP BY columns across many balanced partitions, which the unpartitioned ClickBench schema never triggers. Consistent with that, none of the flagged deltas are attributable to the change: Q4's -19.2% is a COUNT(DISTINCT) aggregation that the new DISTINCT step doesn't touch and sits inside master's variance band with flat CPU, and the small +5-7% GROUP BY deltas on Q28/Q32/Q33 are borderline or within-envelope noise. I sanity-checked the envelope-suppressed rows (Q4, Q33) against the diff and found no inconsistency — the deterministic no_change/not_sure verdicts all hold.

clickbench

⚠️ 3 inconclusive

Flagged queries (3 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 28 not_sure 1028 1104 +7.3% 0.0009 aggregation: GROUP BY query the DISTINCT-step optimization cannot touch; +7.3% is borderline with mixed signals on a noisy query.
⚠️ 32 not_sure 1317 1398 +6.2% 0.0247 aggregation: GROUP BY query untouched by this plan change; +6.2% is borderline and within this query's usual noise.
⚠️ 33 not_sure 1232 1297 +5.3% <0.0001 aggregation: GROUP BY query; the +5.3% delta is consistent but sits inside master's current variance band, so it reads as noise rather than a PR effect.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 4ff7c1de-efdd-409d-b1ab-a99785dc6409
  • MIRAI run: 8b84da5e-2d7c-40a0-a21c-01ef1dfbd52c
  • PR check IDs:
    • clickbench_989192_1785431284
    • clickbench_989199_1785431284
    • clickbench_989210_1785431284
    • tpch_adapted_1_official_989220_1785431284
    • tpch_adapted_1_official_989234_1785431285
    • tpch_adapted_1_official_989263_1785431284

@Algunenano

Copy link
Copy Markdown
Member

Related too in case you want to have a look: Related: #89129 / ClickHouse/clickhouse-private#57450 In case you want to have a look

@novikd novikd self-assigned this Jun 29, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

Dear @novikd, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@novikd novikd self-assigned this Jul 29, 2026
if (!dag)
return;

if (!reading->willOutputEachPartitionThroughSeparatePort()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The size-limit guard is too late here. applyStreamDisjointness now refuses to skip the final merge when max_rows_in_distinct / max_bytes_in_distinct is set, but by the time that pass runs this request has already flipped the read into output_each_partition_through_separate_port.

That means a size-limited query still changes the preliminary DistinctTransform stream topology even though the final merge stays global. This contradicts the new contract in Settings.cpp ("Not applied when max_rows_in_distinct or max_bytes_in_distinct is set"), and it can still change user-visible behavior for distinct_overflow_mode = 'break' as well as EXPLAIN / join-sharding decisions. The same has_size_limits check needs to live in this request pass too, before we touch the read step.

@nihalzp nihalzp Jul 30, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is intentional so that pre-distinct can benefit regardless. Skipping this optimization for pre-distinct is not beneficial if max_rows_in_distinct / max_bytes_in_distinct is set because pre-distinct is already checks these metric per stream.

@clickhouse-gh

clickhouse-gh Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.60% 78.70% +0.10%

Changed lines: Changed C/C++ lines covered: 259/265 (97.74%) · Uncovered code

Full report · Diff report

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All good.

@alexey-milovidov alexey-milovidov self-assigned this Aug 1, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 1, 2026
Merged via the queue into ClickHouse:master with commit 0c113dc Aug 1, 2026
179 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 1, 2026
pull Bot pushed a commit to Mu-L/ClickHouse that referenced this pull request Aug 26, 2026
…the new join algorithm from ClickHouse#109005

- tests/clickhouse-test: randomize `allow_distinct_partitions_independently`,
  `force_distinct_partitions_independently`,
  `max_number_of_partitions_for_independent_distinct` and
  `enable_parallel_single_level_merge`. `force_*` is conditional on `allow_*`,
  because forcing is a no-op when the optimization is not allowed.
- ci/jobs/scripts/stress/stress.py: add `parallel_full_sorting_merge` to the
  `join_algorithm` rotation (skipped in Upgrade check, because the previous
  release may not know this value).
- BuzzHouse: add the four new settings next to their aggregate analogs.

Related: ClickHouse#109005
Related: ClickHouse#108326
Related: ClickHouse#110395

Co-Authored-By: Claude Fable 5 <[email protected]>
@ylw510 ylw510 mentioned this pull request Sep 3, 2026
47 of 72 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

5 participants