Skip to content

Fix logical error when a JOIN USING key resolves to a table function's ALIAS column - #118734

Merged
alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-99931-join-using-alias-column-table-function
Sep 26, 2026
Merged

alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-99931-join-using-alias-column-table-function

Conversation

@groeneai

@groeneai groeneai commented Sep 8, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #99931
Related: #112219

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 LOGICAL_ERROR: Column identifier ... is already registered when analyzer_compatibility_join_using_top_level_identifier = 1 and a JOIN ... USING key resolves to an ALIAS column of a table function such as merge or remote. NATURAL JOIN now also matches ALIAS columns of a table function, as it already did for a table, and no longer takes a non-selectable EPHEMERAL column as a join key on either side; with no other shared name it behaves as a CROSS JOIN rather than failing with Code: 16.

Description

Aborts a debug/sanitizer server; returns Code: 49 on a release server:

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

Resolving a USING key from the SELECT list creates a synthetic column at the left table expression,
which QueryAnalyzer renames (a1 to _a1) when that name is taken there. The census feeding the
rename used GetColumnsOptions::All for a TABLE but AllPhysical for a TABLE_FUNCTION, and
AllPhysical omits ALIAS columns, so the rename never fired and two columns of one source both
rendered __table1.a1. 67b1de6dcfaf fixed this for TABLE; both TABLE_FUNCTION cases were left
behind. remote reproduces it too; MATERIALIZED never did, as AllPhysical contains 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 (AllPhysicalAndAliases
alone returns ALIAS columns after all physical ones), so a plain-table NATURAL JOIN is unchanged.
A join key must be readable, so EPHEMERAL columns are no longer
NATURAL JOIN keys on either side; where one was the only shared name, the join degrades to
CROSS JOIN under the existing no-common-columns rule instead of failing with Code: 16.
De-confliction keeps All: initializeTableExpressionData registers EPHEMERAL names as column
identifiers 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: CollectTableExpressionData visits only the first two USING list
entries, and StorageMerge copies its alias onto each per-child TableNode.


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

Version info

  • Merged into: 26.10.1.710-master (included in 26.10 and later)

groeneai and others added 3 commits September 8, 2026 03:03
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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 8, 2026
@groeneai

groeneai commented Sep 8, 2026

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

Pre-publication review by an independent model (engine: codex) plus an independent cold reviewer pass
over the resulting code, across five bounded rounds. This round: 2 findings, both declined with
recorded evidence; the four findings of the previous round were all accepted and are fixed in the
tree being published.

# Sev Finding Verdict Evidence / action
1 ❌ The de-confliction census omits registered virtual columns, so a projection-derived USING key named after one (merge's _table) is not renamed and the raw virtual value is used instead of the alias expression: 0 rows where a non-colliding alias returns the expected row DISAGREE (real, but pre-existing and unchanged here) The scenario and the wrong result are real, and were measured on this build. What makes it a blocker on this PR is not: GetColumnsOptions::Kind has no virtuals bit at all (ColumnsDescription.h:53-63); virtuals live in the separate virtuals_kind member, default VirtualsKind::None, set only by .withVirtuals(), which this census never calls before or after. Both kinds master passes here (AllPhysical for TABLE_FUNCTION, All for TABLE) leave it at None exactly as this diff does, so the probe cannot separate this tree from master, and it was run single-arm on the fixed build only. The same blindness holds for a plain TABLE, whose census was already All, so it predates even 67b1de6dcfaf, the half-fix this PR completes. Not folded in: broadening the census would rename synthesized columns in queries that work today, unmeasured. A fix task is created for it, carrying this repro (investigating at full effort; fixing-PR link to follow)
2 ⚠️ The two serverError NO_SUCH_COLUMN_IN_TABLE assertions in 05137 return the same error with the compatibility setting on or off, so they do not witness that the projection-alias path ran DISAGREE The finding's own detail concedes the mutation that matters is caught: reverting the de-confliction census to a narrower kind reddens these assertions by restoring the logical exception, measured as mutations M5/M8. The arm is live in the direction the changelog claims: on a master snapshot at the same base, USING (<ephemeral column>) over merge(...) aborts the server, against Code: 16 here. The scenario it does not discriminate is not a change this PR makes, and pinning it would assert _e, the synthesized column's internal name, which no user-visible contract fixes

Accepted and fixed in earlier rounds, for context: the EPHEMERAL-only NATURAL JOIN arm was
unpinned and is now measured on both binaries; a comment overclaimed that the de-confliction census
covers every registrable column-identifier name and was narrowed to the invariant that is true; the
new test now drops its fixtures. Earlier still, the design itself was corrected twice by review: one
column-option constant at every census site regressed working NATURAL JOIN queries over a table
function, while the narrower constant everywhere left a LOGICAL_ERROR alive for
USING (<ephemeral column>). Each census now takes its option kind from its caller, so a join key is
asked for as readable and the de-confliction census as registrable. Eight one-line mutation builds
pin six call-site-by-node-type arms, each with its own witnessing statement.

💡 Corroboration worth stating, since the description had no room for it: the legacy analyzer's
sibling resolveNaturalJoin (Interpreters/TreeRewriter.cpp:694-726) censuses through
getDatabaseAndTablesWithColumns, whose TABLE and TABLE FUNCTION branches are identical
(getOrdinary() plus materialized, aliases and virtuals, getTableExpressions.cpp:79-127) and never
include EPHEMERAL. Both axes this change moves, census symmetry across the two node types and
dropping EPHEMERAL from the key set, move the analyzer toward those legacy semantics.

💡 A labelling call I have deliberately not pre-empted: two arms change results rather than turning an
error into a result, an ALIAS column shared across a table-function NATURAL JOIN becoming a key,
and an EPHEMERAL-only shared name degrading to CROSS JOIN. Both are named in the changelog entry
and in the description; whether that earns Backward Incompatible Change over Bug Fix is yours.

⚠️ Noted, not blocking, neither reproducing a failure: CollectTableExpressionData visits only the
first two USING list entries, and StorageMerge copies its alias onto each per-child TableNode.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by a fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-9:20260908-073400

@clickhouse-gh clickhouse-gh Bot closed this Sep 8, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [dfb898e]

Summary: ✅


AI Review

Summary

This PR fixes the analyzer's column-census mismatch between TABLE and TABLE_FUNCTION when resolving JOIN ... USING keys from the SELECT list, and it now preserves left-side schema order when synthesizing NATURAL JOIN keys. I reviewed the current PR head, the prior inline thread and top-level discussion, and the final QueryAnalyzer.cpp and test changes; the earlier NATURAL JOIN order regression is fixed in the current code, and I did not find any remaining issues that warrant a new review comment.

Final Verdict

✅ No new findings on the current PR head.

LLVM Coverage Report

Measured on commit dfb898e.

Metric Baseline Current Δ
Lines 89.00% 89.00% +0.00%
Functions 91.80% 91.70% -0.10%
Branches 81.40% 81.30% -0.10%

Changed lines: Changed C/C++ lines covered: 44/50 (88.00%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 4/4 on a master debug binary that already contains the previously merged fix for this message. 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); with a1 an ALIAS column on both tables. Independent of data, of the tuple(*) matcher, of LOCAL, of the join kind and of enable_join_runtime_filters.
b Root cause explained? Resolving a USING key from the SELECT list builds a synthetic column sourced at the left table expression and renames it when that name is already taken there. The census feeding the rename used GetColumnsOptions::All for TABLE but AllPhysical for TABLE_FUNCTION; AllPhysical omits ALIAS columns, so the rename never fired and two columns of one pointer-keyed source both rendered __table1.a1.
c Fix matches root cause? Yes. Only the census input changes: both helpers take the option kind from their caller, so TABLE and TABLE_FUNCTION are identical by construction, and each caller names the kind its purpose requires. A NATURAL JOIN key must be readable, so those two censuses ask for AllPhysicalAndAliases; the de-confliction census keeps All because initializeTableExpressionData registers EPHEMERAL names as column identifiers for both node types, so a synthesized name can collide with one. The rename loop, createColumnIdentifier and initializeTableExpressionData are untouched. 67b1de6dcfaf made this same change for the TABLE case.
d Test intent preserved / new tests added? Yes. All 15 pre-existing statements of 03811_join_using_top_level_matcher_type still run and pass with their 6 .reference lines byte-unchanged; this PR appends 4 statements and 4 reference lines to that file. The new 05137_natural_join_ephemeral_key (created with tests/queries/0_stateless/add-test) pins the EPHEMERAL contract, one statement per census and node type. No no-* tags: parallel-safe through currentDatabase().
e Both directions demonstrated? Yes, on one command with randomization off: on the base binary 05137 fails (Code: 16 at the first NATURAL JOIN) and 03811 kills the server (Logical error: 'Column identifier __table1.a1 is already registered'); on the fixed binary both pass, and 50 randomized runs of each give 100/100. Every behaviour change the changelog claims was measured on both binaries, including the CROSS JOIN case: Code: 16 on base, two rows on the fix, with EXPLAIN showing inner … e = e versus cross.
f Fix is general across code paths? Yes. Eight one-line mutation builds, each with its own build id and its own server whose buildId() was asserted before any verdict: the three call sites times both node types give six arms, and each mutation reddens exactly its own assertion. Reverting either table-function arm to master's AllPhysical reddens 03811; narrowing the de-confliction census restores the abort. QUERY/UNION use projection columns, JOIN/CROSS_JOIN recurse, default: returns false and both callers degrade safely.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. The census keys on column NAMES from a storage snapshot, so Nullable/LowCardinality/Array/Map/Const cannot change membership; .withSubcolumns() is preserved at all four arms and the subcolumn skip is untouched. The dimension that matters is column KIND, and all four were measured: Ordinary and MATERIALIZED (already covered, never reproduced), ALIAS (fixed), EPHEMERAL (six carriers measured before and after, including the case where an EPHEMERAL column is the only shared name). Carriers: merge over one and two tables, remote, view.
h Backward compatible? (maintainer-approved exception only) No setting default changes, so no SettingsChangesHistory.cpp entry is owed (verified: the diff touches no DECLARE( line). No format or on-disk change. Three behaviour changes, all named in the changelog entry: an ALIAS column of a table function becomes a NATURAL JOIN key, a non-selectable EPHEMERAL column ceases to be one, and consequently a NATURAL JOIN whose only shared name is EPHEMERAL degrades to CROSS JOIN under the pre-existing no-common-columns rule instead of failing with Code: 16.
i Invariants and contracts preserved? Analysis-time only: nothing is written, so there is no crash/restart re-entry path, and no locks or concurrency contracts are involved. The invariant is now stated per purpose rather than shared: a NATURAL JOIN key must be readable, and the de-confliction census must cover the EPHEMERAL names that initializeTableExpressionData registers as column identifiers. The rename loop still terminates, since each iteration lengthens the name.

Session id: cron:clickhouse-impl-slot-4:20260908-070200

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 8, 2026
@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

cc @yakov-olkhovskiy @nickitat, could you review this? The census that renames a JOIN USING key synthesized from the SELECT list asked for GetColumnsOptions::All on a TABLE but AllPhysical on a TABLE_FUNCTION, so an ALIAS column of merge() was invisible, the rename never fired, and two columns of one source rendered the same column identifier (a logical error, which aborts debug and sanitizer builds). Each census now takes its option kind from its caller, which also makes an ALIAS column a NATURAL JOIN key over a table function as it already is over a table.

Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... label Sep 8, 2026
`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.
@clickhouse-gh

clickhouse-gh Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing dfb898e34 with master 5c0934adb (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

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Job report

…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.
@alexey-milovidov alexey-milovidov self-assigned this Sep 26, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 26, 2026
Merged via the queue into ClickHouse:master with commit e5a2ebb Sep 26, 2026
176 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 26, 2026
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 comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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.

3 participants