Skip to content

Fix AMBIGUOUS_COLUMN_NAME when a JOIN ON condition is repeated in WHERE - #112007

Merged
alexey-milovidov merged 6 commits into
ClickHouse:masterfrom
groeneai:fix/filter-step-and-split-duplicate-input-names
Jul 27, 2026
Merged

alexey-milovidov merged 6 commits into
ClickHouse:masterfrom
groeneai:fix/filter-step-and-split-duplicate-input-names

Conversation

@groeneai

@groeneai groeneai commented Jul 27, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #111955
Related: #111930

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):

Fixes AMBIGUOUS_COLUMN_NAME (Block structure mismatch in (columns with identical name must have identical structure)) for a query that repeats a JOIN ON condition in WHERE with join_use_nulls = 1. Such a query now returns its result instead of failing.

Description

FilterStep::transformPipeline splits an AND chain into one FilterTransform per atom via
ActionsDAG::split. The split promotes each split-out atom into an INPUT of the remainder DAG,
copying result_name verbatim. Duplicate names are legal inside an ActionsDAG but break the
Block invariant, so the remainder's updateHeader throws in Block::insert.

Filter push-down placed both copies of the repeated condition into one filter step: the ON copy
computed on the plain column and the WHERE copy on the join_use_nulls-promoted Nullable
column, both carrying the same name. Splitting that filter's AND chain then made them two
same-named columns of different types in one block.

ActionsDAG::split already owns the guard for this: avoid_duplicate_inputs renames the colliding
input and inserts a compensating ALIAS. FilterStep was the only one of its four external callers
that did not pass it (optimizePrewhere and optimizeLazyMaterialization both do). This passes it
there too.

The two optimizer passes that create the shape (outer-to-inner join conversion and filter push-down)
produce a semantically correct plan: query_plan_convert_outer_join_to_inner_join = 0,
query_plan_merge_filters = 0 and join_use_nulls = 0 all return the same result the fixed build
returns, so the defect is in the split consumer, not in those passes.

The affected set is wider than the report: the collision does not need final = 1, MergeTree, or a
Bool column. Measured throwing on master: Bool, plain UInt8, Int64, String and
LowCardinality(String) repeated predicates, over Memory as well as MergeTree. Measured NOT
throwing, because join_use_nulls promotion is a no-op once the type is already nullable
(makeNullableOrLowCardinalityNullable returns early on isNullableOrLowCardinalityNullable, so both
copies of the predicate are computed on the identical type): Nullable and
LowCardinality(Nullable(String)). The fix keys on the name collision itself, so it covers every
throwing shape, and the test pins both halves of that matrix. The report notes that #104017 made the
logical join step unconditional and thereby widened exposure; the defect itself is not confined to that
step. It does require the analyzer: with enable_analyzer = 0 master builds a plan that never reaches
this split and returns the correct result, so the test pins enable_analyzer = 1.

ActionsDAG also splits internally in splitActionsBeforeArrayJoin, splitActionsBySortingDescription
and splitActionsForFilter, none of which pass the flag on master. splitActionsForFilter has the same
class of defect on a different trigger (a promoted node whose name equals an existing input name) and is
fixed separately in #111930; that change and this one are file-disjoint. For the other two I could not
construct a colliding shape: they split in one pass, on nodes that do not depend on ARRAY JOIN or on
outputs resolved by distinct SortDescription names, so no promoted boundary node takes a name that is
already an input.

The test also covers the ARRAY JOIN and ORDER BY <expression> shapes, which are further affected
forms of the same collision: both throw on master and return the correct result with the fix. Besides
the thirteen result queries it pins the plan shape two ways so the coverage cannot silently go vacuous.

Version info

  • Backported to: 26.7.2.26, 26.6.2.151, 26.5.6.82, 26.3.17.87

groeneai and others added 6 commits July 26, 2026 17:15
A query that repeats a right-table JOIN ON condition in WHERE threw
Code: 352 AMBIGUOUS_COLUMN_NAME "Block structure mismatch ... columns with
identical name must have identical structure" when join_use_nulls = 1.

