Skip to content

Add a preliminary DISTINCT to UNION DISTINCT - #115173

Merged
Algunenano merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/union-distinct-preliminary-distinct-115104
Aug 27, 2026
Merged

Algunenano merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/union-distinct-preliminary-distinct-115104

Conversation

@groeneai

@groeneai groeneai commented Aug 17, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #115104
Related: #114550

Changelog category (leave one):

  • Performance Improvement

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

A UNION DISTINCT B now deduplicates each branch in parallel before merging them, the same way its SELECT DISTINCT * FROM (A UNION ALL B) rewrite already did. Previously every row funnelled through a single DistinctTransform, so the query did not scale with max_threads.

Description

A UNION DISTINCT B and SELECT DISTINCT * FROM (A UNION ALL B) are the same query but got different pipelines: the rewrite deduplicates each branch before the merge, UNION DISTINCT did not.

Root cause. The union branch of Planner::buildPlanForUnionNode (and its old-analyzer twin in InterpreterSelectWithUnionQuery) added one DistinctStep with pre_distinct = false. DistinctStep::getTraits sets returns_single_stream = !pre_distinct, so that one step both merged to one stream and deduplicated.

The change adds a pre_distinct = true step before the existing one, in both planners, when max_threads > 1. liftUpUnion then clones it into each branch, which is how the rewrite gets its per-branch distinct. No new setting.

Scoped to UNION_DISTINCT: INTERSECT/EXCEPT DISTINCT share the is_distinct branch, but IntersectOrExceptStep already emits one stream and liftUpUnion does 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):

max_threads before after
1 60 ms 61 ms
8 44 ms 13 ms
16 59 ms 9 ms

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 preliminaryDistinctIsUseful predicate skips it: max_threads = 1 plans 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, LIMIT and 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:

arm t1 t8 t16
master 60 ms 44 ms 59 ms
#114550 alone 57 ms 22 ms 17 ms
this PR alone 61 ms 13 ms 9 ms
#114550 + this PR 60 ms 11 ms 7 ms

#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 = false at the union site, so the conflict is textual only - whoever merges second rebases.

groeneai and others added 2 commits August 17, 2026 14:02
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
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
the evidence behind each are below. Nothing here needs reviewer action; it is disclosure.

Fixed before publishing

❌ The plan assertions were presence-only. count() > 0 ... ILIKE '%Preliminary DISTINCT%' stays
true if pre_distinct is flipped back to false while the description is kept, so the oracle passed
while liftUpUnion stopped cloning into the branches and the step resized to one stream, i.e. exactly
the regression this PR is about. The assertions are now exact counts (2 preliminary plan steps, one per
branch; 3 DistinctTransforms in EXPLAIN PIPELINE) in both analyzers, and both mutations were shown
to 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 asserted nothing. It printed 600 / 600, the full distinct count, on
both forms, so the limit never bit. StorageMemory::readImpl ignores max_block_size (the parameter is
unnamed), so a TEMPORARY table delivered all 600 rows in one chunk. Reading numbers(600) instead
honours it: break now truncates to 100 on both forms, and the max_block_size sweep
(50 -> 100, 500 -> 500, 8000 -> 600) shows the setting is load-bearing. The two forms still agree, so
this remains a performance change.

⚠️ The description said the distinct size limits now apply "per branch". They apply per stream:
Pipe::addSimpleTransform instantiates the transform once per output port, and a preliminary
DistinctStep preserves the stream count, so each stream gets its own hash table and its own
SizeLimits check. A branch can carry up to max_threads streams. Corrected in the body; the parity
claim with the rewrite is unaffected, since the rewrite builds its preliminary step with the same
limits.

⚠️ Comment wording tightened to state the local invariant only, with the motivation left in the commit
messages.

Raised and not actioned, with the reason

