Skip to content

Rewrite INTERSECT DISTINCT and EXCEPT DISTINCT to JOIN - #129089

Open
m-selmi wants to merge 16 commits into
masterfrom
intersect-except-distinct-as-join
Open

m-selmi wants to merge 16 commits into
masterfrom
intersect-except-distinct-as-join

Conversation

@m-selmi

@m-selmi m-selmi commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

First part of: #115106
Related: #118230
Related: #114550

This change builds on some of the ideas in #118230, thanks to @raimannma.

Execute INTERSECT DISTINCT and EXCEPT DISTINCT as a hash join on all columns instead of the single-threaded IntersectOrExcept step.

  • The columns are compared with <=>, so NULL matches NULL as in the set operation.
  • INTERSECT DISTINCT runs as INNER ANY, which emits each key once. The output columns are always taken form the probe side to keep the hash table a set without RowRefs.
  • EXCEPT DISTINCT runs as LEFT ANTI followed by DISTINCT, or as RIGHT ANTI when the join order optimizer builds the left side.
  • The RIGHT ANTI hash table keeps one row per key, so it emits each key once as well.
  • Where the join already emits each key once, the DISTINCT step skips deduplication and only enforces max_rows_in_distinct. max_bytes_in_distinct is deliberately not enforced, because no DISTINCT set is built whose memory it could limit.
  • Set-operation joins are excluded from join flattening, semi/anti reordering, the join-to-IN conversion, parallel replicas and seal-gated reading, and in distributed plans from the broadcast join and the aggregation push-down. A distributed plan otherwise runs them as a shuffle join.
  • The join does not pass on totals, so a set operation whose arms can produce totals (WITH TOTALS, a remote query with totals or a Merge table) stays on the IntersectOrExcept step.
  • As in the set-operation step, the join reads one block of the left side before it starts the build, so an empty left side never reads the right side.
  • Spilling is allowed so large set operations can now use it.
  • With extremes = 1, the extremes of INTERSECT DISTINCT and EXCEPT DISTINCT are now computed on the result, instead of combining the extremes of the arms.
  • The rows no longer come in the order of the first arm, since the join probes with several streams and RIGHT ANTI emits its rows from the hash table. A query that relied on that order needs ORDER BY, as in 02004_intersect_except_distinct_operators.

Enforced join settings: a set-operation join ignores the join settings of the query, because they would change its result.

  • join_algorithm is always hash.
  • max_rows_in_join and max_bytes_in_join are ignored, as they would truncate the result.
  • allow_dynamic_type_in_join_keys is enabled, so Dynamic values match as in the set operation.

Because INTERSECT and EXCEPT now run as joins, they share the same limitations of ordinary joins:

  • Spilling: with a very small spill threshold, a spilling hash join can exceed the memory limit.
  • Filter push-down: a WHERE condition over the result can be pushed into both arms. An expression that throws for some rows, can then be evaluated on rows it never saw before.
  • Join order algorithms: with query_plan_optimize_join_order_algorithm set to only dphyp or dpsize, EXCEPT fails with Failed to find a valid join order, because it becomes an anti join and these algorithms handle only inner joins.

Changes to the join code that affect other joins:

  • Ordinary INNER ANY joins that select no right column and have no OR in ON now also use the key-only hash table of enable_join_key_only_hash_tables, as LEFT SEMI and LEFT ANTI already did.
  • A key-only hash table keeps a right block for a possible switch to another algorithm (SpillingHashJoin, GraceHashJoin or JoinSwitcher) only when the block added a key, as the ANY hash table already does. Before, it kept every block, so a right side with many duplicates kept all of its rows in memory.

Performance, the new performance test intersect_except_distinct:

On AMD EPYC 9R14 (32 vCPUs) and 64 GiB of RAM

Query Time before Time after Speedup Peak memory before Peak memory after
Unique rows, INTERSECT DISTINCT 4.06 s 0.25 s 16.3× 1.74 GiB 1.55 GiB
Unique rows, EXCEPT DISTINCT 4.30 s 0.25 s 16.9× 1.74 GiB 1.74 GiB
50M rows INTERSECT DISTINCT 5M rows 1.68 s 0.08 s 20.5× 277 MiB 272 MiB
5M rows INTERSECT DISTINCT 50M rows 2.46 s 0.25 s 9.9× 1.50 GiB 1.52 GiB
50M rows EXCEPT DISTINCT 5M rows 3.07 s 0.28 s 11.1× 1.61 GiB 2.75 GiB
5M rows EXCEPT DISTINCT 50M rows 2.40 s 0.12 s 19.3× 1.50 GiB 1.40 GiB
Many duplicates, INTERSECT DISTINCT 0.52 s 0.05 s 9.8× 27 MiB 163 MiB
Many duplicates, EXCEPT DISTINCT 0.50 s 0.07 s 7.7× 26 MiB 159 MiB
Two columns, INTERSECT DISTINCT 7.28 s 0.31 s 23.3× 3.00 GiB 2.61 GiB
Two columns, EXCEPT DISTINCT 9.26 s 0.63 s 14.6× 4.99 GiB 7.12 GiB
Strings, EXCEPT DISTINCT 11.93 s 0.50 s 23.9× 5.82 GiB 4.24 GiB
Rows with NULLs, INTERSECT DISTINCT 6.03 s 0.26 s 23.6× 62 MiB 288 MiB