Under join_use_nulls the right side is promoted, so the WHERE copy of the
predicate is computed on the Nullable column while the ON copy is computed on
the plain one. ActionsDAG::addFunction derives result_name from the function
name plus the argument names, so both copies end up with the same name, and
filter push-down places them in one filter DAG. Duplicate names are legal
inside an ActionsDAG, but FilterStep::transformPipeline then splits the AND
chain with ActionsDAG::split, which promotes each split-out atom into an INPUT
of the remainder DAG copying result_name verbatim. The remainder therefore
carries two same-named inputs of different type, and updateHeader throws while
inserting the second one into the block.

ActionsDAG::split already handles this via avoid_duplicate_inputs: it renames
the colliding input and inserts a compensating ALIAS so the original name stays
resolvable. FilterStep was the only one of its four callers that did not pass
the flag; optimizePrewhere and optimizeLazyMaterialization both do. Pass it
here as well.

The outer-to-inner join conversion and the filter push-down that create this
shape are correct: query_plan_convert_outer_join_to_inner_join = 0,
query_plan_merge_filters = 0 and join_use_nulls = 0 all return the same result
the fixed build returns, so the defect is in the split consumer.

The affected set is wider than the report. The collision needs neither
final = 1, nor MergeTree, nor a Bool column: Bool, UInt8, String,
LowCardinality(String) and LowCardinality(Nullable(String)) repeated predicates
all throw on master, over Memory as well as MergeTree, and with the legacy join
step. The fix keys on the name collision itself, so it covers all of them, and
the new test pins the matrix.

Closes: ClickHouse#111955

Co-Authored-By: Claude Fable 5 <[email protected]>
Review round r1 on the FilterStep avoid_duplicate_inputs fix. The source fix is
unchanged; this only makes its test a real assertion and corrects two coverage
claims.

The test pinned only join_use_nulls, but the fixed code path is reached only
when query_plan_merge_filters is on, and the colliding plan shape needs
query_plan_convert_outer_join_to_inner_join. CI randomizes each of those to 0
with 5 percent probability, so on such a draw every case returned the expected
rows on an unfixed binary and the test asserted nothing. Both settings are now
pinned per query, and a plan assertion in subquery form pins the rename itself.
It discriminates: 1 on the fixed build, 0 on master, 0 on a build with only the
flag reverted. position() is used instead of ILIKE because _ is an ILIKE
wildcard and the pattern has to match the renamed atom only. With both settings
forced to 0 at session level the per-query SETTINGS still win, so the test
passes on the fixed build and still fails on master.

The case pinning query_plan_use_logical_join_step = 0 is removed. That setting
is MAKE_OBSOLETE and no code reads it, so the case was a duplicate of the first
one rather than a second code path.

Two cases are added. ARRAY JOIN above the join and ORDER BY an expression above
the join both throw the same exception on master, because liftUpArrayJoin and
liftUpFunctions consume the remainder DAG the split produces.

ActionsDAG::split has seven call sites, not four. Besides the three external
callers that already pass the flag, splitActionsBeforeArrayJoin,
splitActionsBySortingDescription and splitActionsForFilter pass neither.
splitActionsForFilter is a real carrier of the same class on a different
trigger, a promoted node whose name equals an existing input name, and is fixed
separately in ClickHouse#111930; that change is file-disjoint from this one and the two
were built together to confirm both tests pass. For the other two no colliding
shape could be constructed: they split in one pass, on nodes that do not depend
on ARRAY JOIN or on outputs resolved by distinct SortDescription names.

Co-Authored-By: Claude Fable 5 <[email protected]>
The plan assertion matches analyzer-generated column identifiers (__table2.),
which the old analyzer never produces, so the test failed deterministically in
the old-analyzer stateless job. Pin enable_analyzer for the whole file rather
than tagging it no-old-analyzer: the defect is analyzer-only (with
enable_analyzer = 0 master builds a plan that never reaches this split and
returns the correct result), so nothing is lost and the result queries keep
running under both analyzers.