💡 "Add a chunked case to detect an outer LIMIT propagating into the preliminary DISTINCT." The
scenario is unconstructible. There is exactly one writer of a non-zero DISTINCT limit hint in the tree,
limitPushDown's updateLimitHint, and it requires the step to be the direct child of a LimitStep.
Here the Limit's child is always the final DISTINCT; the preliminary one sits below it, and below the
Union after liftUpUnion. The final step cannot be removed to expose it, because
removeRedundantDistinct explicitly declines the final-over-preliminary case. Both construction sites
pass a literal 0, liftUpUnion clones that 0, and a UnionNode has no LIMIT/OFFSET/LIMIT BY
to derive a hint from in the first place. So the hint is provably always 0 and the proposed assertion
would pin a state the code cannot enter.

💡 EXPLAIN PIPELINE counts a transform name that optimize_distinct_in_order could change.
DistinctSortedStreamTransform would replace DistinctTransform, and that setting is randomized, but
the pass needs a MergeTree or object-storage read with a non-empty sorting key; this test reads only
numbers(), system.one and a temporary Memory table. 50 randomized runs are green.

💡 Coverage for WITH TOTALS / ORDER BY / distributed. DistinctStep::transformPipeline returns
nullptr for non-Main streams, so totals and extremes pass through exactly as they did for the
pre-existing step, and PreDistinct has been a registered serialization name since 2024, predating the
current plan serialization version. No arms added, to keep the test small.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT count() FROM (EXPLAIN PLAN SELECT 1 AS x UNION DISTINCT SELECT 2 AS x) WHERE explain ILIKE '%Preliminary DISTINCT%' returns 0 before, 2 after; the EXPLAIN PIPELINE DistinctTransform count goes 1 -> 3. Not timing-dependent.
b Root cause explained? Yes. The union branch added one DistinctStep with pre_distinct = false; getTraits sets returns_single_stream = !pre_distinct and transformPipeline does resize(1), so that single step both merged and deduplicated, with no preliminary phase.
c Fix matches root cause? Yes. Adds the missing pre_distinct = true step at the two sites that omitted it. No new setting, no widened bound, no change to DistinctStep or any optimizer pass. liftUpUnion already distributes a preliminary step into the branches.
d Test intent preserved / new tests added? Yes. New 04951_union_distinct_preliminary_distinct (SQL, parallel-safe, no no-parallel), plan-shape oracle in SELECT ... FROM (EXPLAIN ...) WHERE ... ILIKE form. Counts are exact, not presence-only, and the EXPLAIN PIPELINE arm asserts the executed shape; query_plan_lift_up_union is pinned so a future randomization cannot make them vacuous. No test weakened; 01556_explain_select_with_union_query's reference update is exactly the plan change it exists to assert.
e Both directions demonstrated? Yes, three ways. Against the unpatched binary the test FAILS with exactly the four count assertions flipping (2 -> 0, 3 -> 1) and every other line unchanged. Two targeted mutations also redden it: setting pre_distinct back to false while keeping the "Preliminary DISTINCT" label fails on the old-analyzer assertions (Planner.cpp mutation: on the analyzer ones), which a presence-only oracle would have passed.
f Fix is general across code paths? Yes. Both planner implementations fixed (analyzer and enable_analyzer = 0), verified by observation. Carriers checked: liftUpUnion + its blocksHaveEqualStructure guard, removeRedundantDistinct (02500 green on both analyzers), applyStreamDisjointness (early-returns for preliminary steps), limitPushDown (reaches only the final step), recursive CTEs (UNION DISTINCT rejected upstream), distributed (01952 green). INTERSECT/EXCEPT DISTINCT excluded on measurement and asserted byte-identical on both analyzers.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Nullable, LowCardinality, LowCardinality(Nullable), Array, Tuple, bare AggregateFunction state, divergent const, coerced branch types (UInt8/Int64, String/FixedString), all-distinct, 2- and 3-branch, mixed DISTINCT/ALL chains, parenthesized nesting, union_default_mode = 'DISTINCT', LIMIT/LIMIT BY/ORDER BY/OFFSET/WITH TIES, WITH TOTALS, extremes, IN subquery: every arm identical to the rewrite and to unpatched master.
h Backward compatible? (maintainer-approved exception only) Yes. No setting added or defaulted differently, so no SettingsChangesHistory.cpp entry is owed (src/Core/ diff is empty). Plan serialization: "PreDistinct" is registered unconditionally alongside "Distinct", with an identical payload, and predates DBMS_QUERY_PLAN_SERIALIZATION_VERSION = 7, so the extra step is additive.
i Invariants and contracts preserved? Yes. Purely additive step; no existing step altered. Totals/extremes ports untouched (transformPipeline returns nullptr for non-Main streams; arm tested). DISTINCT size limits are now enforced per stream as well as globally: the committed test drives an arm where the limit actually fires (numbers(600), max_rows_in_distinct = 100, max_block_size = 50) and both forms return the same truncated count in break mode, with throw raising SET_SIZE_LIMIT_EXCEEDED in both. Disclosed in the description. No locking, lifetime or error-path change.

