Skip to content

Fix LOGICAL_ERROR in join order optimizer for duplicate column names via merged expression - #110227

Merged
alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-choosejoinorder-duplicate-header-stid-4752-593c
Aug 23, 2026
Merged

alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-choosejoinorder-duplicate-header-stid-4752-593c

Conversation

@groeneai

@groeneai groeneai commented Jul 13, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #114113

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 be triggered by a comma join over a multi-table view when query_plan_merge_expression_into_join is enabled.

Description

Found by the SQLancerPP nightly on master (server abort in the sanitizer build), and reported independently as issue #114113:

The pre-reorder guard joinGraphHasOverlappingColumnNames flattens the join graph to check for duplicate qualified column names and skips reordering when it finds any. It peeled only passthrough expression steps. The optimizer's addChildQueryGraph also peels a non-passthrough expression step and flattens the child join beneath it when query_plan_merge_expression_into_join is enabled. So the guard saw one relation fewer than the optimizer produced and missed a duplicated name (__table3.c1); reconstructing the reordered join with JoinExpressionActions then threw the error.

Fix: make the guard peel expression steps the same way as addChildQueryGraph, so it inspects the same relation set the optimizer builds and correctly skips reordering when names overlap.

Known residual, not addressed here: this guard is a read-only mirror of buildQueryGraph, and it does not replicate the get_exposed_columns side-clash suppression that keeps a join boundary collapsed. That predates this PR (the mirror landed in 2ddbf356499caa5, the clash check a week later in 69f802454c23ee6) and can only cost a reordering, never correctness. I have not found a query where the two disagree, so I have left it for a separate change rather than adding an unexercised check here.


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

Version info

  • Merged into: 26.8.1.1954 (included in 26.8 and later)

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Check Result
a Deterministic repro? Yes. clickhouse-local with the 3-way comma join over the multi-table view aborts every run (exit 134) at JoinExpressionActions.cpp:131 <- chooseJoinOrder (optimizeJoin.cpp:1248), identical to the CI stack and headers (left=[__table2.c0, __table3.c1, __table1.c1, __table1.c0], right=[__table3.c1]). Toggling query_plan_merge_expression_into_join 0/1 flips crash off/on deterministically.
b Root cause explained? Yes. The guard joinGraphHasOverlappingColumnNames peeled only passthrough expression steps, so it collected 3 relations (no overlap). The optimizer's addChildQueryGraph also peels a non-passthrough expression step and flattens the child join beneath it when query_plan_merge_expression_into_join=1, producing 4 relations with __table3.c1 twice. The reordered reconstruction places the two on opposite sides of a rebuilt join -> duplicate cross-side name -> LOGICAL_ERROR. Confirmed via debug logging of both the guard's relation set (3) and buildQueryGraph's inputs (4, duplicate __table3.c1).
c Fix matches root cause? Yes. The guard now peels expression steps exactly as addChildQueryGraph does (passthrough always; non-passthrough when merge_expression_into_join), so it inspects the same relation set the optimizer builds and skips reordering on the real overlap.
d Test intent preserved / new tests added? New regression test 04516_join_reorder_duplicate_names_merge_expression. No existing test weakened.
e Demonstrated both directions? Yes. Fails (abort) on master HEAD; passes with the fix (50/50 runs clean, correct results).
f Fix general, not a narrow patch? Yes. The fix is at the shared guard used for the whole flattened relation set, not a single call site; it covers any comma/inner/left/right join whose flattening exposes a merged-expression relation, not just the one reproduced shape.
g Generalizes across inputs? Yes. The peel mirrors addChildQueryGraph's exact condition (single-child ExpressionStep, no ArrayJoin, passthrough OR merge-flag), so it tracks the optimizer for all such expression shapes; verified a distinct-name comma-join-via-view still reorders (no over-skip).
h Backward compatible? Yes. No setting/format change. SettingsChangesHistory.cpp untouched. Behavior change is limited to correctly skipping an unsafe reorder that previously crashed.
i Invariants/contracts preserved? Yes. Upholds the JoinExpressionActions contract (unique names across the two sides). The guard remains a pure over-approximation of the optimizer's flattening; non-overlapping graphs still reorder.

Session id: cron:clickhouse-worker-slot-0:20260713-080600

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @novikd — could you review this? It fixes a LOGICAL_ERROR ("Left and right columns have same names") in the join order optimizer: the pre-reorder overlap guard joinGraphHasOverlappingColumnNames peeled only passthrough expression steps, while addChildQueryGraph also peels a non-passthrough one and flattens the child join beneath it under query_plan_merge_expression_into_join, so the guard undercounted relations and missed a duplicated qualified name. The guard now peels expression steps the same way the optimizer does.