The existing assertion reads FilterStep::describeActions, which splits a clone
of the DAG and never builds a pipeline, so it could not witness the runtime
split that the fix actually guards. Add an EXPLAIN PIPELINE assertion on the
resulting FilterTransform multiplicity, which does build the pipeline. A line
count over FilterTransform would not discriminate here (2 lines with the split
versus 3 without); the multiplicity does (3 versus 0).

Both EXPLAIN assertions also pin the plan-shape settings that CI randomizes,
since any of them can move the two colliding atoms off the shared filter step
and turn the assertion into a spurious failure. The twelve result queries are
left under randomization deliberately.

Co-Authored-By: Claude Fable 5 <[email protected]>
The runtime plan assertion accepted a FilterTransform multiplicity of >= 2,
which a single-atom split already satisfies. The collision this PR fixes only
exists when the AND-chain split iterates, so the assertion did not discriminate
the property it was added for. transformPipeline emits one transform per
extracted atom plus one for the remainder, so require 3: measured as 3 for the
pinned two-atom query and 2 for a one-atom WHERE.

Also drop a false mechanism claim from the ARRAY JOIN / ORDER BY comment. Those
two shapes are genuinely affected (both throw on master, both pass with the
fix), but not because the lift passes consume the split's remainder DAG:
QueryPlan::buildQueryPipeline runs optimize() before walking the tree to build
the pipeline, so both passes run before the runtime split and cannot see its
remainder. The comment now states only what is measured.

Co-Authored-By: Claude Fable 5 <[email protected]>
Retracts a coverage claim that was false as written. The test and the PR
metadata said that LowCardinality(Nullable(String)) and UInt8 repeated
predicates throw on master and that the test pins them as bug cases.

The LowCardinality(Nullable(String)) case does not throw on master. Promotion
under join_use_nulls goes through makeNullableOrLowCardinalityNullable, whose
first statement returns the type unchanged when it is already nullable or
LowCardinality-nullable. Both copies of the predicate are then computed on the
identical type, so no name collision is possible. The case is real
wrapper-matrix coverage of the negative kind, so it is kept, relabelled as
non-regression and grouped with the other non-regression cases, with the reason
recorded in a comment.

There was also no UInt8 column in the test at all. Its only non-Bool repeated
predicate is Int64, and Bool is a UInt8 domain rather than a separate type. A
plain UInt8 case was added and measured throwing on a pristine master build
with the colliding name equals(__table2.flag, 1_UInt8), so the claim now holds
instead of being dropped.

Every case in the file was re-measured individually against a pristine master
build: nine throw 352, four pass, and both plan assertions still discriminate.
The reference was regenerated with --record. No behaviour change, the source
diff this commit carries is comment backticks only.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment-only compliance edit for the inline-code rule in `.claude/CLAUDE.md`:
literal ClickHouse type names in comments belong in inline code blocks. The two
neighbouring names in the same comment were already backticked.

No source, query, or `.reference` change, so the binary and the test output are
untouched.
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

Six review rounds by a second model plus an independent cold review per round, all before this PR
existed. Every finding below was adjudicated against the code, not against prose. The final round
returned zero findings from both reviewers.

❌ Blocker - fixed

Finding Verdict Resolution
The plan assertion fails deterministically in the old-analyzer stateless jobs: it matches analyzer-generated __table2. identifiers, and users.d/analyzer.xml sets allow_experimental_analyzer = 0 for three PR jobs. AGREE The test now pins enable_analyzer = 1 and explain_query_plan_default = 'legacy' for the whole file. Pinned rather than tagged no-old-analyzer, so no coverage is discarded.

⚠️ Major - fixed