Session id: cron:clickhouse-review-slot-49:20260817-172500

@groeneai

Copy link
Copy Markdown
Collaborator Author

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.

@clickhouse-gh

clickhouse-gh Bot commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2848e3e]

Summary: ❌

job_name test_name status info comment
Stress test (amd_tsan) FAIL
Hung check failed, possible deadlock found FAIL cidb IGNORED

AI Review

Summary

This PR adds a preliminary DISTINCT step for UNION DISTINCT in both planner paths, then skips that step when the resolved max_threads is 1. The multi-threaded improvement makes sense, but the new heuristic is applied too early in the optimization pipeline and drops a real one-thread optimization opportunity for ordered inputs, so I do not think the current shape is ready to merge.

Findings

⚠️ Majors

  • [src/Processors/QueryPlan/DistinctStep.cpp:30] preliminaryDistinctIsUseful is evaluated before liftUpUnion, optimizeDistinctInOrder, and applyOrder. At max_threads = 1 that suppresses not only the redundant hash pre-distinct, but also the preliminary step that later optimizer passes can turn into DistinctSortedStreamTransform 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 per-stream order for multi-branch unions. The result is that one-thread UNION DISTINCT still misses the in-order optimization its SELECT DISTINCT * FROM (A UNION ALL B) rewrite already gets.
    Suggested fix: defer the heuristic until order selection is known, or gate only the hashing variant once distinct_sort_desc is known to stay empty.
Tests
  • ⚠️ Add a focused EXPLAIN PIPELINE test for UNION DISTINCT over ordered branch reads with max_threads = 1 and optimize_distinct_in_order = 1. That is the smallest proof that the planner still preserves the sorted preliminary DISTINCT path instead of silently removing it.
Final Verdict

Needs changes.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.30% 87.20% -0.10%
Functions 91.90% 91.90% +0.00%
Branches 79.40% 79.30% -0.10%

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

Full report · Diff report

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
@Algunenano Algunenano added the can be tested Allows running workflows for external contributors label Aug 24, 2026

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

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.

