Skip to content

Run the final DISTINCT on all threads - #119228

Closed
raimannma wants to merge 7 commits into
ClickHouse:masterfrom
raimannma:parallel-final-distinct
Closed

raimannma wants to merge 7 commits into
ClickHouse:masterfrom
raimannma:parallel-final-distinct

Conversation

@raimannma

@raimannma raimannma commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

The final DISTINCT merged all of its input streams into one and deduplicated the whole input in a single transform. It now hash-partitions the streams by the DISTINCT columns, so equal rows land in the same stream and every stream is deduplicated on its own thread. The merge is kept when the input is sorted by the DISTINCT columns, when the global size limits are set, and for a single stream. New setting allow_parallel_final_distinct, on by default.

A sort whose description is left with constants only gathers its streams instead of merging them: a k-way merge over such an input deadlocks behind the scatter.

SELECT DISTINCT of one column over a sorted table with a million distinct values goes from 185ms to 51ms, SELECT DISTINCT number FROM numbers_mt(40000000) from 2.0s to 585ms. Measured with perf.py over sorted_distinct, distinct_in_order, distinct_low_cardinality_prelimit_distinct_in_order and distinct_high_cardinality: 24 queries faster, none slower.

Split out of #118230; it is independent of INTERSECT/EXCEPT and speeds up any SELECT DISTINCT.

Related: #118230

Changelog category (leave one):

  • Performance Improvement

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

The final DISTINCT is executed on all threads by hash-partitioning its input by the DISTINCT columns (new setting allow_parallel_final_distinct).


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

The final `DistinctStep` merged all of its input streams into one and deduplicated the whole input in a single
transform. It now hash-partitions the streams by the `DISTINCT` columns instead, so that equal rows land in
the same stream and every stream is deduplicated on its own thread. The merge is kept when the input is
sorted by the `DISTINCT` columns (the sorted deduplication relies on its stream order), when the global size
limits are set (they are enforced by the single transform that sees the whole input), and for a single
stream. New setting `allow_parallel_final_distinct`, on by default.

The chunks are squashed before the scatter: the scatter turns every chunk into one chunk per partition, and
the preliminary `DISTINCT` in front of it emits a small chunk whenever it collapses its input, so without
squashing the per-chunk cost of the partitions dominates and the step is several times slower than the merge.

`SortingStep` gathers its streams instead of merging them when the sort description is left with constants
only. `SortingTransform` drops the constant columns of the header, and with nothing left `MergeSortingTransform`
passes chunks through as they come; a k-way merge over such an input deadlocks behind the scatter, which does
not consume new input until every partition has accepted the previous chunk.

`SELECT DISTINCT` of one column over a sorted table with a million distinct values goes from 185ms to 51ms,
`SELECT DISTINCT number FROM numbers_mt(40000000)` from 2.0s to 585ms, and the queries whose result is small
enough for the merge to win are unchanged. Measured with `tests/performance/scripts/perf.py` over
`sorted_distinct`, `distinct_in_order`, `distinct_low_cardinality_prelimit_distinct_in_order` and
`distinct_high_cardinality`: 24 queries faster, none slower.

Neither a set operation nor a sort by constants promises a row order, and three tests asserted the one the
previous single-threaded merge happened to produce; they order their results now.
`max_block_size = 5` over a million rows produces two hundred thousand blocks, and the per-block cost of the
pipeline makes the query trip the execution speed limit under ASan. A block size of 1000 is still far below
the 65536 rows the transform squashes to, so it accumulates the same way with a fraction of the blocks.
raimannma added a commit to raimannma/ClickHouse that referenced this pull request Sep 10, 2026
…ut of this PR

Both are independent of `INTERSECT`/`EXCEPT` and are reviewed on their own:

- the final `DISTINCT` on all threads, with the constant-sort gather it needs, in ClickHouse#119228
- the left semi join that stops reading its left side for an empty right side, in ClickHouse#119218

`scatterByPartition`'s limit helpers and the `SortingStep` gather stay here as well, because the partitioned
`INTERSECT`/`EXCEPT` step needs them too; they are the same change in both pull requests.

Related: ClickHouse#119228
Related: ClickHouse#119218
raimannma added a commit to raimannma/ClickHouse that referenced this pull request Sep 10, 2026
The final `DISTINCT` merges its streams again now that the parallel one is reviewed in ClickHouse#119228, so the
`EXPLAIN PIPELINE` of the set-operation step no longer shows a scatter above it.
…heck

The style check lists every new `allow_*` setting that neither `enableAllExperimentalSettings` nor the
ignore list knows about. This one gates an execution strategy, not an experimental feature.
raimannma added a commit to raimannma/ClickHouse that referenced this pull request Sep 10, 2026
…9228

`allow_parallel_final_distinct` is declared there now, and the style check reads the list against the
settings this branch declares.

Related: ClickHouse#119228
@clickhouse-gh clickhouse-gh Bot added comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. external Author is not a member of the ClickHouse organization labels Sep 10, 2026
@maxknv maxknv removed the external Author is not a member of the ClickHouse organization label Sep 11, 2026
@clickhouse-gh clickhouse-gh Bot added the external Author is not a member of the ClickHouse organization label Sep 11, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Sep 12, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [38e1f3b]