Finding Verdict Resolution
The regression test could pass without executing the changed split path: a plan shape that never reaches the split would make every case pass vacuously. AGREE Added two plan assertions: EXPLAIN actions = 1 pins the rename of the colliding atom, and EXPLAIN PIPELINE pins that the AND chain is split on the real execution path. The latter matters because describeActions splits a clone of the DAG and never builds a pipeline.
The runtime oracle can pass without splitting the colliding second atom that exercises the guard. AGREE The pipeline assertion now requires a FilterTransform multiplicity of at least 3 (one transform per extracted atom plus one for the remainder). Measured: the pinned two-atom query gives 3, a one-atom WHERE gives 2, so the threshold pins an iterated split rather than any split.
The test and the description claimed coverage of a legacy join implementation that no longer exists. AGREE Claim removed; the case was replaced by shapes that were each measured on a pristine build.
Two cases did not prove the sibling-splitter coverage their comment and the description claimed. AGREE The sibling-splitter claim was moved out of the test into the description, where it is stated with the measurement that backs it: splitActionsForFilter is a real carrier of the same class on a different trigger and is fixed separately in #111930; for the other two internal splitters no colliding shape could be constructed across 15 probes.
The test did not pin the advertised UInt8 and LowCardinality(Nullable(String)) type matrix. AGREE Both are pinned now, and every case's disposition was measured individually on a pristine build: 8 of the 13 result queries throw on master, 5 are non-regression. One earlier claim was retracted in the process: LowCardinality(Nullable(String)) does not throw, because makeNullableOrLowCardinalityNullable early-returns on isNullableOrLowCardinalityNullable, so promoting an already-nullable column is a no-op and both copies of the predicate are computed on the identical type.

💡 Nits - fixed

Finding Verdict Resolution
Literal ClickHouse names, an exception excerpt and method names were not inline code, and methods were written as f() rather than f, contrary to .claude/CLAUDE.md. AGREE Fixed across the comment, the description and the validation table over three rounds. A backtick-aware sweep of the whole added diff (strip inline-code spans, then match a ClickHouse-name vocabulary against the remainder) now returns nothing.
The comment above the changed call repeated the callee's contract at length. AGREE Cut to three lines stating only the invariant at that spot.
The changelog entry was past tense and implementation-focused. AGREE Rewritten as a user-facing description.
Closes: #111955 did not use the full GitHub URL the template asks for. AGREE Full URLs for both relationships.

Notes

Two accounting errors in the PR metadata were caught by the same reviewer class one round apart and
corrected: the case split was stated as 9 throwing / 4 non-regression when the measured split is
8 / 5, and one probed-but-not-pinned shape was listed among the pinned cases. Both numbers are now
re-derived from the raw per-case log rather than from the previous round's prose.