Peak memory is about the same or lower for seven of the twelve queries. The join uses more for the other five: 1.4 and 1.7 times more for two of the EXCEPT queries, and 4.6 to 6 times more for the queries with many duplicates.

The extra memory is mostly needed by the join to keep the rows needed allow spilling. max_bytes_ratio_before_external_join = 0.5 makes it spill to disk when it reaches half of the memory limit. The old step cannot spill.

TPC-DS, scale 100 (intersect_default_mode and except_default_mode set to DISTINCT):

On AMD EPYC 9R14 (32 vCPUs) and 64 GiB of RAM.

Query Before After Speedup
query_08 298 ms 287 ms 1.0×
query_14a 11111 ms 3750 ms 3.0×
query_14b 7910 ms 2953 ms 2.7×
query_38 3435 ms 2119 ms 1.6×
query_87 3929 ms 2252 ms 1.7×

Changelog category (leave one):

  • Performance Improvement

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

INTERSECT DISTINCT and EXCEPT DISTINCT are now executed as a hash join, which makes them 8 to 24 times faster on synthetic benchmarks. TPC-DS queries that use these operations are up to 3 times faster. The previous execution can be restored with the setting rewrite_intersect_except_distinct_to_join = 0.


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

@m-selmi m-selmi added the can be tested Allows running workflows for external contributors label Nov 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4bd2e1c]

Summary: ❌

job_name test_name status info comment
Performance Comparison (arm_release, master_head, 3/8) FAIL Performance dashboard
tpcds #37 FAIL dashboard
range_hashed_dictionary #0 unstable query history

AI Review

Summary

PR #129089 executes INTERSECT DISTINCT and EXCEPT DISTINCT through hash joins, adds key-only INNER ANY execution, and avoids retaining redundant build blocks. No actionable blockers or majors remain at 4bd2e1ce39818906e38a78f885d4808d432846d5. The earlier serialization finding is addressed; the documented memory and evaluation-order tradeoffs do not warrant reopening the dismissed threads.

Missing context / blind spots
  • ⚠️ Full CI is still running. The head's Fast test passed 15,252 tests, with 4,534 skipped. Local differential checks using that build matched results across rewrite settings, swapped inputs, parallel layouts, nested operations, materialized CTEs, complex types, and plan serialization; they do not replace the pending server and distributed integration checks.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Nov 3, 2026
Comment thread src/Planner/Planner.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 4bd2e1ce3 with master 8b903d107 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes ⚠️

81 object files changed (+2.55 MiB total), 3 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/RightHashJoinAntiMapsOne.cpp.o new 1.27 MiB +1.27 MiB
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/InnerHashJoinAnyMapsSet.cpp.o new 1.13 MiB +1.13 MiB
src/CMakeFiles/dbms.dir/Planner/Planner.cpp.o 397.54 KiB 444.15 KiB +46.61 KiB (+11.73%)
src/CMakeFiles/dbms.dir/Storages/StorageJoin.cpp.o 1.93 MiB 1.97 MiB +35.49 KiB (+1.79%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

1854 translation units recompiled, 9134 s compile time in total, 1851 of them have a recent master baseline.

Translation units without a recent master baseline:

  • src/Interpreters/HashJoin/RightHashJoinAntiMapsOne.cpp: 7.7 s
  • src/Interpreters/HashJoin/InnerHashJoinAnyMapsSet.cpp: 7.7 s
Symbol sizes
Binary Symbol Master PR Δ
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)0, (DB::JoinStrictness)2, DB::HashJoin::MapsTemplat… new 136.95 KiB +136.95 KiB
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)2, (DB::JoinStrictness)6, DB::HashJoin::MapsTemplat… new 131.44 KiB +131.44 KiB

Job report

@clickhouse-gh clickhouse-gh Bot added comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... and removed comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Nov 4, 2026
@m-selmi
m-selmi force-pushed the intersect-except-distinct-as-join branch 2 times, most recently from 3e13652 to 49b6645 Compare November 4, 2026 23:29
@m-selmi
m-selmi force-pushed the intersect-except-distinct-as-join branch 2 times, most recently from a05cd3a to b96db76 Compare November 5, 2026 14:54
@m-selmi
m-selmi added this pull request to stack #129531 November 5, 2026 16:02
@m-selmi
m-selmi force-pushed the intersect-except-distinct-as-join branch from b96db76 to 3723a66 Compare November 5, 2026 16:42
Comment thread src/Processors/QueryPlan/DistinctStep.h Resolved
@m-selmi
m-selmi force-pushed the intersect-except-distinct-as-join branch from 4226096 to d75649d Compare November 16, 2026 16:39

