Skip to content

Fix distributed RIGHT JOIN - #118611

Merged
alexey-milovidov merged 8 commits into
ClickHouse:masterfrom
ianton-ru:fix/distributed-global-right-join
Sep 12, 2026
Merged

alexey-milovidov merged 8 commits into
ClickHouse:masterfrom
ianton-ru:fix/distributed-global-right-join

Conversation

@ianton-ru

@ianton-ru ianton-ru commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Fix distributed RIGHT JOIN.
Closes #95728

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fix distributed RIGHT JOIN.

Broadcast the original left table and keep the preserved right side sharded, so unmatched right rows are not duplicated on every shard.


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

Version info

  • Merged into: 26.9.1.1232 (included in 26.9 and later)

Broadcast the original left table and keep the preserved right side sharded, so unmatched right rows are not duplicated on every shard.

Related: ClickHouse#95728
Related: Altinity#1664
Co-authored-by: Cursor <[email protected]>
@ianton-ru
ianton-ru marked this pull request as ready for review September 7, 2026 16:06
@alexey-milovidov alexey-milovidov self-assigned this Sep 7, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Sep 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6b52e28]

Summary: ✅


AI Review

Summary

This PR fixes distributed RIGHT JOIN planning on the analyzer path by either swapping eligible joins into LEFT JOIN or forcing the remaining right-preserving cases back to the initiator, and it adds focused regressions for USING/NATURAL, nested joins, right-side topologies, and wrapper storages. The analyzer-side repair looks coherent, but the legacy interpreter path still appears to return wrong results for the same query shape, so this is not ready to merge yet.

Findings

❌ Blockers

  • tests/queries/0_stateless/05137_distributed_global_right_join.sql:3 The new regressions only cover enable_analyzer = 1, but the actual bug fix is analyzer-only too. With enable_analyzer = 0, StorageDistributed::read still goes through the legacy AST path (src/Storages/StorageDistributed.cpp:1049-1055), where InJoinSubqueriesPreprocessor globalizes RIGHT JOIN normally (src/Interpreters/InJoinSubqueriesPreprocessor.cpp:98-116) and GlobalSubqueriesVisitor always materializes the syntactic right table expression (src/Interpreters/GlobalSubqueriesVisitor.cpp:216-261). That means a sharded left Distributed table still executes GLOBAL RIGHT JOIN with the preserved right side broadcast to every shard, so unmatched right rows remain duplicated under a supported setting.
    Suggested fix: apply the same right-side swap / initiator-fallback logic to the old interpreter path, or explicitly scope the bug fix to enable_analyzer = 1 and prevent the legacy path from advertising the unsupported behavior.
Final Verdict

❌ Changes requested. The analyzer planner is fixed, but the old interpreter still appears to preserve the original wrong-result behavior for distributed GLOBAL RIGHT JOIN.

LLVM Coverage Report

Measured on commit 6b52e28.

Metric Baseline Current Δ
Lines 88.90% 88.90% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.30% 81.30% +0.00%

Changed lines: Changed C/C++ lines covered: 82/87 (94.25%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 7, 2026
Comment thread src/Planner/PlannerJoinTree.cpp Resolved
Comment thread src/Planner/PlannerJoinTree.cpp Resolved
Comment thread src/Planner/PlannerJoinTree.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... label Sep 7, 2026
ianton-ru and others added 2 commits September 8, 2026 09:32
The rewrite that swaps the sides of a `GLOBAL RIGHT JOIN` between two
`Distributed` tables only accepted an `ON` condition, so a join written with
`USING` or `NATURAL` kept duplicating its unmatched rows once per shard.

A `USING` key records its sides positionally, the left one first. The join
condition, the `USING (a AS b)` clause shipped to the shards and the key
supertype all read that order, so the sides are swapped together with the table
expressions. A key that does not hold a plain column per side is not swappable
that way and the query is left alone. `NATURAL` needs no separate handling
because the analyzer turns it into `USING` before the planner sees it.

Related: ClickHouse#118611
Co-authored-by: Cursor <[email protected]>
The rewrite that swaps the sides of a `GLOBAL RIGHT JOIN` required both sides to
be `Distributed` tables with at least two shards, so it covered one shape out of
seven. Only the left table fans the query out across shards, and that fanout is
what makes every shard emit the rows of the preserved side again, so the right
side has no bearing on it. With a sharded table on the left the rows were
duplicated for a plain `MergeTree`, a single-shard `Distributed` table, a `Merge`
table, a subquery, `numbers` and `remote` on the right alike.

Gate the rewrite on the left table alone. Once the preserved side moves out of
the broadcast position it keeps running on the shards if it is a sharded
`Distributed` table of its own, and runs on the initiator otherwise, which is
slower but is the only way to emit those rows once.

`ANY`, `SEMI` and `ANTI` mirror into their `LEFT` counterparts exactly as `ALL`
does, so they are rewritten too. `ASOF` stays excluded because swapping the sides
reverses the direction of its inequality, and `RightAny` because the strictness
itself names the side to take a row from.

`FULL JOIN` duplicates the same way but is symmetric, so swapping cannot repair
it. That is left alone.

Related: ClickHouse#118611
Co-authored-by: Cursor <[email protected]>
Comment thread src/Planner/PlannerJoinTree.cpp Resolved
ianton-ru and others added 2 commits September 8, 2026 10:32
The rewrite only ever looked at the root of the join tree. Join trees are left
deep, so in `a GLOBAL RIGHT JOIN b INNER JOIN c` the root is the `INNER` join and
the `RIGHT` join sits one level below it, where the rewrite never saw it and the
rows preserved by the `RIGHT` join were emitted once per shard.

Walk down to the deepest join before applying the existing checks. That join
reads the leftmost table, and it is the only one whose sides can be swapped
without moving a join into the right table expression, which is a tree shape no
query can produce and the planner therefore never sees.

The remaining shapes are the ones where the join that preserves broadcast rows
has another join on its left, such as `a INNER JOIN c GLOBAL RIGHT JOIN b`, and
`FULL JOIN`, which is symmetric and cannot be repaired by swapping at all. Read
the leftmost table through a subquery for those, so the join runs on the
initiator, where the preserved rows are emitted once. That costs the distributed
execution of the join and makes shard specific values such as `shardNum` stop
varying, so it is done only for the join trees that are wrong without it. A join
tree the swap has already fixed keeps running on the shards.

Related: ClickHouse#118611
Co-authored-by: Cursor <[email protected]>
`test_cluster_one_shard_localhost` is not defined in the test configuration,
so the two `Distributed` tables the test creates over it could not be read.
`test_shard_localhost` is the single shard cluster of the test configuration
and produces the same rows, so the reference is unchanged.

Co-authored-by: Cursor <[email protected]>
ianton-ru added a commit to Altinity/ClickHouse that referenced this pull request Sep 8, 2026
Port of the review fixes made for the `master` pull request
ClickHouse#118611

`tryRewriteGlobalRightJoinAsLeftJoin` only recognised a narrow shape of the
query it was meant to fix, so a `GLOBAL RIGHT JOIN` whose left table is a
sharded `Distributed` table still emitted the rows preserved from the
broadcast side once per shard in these cases:

* `USING` and `NATURAL` joins were skipped, because only `ON` was accepted.
  A `USING` key stores its sides positionally, so the key pairs are now
  swapped together with the table expressions, and a key that does not hold
  a plain column per side leaves the query alone.

* The rewrite required the right side to be a sharded `Distributed` table
  too. Only the left table fans the query out across shards, so the gate is
  now on the left table alone, and a local table, a one shard `Distributed`
  table, a subquery or a table function on the right is handled as well.
  `Any`, `Semi` and `Anti` join over to the swapped sides the same way `All`
  does and are accepted; `Asof` and `RightAny` do not mirror and stay out.

* Only the topmost join was examined. Join trees are left deep, so the walk
  now descends to the join that reads the leftmost table.

A `RIGHT` or `FULL` join that survives the rewrite, such as the one in
`(A INNER C) RIGHT B`, cannot be swapped without moving a join into the right
table expression. Those now read the leftmost table through a subquery, which
keeps the join on the initiator, the only remaining way to emit the preserved
rows once.

`getDistributedStorageFromTableExpression` also missed `remote` and
`clusterAllReplicas` on the left, because it only looked at `TableNode`.

Co-authored-by: Cursor <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

✅ No significant changes.

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.

Compile time of recompiled translation units

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

Job report

The flaky check ran 50 copies of the combined matrix at once. Successful
runs already took 56-95 s, and two of them exceeded the 180 s limit.

https: //github.com/ClickHouse/ClickHouse/actions/runs/34228156778/job/102106056610?pr=118611
https: //github.com/ClickHouse/pull/118611
Co-authored-by: Cursor <[email protected]>
Comment thread src/Planner/PlannerJoinTree.cpp Resolved
ianton-ru and others added 2 commits September 9, 2026 12:36
`getDistributedStorageFromTableExpression` only recognised a bare
`StorageDistributed`, so an `Alias` (and the same for `MaterializedView`
and `StorageProxy`) of a sharded `Distributed` table still skipped the
`GLOBAL RIGHT JOIN` rewrite and duplicated unmatched rows once per shard.

https: //github.com/ClickHouse/pull/118611
Co-authored-by: Cursor <[email protected]>
`getDistributedStorageFromTableExpression` already unwrapped `Alias`,
`MaterializedView` and `StorageProxy`, but `Buffer` still forwarded the
unrepaired join to its `Distributed` destination and duplicated unmatched
rows once per shard.

https: //github.com/ClickHouse/pull/118611
Co-authored-by: Cursor <[email protected]>
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 12, 2026
Merged via the queue into ClickHouse:master with commit d247a70 Sep 12, 2026
174 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 12, 2026
@clickgapai

clickgapai commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor
Reproducer
-- Stock server; `test_cluster_two_shards_localhost` ships in the default config.
CREATE TABLE l (k1 UInt32) ENGINE = MergeTree ORDER BY k1;
CREATE TABLE r (k2 UInt32) ENGINE = MergeTree ORDER BY k2;
CREATE TABLE ld AS l ENGINE = Distributed('test_cluster_two_shards_localhost', currentDatabase(), l);
CREATE TABLE rd AS r ENGINE = Distributed('test_cluster_two_shards_localhost', currentDatabase(), r);
INSERT INTO l VALUES (1);
INSERT INTO r VALUES (1), (3);

-- Reference: same join forced onto the initiator. Returns 6.
SELECT count() FROM (SELECT * FROM ld) AS l RIGHT JOIN (SELECT * FROM rd) AS r ON l.k1 = r.k2;

-- Returns 8 on 26.8 / 26.7 / 26.6 / 26.3: the 2 unmatched right rows (k2 = 3)
-- are emitted once per shard. Same 8 for `SETTINGS distributed_product_mode='global'`
-- and for `GLOBAL FULL JOIN`.
SELECT count() FROM ld AS l GLOBAL RIGHT JOIN rd AS r ON l.k1 = r.k2;

Results:

  • Reproduces on: 26.8, 26.7, 26.6, 26.3
  • Does not reproduce on: master
  • Tested versions: master, 26.8, 26.7, 26.6, 26.3
  • Also tested (unsupported, context only): 26.2 reproduces
  • ✓ Fix is on master — this PR's change fixes the bug on master. The releases listed above still have the bug and need the backport.

Backport the fix to 26.8, 26.7, 26.6, 26.3.

CC component owner: @vdimir @yariks5s

Analysis metadata

comp-joins · Severity P2 · Finding phase_d_pr118611

  • Verified against master build 3476b12ea2ce (aarch64)
Introducing change: predates `v23.8.16.40` (oldest testable release)
  • v23.8.16.40 is the oldest release with a downloadable binary for this reproducer, and it already reproduces — the introducing change predates it and cannot be identified from release builds.
  • Walked 6 release(s) below the supported window: still reproduces down to 25.8.
  • Secondary components: comp-testing, comp-distributed

pull Bot pushed a commit to AnotherGenZ/ClickHouse that referenced this pull request Sep 28, 2026
The filter was bound to the left `Distributed` table before the join sides were swapped, then followed that table into a `Memory` temporary table which does not support `PREWHERE`. Relocate it into the broadcast subquery when that table owns it, keep it on the initiator wrap otherwise, and preserve it when a remote non-leftmost table is wrapped.

https: //github.com/ClickHouse/issues/119621
https: //github.com/ClickHouse/pull/118611
Co-authored-by: Cursor <[email protected]>
pull Bot pushed a commit to AnotherGenZ/ClickHouse that referenced this pull request Sep 28, 2026
Cover the original no-op `PREWHERE` reproducer and preserve filters when a remote non-leftmost table is wrapped for a join.

https: //github.com/ClickHouse/issues/119621
https: //github.com/ClickHouse/pull/118611
Co-authored-by: Cursor <[email protected]>
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-bugfix Pull request with bugfix, not backported by default 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.

GLOBAL RIGHT OUTER JOIN on Distributed tables duplicates unmatched rows across shards without diagnostics

4 participants