@clickhouse-gh

clickhouse-gh Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4ce0bc6]

Summary: ✅


AI Review

Summary

This PR fixes the reproduced LOGICAL_ERROR by teaching the duplicate-name pre-check to peel the same non-passthrough ExpressionStep that addChildQueryGraph peels when query_plan_merge_expression_into_join is enabled. I do not see a remaining correctness hole in the crash fix itself, but one previously raised optimization-regression concern is still present in the current code.

Findings

⚠️ Majors

  • [src/Processors/QueryPlan/Optimizations/optimizeJoin.cpp:1557] [dismissed by author -- https://github.com/Fix LOGICAL_ERROR in join order optimizer for duplicate column names via merged expression #110227#discussion_r3748975587] collectJoinGraphRelationHeaders still does not mirror the sibling-clash suppression in buildQueryGraph, and after this patch that gap now applies to non-passthrough view wrappers too. For the same shape as the added regression test, a two-relation query over the projected view and the reused base table would be kept collapsed by buildQueryGraph at 887-922, because exposing the inner join would clash with its sibling, but the helper here still peels and descends at 1539-1558 and joinGraphHasOverlappingColumnNames then counts the hidden inner header at 1581-1589 anyway. That makes the pre-check skip a safe view JOIN table reorder that the real builder can still perform, so the crash fix currently trades one query family for a join-order optimization regression on another. Mirror the get_exposed_columns clash check before recursing so the guard sees the same relation boundaries as buildQueryGraph.
Final Verdict

⚠️ One major concern remains open. I would keep the existing review thread open and fix the missing side-clash suppression before merge.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.00% 87.10% +0.10%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.40% +0.10%

Changed lines: Changed C/C++ lines covered: 29/29 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 10, 2026
if (child_join_step->getJoinSettings() == join_settings && join_steps_limit > 1 && allow_child_join_kind)
{
collectJoinGraphRelationHeadersForJoin(*node, join_steps_limit, join_settings, relation_headers);
collectJoinGraphRelationHeadersForJoin(*effective, join_steps_limit, join_settings, merge_expression_into_join, relation_headers);

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.

collectJoinGraphRelationHeadersForJoin still does not mirror the real buildQueryGraph flattening path here. buildQueryGraph runs the per-join get_exposed_columns / "Column name clash detected between join sides" check before recursing, and if flattening a child join would expose overlapping names across that boundary it keeps that boundary collapsed instead of descending further. After this patch we now peel through non-passthrough ExpressionSteps as well, but the header collector still recurses unconditionally once join_steps_limit > 1, so it can inspect leaf headers that the optimizer would never expose and joinGraphHasOverlappingColumnNames will skip reordering for a plan that buildQueryGraph can still optimize safely. Please mirror the same side-clash suppression in this helper before descending, otherwise the new expression-step peel widens the false-positive surface into a user-visible join-order optimization regression.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed on the mechanism, and it is worth fixing: collectJoinGraphRelationHeadersForJoin has no
equivalent of the get_exposed_columns side-clash check, so it can descend where buildQueryGraph
keeps a boundary collapsed. The direction is a lost reordering, never a wrong result.

I am not adding the check in this PR, for three reasons.

  1. The gap is pre-existing and untouched here. buildQueryGraph, including the clash check and its
    own query_plan_merge_expression_into_join peel inside get_exposed_columns, is byte-identical at
    the merge base (3d31d8f) and at this head. The pre-PR collector already recursed on
    join_steps_limit > 1 with no clash check. The collector landed in 2ddbf356499caa5 (2026-06-04)
    and the clash check in 69f802454c23ee6 (2026-06-11), and the mirror was never updated.

  2. On the peel axis this patch moves the collector toward the optimizer, not away from it.
    get_exposed_columns already peeled non-passthrough expression steps under that setting before this
    PR; the collector did not, and that undercount is what aborts the server. One more boundary class
    does become reachable, so I will not claim the surface is untouched, but at those boundaries the
    collector now observes the relation set the optimizer actually builds.

  3. A loss is not demonstrated, and it is not easy to construct. The clash check compares the exposed
    column sets of the peeled join's two children, which is close to what the collector collects, so
    when the check fires the collector usually finds the same duplicate and bails identically. Losing a
    reordering needs a cross-side clash at the inner boundary while the flattened leaf set has no
    duplicate. Without such a query the requested regression test would pass in both arms and prove
    nothing.

Adding the check without a demonstrated case would be a speculative change, and this PR fixes a
master server abort still recurring on the nightly SQLancer run (latest aa1a69b2, 2026-08-10).
Mirror fidelity deserves its own PR; I have noted it in the description rather than folding it in
here.

One note for whoever picks that up: buildQueryGraph cannot simply be reused as the predicate,
since it is destructive (detachExpressions, mergeInplace(std::move(...)), and
optimizeJoinLogicalImpl on children). That is why a read-only mirror exists, and keeping the two
in sync is the underlying issue.

@clickhouse-gh

clickhouse-gh Bot commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.80% 85.80% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 78.00% 78.00% +0.00%

Changed lines: Changed C/C++ lines covered: 29/29 (100.00%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3a1e171

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_debug sequential; amd_tsan sequential 2/2; amd_msan WasmEdge sequential 2/2; amd_tsan s3 sequential 2/2) / 02346_text_index_bug108519_qcc_skip_index randomized materialize_statistics_on_insert builds a minmax statistic that prunes the row before the skip-index query-condition-cache path runs, so the expected cache reuse never happens. The harness minimized that setting itself, and the test passes 159/159 with randomization disabled fixing PR 110260 (mine, merged 2026-07-13T15:05Z), which pins auto_statistics_types = '' on exactly the table whose assertion fails here. This run was created at 08:51Z the same day, so its tree predates the fix; a rebase picks it up
Stateless tests (amd_asan_ubsan, distributed plan, parallel) / 01730_distributed_group_by_no_merge_order_by_long transient MEMORY_LIMIT_EXCEEDED under the test's own 100Mi cap; 14/14 reruns passed with the same randomized settings. 168 distinct PRs and 18 master hits in 30 days a fix task owns it; fixing-PR link to follow here
Stateless tests (amd_tsan, s3 storage, sequential 2/2) / Scraping system tables infra: the minio_audit_logs dump times out after 600s a fix task owns it; fixing-PR link to follow here

None is caused by this PR: the diff is confined to optimizeJoin.cpp and its own 04516 test.
02346 contains no JOIN, so the join-order optimizer cannot reach it, and the same test failed
the same way on an unrelated PR. I will rebase this branch so the 02346 lines pick up 110260.

Session id: cron:our-pr-ci-monitor:20260810-173000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Correction to the ledger above (same head, 3a1e171)

Two lines in the comment above are wrong, and both fail the same way: I gave them a fix-task owner
when a MERGED fixing PR already exists. Corrected:

Check / test Corrected owner / fixing PR
Stateless tests (amd_asan_ubsan, distributed plan, parallel) / 01730_distributed_group_by_no_merge_order_by_long fixing PR 109847 (@ azat, merged 2026-07-22). Root cause was 107643 deriving the aggregation hash-table stats cache key from the query plan, which over-reserves for table functions such as remote(...) and trips max_memory_usage = 100Mi. Absent from this branch: 109847's own new test 04509_hash_table_sizes_stats_table_functions does not exist in the tested tree, and CIDB shows exactly one 01730 failure anywhere since that merge, this one
Stateless tests (amd_tsan, s3 storage, sequential 2/2) / Scraping system tables fixing PR 110099 (mine, merged 2026-07-20), which drops the MinIO webhook log tables from the stateless CI setup. The minio_audit_logs dump-timeout signature went to zero on master after that merge

So all three failures on this head have the same cause: the branch is from 2026-07-13 and predates
every fix. Rebasing onto master picks up 110260, 109847 and 110099 together, and I will do that
rather than open any new fix task.

Session id: cron:our-pr-ci-monitor:20260810-173000

…via merged expression

The pre-reorder guard joinGraphHasOverlappingColumnNames peeled only passthrough
expression steps when flattening the join graph, while the optimizer's
addChildQueryGraph also peels a non-passthrough expression step and flattens the
child join underneath when query_plan_merge_expression_into_join is enabled. The
guard therefore saw one relation fewer than the optimizer produced and missed a
duplicated qualified column name, so reconstructing the reordered join with
JoinExpressionActions threw 'Left and right columns have same names'.

Make the guard peel expression steps the same way as addChildQueryGraph so it sees
the same relation set the optimizer builds, and skip reordering when column names
overlap.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai
groeneai force-pushed the fix-choosejoinorder-duplicate-header-stid-4752-593c branch from 3a1e171 to 3a78b0a Compare August 10, 2026 19:18
@groeneai

Copy link
Copy Markdown
Collaborator Author

Rebased onto master (2850e469dcac84ba); the branch was about a month behind, and all three
CI failures in the previous run's ledger were staleness rather than defects. They are now
resolved by the rebase itself:

Previously failing Owner
02346_text_index_bug108519_qcc_skip_index (4 flavours) #110260, merged 6h after that run started
01730_distributed_group_by_no_merge_order_by_long #109847, merged 2026-07-22
Scraping system tables (minio audit dump) #110099, merged 2026-07-20

All three merge commits are now ancestors of the head, verified with
git merge-base --is-ancestor.

I re-verified the fix on the rebased tree rather than assuming it survived, since master
touched optimizeJoin.cpp 15 times in that window:

  • Without the change, the abort is still live on today's master: LOGICAL_ERROR: Left and right columns have same names: [__table2.c0, __table3.c1, __table1.c1, __table1.c0], [__table3.c1] at optimizeJoin.cpp:1307 in chooseJoinOrder, 50/50 runs.
  • With the change, 50/50 runs pass. The 40 neighbouring join-order/join-reorder tests pass.
  • buildQueryGraph is byte-identical to the version this guard mirrors, and the peel logic
    in addChildQueryGraph is unchanged, so the mirrored contract still holds.

The only content change since the last review is a shorter comment above the peel in
collectJoinGraphRelationHeaders: it now states the invariant rather than describing the
defect, and the rationale lives in the commit message instead.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3a78b0a

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

None of these is caused by this PR: the diff touches only optimizeJoin.cpp plus its own
stateless test, and each signature below is reproducible on master independently of it.

Check / test Reason Owner / fixing PR
Stress test (amd_tsan) / Logical error: Not-ready Set is passed as the second argument for function 'globalIn' (STID 0250-41a5) trunk logical error, 218 rows / 172 PRs / 13 master-or-release rows in 30 d #102308 (external, open)
Stress test (arm_debug) / Hung check failed, possible deadlock found trunk hang: a cancelled DROP TABLE prometheus parks in waitTableFinallyDropped (760 s, single-threaded) and convoys DROP DATABASE / DETACH DATABASE behind getDDLGuard; fatal.log empty, so a hang and not an abort a fix task is being worked at full effort (fixing-PR link to follow on this PR)
Stress test (arm_asan_ubsan) / Sanitizer (STID 1367-26c6) LeakSanitizer all-indirect retain cycle rooted at Context::createCopy, issue #113954 #113397 (external, open)
Stateless tests (arm_binary, parallel) / 04357_distributed_alias_same_expression wrong results for duplicate-ALIAS GROUP BY on a Distributed table under two-level aggregation, issue #112987; the runner's own diagnosis reports 15/82 reruns failed #108855 (mine, open)
Build (arm_release) / Post Hooks build-profile bookkeeping hook; the Build (arm_release) check itself concluded success not a test failure, no owner needed
Sync - CH Inc sync (private, not actionable by me)

Session id: cron:our-pr-ci-monitor:20260811-013000

@clickhouse-gh

clickhouse-gh Bot commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 4ce0bc691 with master 6ae413899 (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
Binary Master PR Δ
programs/clickhouse-stripped 705.43 MiB 702.41 MiB -3.03 MiB (-0.43%)

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.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — a3733ee

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Fast test (arm_darwin) · AST fuzzer (amd_tsan) · Stress test (amd_debug) · Stress test (amd_msan) · Integration tests (amd_llvm_coverage, 1/8) · Integration tests (amd_msan, 7/8) · Stateless tests (amd_llvm_coverage, 1/3) infra — all 7 died in GitHub's Set up job step before checkout: ##[error]Failed to download archive 'https://codeload.github.com/actions/checkout/tar.gz/d234...' after 3 attempts (429/502/503). No test ran a fix task is created (investigating at full effort — fixing-PR link to follow on this PR)
LLVM Coverage / Generate LLVM Coverage Diff Report Coverage degraded: master 86.80% → PR 86.40% (dropped 0.40 pp) measured against an INCOMPLETE PR profile set — 2 of this head's 22 amd_llvm_coverage jobs (Stateless 1/3, Integration 1/8) never produced a profile #112832 (ours, open)
Upgrade check (amd_release) / Check failed infra — the previous-release resolver returned the stale tag 22.12.3.5, whose clickhouse-common-static then failed dpkg -i: trying to overwrite '/usr/bin/clickhouse-library-bridge', which is also in package clickhouse-library-bridge 25.1.5.31 #112974 (ours, open)

Note: this run was already attempt 2 and the Set up job class reddened again, so it is not self-clearing.
The auto-retry workflow will not rerun it either — it requires every failed job in the run to be infra,
and this run also has 2 genuine failures.

Session id: cron:our-pr-ci-monitor:20260817-183000

@groeneai groeneai added the groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding label Aug 19, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

Re-verified on today's master — this abort is still recurring on the nightly

The SQLancerPP (arm_asan_ubsan) nightly hit the same server abort again on master
0b1c827dc5fcf15419fad75ad38f059f32c68cfa (2026-08-22):

https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=0b1c827dc5fcf15419fad75ad38f059f32c68cfa&name_0=NightlySQLancer&name_1=SQLancerPP

The FUZZING oracle reported Found a potential bug; the server log shows the abort and the
subsequent ABORTED: The server is shutting down due to a fatal error that failed the three other
databases in the run:

<Fatal> : Logical error: 'Left and right columns have same names: [__table3.c0, __table1.c0, __table1.c1], [__table3.c0, __table3.c1]'.
5. src/Interpreters/JoinExpressionActions.cpp:145: DB::JoinExpressionActions::JoinExpressionActions(...)
6. src/Processors/QueryPlan/Optimizations/optimizeJoin.cpp:1361: DB::QueryPlanOptimizations::chooseJoinOrder(...)
7. src/Processors/QueryPlan/Optimizations/optimizeJoin.cpp:1650: DB::QueryPlanOptimizations::optimizeJoinLogicalImpl(...)

The generated case is the same shape this PR fixes — a comma join over a multi-table view:

CREATE TABLE database2_t9 (c0 INT, c1 VARCHAR, PRIMARY KEY(c0));
CREATE TABLE database2_t0 (c0 VARCHAR(500), c1 BOOLEAN, PRIMARY KEY(c0));
CREATE VIEW database2_v0 (c0) AS
    SELECT (NOT CAST((NOT database2_t9.c0) AS BOOLEAN)) FROM database2_t0, database2_t9 HAVING database2_t0.c1;

SELECT * FROM database2_t0, database2_v0, database2_t9 WHERE database2_t0.c1;

Verified locally against master 52ff7f99c16 (arm64, release), building only
optimizeJoin.cpp with and without this PR's change:

Query master with this PR
the SQLancer query above Code: 49 ... [__table3.c0, __table1.c0, __table1.c1], [__table3.c0, __table3.c1] — byte-identical to the nightly 16 rows
reproducer from issue #114113 Code: 49 ... [__table2.c_pk, ...], [__table2.c_pk, ...] 6 rows
this PR's own 04516_join_reorder_duplicate_names_merge_expression.sql Code: 49 ... 8 (matches the reference)

So the two independent reports — the nightly and issue #114113 — are the same defect, and this
change fixes both. I have added Closes: for #114113 and the new nightly link to the description.

The branch is MERGEABLE against master, approved, and the remaining red checks on
a3733ee9735d are the infra failures already itemised in the ledger above.

…4752-593c

Refresh a five-day-old branch and re-run CI: the previous run lost seven jobs
in GitHub's `Set up job` step (codeload 429/502), so they never executed.

`optimizeJoin.cpp` and `JoinExpressionActions.cpp` are byte-identical between
master `6ae413899fc` and the tree the fix was last verified on, and the merged
`optimizeJoin.cpp` is byte-identical to the built and tested file, so the
Cascades work merged meanwhile (ClickHouse#86353) does not disturb this change.

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

Merged master (6ae413899fcd06fe9fda01ca65af369c3d6420cf) into the branch as
4ce0bc69196c807e2d47ffb7f9a4822e3267b93c, to re-run CI: on a3733ee9735d seven jobs died in
GitHub's Set up job step (codeload 429/502) and never executed, which is what leaves the PR
BLOCKED. No content change — the merge is clean and the diff against master is still exactly the
three files of this PR.

Checked before pushing, since master touched optimizeJoin.cpp meanwhile (the Cascades merge,
#86353, landed 2026-08-18):

  • optimizeJoin.cpp and JoinExpressionActions.cpp are byte-identical between master
    6ae413899fc and 52ff7f99c16, the tree I verified the fix on yesterday — and that tree already
    contains Cascades cost-based optimizer for distributed query plans #86353.
  • The merged tree's optimizeJoin.cpp is byte-identical to the file I built and tested, so the
    verification in my previous comment carries over to this head unchanged.

@vdimir your approval carried over; nothing to re-review.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 23, 2026
Merged via the queue into ClickHouse:master with commit 3fbd1b0 Aug 23, 2026
178 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 23, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi — this looks like a backport candidate for 26.7. I ran this PR's own regression test against each branch's binary and the bug reproduces there (the fix isn't present yet).

@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @vdimir @alexey-milovidov — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@vdimir could you apply v26.7-must-backport here? I measured the scope and 26.7 is the only affected release.

branch query_plan_merge_expression_into_join PR's own test
master (with this fix) default 1 clean
26.7.6.11 present, default 1 Code: 49 Left and right columns have same names
26.6.4.15 absent clean
26.5.8.14 absent clean
26.3.22.4 absent clean
25.8.33.4 no join reorder optimizer n/a

Binaries from builds.clickhouse.com. The setting defaults to 1 on 26.7, so it reproduces there with no SET at all.

Why only 26.7: the bug is the peel asymmetry between the guard and addChildQueryGraph. On 26.7 addChildQueryGraph has the else if (...merge_expression_into_join) branch and its peel prefix is byte-identical to pre-fix master, so the undercount exists. On 26.6 it peels passthrough only, which matches the guard. 26.5 and 26.3 have no joinGraphHasOverlappingColumnNames at all, and 25.8 has no chooseJoinOrder. The three guard functions on 26.7 are byte-identical to pre-fix master.

Controls: the master build containing the merge is clean (oracle works), and the reorder optimizer is confirmed live on 26.6/26.5/26.3 by a separate 3-table join fixture whose plan changes with query_plan_optimize_join_order_limit, so their clean runs are real declines and not a dead path.

Cherry-pick onto 26.7 is clean (git merge-tree rc=0), touches exactly the 3 files, and every symbol it needs (isPassthroughActions, ActionsDAG::hasArrayJoin, getExpression, optimization_settings.merge_expression_into_join) has an identical signature on 26.7, so it compiles there.

v26.7-must-backport expands to exactly [26.7] while 26.7 is newest; pr-must-backport would target branches where the code path does not exist.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Correcting the "Known residual" sentence in the description above, because it reads more broadly than I measured.

#116036, filed against this PR, is a real wrong-results bug in the same guard at default settings: a merged expression whose output name shadows a column of one of its own flattened inner relations. I confirmed it, and I also confirmed it is pre-existing rather than introduced here, by running the same arms on a pre-merge snapshot (b1383f4e, not containing 3fbd1b027f56) and getting identical results.

It is not the residual that sentence describes. That one was the missing get_exposed_columns side-clash suppression, which does not fire on this query (Column name clash detected between join sides appears zero times at trace level, with the optimizeJoin logger confirmed emitting). So "can only cost a reordering, never correctness" was true of that specific gap but is easy to read as a safety claim about the guard overall, and the guard does have a correctness hole on a different axis. I did not know that when I wrote it.

Details and the per-release scope, including 26.7, are in #116036. I am picking up the fix and will link the PR there.

pull Bot pushed a commit to Spencerx/ClickHouse that referenced this pull request Aug 25, 2026
Refusing to merge an expression whose output shadows its own input made
04516_join_reorder_duplicate_names_merge_expression stop reaching the
merge-then-flatten path it was written for, while both of its oracles still
passed. Its view projection is renamed so it no longer shadows an inner
relation, and it now asserts that the view's inner relations really are
flattened into the parent graph. Verified against a build with the guard from
ClickHouse#110227 reverted: the renamed test still hits the original
"Left and right columns have same names" logical error, so the coverage that
test exists for is intact.

05038 gains three things its previous arms could not tell apart or did not
reach: that the parent join is still reordered when the merge is refused,
paired with a control where reordering is off; and a stored CREATE VIEW
variant, which pushes a second expression step converting the subquery result
to the view structure and therefore reaches the peel through a different plan
shape than view() does. The stored view returns skewed values without the fix
and equal values with it.

The wrapper matrix behind the both-directions claim used idempotent shadowing
expressions, which cannot show a double application in their values, so it is
restated with non-idempotent ones per wrapper.
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 groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding 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.

LOGICAL_ERROR (Code 49) in a three-way join with a VIEW

7 participants