Repository navigation
Conversation
`IntersectOrExceptStep` resized each input to a single stream and ran one `IntersectOrExceptTransform`, so the whole set operation was single-threaded. Now both inputs are hash-scattered by the whole row into `max_threads` partitions (`scatterByPartition`) and one transform runs per partition. Equal rows land in the same partition on both sides, so every partition is an exact `INTERSECT`/`EXCEPT` on its subset and the union of the outputs is the result. This covers both `ALL` (multiset) and `DISTINCT` modes. The output streams are disjoint by all columns, which `applyStreamDisjointness` now reports so that the final `DistinctStep` of `INTERSECT DISTINCT` / `EXCEPT DISTINCT` keeps the streams instead of merging them. With a huge `max_threads` the partition count is capped by the scatter connection limit instead of failing. `checkScatterConnectionLimit` moved from `SortingStep` to `scatterByPartition` to share the limit. Tests that relied on the output order of a set operation without an outer `ORDER BY` now pin `max_threads = 1`. Closes: ClickHouse#115106
- 05047_parallel_intersect_except_explain: the CI test config (users.d/limits.yaml) sets max_rows_in_distinct / max_bytes_in_distinct to 10G, and DISTINCT size limits keep the stream merge before the final DISTINCT, so the disjointness did not apply. Reset both to 0 like the other tests of allow_distinct_partitions_independently do. - 03927_except_all_ast_formatting_roundtrip, 04340_any_join_not_ready_set_null_in: the output order of INTERSECT ALL / EXCEPT ALL now depends on the number of threads; pin max_threads = 1. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=117020&sha=dea2da7108b1f953865b957c919e0aaad63f8206&name_0=PR&name_1=Fast%20test PR: ClickHouse#117020 Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01VuKaVfEaqYbD872fGgjx8p
`IntersectOrExceptTransform` started in a `ReadLeftInput` stage that pulled chunks from the left input until one had rows, and only then drained the whole right input. With one transform per partition that deadlocks the pipeline: `ScatterByPartitionTransform` does not push empty chunks, so a partition whose share of the left input is empty gets nothing and keeps waiting for it. A partition that did receive left rows stops reading its left port while it drains its right one, which blocks the left scatter for every other partition, and those partitions never drain the right scatter the first one waits on. Sample the left port from within `ReadRightInput` instead of waiting on it first. The transform still stops before reading a possibly unbounded right input when the left one turns out to be empty, but it never blocks on the left port, so the cycle is gone. Reproduced on the pull request branch before the fix with `SELECT number % 2 FROM numbers_mt(10000000) EXCEPT ALL SELECT number FROM numbers_mt(10000000)` at `max_threads = 8`, which raised the `Pipeline stuck. Current state:` exception with all eight transforms in `NeedData`. `04039_intersect_except_duplicate_column_names` compares the output of a set operation that has no outer `ORDER BY`, whose row order is not deterministic once the partitions are processed in parallel; it failed 12 times out of 20 runs. Pin `max_threads` there like the other order-dependent tests. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01MELPeVV73Q4cR5NH68NUxE
…peline Keep the left-first startup for the single-transform case. Removing `Stage::ReadLeftInput` outright made the non-partitioned path start draining the right input before the left one had produced a row, so a query whose left branch ends up empty could still materialize the whole right side. Restore the stage and select it with a constructor flag, so only the partitioned transforms, which cannot wait on their left port without deadlocking the shared scatters, sample it from `ReadRightInput`. With an empty left branch and `max_threads = 1` the right input is again read for zero rows, against one block for the partitioned path. Drop the stream disjointness property of `IntersectOrExceptStep` when its output header has a duplicated column name. The scatter partitions by column position, but the property is matched downstream through `findInOutputs` and `matchTrees`, which resolve columns by name and so collapse the duplicates. Such a header is legal, `SELECT id, *, b` produces one, and claiming a partitioning that the names cannot express could let the final `DISTINCT` skip the cross-stream merge on a key that does not determine the partition. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01MELPeVV73Q4cR5NH68NUxE
`04039_intersect_except_duplicate_column_names` is pinned to `max_threads = 1`, so nothing exercised the partitioned `INTERSECT DISTINCT` / `EXCEPT DISTINCT` path with a duplicate-name output header. The new test runs the four set operations over `SELECT id, *, b` with `max_threads = 4` and asserts, via `EXPLAIN`, that the inputs are still scattered while the final `DistinctStep` keeps merging the streams. The unique-name variant of the same query is checked to still report `Skip stream merging: 1`, so the assertion fails if the bailout is removed. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01WbMXskfhLbhKs1cDe86NVs
The old analyzer deduplicates the repeated `id` and `b` columns once the set operation is wrapped in `SELECT * FROM (...)`, so the test failed in the old-analyzer stateless job with a three-column result. Run the set operations at the top level instead, as `04039_intersect_except_duplicate_column_names` does; every result is a single row, so no outer ordering is needed. CI: ClickHouse#117020 Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_014TAD8QfFoj773Uby3ijcDT
The cap was applied per branch, so each branch's scatter stayed within `scatter_connection_count_limit` while the step as a whole could wire up twice that many connections plus one `IntersectOrExceptTransform` per partition. Count the whole step instead: every partition costs one connection per input stream of every branch, plus the transform that consumes one output of each branch's scatter and produces one output. With two branches of 6144 streams each and `max_threads = 6144`, the partition count now settles at 81 (1000000 / (2 * 6144 + 3)) instead of 162. Keep capping rather than restoring the hard failure: before the parallel path a huge `max_threads` simply built one transform, so throwing `LIMIT_EXCEEDED` would make previously working queries fail on a setting value alone. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01Tb5JT3NGo1b6aPoCmNJLtG
…edicts to saturate `ApproximateRuntimeFilter` sizes its Bloom filter from the build-side key count of the hash table statistics, but the size is capped at 4 MiB. With more distinct keys than fit at `join_runtime_bloom_filter_max_ratio_of_set_bits`, every build thread filled and merged its 4 MiB copy only for `checkBloomFilterWorthiness` to discard the result: on a 30M-key `SEMI JOIN` that was a third of all CPU time, and the query's profile events showed no row ever checked against the filter. The same formula that sizes the filter predicts its fill rate at the capped size, `1 - exp(-keys * hashes / bits)`. When that exceeds the maximal ratio, the filter is disabled before the build instead of after it. The min/max envelope for index analysis is still tracked. New profile event `RuntimeFilterBloomFilterBuildsSkipped`. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01LGYF2mcxx48Tg779vd8Djj
The final `DISTINCT` merged all streams into one `DistinctTransform`, which made `SELECT DISTINCT a` four times slower than `GROUP BY a` on a 30M-row table and was the larger half of the cost of the `SEMI JOIN` + `DISTINCT` rewrite of `INTERSECT DISTINCT`. `DistinctStep` now scatters its streams by the hash of the `DISTINCT` columns with `scatterByPartition`, so equal rows land in the same stream and every stream is deduplicated independently and completely. The merge is kept for a sorted input (`DistinctSortedStreamTransform` relies on its stream order), for the global `max_rows_in_distinct` / `max_bytes_in_distinct` limits, for a single thread, and when the stream disjointness pass already skipped it. Controlled by the new setting `allow_parallel_final_distinct`, enabled by default. The duplicate-name case of `05056_parallel_intersect_except_duplicate_column_names` now shows the scatter of the `DISTINCT` itself instead of a merge. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01LGYF2mcxx48Tg779vd8Djj
…tyle check The setting controls an optimization, not an experimental feature, like the neighbouring `allow_*_distinct_*` settings. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01LGYF2mcxx48Tg779vd8Djj
|
Workflow [PR], commit [964a452] Summary: ❌
|
…count predicts to saturate" This reverts commit 34e2c85.
…T test The CI test config (`tests/config/users.d/limits.yaml`) sets `max_rows_in_distinct` and `max_bytes_in_distinct`, and the parallel final `DISTINCT` keeps the single-stream merge under those limits, so the `EXPLAIN PIPELINE` in the test showed the merge in CI. Fast test report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118230&sha=eac785659bde4ca77989e4eb2bac9f2082f7dec7&name_0=PR&name_1=Fast%20test PR: ClickHouse#118230 Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01SGvsqqytvRcokXN8TWn2Mr
…t-except # Conflicts: # src/Processors/QueryPlan/IntersectOrExceptStep.cpp # src/Processors/QueryPlan/IntersectOrExceptStep.h
Build profile diff (arm_release)Commit See the job log for details. |
|
📊 Cloud Performance Report ✅ AI verdict: This PR rewrites INTERSECT DISTINCT and EXCEPT DISTINCT into a semi or anti join followed by DISTINCT. To support that, it adds a set-operation flag to the join and a preliminary DISTINCT that gives up after the first chunk. The only flagged queries are ClickBench Q33 (-5.7%) and Q34 (-5.9%), both plain GROUP BY aggregations that use no set operation, join or DISTINCT, so the new code does not run for them. Both were downgraded to not_sure: they are noisy on master, Q33's PR median sits inside master's recent range, and the PR's ClickBench and TPC-H runs shared one machine. No benchmark query here uses INTERSECT or EXCEPT, so this run says nothing about how the rewrite itself performs. clickbenchFlagged queries (2 of 43)
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
|
|
After reading #117020 (comment), I thought that we'll rewrite to a SEMI JOIN (this PR goes the opposite route). |
…ndent of the read pipeline The case reads a single in-order stream, and the processors above the `DISTINCT` (virtual rows, in-order merges, parallel replicas) depend on the randomized settings, so the indentation of the `Distinct` lines differed between CI runs. Print the transforms without indentation, which is all the case checks. CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118230&sha=d4f1ae86e8d545d68644d7c14dbd10756eda1584&name_0=PR PR: ClickHouse#118230 Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01DKCn7rgmmufCUs2bvhMAge
The preliminary `DISTINCT` of a set operation input is only added for more than one thread, and the stateless test runner randomizes `max_threads`, so the plan section of the test lost the steps in the runs with one thread. Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118230&sha=2dd35901ec68fb644c36356a43a3c7c315a76895&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20targeted%29 PR: ClickHouse#118230 Co-Authored-By: Claude Fable 5.1 <[email protected]>
… serialization `clone` and `serialize` / `deserialize` rebuilt the step without `is_set_operation`, so a copied or shipped plan fragment lost `TableJoin::setReadsLeftWhileFillingRight` in `buildPhysicalJoinImpl`. The mark now goes into the flags byte at step version 1 of `Join`, anchored at plan version 20, which no release has shipped. Co-Authored-By: Claude Fable 5.1 <[email protected]>
`deserialize` always rebuilt the step with the default window of `DeduplicationAbandonController`, so the preliminary `DISTINCT` of a set operation input lost `abandonAfterFirstChunk` once the plan went over the wire. The window is written at step version 2 of `Distinct` and `PreDistinct`. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…by the join kind it needs `EXCEPT DISTINCT` needs an `ANTI` join, which `partial_merge` cannot execute, so the modes do not share one applicability test. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…on to a join The rewrite treated `join_algorithm` as a capability set: with `grace_hash,hash`, a spill threshold and no temporary storage, `hash` made it rewrite while `chooseJoinAlgorithm` throws on the leading `grace_hash` before reaching `hash`. The list is now walked in order like `tryCreateJoin` does: an algorithm that cannot execute the join is passed over, and the set-operation step is kept where the planner would throw. Co-Authored-By: Claude Fable 5.1 <[email protected]>
The CI randomizes `query_plan_optimize_join_order_randomize`, which swaps the sides of the nested join of the three-arm `INTERSECT DISTINCT` and reorders its `EXPLAIN` lines. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118230&sha=cf191efc48b06d4d736df93e27a5465ae134dce6&name_0=PR ClickHouse#118230 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…pill threshold The rewrite sampled the temporary storage of the server rewriting the query, but the join is built on every server that executes the plan (parallel replicas, a distributed plan) from that server's own temporary storage. A worker without it would throw on a leading `grace_hash` where the set-operation step would have succeeded, so fail closed and keep the step whenever `grace_hash` with a spill threshold is the first algorithm that decides. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…t-except Co-Authored-By: Claude Opus 5.5 <[email protected]>
…except Resolve the conflict with the move of the settings changes history into the setting declarations (ee6b44f): the history records this PR added to `SettingsChangesHistory.cpp` now live as trailing arguments of the `DECLARE` of each setting. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
# Conflicts: # src/Core/ProtocolDefines.h # src/Core/Settings.cpp
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…t-except Co-Authored-By: Claude Opus 5.5 <[email protected]>
…t-except # Conflicts: # src/Core/ProtocolDefines.h # src/Processors/QueryPlan/JoinStepLogical.cpp
…T` and keep its semantics Rewrite only when the join is a hash join that reads all of both sides: the merge joins compare some keys differently, and `max_rows_in_join` / `max_bytes_in_join` cut the right side short. This replaces the walk over `join_algorithm` and the merge-unsafe keys. The preliminary `DISTINCT` of the join inputs no longer inherits the limits of `DISTINCT`, which bound the result of the query, and uses the default abandon window. The mark of a set operation is no longer serialized: a peer executes an ordinary join. The Cascades statistics of semi and anti joins are dropped. A set operation stops reading its right side once all its left streams turn out empty, after about one block per thread that builds the right side, unless it is a right anti join, whose result comes from the right side. ClickHouse#118230
…usted left stream Counting the empty left streams in a counter shared with the transforms filling the right side did not stop a right side that produces nothing until it is read to the end, such as `SELECT max(number) FROM system.numbers`: nothing woke the transforms filling it. Now a `JoiningTransform` of a set operation whose left stream is exhausted before the right side is filled closes its port to the right side, and once all of them have, the right side stops being read. A left semi or anti join outputs only left rows, so the sides of a set operation are no longer swapped. The join it is executed as is serialized with its mark again, so that a replica stops the same way. Drop `05155_intersect_except_as_join_float_keys`, which covered the removed rules, and keep its nested float keys in `05388_intersect_except_as_join_kept_semantics`.
…operation in Cascades A spilling join switches to `GraceHashJoin` while the right side is still read, so the state does not tell whether the build finished: the delayed blocks of a build abandoned after the switch were read while a filling transform could still write its buckets. `SpillingHashJoin::getDelayedBlocks` now checks that the build phase finished. `JoinCommutativity` no longer swaps the join of a set operation, like the other join reordering.
The set-operation step passes on the totals of its inputs, while the join joined the default totals of the left side with the totals of the right one, so a right arm `WITH TOTALS` returned a different totals row.
…t-except # Conflicts: # src/Processors/Transforms/JoiningTransform.cpp # tests/queries/0_stateless/02004_intersect_except_distinct_operators.sql
… settings history The setting is not in any release yet, and the current version is now 26.11.
Closes: #115106
Related: #120479 (the parallel
INTERSECT ALLandEXCEPT ALL, split out of this PR)Related: #115301
Related: #118336 (the join runtime filter Bloom filter skip, split out of this PR)
Related: #119218 (the left semi join empty-set check, split out of this PR)
Related: #119012 (the parallel final
DISTINCT)Related: #117020 (auto-closed when its base branch was merged; this is the same branch retargeted to
master)The query tree pass
RewriteIntersectExceptToJoinPassrewritesINTERSECT DISTINCTandEXCEPT DISTINCTtoSELECT DISTINCT l.* FROM (arm_1) l SEMI|ANTI LEFT JOIN (arm_2) r ON l.c_i <=> r.c_i ..., folding more arms from the left, so that they use the join algorithms and their optimizations (spilling, parallel replicas). The null-safe comparison matchesNULLwithNULLlike the set operation does, and an arm whose column types differ from the union's result types is wrapped in a subquery converting them once. A rewritten arm of a rewritten set operation drops its ownDISTINCT, since a semi or anti join needs neither side deduplicated. New settingoptimize_rewrite_intersect_except_to_join, on by default.The rewrite happens only where the join returns exactly what the set operation does: a hash join reading all of both sides. So
join_algorithmmust enable onlydefault,hashandparallel_hash(besidesdirectandie_join, which never take such a join), since a merge join compares some keys differently (-0.0and0.0,NaNs, states of aggregate functions), and neithermax_rows_in_joinnormax_bytes_in_joinmay be set, since they throw or, withjoin_overflow_mode = 'break', cut the right side short. The set-operation step is also kept forDynamiccolumns (not a join key), duplicate column names in an arm, and arms with totals.The join a set operation is executed as is marked in the query tree (
JoinNode::isSetOperation), and the mark changes how it runs:DISTINCTon both inputs, so that each stream drops its own duplicates before the join hashes them. It is only an optimization, so the limits ofDISTINCT, which bound the result, do not apply to it.JoiningTransformasks the left input for data while the right side is still filled, the wayIntersectOrExceptStepreads its inputs.SELECT max(number) FROM system.numbers). So an empty left arm does not read an unbounded right one. For this the sides of the join are not swapped.The first two came out of the
tpcdsregressions of an earlier revision of this PR (report): query 14 was 27% slower and query 38 20%.Benchmarks, 16 threads, join rewrite vs the set-operation step:
INTERSECT DISTINCTof 30M and 20M unique rows 0.42s vs 0.87s, of 1M and 30M rows 0.47s vs 1.12s, of 30M and 20M rows with a few thousand distinct ones 0.022s vs 0.034s,EXCEPT DISTINCTof 1M and 30M rows 0.43s vs 1.03s, of 3M and 2M unique rows 0.12s vs 0.28s.Behaviour changes of the
DISTINCTmodes with the rewrite: an empty left arm stops reading the right one only once every stream of the join has seen its end, which may be after a few blocks per thread;extremesare those of the result, not of the unfiltered left input.Existing tests that relied on the output order of a
DISTINCTset operation without an outerORDER BYnow order their results, and tests of the set-operation step itself turn the rewrite off.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
INTERSECT DISTINCTandEXCEPT DISTINCTare executed as a semi or anti join followed byDISTINCT, so they use the join algorithms and their optimizations (new settingoptimize_rewrite_intersect_except_to_join).Workflow [PR]
Sync PR [sync-upstream/pr/118230]