Session id: cron:clickhouse-review-slot-11:20260727-025600

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100% of runs, no server needed: clickhouse local --path=<tmp> --queries-file q.sql < /dev/null with two Memory tables and SELECT m1.id, m2.reviewer FROM m1 LEFT JOIN m2 ON m1.id = m2.id AND m2.enabled = true WHERE m1.grp = 10 AND m2.reviewer = 100 AND m2.enabled = true SETTINGS join_use_nulls = 1. Neither final = 1 nor MergeTree is needed, contrary to the report.
b Root cause explained? Yes. join_use_nulls = 1 promotes the right side, so the WHERE copy of the repeated predicate is computed on Nullable(UInt8) while the ON copy is on the plain column; addFunction derives result_name from function plus argument names, so both are named equals(__table2.enabled, 1_Bool). Filter push-down puts them in one DAG (legal: duplicate names are allowed inside an ActionsDAG). FilterStep::transformPipeline then splits the AND chain via ActionsDAG::split, iterating once per atom. The first split promotes the ON copy into the remainder DAG as an INPUT, copying result_name verbatim; the second split runs on that remainder, whose inputs already carry that name, and promotes the WHERE copy under it. The remainder ends up with two same-named inputs of different type and updateHeader -> Block::insert -> checkColumnStructure throws AMBIGUOUS_COLUMN_NAME. A single split over the same colliding DAG does not throw, which pins the iteration as the trigger.
c Fix matches root cause? Yes. ActionsDAG::split already owns the guard for exactly this (avoid_duplicate_inputs renames the colliding input and inserts a compensating ALIAS, seeding its name set from the DAG's existing inputs); FilterStep.cpp:199 was the only one of its four external callers not passing it. Not a band-aid: no widened bound, no no-random-* tag, no guard at the throw site (Block::insert is right to throw), and the upstream optimizer passes are proven semantically correct (see e), so patching them would be attacking a carrier.
d Test intent preserved / new tests added? Yes. No existing test modified or weakened. New stateless SQL test 04650_join_use_nulls_repeated_on_condition_in_where with 13 query cases (8 that throw on master, 5 non-regression, each disposition measured individually on a pristine build) plus two plan assertions: that the colliding atom is renamed (EXPLAIN actions = 1), and that the AND chain is split into two atoms on the real execution path (EXPLAIN PIPELINE, which builds the pipeline instead of describing a clone, so the runtime coverage cannot silently go vacuous). The pipeline assertion requires a FilterTransform multiplicity of 3 (one transform per extracted atom plus one remainder), measured: the pinned two-atom query gives 3, a one-atom WHERE gives 2, so the threshold pins the iterated split the collision needs rather than any split. Mutation-tested: reverting only the flag and rebuilding makes the query cases throw 352 again, the rename assertion return 0, and the pipeline assertion throw 352 itself, each verified in isolation so no earlier throw can mask it.
e Both directions demonstrated? Yes. Pristine master binary at the same commit gives RC=96 with Code: 352 ... (AMBIGUOUS_COLUMN_NAME); fixed binary matches the reference byte for byte. Also through the real runner against a live server (buildId verified against the binary): [ OK ], and --test-runs 50 gives 50/50. Hostile-draw check: with the two gating settings and all nine randomized plan-shape settings forced to their opposite values at session level, the per-query SETTINGS win, so the fixed build still passes and the pristine build still fails; same result under an old-analyzer session. Semantic oracle: the pristine binary with query_plan_merge_filters = 0 (which disables only the code path being fixed) produces byte-identical output to the fixed build, so this removes a spurious exception without changing results.
f Fix is general across code paths? Yes for this call site, with the whole class accounted for. All seven ActionsDAG::split call sites were enumerated. Four external: FilterStep.cpp:199 (fixed here), optimizePrewhere.cpp:114, optimizeLazyMaterialization.cpp:275 and :327 (all already pass the flag). Three internal pass neither argument. Of those, splitActionsForFilter is a real carrier of the same class on a different trigger (a promoted node whose name equals an existing input name rather than an iterated split); I verified that by running #111930's test on both a pristine master binary and this build, where it aborts identically. It is fixed by #111930, which is file-disjoint from this PR (ActionsDAG.cpp + splitFilter.cpp vs FilterStep.cpp) and merges cleanly with it; the two are complementary halves kept apart per the one-concern rule. For splitActionsBeforeArrayJoin and splitActionsBySortingDescription no colliding shape could be constructed across 15 probes on both binaries, including the correct promoted-name-equals-input-name recipe: they split in one pass, on nodes that do not depend on ARRAY JOIN or on outputs resolved by distinct SortDescription names. FilterStep's three splitAndChainIntoMultipleFilters callers (transformPipeline, and describeActions text and JSON) route through the single fixed helper.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes, and the affected set is wider than reported. Every case below was measured on a pristine master build at the same commit, not inferred. Throwing on master and fixed here: Bool, plain UInt8, Int64, String and LowCardinality(String) repeated predicates, over Memory as well as ReplacingMergeTree with final = 1 and both prewhere settings off. Bool is a UInt8 domain (one underlying type, different display name), but the display name is part of the colliding column name (1_Bool vs 1_UInt8), so both are pinned. Two further plan shapes above the join throw the same way on master and are also fixed: ARRAY JOIN and ORDER BY <expression>. Not colliding today, pinned as non-regression cases: Nullable, LowCardinality(Nullable(String)), and RIGHT/FULL/INNER. (An Array has shape was also measured as non-colliding while probing, but it is not pinned in the test.) For the two nullable-wrapper cases the reason is that join_use_nulls promotion is a no-op once the type is already nullable or LowCardinality-nullable (makeNullableOrLowCardinalityNullable early-returns on isNullableOrLowCardinalityNullable), so both copies of the predicate are computed on the identical type and no collision can arise. On the analyzer axis the defect is analyzer-only: with enable_analyzer = 0 master builds a plan that never reaches this split and returns the correct result, so the test pins enable_analyzer = 1 (a pin that costs no coverage, rather than a no-old-analyzer tag).
h Backward compatible? (maintainer-approved exception only) Yes, nothing engaged. No setting added or defaulted differently, so no SettingsChangesHistory.cpp entry; no serialization or format change, no protocol or ABI change, no experimental gate. The only observable change beyond no longer throwing is a _0 suffix in EXPLAIN text for a renamed atom, and only for plans that throw on master today. The two reference files pinning AND column: lines are unchanged and pass.
i Invariants and contracts preserved? Yes. Invariant: a FilterStep AND-split must not create two same-named boundary inputs of different structure. split's rename block is unconditional once the flag is set, so no early-return or error path can skip it, and it keeps the DAG contract by inserting an ALIAS under the original name so remainder consumers still resolve it. The change strengthens the Block invariant rather than relaxing anything; no lock, concurrency, or error-handling behaviour changes, and this is in-memory plan construction with no persisted state. Regression check: 231 tests (join_use_nulls, filter_push_down, prewhere, merge_filters, including the two AND column: reference files) were run against both a fixed-binary and a pristine-binary server, each with buildId verified. Every name-level difference was chased down and none is caused by this change: the four fixed-only names are all 600s Timeout! entries from host contention (the whole run inflated ~10x under a load average of ~9-10) and all four pass in 0.73-30.70s on the fixed binary once uncontended, matching the pristine timings; the one pristine-only name is the new test itself. An earlier 121-test round reached the same zero-delta conclusion via the sandbox CLUSTER_DOESNT_EXIST signature.

Session id: cron:clickhouse-review-slot-11:20260727-025600

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @davenger @novikd — could you review this? FilterStep splits an AND chain one atom at a time via ActionsDAG::split, which promotes each atom into an INPUT of the remainder DAG under its verbatim result_name; when join_use_nulls = 1 makes the ON and WHERE copies of a repeated predicate differ in type but not in name, the remainder ends up with two same-named inputs and updateHeader throws AMBIGUOUS_COLUMN_NAME. It passes avoid_duplicate_inputs, which split already implements and which the other three external callers already pass.

@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3bd0b4c]

