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
…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
…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
…d count and the scatter connection limit The scatter used the stream count as the partition count without a cap, so a plan with a large fan-in built a streams-squared processor graph. Use the pipeline's thread count, cap it so that partitions times streams stays under `scatter_connection_count_limit`, and keep the merge when the cap leaves a single partition. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01DKCn7rgmmufCUs2bvhMAge
… followed by DISTINCT The planner builds `SELECT DISTINCT l.* FROM (arm_1) l SEMI|ANTI LEFT JOIN (arm_2) r ON l.c_i <=> r.c_i ...` from the resolved arms of the union node, folding more arms from the left, and plans that query instead of the `IntersectOrExceptStep`. The null-safe comparison matches `NULL` with `NULL` like the set operation, and the arms' columns are cast to the union's result types like the step converts its inputs. The join gets the join algorithms and their optimizations (build side choice, runtime filters), and the parallel final `DISTINCT` deduplicates its output. Arms with duplicate column names or `Dynamic` columns keep the step, as do the `ALL` modes, which have no join equivalent. New setting `optimize_rewrite_intersect_except_to_join` (default on) controls the rewrite. Related: ClickHouse#118230 Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01DKCn7rgmmufCUs2bvhMAge
The rewrite is a query tree to query tree transformation, so it runs as `RewriteIntersectExceptToJoinPass` right after the projection pruning, replacing the union node in place and re-pointing the columns of the outer queries that were sourced by it. The later passes and the tree-level analyses (parallel replicas selection, `EXPLAIN QUERY TREE`) then see the join, and the planner needs no nested planner for it. An arm whose column types differ from the union's result types is wrapped in a subquery converting them once, instead of casting in the join keys and again in the projection. A rewritten arm of a rewritten set operation drops its own `DISTINCT`: a semi or anti join needs neither side deduplicated, and the outer `DISTINCT` covers the output. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…e final DISTINCT `clampScatterPartitions` reduces a free partition count so that the scatter stays within the connection limit; both steps used their own arithmetic for it. The set-operation step also builds its single-partition pipeline through the same transform loop as the partitioned one. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
…es and keep the set-operation step for join algorithms without semi joins The planner identifies columns by the alias of their table expression and the analyzer assigned its `__tableN` aliases before the pass, so two generated subqueries with a common column name collided with `Column identifier x is already registered`. Every subquery the pass creates now gets its own alias. `join_algorithm` values that cannot execute a semi or anti join (`full_sorting_merge`, `partial_merge`, `direct` alone) failed the rewritten queries; the pass keeps the set-operation step for them. Correlated unions keep it as well. The queries of `02004_intersect_except_distinct_operators` with several result rows are ordered, since the output order of a join depends on the join settings. Co-Authored-By: Claude Fable 5.1 <[email protected]>
… join rewrite pass The pass asks `TableJoin::isEnabledAlgorithm` which join algorithms are enabled, per strictness, since the partial merge join executes semi joins but not anti joins; it checks the node type before the settings and skips the column-source fix-up when only the root was rewritten. The final `DISTINCT` uses `SizeLimits::hasLimits` and one loop for its key columns. The set-operation step collects the processors of a branch once, and the scatter connection limit is local to its module. The tests of the set-operation step pin the rewrite off, and the queries of both `02004` tests with several result rows are ordered instead of pinning `max_threads`. Co-Authored-By: Claude Fable 5.1 <[email protected]>
A left semi join keeps only the left rows with a match, so an empty right side makes it empty like an inner join; `alwaysReturnsEmptySet` now says so for the hash join and the grace hash join, and the joining transform stops reading the left input. `INTERSECT DISTINCT` with an empty right arm then stops like the set-operation step does. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ns its input A final `DISTINCT` that hash-partitions its input, or keeps disjoint streams, deduplicates every stream completely on its own, so the preliminary `DISTINCT` before it only hashes every row once more. The plan optimization removes it when the final `DISTINCT` will not merge its streams: no sort description, no global size limits, more than one thread. A sorted preliminary `DISTINCT` stays, since it deduplicates its stream without a hash table. Measured on 30M rows with 16 threads: `SELECT DISTINCT` of two columns 0.73s to 0.64s with 20M distinct rows and 0.26s to 0.23s with 100k distinct rows; the `INTERSECT DISTINCT` join 1.47s to 1.40s. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ts Cascades estimate The join rewrite of `INTERSECT DISTINCT` / `EXCEPT DISTINCT` turns the query into a `SELECT DISTINCT` over a semi or anti join, which plans like any other `SELECT DISTINCT`: the preliminary `DISTINCT` that `04951_union_distinct_preliminary_distinct` asserts to be absent is now expected, and the `Distinct` bound by the smallest input that `04838_cascades_filter_selectivity` asserts is replaced by the semi join estimate, which keeps the left input for a key without statistics. Both tests are about the set-operation step, so they turn the rewrite off. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118230&sha=af79d93010057489b1912d745b5604733e27a871&name_0=PR&name_1=Fast%20test PR: ClickHouse#118230 Co-Authored-By: Claude Fable 5.1 <[email protected]>
…pt-all # Conflicts: # src/Core/SettingsChangesHistory.cpp
Build profile diff (arm_release)Comparing 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. The official master build is compiled with Object file sizes
|
| Object file | Master | PR | Δ |
|---|---|---|---|
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinAntiMapsCount.cpp.o |
new | 2.54 MiB | +2.54 MiB |
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinSemiMapsCount.cpp.o |
new | 2.45 MiB | +2.45 MiB |
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/HashJoin.cpp.o |
3.28 MiB | 3.89 MiB | +624.78 KiB (+18.58%) |
src/CMakeFiles/dbms.dir/Interpreters/ConcurrentHashJoin.cpp.o |
1.00 MiB | 1.17 MiB | +168.02 KiB (+16.34%) |
src/CMakeFiles/dbms.dir/Analyzer/Passes/RewriteIntersectExceptToJoinPass.cpp.o |
new | 147.59 KiB | +147.59 KiB |
src/CMakeFiles/dbms.dir/Planner/Planner.cpp.o |
790.93 KiB | 838.13 KiB | +47.20 KiB (+5.97%) |
719 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
398 translation units recompiled, 3768 s compile time in total, 395 of them have a recent master baseline.
Translation units without a recent master baseline:
src/Interpreters/HashJoin/LeftHashJoinAntiMapsCount.cpp: 16.2 ssrc/Interpreters/HashJoin/LeftHashJoinSemiMapsCount.cpp: 15.7 ssrc/Analyzer/Passes/RewriteIntersectExceptToJoinPass.cpp: 6.1 s
…t-except-all # Conflicts: # src/Core/SettingsChangesHistory.cpp
…join` The `EXPLAIN` part of the test depended on randomized settings: the preliminary `DISTINCT` of the set operation inputs is planned only when `max_threads` is greater than 1, and a swap of the join sides (`query_plan_join_swap_table`) reorders the inputs of the nested set operation. The test now sets `max_threads = 2` and `query_plan_join_swap_table = 'false'` for the plan section. ClickHouse#120479 https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120479&sha=e62f358baf2a3bf0c6580336846acff457447909&name_0=PR Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ion of `JoinStepLogical` The flag enables `readsLeftWhileFillingRight` in the physical join, but `JoinStepLogical::clone` did not copy it and the step serialization did not write it, so a cloned step (for example the `JoinCommutativity` alternative) or a step shipped to a remote planner lost the early read of the left side. `clone` copies the flag now, and `serialize` / `deserialize` carry it in the first bit of the step `flags` byte, which was always zero and is ignored by peers that do not know it. ClickHouse#120479 Co-Authored-By: Claude Fable 5.1 <[email protected]>
…t-except-all # Conflicts: # src/Interpreters/HashJoin/HashJoin.cpp
|
|
||
| /// A multiset ANTI join (see `JoinOperator::multiset`) keeps the left rows of a key that outnumber its | ||
| /// right rows, while the `NOT IN` runtime filter of an ANTI join would drop every left row of that key. | ||
| if (join_operator.multiset && join_operator.strictness == JoinStrictness::Anti) |
There was a problem hiding this comment.
This still leaves INTERSECT ALL without any runtime filter at all. The new guard only excludes multiset ANTI, but the key-extraction path below still skips every NullSafeEquals predicate (predicate_op != JoinConditionOperator::Equals here, and again in JoinStepLogical::preCalculateKeys at src/Processors/QueryPlan/JoinStepLogical.cpp:2461). The multiset rewrite builds only <=> predicates, so join_keys_build_side stays empty and the pass returns before creating any filter.
That contradicts the PR description's claim that the ALL rewrite gets join runtime filters, and it leaves large selective INTERSECT ALL queries without one of the advertised speedups. Please either treat NullSafeEquals as a valid equi-key here too, or drop the runtime-filter claim/tests for the multiset SEMI path.
| JoinKind::Left, is_intersect ? JoinStrictness::Semi : JoinStrictness::Anti, JoinLocality::Unspecified, std::move(predicates)); | ||
| join_operator.multiset = true; | ||
|
|
||
| auto join_step = std::make_unique<JoinStepLogical>( |
There was a problem hiding this comment.
This synthesized multiset join is never marked as a set operation. buildPhysicalJoinImpl only enables the set-operation startup path through logical_join_info.is_set_operation (src/Processors/QueryPlan/JoinStepLogical.cpp:1684), so INTERSECT ALL / EXCEPT ALL still use ordinary fill-right-first scheduling: the left arm does not start until the right arm is fully built.
TableJoin's own comment in src/Interpreters/TableJoin.h:292-295 calls out set operations as the case where both whole-query arms should overlap, and the DISTINCT rewrite already preserves that flag. Omitting join_step->setIsSetOperation(true); here gives back part of the speedup on queries where both sides are expensive.
…t-except-all Co-Authored-By: Claude Opus 5.5 <[email protected]>
| key_conditions.reserve(result_columns.size()); | ||
| for (size_t i = 0; i < result_columns.size(); ++i) | ||
| key_conditions.push_back(makeFunction( | ||
| "isNotDistinctFrom", {makeColumn(left.columns[i], left.node), makeColumn(right.columns[i], right.node)}, context)); |
There was a problem hiding this comment.
This rewrite keys the synthesized join entirely with isNotDistinctFrom, but the remaining "equi-key" optimizer paths still recognize only plain Equals: tryAddJoinRuntimeFilter / preCalculateKeys in joinRuntimeFilter.cpp + JoinStepLogical.cpp, tryMakeDistributedJoin in makeDistributed.cpp, and HashJoinImplementation::extractEquiJoinKeys.
That means rewritten INTERSECT DISTINCT / EXCEPT DISTINCT joins still never get runtime filters and cannot use distributed/shuffle hash-join planning, even though moving them onto a join is supposed to pick up those join-side optimizations. The current tests only compare results and plan shape, so this gap slips through.
Please either emit plain Equals when a compared pair is known non-nullable, or teach the equi-key extraction sites above to handle NullSafeEquals consistently as a join key too.
…except-all 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]>
| { | ||
| auto left = join_expression_actions.findNode(left_header->getByPosition(i).name, /*is_input=*/ true); | ||
| auto right = join_expression_actions.findNode(right_names[i], /*is_input=*/ true); | ||
| predicates.push_back(JoinActionRef::transform({left, right}, JoinActionRef::AddFunction(JoinConditionOperator::NullSafeEquals))); |
There was a problem hiding this comment.
INTERSECT ALL / EXCEPT ALL still cannot take the distributed hash-join path from here, because the synthesized predicates are all NullSafeEquals and the distributed planners still treat only plain Equals as equi-keys: shuffleJoinKeysHaveCommonType / tryMakeDistributedJoin in makeDistributed.cpp and the Cascades HashJoinImplementation::extractEquiJoinKeys all skip this join.
That means the multiset rewrite still gathers both arms to one node on distributed plans instead of picking up the join-side distribution strategies the setting text promises. The current tests only cover local plans, so this slips through.
Please either emit plain Equals for known non-nullable pairs here, or teach those equi-key extractors to accept NullSafeEquals too. If you take the latter route, keep the broadcast path disabled for join_operator.multiset, because replicating the right-side counts would overmatch across workers.
|
📊 Cloud Performance Report ✅ AI verdict: This PR runs INTERSECT/EXCEPT DISTINCT as a semi or anti join and adds count maps to the hash join so INTERSECT/EXCEPT ALL can run as a multiset join; neither ClickBench nor TPC-H uses INTERSECT or EXCEPT. The two flagged results, ClickBench Q33 (-9.1%) and Q34 (-9.7%), are plain GROUP BY aggregations with no joins or set operations, so the PR cannot plausibly explain them. Both are downgraded to not sure: their history is noisy, and Q33's new median is still inside master's recent range. No regressions were flagged, and nothing in this run is a performance change you need to act on. 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
|
…t-except-all Co-Authored-By: Claude Opus 5.5 <[email protected]>
…t-except-all # Conflicts: # src/Core/ProtocolDefines.h # src/Interpreters/HashJoin/HashJoin.cpp # src/Processors/QueryPlan/JoinStepLogical.cpp
Only the `DISTINCT` rewrite set the flag, so the multiset join did not start reading its left side while its right side was being built.
…t-except-all # Conflicts: # src/Planner/Planner.cpp # src/Processors/QueryPlan/DistinctStep.cpp # src/Processors/Transforms/DistinctTransform.cpp # src/Processors/Transforms/DistinctTransform.h
…set operation join Master now derives the thread count through `getEffectiveMaxThreads`, and `PlannerJoinTree.cpp` no longer declares `Setting::max_threads`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…t-except-all # Conflicts: # src/Interpreters/HashJoin/HashJoinMethodsImpl.h # src/Processors/QueryPlan/DistinctStep.cpp # src/Processors/QueryPlan/DistinctStep.h # src/Processors/Transforms/DistinctTransform.cpp # src/Processors/Transforms/DistinctTransform.h # src/Processors/Transforms/JoiningTransform.cpp # tests/queries/0_stateless/02004_intersect_except_distinct_operators.sql # tests/queries/0_stateless/04027_redundant_equals_variant_type.sql
… settings history The setting is not in any release yet, and the current version is now 26.11.
|
@raimannma, It's unclear why this was closed. |
Hey, @alexey-milovidov |
|
We picked this up already.
Thanks @raimannma |
Related: #115106
Related: #118230 (the
INTERSECT DISTINCTandEXCEPT DISTINCTjoin rewrite; this branch contains it, so the diff shows its changes until it is merged)Related: #117020
INTERSECT ALLandEXCEPT ALLare executed as a join, as suggested in #117020 (comment). The planner builds aJoinStepLogicalfor them: aSEMI LEFT JOINorANTI LEFT JOINof the two arms on all columns with null-safe comparison, marked as multiset (JoinOperator::multiset).HashJoinruns a multiset join on new count maps (JoinMapsKind::Count): the build side counts the right rows of a key instead of storing them, and each probe row takes one atomically, so a left row is kept (SEMI) or dropped (ANTI) as many times as its key occurs on the right. That is the cost profile of the old set-operation step, inside the join, with the join's parallel build, runtime filters, statistics and memory accounting. Thehashandparallel_hashalgorithms execute the multiset join, without spilling, and the optimizer does not swap its sides; the set-operation step stays for the other algorithms, forDynamiccolumns and for duplicate column names. Existing settingoptimize_rewrite_intersect_except_to_joinnow covers theALLmodes too.The rewrite lives in the plan and not in the query tree because SQL has no syntax for the multiset join: a query tree join node would be shipped to remote shards as a plain
SEMI JOINand lose the duplicates, while the union node keeps its meaning. TheJoinplan step gets serialization version 1 with the multiset flag.Benchmarks on 30M rows per side, 16 threads, best of 5, the multiset join vs the set-operation step (single-threaded, as on master), in seconds:
INTERSECT ALL, UInt64EXCEPT ALL, UInt64INTERSECT ALL, two UInt64 columnsINTERSECT ALL, five columnsEXCEPT ALL, StringINTERSECT ALL, LowCardinality(String)INTERSECT ALL, Nullable(UInt64)INTERSECT ALL, 60M rows against 3MINTERSECT ALL, UInt64, 1 threadPeak memory is lower than the step's in every case (1.04 vs 1.49 GiB for the first row). Nullable keys pay for the null-safe comparison, which wraps them into a tuple; a separate change plans them as fixed-width keys. The hash-partitioned set-operation step this PR carried before was at 0.47s, 0.53s and 0.29s for the first, third and eighth rows. Inputs of a thousand rows pay a few milliseconds of join setup.
Behaviour changes of the
ALLmodes as a join, the same as #118230 lists for theDISTINCTmodes: a filter over the result may be propagated to both arms, so it also runs on rows of the right arm;extremesare those of the result rather than the union of the arms' extremes; the output order of a set operation without an outerORDER BYfollows the join; the join limits (max_rows_in_join,max_bytes_in_join) apply. Tests that pin the set-operation step setoptimize_rewrite_intersect_except_to_join = 0.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
INTERSECT ALLandEXCEPT ALLare executed as a multiset semi or anti hash join, in parallel, instead of the single-threaded set-operation step (settingoptimize_rewrite_intersect_except_to_join).🤖 Generated with Claude Code
https://claude.ai/code/session_01FYLDTxBFLMUr7L6wVCnjLi
Workflow [PR]
Sync PR [sync-upstream/pr/120479]