Summary: ✅


AI Review

Summary

This PR parallelizes the final DISTINCT by hash-partitioning input streams, keeps the single-stream path when order or global DISTINCT limits matter, and avoids the ORDER BY-constant deadlock above scattered inputs by gathering instead of k-way merging. I did not find a remaining correctness, safety, or test-coverage issue in the current patch.

Missing context / blind spots
  • ⚠️ The full CI matrix for commit 38e1f3b36935d653a5ad095e09650e6f5b45a3ea was still running at review time on 2026-09-12; only the early Style check, Fast test, and Build profile diff jobs had finished successfully.
Final Verdict

✅ No new findings.

LLVM Coverage Report

Measured on commit 38e1f3b.

Metric Baseline Current Δ
Lines 89.00% 89.00% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 81.30% 81.40% +0.10%

Changed lines: Changed C/C++ lines covered: 74/74 (100.00%) · Uncovered code

Full report · Diff report

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

clickhouse-gh Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 38e1f3b36 with master eea50a05f (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 (+28.14 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/QueryPipeline/scatterByPartition.cpp.o 49.09 KiB 67.79 KiB +18.70 KiB (+38.10%)

716 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

674 translation units recompiled, 5201 s compile time in total, 674 of them have a recent master baseline.

Job report

raimannma and others added 2 commits September 12, 2026 17:12
…al order through it

`applyOrder` lets the global order of the input survive a `DistinctStep`, and the steps above may
rely on it, so the hash scatter into partition streams must not run for such a step. It now marks the
step with `keepGlobalOrder`, and the step keeps the single-stream merge.

This is a defensive change: every source of a global order today ends in a single stream, which the
scatter never sees, so no query changed its plan.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01K1wpba9fdyc4QQYKWwVMWU
…of the parallel `DISTINCT` test

With the randomized `MergeTree` settings the sorted table can be read in order through several streams,
which shows up as a stream count on the preliminary `DistinctSortedStreamTransform`. The check only
cares that no scatter appears.

Failed in https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119228&sha=0519b038c67fa15c2cf04fab1d769ce069e05c91&name_0=PR&name_1=Stateless%20tests%20(amd_tsan,%20s3%20storage,%20parallel,%20selected%20tests)

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01K1wpba9fdyc4QQYKWwVMWU
@clickhouse-gh

clickhouse-gh Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR adds parallel final DISTINCT (hash-partition the streams instead of merging into one) plus a constants-only sort guard; the only execution-path changes live in DistinctStep and SortingStep and take effect for SELECT DISTINCT queries. TPC-H Q9 is a multi-join aggregation with no DISTINCT, so it doesn't exercise the changed code and the flagged +16.7% (+16.5 ms, 99.0 -> 115.5 ms) is not plausibly caused by this change. It also ran co-located with another benchmark on the same node and has no history baseline, both of which favor noise; downgraded to not sure. No cross-query pattern: only one query was flagged.

clickbench

🟢 No significant changes

tpch_adapted_1_official

⚠️ 1 inconclusive

Flagged queries (1 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 9 not_sure 99 116 +16.7% <0.0001 plan_change: TPC-H Q9 has no SELECT DISTINCT, so the new parallel-final-DISTINCT path (the only execution-code change) cannot touch it. The +16.7% (+16.5 ms) looks like run-to-run variance rather than a real 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.

Debug info
  • StressHouse run: 16a59ea1-96ed-47f5-a937-910d96b7f396
  • MIRAI run: 5e7bceb7-0488-4bc1-acfa-599678e57bdd
  • PR check IDs:
    • clickbench_236016_1789254733
    • clickbench_236129_1789254752
    • clickbench_236247_1789254780
    • tpch_adapted_1_official_236261_1789254780
    • tpch_adapted_1_official_236267_1789254781
    • tpch_adapted_1_official_236289_1789254780

…T` test

The old analyzer nests the inner pipeline of
`05194_parallel_final_distinct_keeps_global_order` one level less deep than the
new one, so the `EXPLAIN PIPELINE` lines differed only by their indentation and
the test failed in the jobs that run with the old analyzer. The test now trims
the leading whitespace: it checks which transforms appear and in which order,
which is the same under both analyzers.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119228&sha=fc4c7194ac1896f7c006228157638bf554fb59bc&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20old%20analyzer%2C%20s3%20storage%2C%20DBReplicated%2C%20parallel%2C%203%2F3%29
PR: ClickHouse#119228

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01M5DPfWFrJ8G7XxrUxD6EUD
@rschu1ze

Copy link
Copy Markdown
Member

This PR looks almost the same as #119012

@nihalzp Would you check, please?

@rschu1ze rschu1ze 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.

Duplicates #119012

@rschu1ze

Copy link
Copy Markdown
Member

Actually, the other PR (mapping to highly optimized aggregation instead of custom parallelization) seems more promising. Thanks for sending this PR anyways @raimannma

@rschu1ze rschu1ze closed this Sep 14, 2026
@raimannma
raimannma deleted the parallel-final-distinct branch September 14, 2026 19:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. external Author is not a member of the ClickHouse organization pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants