Skip to content

Fix exception in join order optimizer with overlapping column names (parallel replicas) - #106418

Merged
vdimir merged 2 commits into
masterfrom
fix-join-reorder-overlapping-names-parallel-replicas
Jun 4, 2026
Merged

vdimir merged 2 commits into
masterfrom
fix-join-reorder-overlapping-names-parallel-replicas

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jun 4, 2026 •

Copy link
Copy Markdown
Member

Related: #89166

The join order optimizer reconstructs join steps using JoinExpressionActions, which requires column names to be unique across the two sides of every reconstructed join. When two relations in the join graph share a column name, reordering can place them on opposite sides of a reconstructed join and raise a LOGICAL_ERROR (Left and right columns have same names).

This happens when the join is executed with parallel replicas: the query is re-analyzed for the shard and table identifiers can be reused, so two relations end up with the same __table1-prefixed column names. It was seen on master in the Stress test (arm_release) on the query SELECT * FROM t2 AS x INNER JOIN t1 AS y ON x.a = y.a from 02151_hash_table_sizes_stats_joins.sh, and is also reproduced deterministically by an empty-left INNER JOIN under parallel replicas (see the linked issue).

A previous fix only compared the two immediate children of the join. This generalizes the check to the whole flattened relation set the optimizer would build (mirroring buildQueryGraph), so it also covers overlaps that only become visible after flattening a multi-way join. As before, when an overlap is detected the reordering is skipped and the unoptimized join — which handles overlapping names correctly — is used. The check is read-only and runs before the (destructive) buildQueryGraph; for queries without overlaps (the normal case) it is a no-op, so valid reordering is unaffected.

Note: this extends the existing skip-on-overlap mitigation rather than removing the underlying limitation of the name-based reconstruction; a deeper fix is discussed in the linked issue.

CI report with the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=3fca01d3c822b27f51779bda78ba8afac8ffc460&name_0=MasterCI&name_1=Stress%20test%20%28arm_release%29

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 a logical error (Left and right columns have same names) in the join order optimizer that could occur for joins executed with parallel replicas when two relations in the join graph share column names.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.6.1.382

…ross the whole join graph

The join order optimizer reconstructs join steps using `JoinExpressionActions`,
which requires column names to be unique across the two sides of every
reconstructed join. When two relations in the join graph share a column name,
reordering can place them on opposite sides of a reconstructed join and raise a
`LOGICAL_ERROR` ("Left and right columns have same names").

This can happen when the join is executed with parallel replicas: the query is
re-analyzed for the shard and table identifiers can be reused, so two relations
may end up with the same `__table1`-prefixed column names. It can also happen
when scalar subquery results collide with join table aliases.

A previous fix only compared the two immediate children of the join. This
generalizes the check to the whole flattened relation set the optimizer would
build (mirroring `buildQueryGraph`), so it also covers overlaps that only appear
after flattening a multi-way join. As before, when an overlap is detected the
reordering is skipped and the unoptimized join, which handles overlapping names
correctly, is used.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=3fca01d3c822b27f51779bda78ba8afac8ffc460&name_0=MasterCI&name_1=Stress%20test%20%28arm_release%29

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2c117e5]

Summary: ✅


AI Review

Summary

The PR avoids a LOGICAL_ERROR in join-order reconstruction by skipping reorder when the flattened join graph contains overlapping relation column names. The code change follows the existing buildQueryGraph flattening rules closely, but the added regression test can pass without exercising the changed optimizer path.

Findings

⚠️ Majors

  • [tests/queries/0_stateless/04303_join_reorder_overlapping_names_parallel_replicas.sql:26] The regression test only pins query_plan_optimize_join_order_algorithm; if stateless random settings inject query_plan_optimize_join_order_limit = 0, optimizeJoinLogicalImpl returns before joinGraphHasOverlappingColumnNames, so the query passes because join reordering is disabled. Suggested fix: also pin query_plan_optimize_join_order_limit = 10 next to the algorithm setting.
Missing context / blind spots
  • ⚠️ I did not run the stateless test locally because this checkout does not contain a build* directory. The Praktika CI report fetched from the PR bot comment showed no failed checks.
Final Verdict

Status: ⚠️ Request changes

Minimum required action: make the regression test force the join-order optimizer path by setting query_plan_optimize_join_order_limit = 10.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 4, 2026
Replace the seed-based scenario test with the exact reproducer from the issue:
an empty-left `INNER JOIN` executed with parallel replicas deterministically
raised the `LOGICAL_ERROR` ("Left and right columns have same names:
[__table1.id], [__table1.id]") before the fix.

#89166

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@alexey-milovidov alexey-milovidov changed the title Fix exception in join order optimizer for overlapping column names across the whole join graph Fix exception in join order optimizer with overlapping column names (parallel replicas) Jun 4, 2026
@alexey-milovidov
alexey-milovidov requested a review from vdimir June 4, 2026 07:14
SET max_parallel_replicas = 3;
SET cluster_for_parallel_replicas = 'parallel_replicas';
SET parallel_replicas_for_non_replicated_merge_tree = 1;
SET query_plan_optimize_join_order_algorithm = 'greedy';

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.

This regression test can pass without exercising the fixed path if the stateless runner injects query_plan_optimize_join_order_limit = 0: optimizeJoinLogicalImpl returns before joinGraphHasOverlappingColumnNames, so the query succeeds because join reordering is disabled. Please pin query_plan_optimize_join_order_limit = 10 here as well, so CI actually drives the join-order optimizer path changed by this PR.

@clickhouse-gh

clickhouse-gh Bot commented Jun 4, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.40% 84.50% +0.10%
Functions 92.40% 92.40% +0.00%
Branches 77.00% 77.10% +0.10%

Changed lines: Changed C/C++ lines covered by tests: 48/51 (94.12%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 1 line(s) · Uncovered code

Full report · Diff report

@vdimir vdimir self-assigned this Jun 4, 2026

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

Looks a bit ad-hoc, but since we already have a similar check for scalar subqueries and the fix is isolated, we can go with it. I'm not entirely sure why duplicate columns occur for parallel replicas, but maybe we can investigate further once this fix is merged.

@vdimir
vdimir added this pull request to the merge queue Jun 4, 2026
Merged via the queue into master with commit 085fdc8 Jun 4, 2026
166 checks passed
@vdimir
vdimir deleted the fix-join-reorder-overlapping-names-parallel-replicas branch June 4, 2026 11:46
@clickgapai

Copy link
Copy Markdown
Contributor

Hi — could this be a backport candidate for 26.5, 26.4, 26.3 (LTS)? No backport label was found, and the affected code appears to exist in those branches based on a file/function presence check.

Affected code: optimizeJoinLogicalImpl / joinGraphHasOverlappingColumnNames in src/Processors/QueryPlan/Optimizations/optimizeJoin.cpp — introduced in 25.12.

Why this might apply: The join-order reorder optimizer became default-on when query_plan_optimize_join_order_limit default flipped from 1 to 10 in 25.12 (SettingsChangesHistory.cpp:281) and the greedy algorithm setting was added in 25.12 (line 307). Supported branches 26.3/26.4/26.5 are all post-25.12 and therefore can hit the LOGICAL_ERROR on valid SQL under parallel replicas. 25.8 predates the 25.9 introduction of the setting (line 398) and ships it default-off, so it is excluded.

Other supported branches (25.8) predate 25.12 and do not contain this code.

Caveat: I verified that the modified code exists in those branches, but not whether the bug is actually reachable there — a new caller in master may be what makes this newly observable. If older branches can't reach the affected path, please ignore this; otherwise consider pr-must-backport or a version label like v26.5-must-backport.

@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 4, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jun 10, 2026
STID 4752-593c: a debug-build LOGICAL_ERROR "Input nodes size mismatch in
dag" raised by the JoinExpressionActions constructor while the join order
optimizer reconstructs a join. It fired when a relation's output header carried
duplicate column names within one side (for example a subquery projecting the
same alias twice, kept distinct by QUALIFY: SELECT 1 AS x, 2 AS y, x, y QUALIFY
7). foldActionsByProjection deduplicates INPUT nodes by name, so the folded
DAG's input count no longer matched left_header.columns() + right_header.columns().

This is already fixed on master: PR ClickHouse#106418 (commit 2ddbf35) generalized the
pre-reorder overlap guard into joinGraphHasOverlappingColumnNames, which feeds the
output headers of every relation in the flattened join graph through a single
shared name set and skips reordering on any duplicate, whether within one side or
across sides. That subsumes the within-side case here, so no source change is
needed. PR ClickHouse#106418's own test covers only the cross-side parallel-replicas
manifestation; this adds coverage for the within-side QUALIFY/duplicate-projection
manifestation. All queries verified passing on master HEAD.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jun 10, 2026
STID 4752-593c: a debug-build LOGICAL_ERROR "Input nodes size mismatch in
dag" raised by the JoinExpressionActions constructor while the join order
optimizer reconstructs a join. It fired when a relation's output header carried
duplicate column names within one side (for example a subquery projecting the
same alias twice, kept distinct by QUALIFY: SELECT 1 AS x, 2 AS y, x, y QUALIFY
7). foldActionsByProjection deduplicates INPUT nodes by name, so the folded
DAG's input count no longer matched left_header.columns() + right_header.columns().

This is already fixed on master: PR ClickHouse#106418 (commit 2ddbf35) generalized the
pre-reorder overlap guard into joinGraphHasOverlappingColumnNames, which feeds the
output headers of every relation in the flattened join graph through a single
shared name set and skips reordering on any duplicate, whether within one side or
across sides. That subsumes the within-side case here, so no source change is
needed. PR ClickHouse#106418's own test covers only the cross-side parallel-replicas
manifestation; this adds coverage for the within-side QUALIFY/duplicate-projection
manifestation. All queries verified passing on master HEAD.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jun 10, 2026
STID 4752-593c: a debug-build LOGICAL_ERROR "Input nodes size mismatch in
dag" raised by the JoinExpressionActions constructor while the join order
optimizer reconstructs a join. It fired when a relation's output header carried
duplicate column names within one side (for example a subquery projecting the
same alias twice, kept distinct by QUALIFY: SELECT 1 AS x, 2 AS y, x, y QUALIFY
7). foldActionsByProjection deduplicates INPUT nodes by name, so the folded
DAG's input count no longer matched left_header.columns() + right_header.columns().

This is already fixed on master: PR ClickHouse#106418 (commit 2ddbf35) generalized the
pre-reorder overlap guard into joinGraphHasOverlappingColumnNames, which feeds the
output headers of every relation in the flattened join graph through a single
shared name set and skips reordering on any duplicate, whether within one side or
across sides. That subsumes the within-side case here, so no source change is
needed. PR ClickHouse#106418's own test covers only the cross-side parallel-replicas
manifestation; this adds coverage for the within-side QUALIFY/duplicate-projection
manifestation. All queries verified passing on master HEAD.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jun 10, 2026
STID 4752-593c: a debug-build LOGICAL_ERROR "Input nodes size mismatch in
dag" raised by the JoinExpressionActions constructor while the join order
optimizer reconstructs a join. It fired when a relation's output header carried
duplicate column names within one side (for example a subquery projecting the
same alias twice, kept distinct by QUALIFY: SELECT 1 AS x, 2 AS y, x, y QUALIFY
7). foldActionsByProjection deduplicates INPUT nodes by name, so the folded
DAG's input count no longer matched left_header.columns() + right_header.columns().

This is already fixed on master: PR ClickHouse#106418 (commit 2ddbf35) generalized the
pre-reorder overlap guard into joinGraphHasOverlappingColumnNames, which feeds the
output headers of every relation in the flattened join graph through a single
shared name set and skips reordering on any duplicate, whether within one side or
across sides. That subsumes the within-side case here, so no source change is
needed. PR ClickHouse#106418's own test covers only the cross-side parallel-replicas
manifestation; this adds coverage for the within-side QUALIFY/duplicate-projection
manifestation. All queries verified passing on master HEAD.

The greedy multi-join query pins query_plan_optimize_join_order_algorithm=greedy
and query_plan_optimize_join_order_limit=16 so randomized stateless runs always
exercise the greedy chooseJoinOrder path; a randomized limit of 0 or a dpsize-first
algorithm list would otherwise skip it and stop covering the intended path.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

4 participants