@clickhouse-gh clickhouse-gh Bot left a comment

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.

AI review approves this commit, see the AI Review comment.

@harikrishnan94 harikrishnan94 self-assigned this Nov 17, 2026

@harikrishnan94 harikrishnan94 left a comment

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.

Description and changelog:

  1. "4 to 13 times faster" is the 50M-row synthetic test. TPC-DS SF100 in the description is 1.0x to 3.0x. pls say which is which.
  2. pls add peak memory next to the times: 23 -> 399 MiB, 25 -> 402 MiB, 16 -> 852 MiB on the 3 duplicate-heavy queries of the perf test (amd). And say why this is a fair trade-off: the join spills by default, so its memory stays bounded. The old step can't spill: it keeps the hash set of the second arm in memory, and a large one runs out of memory.
  3. not mentioned: result order no longer follows the first arm (02004 needed ORDER BY), and ordinary INNER ANY joins that select no right column now run on the key-only table. The text of enable_join_key_only_hash_tables still lists only LEFT ANTI and LEFT SEMI.
  4. "excluded from ... distributed execution": only parallel replicas and the broadcast join are excluded, 05443 runs with make_distributed_plan = 1.

Comment thread src/Interpreters/HashJoin/HashJoin.cpp Resolved
Comment thread src/Processors/QueryPlan/JoinStep.cpp Resolved
@stresshouse

stresshouse Bot commented Nov 20, 2026

Copy link
Copy Markdown

📊 Cloud Performance Report

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

no significant changes detected. K_source=4 K_base=20 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 0621f4de-3eaa-4b00-97b6-3f3727d0a20d
  • MIRAI run: 6f7a965d-a285-4ed2-a878-069d4e4d105d
  • PR check IDs:
    • clickbench_532419_1795204617
    • clickbench_532426_1795204617
    • tpch_adapted_1_official_532432_1795204617
    • tpch_adapted_1_official_532447_1795204617

# Conflicts:
#	src/Processors/QueryPlan/JoinStepLogical.cpp
#	src/Processors/QueryPlan/Optimizations/Cascades/Rules/HashJoinImplementation.cpp
@m-selmi

m-selmi commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor Author

Regarding the regression in the CI for TPC-DS q37. The query runs in about 66 ms with existing IntersectOrExcept and 77 ms with join rewrite on ARM.

The query runs a SELECT DISTINCT on each arm before the set-operation join, which at sf1 results in many small chunks. At 16 threads that is about 200 chunks of 150 rows.
Measured locally, the hash join build pays a fixed cost of about 13 µs per chunk, against 4 µs in the old IntersectOrExcept step. At this size the build gets the serial layout, so it runs on one thread at the end of each arm.

It only shows up when the inputs are tiny (see TPC-DS sf100 numbers above), and it costs a few milliseconds in absolute terms, so I think it's safe to accept.

@harikrishnan94

Copy link
Copy Markdown
Contributor

@m-selmi

The query runs in about 66 ms with existing IntersectOrExcept and 77 ms with join rewrite on ARM.

Agreed. That's fine.

In general I'd accept every regression that comes out of the JOIN step or the planner's decisions, we're working on both anyway. Anything that can be expressed as a JOIN should be, regardless of regressions. When JOINs get faster, all of these queries get faster for free. We could also special-case the join planner to bring cases like this one back to parity, but that's ugly. The join planner's decisions should stay generic.

The 13 µs vs 4 µs per-chunk build cost is worth a separate look though. Lots of small blocks going into the build is a general join problem, not something specific to this PR.

@m-selmi

m-selmi commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor Author

@m-selmi

The query runs in about 66 ms with existing IntersectOrExcept and 77 ms with join rewrite on ARM.

Agreed. That's fine.

In general I'd accept every regression that comes out of the JOIN step or the planner's decisions, we're working on both anyway. Anything that can be expressed as a JOIN should be, regardless of regressions. When JOINs get faster, all of these queries get faster for free. We could also special-case the join planner to bring cases like this one back to parity, but that's ugly. The join planner's decisions should stay generic.

The 13 µs vs 4 µs per-chunk build cost is worth a separate look though. Lots of small blocks going into the build is a general join problem, not something specific to this PR.

yes, I agree as long as the regression does not affect larger data sizes in a meaningful way like in this case.

Regarding the per chunk overhead on build size, one thing is that in parallel layout we squash chunks to get a minimum size, so this overhead is only apparent on serial layout. I will try to look into it the overhead better, but separately from this change.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants