Repository navigation
Fix logical error when a JOIN USING key resolves to a table function's ALIAS column - #118734
Conversation
With analyzer_compatibility_join_using_top_level_identifier = 1, a USING key
can be resolved from the SELECT list. QueryAnalyzer then synthesizes a column
sourced at the left table expression and renames it (a1 -> _a1) when that name
is already taken there, so that two columns of one source never render the same
column identifier.
The census that decides "already taken" asked the storage snapshot for
GetColumnsOptions::All when the table expression is a TABLE, but for
AllPhysical when it is a TABLE_FUNCTION. AllPhysical is Ordinary | Materialized
and therefore omits ALIAS columns, so for a table-function carrier whose
matching column is an ALIAS column the rename never fired:
CREATE TABLE t0 (a Int32, b String, a1 Int32 ALIAS a+1) ENGINE = Memory;
CREATE TABLE t1 (a Int16, b String, a1 Int16 ALIAS a+1) ENGINE = Memory;
SET analyzer_compatibility_join_using_top_level_identifier = 1;
SELECT CAST(a1, 'UInt8') AS a1
FROM merge(currentDatabase(), '^t0$') AS m JOIN t1 USING (a1);
-- Logical error: Column identifier __table1.a1 is already registered
PlannerContext keys table expression data by node pointer, so the synthetic
column and the table function's own a1 shared one TableExpressionData, both
rendered __table1.a1, and the second createColumnIdentifier threw. Confirmed
directly with EXPLAIN QUERY TREE, which names the synthesized column _a1 for
FROM t0 and a1 for FROM merge(...). Reproduces with remote() as well, and
MATERIALIZED never reproduced because AllPhysical already contains it.
67b1de6 made this same change for the TABLE
case of getColumnsFromTableExpression; both TABLE_FUNCTION cases were left
behind. This aligns them with their TABLE siblings and leaves the rename guard
itself untouched.
The sibling census getOrderedColumnsFromTableExpression carries the same
asymmetry and feeds NATURAL JOIN key synthesis, so it changes too: an ALIAS
column common to both sides now becomes a join key regardless of whether the
side is a table or a table function, which a plain table has done since the
commit above. Fixing only the first site would have introduced a fresh
left-versus-right asymmetry, because the two NATURAL JOIN sides read different
censuses.
All is used rather than the narrower AllPhysicalAndAliases to match the TABLE
cases verbatim. The visible difference is EPHEMERAL columns, which All admits:
that turns a USING key naming an ephemeral column of a table function from an
abort into the Code 16 a plain table already returns, and likewise makes an
ephemeral column common to both sides of a NATURAL JOIN over a table function
return Code 16 instead of a result.
Co-Authored-By: Claude Opus 5 <[email protected]>
The two column censuses in QueryAnalyzer feed two purposes that want
different answers, so each caller now names the option kind it needs
instead of both helpers hardcoding one.
A NATURAL JOIN key must be readable. EPHEMERAL columns are not, so
admitting them into the key intersection turns a working query into
Code: 16 NO_SUCH_COLUMN_IN_TABLE. Both NATURAL JOIN censuses therefore ask
for AllPhysicalAndAliases.
The census that de-conflicts the synthesized USING column must instead
cover every name that can be registered as a column identifier, EPHEMERAL
included: initializeTableExpressionData builds column_names_and_types with
All for TABLE and TABLE_FUNCTION alike, so an ephemeral name is registrable
and can collide. Narrowing it is not academic. With AllPhysicalAndAliases
there, SELECT CAST(e, 'UInt8') AS e FROM e0 JOIN e1 USING (e) aborts with
Column identifier __table1.e is already registered, which is the same
defect this change removes for ALIAS columns.
Measured on e0/e1 = (a, e EPHEMERAL, c DEFAULT e + 1), before and after:
e0 NATURAL JOIN e1 Code: 16 -> rows
e0 NATURAL JOIN merge('^e1$') rows -> rows
merge('^e0$') NATURAL JOIN e1 rows -> rows
USING (e) over e0 Code: 16 -> Code: 16
USING (e) over merge('^e0$') ABORT -> Code: 16
No arm regresses, the abort is gone, and a NATURAL JOIN over two plain
tables sharing an EPHEMERAL column now returns rows instead of Code: 16.
This supersedes the last two paragraphs of the previous commit, which
described using All at every site: that choice removed the abort but made
non-selectable EPHEMERAL columns implicit join keys, regressing the second
and third rows above. Branch history is append-only here, so the reasoning
is corrected forward rather than rewritten.
05137_natural_join_ephemeral_key pins the contract with one assertion per
census and node type. Six of its eight statements are single-site
witnesses: a key set is the INTERSECTION of the two censuses, so a name
admitted by one census alone never becomes a key, and a statement can only
witness one census if the other side spells that column ORDINARY. The
remaining two are the plain-table and table-function improvement rows,
which redden on master.
Co-Authored-By: Claude Opus 5 <[email protected]>
05137_natural_join_ephemeral_key gained the one user-visible arm of the census split that nothing else reached. p0 and p1 share exactly one column name, an EPHEMERAL one, so after this change the key set is empty and the join takes the pre-existing no-common-columns path: setKind(JoinKind::Cross), no diagnostic, N*M rows. On master the same statement fails with Code: 16 NO_SUCH_COLUMN_IN_TABLE, because both TABLE censuses were All and the ephemeral name became the sole synthesized key. EXPLAIN states it directly, inner with "e = e" before and cross after, so the statement reverts with the code rather than describing it. The degrade rule itself is untouched and predates this change. It is a CROSS JOIN where an error used to be, which is the one behaviour change here that is silent, so the changelog entry and the PR description both name it. The statement is a joint witness, not a per-site one: a NATURAL JOIN key set is the intersection of the two censuses, so admitting EPHEMERAL on one side alone still leaves it empty. A table-function spelling was left out for that reason, since master's AllPhysical already excludes the column there and no single-site mutation can redden it. The comment on the de-confliction census claimed to cover every registrable column-identifier name. It does not: it passes a bare GetColumnsOptions::All, whose virtuals_kind defaults to VirtualsKind::None, while initializeTableExpressionData censuses with withVirtuals(VirtualsKind::All), so virtual names are registrable and uncovered. The comment now states the load-bearing fact instead: initializeTableExpressionData registers EPHEMERAL names as column identifiers, so a synthesized name can collide with one, and that is why this census keeps All while the NATURAL JOIN censuses do not. Narrowing it here would abort again on USING (<ephemeral column>) over a table function, which mutations M5 and M8 measured. The census itself is deliberately not broadened to virtual columns. That gap is neither introduced nor widened by this change, and closing it would rename synthesized columns in queries that work today. Comment-only in src/, verified by stripping comments from both revisions and comparing tokens, so the binary is unchanged. Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex) plus an independent cold reviewer pass
Accepted and fixed in earlier rounds, for context: the 💡 Corroboration worth stating, since the description had no room for it: the legacy analyzer's 💡 A labelling call I have deliberately not pre-empted: two arms change results rather than turning an
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-9:20260908-073400 |
|
Workflow [PR], commit [dfb898e] Summary: ✅
AI ReviewSummaryThis PR fixes the analyzer's column-census mismatch between Final Verdict✅ No new findings on the current PR head. LLVM Coverage ReportMeasured on commit dfb898e.
Changed lines: Changed C/C++ lines covered: 44/50 (88.00%) · Uncovered code |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-4:20260908-070200 |
|
cc @yakov-olkhovskiy @nickitat, could you review this? The census that renames a |
`ColumnsDescription::get` builds `AllPhysicalAndAliases` as `getAllPhysical()` followed by `getAliases()`, so it returns `ALIAS` columns after every physical column instead of in schema order. `getOrderedColumnsFromTableExpression` passed the requested kind straight to the census, so narrowing the `NATURAL JOIN` left-side census to `AllPhysicalAndAliases` reordered the synthesized key list for a plain table as well: over `(a, x ALIAS a + 100, b)` it produced `USING (a, b, x)` where master produces `USING (a, x, b)`. `SELECT *` over such a `NATURAL JOIN` projects the keys, so both the column order and the value under each name changed for a spelling this fix was not meant to touch. Census `All`, which iterates the columns in schema order, and keep the names the requested kind admits. The key set is unchanged, only its order is restored: the plain-table arm is now byte-identical to master, `EXPLAIN QUERY TREE` included. Leaving the ordered census at `All` and relying on the right-hand census to keep `EPHEMERAL` out of the intersection would preserve the order too, but then a left-side `EPHEMERAL` column whose name is an ordinary column on the right becomes a key that cannot be read; 05137 pins that case. The statements already in this PR could not catch the reordering: their `ALIAS` column is declared last, where the two orders coincide.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units7 translation units recompiled, 19 s compile time in total, 7 of them have a recent master baseline. |
…g-alias-column-table-function Both sides gave `getColumnsFromTableExpression` a new parameter for a different purpose - a caller-chosen `GetColumnsOptions::Kind` here, a `VirtualsKind` in master - so it takes both, and the two internal call sites now differ only in the kind the caller passes. The `JOIN USING` synthesized-name check needs both `GetColumnsOptions::All` and `VirtualsKind::All`: the name must avoid `EPHEMERAL` and virtual columns alike.
Related: #99931
Related: #112219
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix
LOGICAL_ERROR: Column identifier ... is already registeredwhenanalyzer_compatibility_join_using_top_level_identifier = 1and aJOIN ... USINGkey resolves to anALIAScolumn of a table function such asmergeorremote.NATURAL JOINnow also matchesALIAScolumns of a table function, as it already did for a table, and no longer takes a non-selectableEPHEMERALcolumn as a join key on either side; with no other shared name it behaves as aCROSS JOINrather than failing withCode: 16.Description
Aborts a debug/sanitizer server; returns
Code: 49on a release server:Resolving a
USINGkey from the SELECT list creates a synthetic column at the left table expression,which
QueryAnalyzerrenames (a1to_a1) when that name is taken there. The census feeding therename used
GetColumnsOptions::Allfor aTABLEbutAllPhysicalfor aTABLE_FUNCTION, andAllPhysicalomitsALIAScolumns, so the rename never fired and two columns of one source bothrendered
__table1.a1.67b1de6dcfaffixed this forTABLE; bothTABLE_FUNCTIONcases were leftbehind.
remotereproduces it too;MATERIALIZEDnever did, asAllPhysicalcontains it.Both censuses now take the option kind from their caller, so the node types agree by construction and
each caller asks for what it needs. The ordered census keeps schema order (
AllPhysicalAndAliasesalone returns
ALIAScolumns after all physical ones), so a plain-tableNATURAL JOINis unchanged.A join key must be readable, so
EPHEMERALcolumns are no longerNATURAL JOINkeys on either side; where one was the only shared name, the join degrades toCROSS JOINunder the existing no-common-columns rule instead of failing withCode: 16.De-confliction keeps
All:initializeTableExpressionDataregistersEPHEMERALnames as columnidentifiers for both node types, so a synthesized name can collide with one, and the narrower kind
would leave
USING (<ephemeral column>)over a table function aborting.Also noticed, not reachable:
CollectTableExpressionDatavisits only the first twoUSINGlistentries, and
StorageMergecopies its alias onto each per-childTableNode.Workflow [PR]
Sync PR [sync-upstream/pr/118734]
Version info
26.10.1.710-master(included in26.10and later)