@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 2848e3ee5 with master 3bb0d50ee (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 1a47863ae; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 711.27 MiB 708.22 MiB -3.05 MiB (-0.43%)

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 units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

Measured both directions on a release build (RelWithDebInfo, clang-21), 8M rows per branch (16M input rows), MergeTree, FORMAT Null, best of 7 from system.query_log. Form A is UNION DISTINCT, form B is SELECT DISTINCT * FROM (A UNION ALL B). Form B is the control: this change does not alter its plan, so it also calibrates run-to-run noise on a shared box.

per-branch distinct duplicate ratio max_threads A base A fix fix/base B base
2000 4000x 1 62 61 0.98x 60
2000 4000x 16 44 12 0.27x 11
100k 80x 1 225 179 0.80x 184
100k 80x 16 128 40 0.31x 46
1M 8x 1 221 234 1.06x 239
1M 8x 16 144 141 0.98x 208
2M 4x 1 249 342 1.37x 337
2M 4x 16 319 388 1.22x 370
8M (all distinct) 1x 1 380 672 1.77x 713
8M (all distinct) 1x 16 375 321 0.86x 460

You are right that the detrimental case is real, and it concentrates at max_threads = 1. With one thread there is no parallelism for the preliminary step to exploit, and when nothing is removed it exactly doubles the hash insertions: 16M (final only) becomes 8M + 8M + 16M. That predicts 2x and matches, 380 -> 672 ms; a 15-rep re-run of that cell gives 304 -> 644 ms, 2.12x. At max_threads = 16 the worst cell is 1.22x and most are at or below parity. The crossover sits near an 8x duplicate ratio.

The cost is not new, though. At max_threads = 1 on all-distinct data the documented rewrite already pays 649-713 ms on unpatched master, and the fix puts UNION DISTINCT at 644 ms, so the two forms converge (0.99x) instead of this change inventing a cost. That is the intent, but it does mean the parity is with a shape that is itself suboptimal at one thread.

If you want the detrimental column gone without any statistics, the data points at one cheap lever: skip the preliminary step when max_threads = 1. The effective value is already computed a few lines above both plan sites (Planner.cpp and InterpreterSelectWithUnionQuery.cpp), so it is one condition each, and it removes precisely the column where the step can never pay off. The cost is that the new test's plan assertions become max_threads-dependent and need pinning. Happy to add it here, or to leave the plan-shape parity with the rewrite as it stands and keep the heuristic for the follow-up you describe. Your call.

@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

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
  • StressHouse run: b5a7be04-6f38-47a5-ab72-9e19473baf3f
  • MIRAI run: c939327e-25b8-4c7e-8a21-5f83b2e980f6
  • PR check IDs:
    • clickbench_463882_1787756494
    • clickbench_463888_1787756495
    • clickbench_463899_1787756494
    • tpch_adapted_1_official_463911_1787756495
    • tpch_adapted_1_official_463920_1787756495
    • tpch_adapted_1_official_463952_1787756495

@Algunenano

Copy link
Copy Markdown
Member

If you want the detrimental column gone without any statistics, the data points at one cheap lever: skip the preliminary step when max_threads = 1. The effective value is already computed a few lines above both plan sites (Planner.cpp and InterpreterSelectWithUnionQuery.cpp), so it is one condition each, and it removes precisely the column where the step can never pay off. The cost is that the new test's plan assertions become max_threads-dependent and need pinning. Happy to add it here, or to leave the plan-shape parity with the rewrite as it stands and keep the heuristic for the follow-up you describe. Your call.

I think we should do it.

OTOH, what happens with SELECT DISTINCT * FROM (A UNION ALL B)? Does it have the same issue too? If so, then we should fix it in both and have the same pipeline levers in both places (ideally sharing code)

…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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed 2848e3e.

The skip is in, for UNION DISTINCT in both planners. The rule lives in one place,
preliminaryDistinctIsUseful(), and takes the effective thread count each union site has already
resolved for its UnionStep, so the guard and the step cannot disagree about the thread count. At one thread the plan and the pipeline are byte identical to master
again; at two or more nothing changes. 01556 and 04951 now pin max_threads, and also
max_threads_min_free_memory_per_thread = 0, which otherwise lowers max_threads to 1 under
memory pressure and would make both expected plans depend on free memory.

SELECT DISTINCT * FROM (A UNION ALL B): yes, it has the same issue. On master, in both
analyzers, it carries two preliminary DISTINCT steps at every thread count including
max_threads = 1, where they cannot reduce anything. At 8M all-distinct rows per branch and one
thread that costs it 649-713 ms, against 380 ms for UNION DISTINCT with no preliminary step at
all.

I did not apply the skip there, because the same condition is wrong in that path. Its
preliminary step already exists, and applyOrder may later turn it into a
DistinctSortedStreamTransform, which replaces hashing with a range scan and therefore pays off
at one thread too. The planner decides whether to add the step before that pass runs, so skipping
at max_threads = 1 drops in-order preliminary DISTINCTs along with the redundant hash ones.
Measured: three tests that pin max_threads = 1 themselves lose the transform they assert
(02862_sorted_distinct_sparse_fix, 04511_distinct_overflow_mode_break,
04649_distinct_in_order_final_float_equality), and ten more change plan at one thread. So that
half belongs in the optimization stage, after applyOrder, rather than in the planner. Say the
word and I will do it as a follow-up.

Separately, under a small outer LIMIT the preliminary steps hash a chunk before the final step's
pushed-down limit hint stops the pipeline. That is not new here: on master the rewrite measures
153 ms against 150 ms for UNION DISTINCT without the steps (LIMIT 1, 2x2M distinct rows), and
the two forms measure the same after this PR. The place to fix it is limitPushDown, where that
hint is assigned.


bool preliminaryDistinctIsUseful(size_t max_threads)
{
return max_threads > 1;

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 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?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 2848e3e

CI is fully finished at this commit. One check failed, and it has an owner.

Check / test Reason Owner / fixing PR
Stress test (amd_tsan) / Hung check failed, possible deadlock found trunk defect in groupConcat, not caused by this PR. There is exactly one hung query, an AST-fuzzer mutation reading merge(currentDatabase(), 't.*') and aggregating groupConcat(',')(CAST(st, 'String')); it is already cancelled at 3739 s elapsed with is_cancelled: 1. Its worker thread sits in ConvertImpl<DataTypeFixedString, DataTypeString, NameToString>::execute beneath GroupConcatImpl::add, which re-casts the whole FixedString column once per row, so a single aggregation batch runs quadratically and reaches no cancellation point, and the initiator is left parked in PullingAsyncPipelineExecutor::cancel. This PR touches only InterpreterSelectWithUnionQuery.cpp, Planner.cpp, DistinctStep.cpp, DistinctStep.h and two stateless tests, and the hung query contains neither UNION nor DISTINCT. Breadth of this hung-check row in CIDB over 7 days: 77 rows across 64 distinct pull requests, 6 of them on master itself, against a negative control of 0 on a fabricated test name. a fix task is created (investigating at full effort, fixing-PR link to follow on this PR)

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115173&sha=2848e3ee55e51800a4bf0b7a609de7f26c6e2d93&name_0=PR&name_1=Stress%20test%20%28amd_tsan%29

Everything else at this commit is green. Config Workflow, Style check, Fast test and Finish Workflow all succeeded; praktika result_pr.json reports 175 jobs as 158 OK, 16 SKIPPED and the one FAIL above, with zero dropped. A CIDB query at this commit returns exactly 1 FAIL row, the one owned above, out of 312,495 rows over 161 checks; the other non-OK tokens are 12,164 success and 14 unstable per-query verdicts from Performance Comparison shards that themselves report success, plus 9 NOT_FAILED rows, none of which is a failure.

Session id: cron:our-pr-ci-monitor:20260826-180000

@Algunenano
Algunenano enabled auto-merge August 27, 2026 16:15
@Algunenano

Copy link
Copy Markdown
Member

@groeneai Please open an issue about the stress test failure and tackled it in the simplest and more concise way possible

@Algunenano
Algunenano added this pull request to the merge queue Aug 27, 2026
Merged via the queue into ClickHouse:master with commit 91ccf2f Aug 27, 2026
177 of 179 checks passed
@groeneai

Copy link
Copy Markdown
Collaborator Author

Issue: #116740

The hung check is a whole-column cast inside a per-row callback: GroupConcatImpl::add() casts the
entire block to String for every row and keeps one row of the result
(AggregateFunctionGroupConcat.cpp:102-107), so one block costs O(rows^2) and no cancellation point
is reached inside the batch. Measured on master 26.9.1.209: 23.3 s for 200k FixedString(3) rows
against 0.34 s for the same query over String, and linear in max_block_size at a constant row
count. The hung worker stack in the artifact is that exact path.

The fix is a few lines in add(): read the FixedString bytes directly and cut trailing zero bytes,
which is all the cast was doing. Output stays byte-identical. I will link the PR here.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Done, both parts. Issue: #116740. Fix: #116795.

It was not a deadlock. For a FixedString argument groupConcat called castColumn on the whole block column once per row, so add was quadratic in the block size and the cancelled query kept running for 526 s against max_execution_time = 10, which the hung check reported. The fix reads the row directly from ColumnFixedString and strips trailing zero bytes, which is what CAST(FixedString AS String) already does, so output is unchanged: 45.3 s to 0.11 s for 400,000 rows. It is 18 added lines in one function plus a regression test.

@Algunenano

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 groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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.

UNION DISTINCT skips the preliminary parallel DISTINCT that the equivalent rewrite gets

3 participants