Repository navigation
Fix AMBIGUOUS_COLUMN_NAME when a JOIN ON condition is repeated in WHERE - #112007
alexey-milovidov merged 6 commits into
Conversation
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.
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 ❌ Blocker - 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
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-review-slot-11:20260727-025600 |
|
cc @davenger @novikd — could you review this? |
|
Workflow [PR], commit [3bd0b4c] Summary: ✅
AI ReviewSummaryThis PR fixes the Final VerdictStatus: ✅ Approve |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 3/3 (100.00%) · Uncovered code |
alexey-milovidov
left a comment
There was a problem hiding this comment.
The change looks good, thank you!
…ndition is repeated in WHERE
Backport #112007 to 26.7: Fix AMBIGUOUS_COLUMN_NAME when a JOIN ON condition is repeated in WHERE
Backport #112007 to 26.5: Fix AMBIGUOUS_COLUMN_NAME when a JOIN ON condition is repeated in WHERE
Backport #112007 to 26.3: Fix AMBIGUOUS_COLUMN_NAME when a JOIN ON condition is repeated in WHERE
…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]>
…ndition is repeated in WHERE
Backport #112007 to 26.6: Fix AMBIGUOUS_COLUMN_NAME when a JOIN ON condition is repeated in WHERE
…JOIN ON condition is repeated in WHERE
…JOIN ON condition is repeated in WHERE
…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]>
Closes: #111955
Related: #111930
Changelog category (leave one):
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 aJOIN ONcondition inWHEREwithjoin_use_nulls = 1. Such a query now returns its result instead of failing.Description
FilterStep::transformPipelinesplits anANDchain into oneFilterTransformper atom viaActionsDAG::split. The split promotes each split-out atom into anINPUTof the remainder DAG,copying
result_nameverbatim. Duplicate names are legal inside anActionsDAGbut break theBlockinvariant, so the remainder'supdateHeaderthrows inBlock::insert.Filter push-down placed both copies of the repeated condition into one filter step: the
ONcopycomputed on the plain column and the
WHEREcopy on thejoin_use_nulls-promotedNullablecolumn, both carrying the same name. Splitting that filter's
ANDchain then made them twosame-named columns of different types in one block.
ActionsDAG::splitalready owns the guard for this:avoid_duplicate_inputsrenames the collidinginput and inserts a compensating
ALIAS.FilterStepwas the only one of its four external callersthat did not pass it (
optimizePrewhereandoptimizeLazyMaterializationboth do). This passes itthere 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 = 0andjoin_use_nulls = 0all return the same result the fixed buildreturns, 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 aBoolcolumn. Measured throwing on master:Bool, plainUInt8,Int64,StringandLowCardinality(String)repeated predicates, overMemoryas well asMergeTree. Measured NOTthrowing, because
join_use_nullspromotion is a no-op once the type is already nullable(
makeNullableOrLowCardinalityNullablereturns early onisNullableOrLowCardinalityNullable, so bothcopies of the predicate are computed on the identical type):
NullableandLowCardinality(Nullable(String)). The fix keys on the name collision itself, so it covers everythrowing 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 = 0master builds a plan that never reachesthis split and returns the correct result, so the test pins
enable_analyzer = 1.ActionsDAGalso splits internally insplitActionsBeforeArrayJoin,splitActionsBySortingDescriptionand
splitActionsForFilter, none of which pass the flag on master.splitActionsForFilterhas the sameclass 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
SortDescriptionnames, so no promoted boundary node takes a name that isalready an input.
The test also covers the
ARRAY JOINandORDER BY <expression>shapes, which are further affectedforms 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
26.7.2.26,26.6.2.151,26.5.6.82,26.3.17.87