Summary: ✅


AI Review

Summary

This PR fixes the FilterStep AND-split path so repeated JOIN ON predicates no longer produce duplicate boundary inputs with incompatible structures under join_use_nulls = 1, and it adds focused regression coverage for the affected planner shapes. The change is narrow, the rename-and-ALIAS flow in ActionsDAG::split preserves the remainder DAG contract, and I did not find a correctness or coverage gap in the current code.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 27, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.20% -0.10%
Functions 92.00% 92.00% +0.00%
Branches 78.40% 78.40% +0.00%

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

Full report · Diff report

@alexey-milovidov alexey-milovidov 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.

The change looks good, thank you!

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 27, 2026
Merged via the queue into ClickHouse:master with commit c71a26c Jul 27, 2026
178 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jul 27, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Jul 27, 2026
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 27, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Jul 27, 2026
clickhouse-gh Bot added a commit that referenced this pull request Jul 27, 2026
Backport #112007 to 26.7: Fix AMBIGUOUS_COLUMN_NAME when a JOIN ON condition is repeated in WHERE
alexey-milovidov added a commit that referenced this pull request Jul 29, 2026
Backport #112007 to 26.5: Fix AMBIGUOUS_COLUMN_NAME when a JOIN ON condition is repeated in WHERE
alexey-milovidov added a commit that referenced this pull request Jul 30, 2026
Backport #112007 to 26.3: Fix AMBIGUOUS_COLUMN_NAME when a JOIN ON condition is repeated in WHERE
PedroTadim pushed a commit to smundhra-git/ClickHouse that referenced this pull request Jul 30, 2026
…release branches

