Repository navigation
Add a preliminary DISTINCT to UNION DISTINCT - #115173
Algunenano merged 3 commits into
Conversation
A UNION DISTINCT B and SELECT DISTINCT * FROM (A UNION ALL B) are the same query but got different pipelines. The union branch of the planner added a single DistinctStep with pre_distinct = false; getTraits sets returns_single_stream = !pre_distinct and transformPipeline does resize(1), so that one step both merged the streams and deduplicated them. Every input row therefore funnelled through one DistinctTransform and the query did not scale with max_threads, while the rewrite deduplicated each branch first. Add the missing pre_distinct = true step before the existing one, in the analyzer planner and in InterpreterSelectWithUnionQuery. liftUpUnion clones a preliminary DISTINCT into every branch, which is how the rewrite gets its per-branch distinct, so this reuses that path instead of adding a mechanism. Scoped to UNION_DISTINCT. INTERSECT_DISTINCT and EXCEPT_DISTINCT share the same is_distinct branch, but IntersectOrExceptStep already resizes every branch to a single stream and liftUpUnion does not handle it, so a preliminary step there would only cost an extra hash-table pass. Their plans are unchanged, which is why the final step's description is set only when the preliminary step is added. Measured on a release build, 8M rows per branch and 2000 distinct values, best of 7 by server-side query_duration_ms: 44 -> 13 ms at max_threads = 8 and 59 -> 9 ms at 16. With all-distinct data the preliminary step is pure overhead, at the same cost the rewrite already pays today. Closes: ClickHouse#115104
Review round 1. The source fix is unchanged; this addresses the test and one
label.
The plan assertions were presence-only (count() > 0 ... ILIKE '%Preliminary
DISTINCT%'). Setting pre_distinct back to false while keeping the "Preliminary
DISTINCT" description still leaves exactly one matching row, so the oracle
passed while liftUpUnion stopped cloning into the branches and the step resized
to a single stream: the parallelism this change is about was gone and the test
was green. The assertions are now exact counts (2 preliminary steps, one per
branch) plus an EXPLAIN PIPELINE DistinctTransform count, which asserts the
executed shape rather than a plan label. Both mutations above now fail the test.
query_plan_lift_up_union is pinned next to them, since the counts depend on it
and it is not in the test runner's randomizer.
The size-limit section printed the full distinct count on both forms, so it
could not distinguish them and asserted nothing. The source was a TEMPORARY
Memory table, and StorageMemory::readImpl ignores max_block_size (the parameter
is unnamed), so all 600 rows arrived in one chunk and DistinctTransform emitted
them before checking the limit. Reading from numbers() instead honours
max_block_size, so break now truncates to 100 in both forms and the throw arm
still raises SET_SIZE_LIMIT_EXCEEDED.
Also drop setStepDescription("DISTINCT") from the old-analyzer final step.
InterpreterSelectQuery::executeDistinct labels only the preliminary step, so the
label was inconsistent within that analyzer and no assertion needed it; without
it the old-analyzer UNION DISTINCT plan is byte-identical to its SELECT DISTINCT
over UNION ALL sibling. The analyzer path keeps its label, scoped to
UNION_DISTINCT so INTERSECT/EXCEPT plans stay byte-identical.
Co-Authored-By: Claude Fable 5 <[email protected]>
Internal second-model review (2 rounds, 9 findings adjudicated)An independent model reviewed this change cold against the PR contract, in two rounds. Verdicts and Fixed before publishing❌ The plan assertions were presence-only. ❌ The size-limit section asserted nothing. It printed
Raised and not actioned, with the reason💡 "Add a chunked case to detect an outer LIMIT propagating into the preliminary DISTINCT." The 💡 💡 Coverage for |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-review-slot-49:20260817-172500 |
|
cc @vdimir @yariks5s, could you review this? The union branch of the planner added a single DistinctStep with pre_distinct = false, and getTraits sets returns_single_stream = !pre_distinct, so that one step both merged the branches and deduplicated them; adding the missing preliminary step lets liftUpUnion distribute it per branch, the same way SELECT DISTINCT over UNION ALL already worked. |
|
Workflow [PR], commit [2848e3e] Summary: ❌
AI ReviewSummaryThis PR adds a preliminary Findings
Tests
Final VerdictNeeds changes. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 30/30 (100.00%) · Uncovered code |
Algunenano
left a comment
There was a problem hiding this comment.
Changes make sense to me, but I wonder what the impact in performance is from adding the extra pre-DISTINCT step for each branch before doing the UNION (and then another DISTINCT). If the step removes data then sure, it will be effective, but if it doesn't remove data, aren't we doing extra work unnecessarily?
We should test things in both cases, the beneficial and the detrimental ones to decide and probably in the future we should try to decide whether to do prior deduplication based on statistics / metrics from previous runs / whatever good heuristic we have.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Compile time of recompiled translation units26 translation units recompiled, 181 s compile time in total, 26 of them have a recent master baseline. |
|
Measured both directions on a release build (RelWithDebInfo, clang-21), 8M rows per branch (16M input rows), MergeTree,
You are right that the detrimental case is real, and it concentrates at The cost is not new, though. At If you want the detrimental column gone without any statistics, the data points at one cheap lever: skip the preliminary step when |
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=6 K_base=27 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
I think we should do it. OTOH, what happens with |
…hing A preliminary DISTINCT exists so that each stream is deduplicated in parallel and the final single-stream DISTINCT has fewer rows to merge. At max_threads = 1 there is no second stream to reduce, so the step only hashes every row a second time: a density sweep over 2000..8M distinct values per branch measured it detrimental only in that column, worst cell 1.77x on all-distinct data (2.12x over 15 repetitions). preliminaryDistinctIsUseful() holds that rule in one place so the two planner implementations cannot drift apart. It takes the effective thread count, which both union sites have already resolved for their UnionStep, so the guard and the step it guards cannot end up disagreeing about how many threads there are. With one thread the UNION DISTINCT plan and pipeline are byte identical to master's again; at two or more threads nothing changes. The ordinary SELECT DISTINCT path is deliberately left alone. Its preliminary step already exists, and applyOrder may later turn it into a DistinctSortedStreamTransform, which replaces hashing with a range scan and pays off at one thread too. The planner cannot know that yet, so skipping there would drop in-order preliminary DISTINCTs; 02862, 04511 and 04649 assert exactly those transforms at max_threads = 1. 01556 and 04951 pin max_threads, since their expected plans contain a preliminary DISTINCT, and disable max_threads_min_free_memory_per_thread, which otherwise lowers max_threads to one under memory pressure and would make both plans depend on how much memory the server happens to have free. In 04951 the pin has to be a session-level SET: a trailing SETTINGS clause on a UNION query binds to its last branch and never reaches the union node.
|
Pushed 2848e3e. The skip is in, for
I did not apply the skip there, because the same condition is wrong in that path. Its Separately, under a small outer |
|
|
||
| bool preliminaryDistinctIsUseful(size_t max_threads) | ||
| { | ||
| return max_threads > 1; |
There was a problem hiding this comment.
The max_threads > 1 heuristic is firing too early here. This decision is made before liftUpUnion, optimizeDistinctInOrder, and applyOrder, so at max_threads = 1 it also removes the preliminary DistinctSteps that would later become DistinctSortedStreamTransforms for ordered union branches. A final DistinctStep above UnionStep cannot recover that path, because applyOrder only lets a non-preliminary distinct consume global order, while UnionStep exposes only per-stream order for multi-branch unions.
That leaves one-thread UNION DISTINCT slower than its SELECT DISTINCT * FROM (A UNION ALL B) rewrite for ordered inputs, even though the rewrite already has a working in-order preliminary path (02317_distinct_in_order_optimization exercises that class of plan at max_threads = 1). Can we move this heuristic after order selection, or at least keep the preliminary step when it can become sorted distinct instead of generic hashing?
There was a problem hiding this comment.
The mechanism is right, but the fix it points to is measurably wrong, so I am not making the change.
Confirmed first. On an ordered fixture at max_threads = 2 the preliminary steps liftUpUnion pushes into the branches really do become DistinctSortedStreamTransform, and ReadFromMergeTree switches to Read type: InOrder; at max_threads = 1 the skip removes both. The recovery claim holds as well: optimizeDistinctInOrder returns early unless isPreliminary, and applyOrder only lets a non-preliminary distinct take a Global sort scope, so the final DistinctStep above UnionStep cannot pick that path up.
Then measured. The instrument is release master 26.9.1.157: at one thread it produces this PR's plan and pipeline for A UNION DISTINCT B exactly (checked side by side on one fixture, build ids e4535320 and ffe55ce5), and SELECT DISTINCT * FROM (A UNION ALL B) already carries the shape an un-skipped UNION DISTINCT would get. 8M rows per branch, ORDER BY x, max_threads = 1, best of 7 from system.query_log, result sets identical in every cell:
| per-branch distinct | dup ratio | no preliminary step (this PR) | sorted preliminary | hash preliminary |
|---|---|---|---|---|
| 2000 | 4000x | 28 ms | 15 ms | 28 ms |
| 500k | 16x | 94 ms | 88 ms | 110 ms |
| 8M | 1x | 390 ms | 467 ms | 671 ms |
The last two columns are optimize_distinct_in_order set to 1 and to 0.
At 4000x you are right: the skip declines a 1.9x win. But sortedness is not the predicate. At 1x the sorted step is still 1.20x slower than not having it, 1.22x in a second run. That is also the most favourable form of the proposal, because x is the whole sort prefix, so DistinctSortedStreamTransform keeps one row per range and never hashes. Keeping the step whenever it can become sorted would trade the detrimental column this PR removed for a new one.
What separates the two regimes is the duplicate ratio, not the ordering, so it needs the cardinality heuristic already parked as future work rather than a relocation of the current condition. I am leaving the lever as it is: at one thread the plan is master's, so nothing that works today gets slower, and from two threads up the step survives and does become the sorted transform on ordered input.
CI finish ledger - 2848e3eCI is fully finished at this commit. One check failed, and it has an owner.
Everything else at this commit is green. Session id: cron:our-pr-ci-monitor:20260826-180000 |
|
@groeneai Please open an issue about the stress test failure and tackled it in the simplest and more concise way possible |
91ccf2f
|
Issue: #116740 The hung check is a whole-column cast inside a per-row callback: The fix is a few lines in |
|
Done, both parts. Issue: #116740. Fix: #116795. It was not a deadlock. For a |
Closes: #115104
Related: #114550
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
A UNION DISTINCT Bnow deduplicates each branch in parallel before merging them, the same way itsSELECT DISTINCT * FROM (A UNION ALL B)rewrite already did. Previously every row funnelled through a singleDistinctTransform, so the query did not scale withmax_threads.Description
A UNION DISTINCT BandSELECT DISTINCT * FROM (A UNION ALL B)are the same query but got different pipelines: the rewrite deduplicates each branch before the merge,UNION DISTINCTdid not.Root cause. The union branch of
Planner::buildPlanForUnionNode(and its old-analyzer twin inInterpreterSelectWithUnionQuery) added oneDistinctStepwithpre_distinct = false.DistinctStep::getTraitssetsreturns_single_stream = !pre_distinct, so that one step both merged to one stream and deduplicated.The change adds a
pre_distinct = truestep before the existing one, in both planners, whenmax_threads > 1.liftUpUnionthen clones it into each branch, which is how the rewrite gets its per-branch distinct. No new setting.Scoped to
UNION_DISTINCT:INTERSECT/EXCEPT DISTINCTshare theis_distinctbranch, butIntersectOrExceptStepalready emits one stream andliftUpUniondoes not handle it, so a preliminary step there is overhead. Their plans are unchanged.Measured (release build, 8M rows/branch, 2000 distinct values, best of 7):
The rewrite scores 13 ms / 8 ms here, so the two forms now agree. A density sweep found the step detrimental only at one thread (worst cell 1.77x, all-distinct data), where it cannot reduce anything, so a shared
preliminaryDistinctIsUsefulpredicate skips it:max_threads = 1plans stay byte-identical to master.The step carries the same
max_rows_in_distinct/max_bytes_in_distinct, so as in the rewrite they bind per stream as well as globally; both overflow modes measured identical to the rewrite.The new test asserts plan shape, not timing, and checks results against the rewrite across
Nullable,LowCardinality,Array, aggregate-state and coerced-type branches, chains,LIMITand size limits, at one and several threads.Interaction with #114550 (measured)
#114550 "Deduplicate the final DISTINCT in parallel" attacks the same bottleneck from the other side and edits the same two functions. Measured on its head
1e783f46, same fixture and method:#114550 parallelizes the final dedup; this PR reduces how many rows reach it. They stack, and #114550 alone does not close the reported gap. It keeps
pre_distinct = falseat the union site, so the conflict is textual only - whoever merges second rebases.