The test was added by ClickHouse#112007, which carries v26.3-must-backport and
v26.4-must-backport. It named two settings that do not exist on all backport
targets, so the backported copies aborted deterministically:

  - explain_query_plan_default was added in 26.7, so on 26.6/26.5/26.4/26.3 the
    second statement failed with UNKNOWN_SETTING at line 5. This is what CI
    reported on the 26.3 and 26.5 backport PRs.
  - query_plan_optimize_join_order_randomize was added in 26.4, so it is also
    missing on 26.3. This one was latent: the run aborted on the first setting
    before reaching it, so fixing only the reported setting would have left the
    26.3 backport red a second time.

Neither is a real dependency of the assertions. explain_query_plan_default has a
single consumer, which only installs actions/compact/pretty as defaults that
AST-spelled options override, so deleting the session pin and spelling
"actions = 1, compact = 0, pretty = 0" on the one plan-asserting EXPLAIN
reproduces exactly the output the pin guaranteed; all three option names exist
back to 26.3. query_plan_optimize_join_order_limit = 0 replaces the randomize
pin: it exists back to 26.3 and is strictly stronger, early-returning before the
randomize seed is read.

The reference file is unchanged, which is the check that the change is
output-preserving. Every assertion, behaviour case and wrapper matrix entry is
kept as-is.

Validated against the published 26.3, 26.4, 26.5, 26.6 and 26.7 binaries: all 14
settings the test names are accepted on all of them after the change, and the
asserted "AND column:" lines are emitted identically on all six branches. The
26.7 binary and a master build both reproduce the unchanged reference byte for
byte. On master the test passes through the runner, with 50 randomized and 50
non-randomized runs green; that matters because the runner also randomizes
query_plan_optimize_join_order_limit, so the statement-level pin has to hold
under injection.

Co-Authored-By: Claude Fable 5 <[email protected]>
clickhouse-gh Bot pushed a commit that referenced this pull request Aug 3, 2026
clickhouse-gh Bot added a commit that referenced this pull request Aug 3, 2026
Backport #112007 to 26.6: Fix AMBIGUOUS_COLUMN_NAME when a JOIN ON condition is repeated in WHERE
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
alexey-milovidov pushed a commit to canhld94/ClickHouse that referenced this pull request Nov 8, 2026
…h one name

With join_use_nulls = 1, the WHERE copy of a JOIN ON condition repeated in
WHERE is computed on toNullable(col) but keeps the name of the ON copy, so
the PREWHERE DAG holds two different nodes with one name and two types
(e.g. equals(__table2.enabled, 1_Bool) as Nullable(UInt8) and UInt8).
tryBuildPrewhereSteps clones every node into its step under its own name,
the steps pass columns to each other through a Block by name, and a
non-last step keeps its filter column in the block. When the two copies
fall into non-adjacent, non-last steps, the later step inserts a column of
the same name and another type and Block::insert throws 352. Two repeated
two-condition groups collide the same way through the generated `and` name.

Clone the non-INPUT nodes whose name is shared with another node, and that
are not outputs of PREWHERE, under new names (`__prewhere_<name>`). Only the
step clones are renamed: the original DAG, and so its conjunct hashes used by
the query condition cache attribution, are unchanged, and the step
boundaries stay where they are, so an earlier condition still filters the
rows a later default expression is evaluated on (a one-step fallback would
throw there). The helper has the same shape as the one in ClickHouse#125670, which
renames for a computed node named like a stored column.

Same class as ClickHouse#111955, fixed for the FilterStep split by ClickHouse#112007.

Co-Authored-By: Claude Opus 5.5 <[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 pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.3-must-backport v26.4-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

AMBIGUOUS_COLUMN_NAME: Block structure mismatch when a LEFT JOIN ON condition is repeated in WHERE (join_use_nulls = 1, final = 1)

6 participants