Skip to content

Fix MULTIPLE_EXPRESSIONS_FOR_ALIAS for distributed JOIN with same-named ALIAS columns - #108025

Closed
yakov-olkhovskiy wants to merge 4 commits into
masterfrom
cursor/distributed-join-same-name-alias-3628
Closed

yakov-olkhovskiy wants to merge 4 commits into
masterfrom
cursor/distributed-join-same-name-alias-3628

Conversation

@yakov-olkhovskiy

@yakov-olkhovskiy yakov-olkhovskiy commented Jun 20, 2026 •

Copy link
Copy Markdown
Member

Closes: #107990

When a Distributed query JOINs two tables that each define an ALIAS column with the same name, and that name is referenced in an expression clause (WHERE/GROUP BY/ORDER BY/HAVING/JOIN ON), the query failed during analysis with MULTIPLE_EXPRESSIONS_FOR_ALIAS:

CREATE TABLE a_local (id UInt64, x UInt64, foo UInt64 ALIAS x) ENGINE = MergeTree ORDER BY id;
CREATE TABLE b_local (id UInt64, x UInt64, foo UInt64 ALIAS x) ENGINE = MergeTree ORDER BY id;
CREATE TABLE a_dist AS a_local ENGINE = Distributed(test_cluster_two_shards_localhost, currentDatabase(), a_local, rand());
CREATE TABLE b_dist AS b_local ENGINE = Distributed(test_cluster_two_shards_localhost, currentDatabase(), b_local, rand());

SELECT l.id FROM a_dist AS l INNER JOIN b_dist AS r ON l.id = r.id
WHERE l.foo > 0 AND r.foo > 0
SETTINGS distributed_product_mode = 'local';
-- Multiple expressions __table2.x AS foo and __table1.x AS foo for alias foo. (MULTIPLE_EXPRESSIONS_FOR_ALIAS)

Root cause

For shard transport, ALIAS columns are inlined into their defining expressions and the bare column name was re-applied as an alias on every inlined expression. After createUniqueAliasesIfNecessary qualifies the table sources, the two structurally different expressions __table1.x and __table2.x both carry the alias foo in one scope, which the analyzer rejects.

Fix

The inlined alias only needs to preserve the logical column name for top-level projection items (so the mergeable-state output column keeps its name). Inside expression clauses and nested expressions the alias is redundant and only creates the conflicting scope entry, so the inliner now sets the alias only for top-level projection items. Grouping/sorting/filtering still match the projection by expression (action node name), independent of the SQL alias. Each inlined expression is cloned so per-occurrence aliasing does not mutate shared nodes.

This is new-analyzer only.

Inliner consolidation

This PR also consolidates the ALIAS-column inliner into a single shared helper inlineAliasColumnsForDistributed in buildQueryTreeForShard. Previously the shard-transport inliner lived in StorageDistributed while a second copy (InlineAliasColumnsForNamingVisitor, added by #107913 for shard-header name computation) lived in buildQueryTreeForShard. Both now use the one implementation; name computation reuses the no-alias inliner (aliasing is irrelevant for action node names). The duplicate-ALIAS column-count fix (#107913) keeps working — verified by 04357_distributed_alias_same_expression.

Tests

04401_distributed_alias_name_collision covers same-named ALIAS columns referenced in WHERE, GROUP BY, ORDER BY, a projection expression, and a GLOBAL JOIN subquery (the original report), each checked for correct results.

Related: #107913
Related: #79916

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 MULTIPLE_EXPRESSIONS_FOR_ALIAS error when querying a Distributed table with a JOIN where both tables have an ALIAS column of the same name referenced in WHERE/GROUP BY/ORDER BY/JOIN ON.

Open in Web Open in Cursor 

…ed ALIAS columns

When a Distributed query JOINs two tables that each define an `ALIAS` column with the same name and
the name is referenced in an expression clause (`WHERE`/`GROUP BY`/`ORDER BY`/`HAVING`/`JOIN ON`),
inlining the `ALIAS` columns for shard transport re-applied the bare column name as an alias on each
inlined expression. After unique table aliases are assigned the two different expressions
(`__table1.x` and `__table2.x`) ended up sharing one alias in the same scope, which the analyzer
rejects with `MULTIPLE_EXPRESSIONS_FOR_ALIAS`, e.g.:

    SELECT l.id FROM a_dist AS l INNER JOIN b_dist AS r ON l.id = r.id
    WHERE l.foo > 0 AND r.foo > 0;   -- a.foo and b.foo are both `ALIAS x`

The inlined alias only needs to preserve the logical column name for top-level projection items (so
the mergeable-state output column keeps its name). Inside expression clauses and nested expressions
the alias is redundant and only creates the conflicting scope entry. The inliner now sets the alias
only for top-level projection items, and clones each inlined expression so per-occurrence aliasing
does not mutate shared nodes.

This is new-analyzer only.

Closes: #107990

Co-authored-by: Yakov Olkhovskiy <[email protected]>
@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@clickhouse-gh

clickhouse-gh Bot commented Jun 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [71bb389]

Summary: ✅


AI Review

Summary

This PR consolidates the distributed ALIAS-column inliner and narrows alias preservation to top-level projection items to avoid MULTIPLE_EXPRESSIONS_FOR_ALIAS in distributed JOIN queries. The added JOIN ON regression now covers the previously missing branch, but one alias-cleanup gap remains in the current code, so I would not merge yet.

Findings

⚠️ Majors

  • [src/Storages/buildQueryTreeForShard.cpp:821] The inliner promises that expression clauses do not retain aliases from inlined ALIAS columns, but getInlineableAliasColumnExpression clones the stored expression and inserts it without clearing aliases already present inside that expression. Valid definitions like foo UInt64 ALIAS (x AS v) can still produce two different inlined expressions with alias v in one remote-analysis scope for WHERE or JOIN ON, preserving the original MULTIPLE_EXPRESSIONS_FOR_ALIAS failure. Suggested fix: clear aliases recursively on the cloned expression before using it in expression clauses, stopping at QUERY/UNION/LAMBDA boundaries like the analyzer alias cleanup, and only set the output alias for the top-level projection case.
Tests
  • ⚠️ Add a focused regression where both distributed tables define the same-named ALIAS column using an alias-bearing expression, for example foo UInt64 ALIAS (x AS v), and reference both sides in WHERE and JOIN ON. That is the remaining path where the current clone can still leak aliases into the remote query scope.
Final Verdict

Status: ⚠️ Request changes

Minimum required action: clear aliases recursively on cloned inlined expressions for non-projection use and add the focused nested-alias regression test.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 20, 2026
cursoragent and others added 2 commits June 23, 2026 12:26
…join-same-name-alias-3628

Co-authored-by: Yakov Olkhovskiy <[email protected]>
… helper

After merging master (which brought in #107913), there were two copies of the ALIAS-column
inliner: the shard-transport inliner in `StorageDistributed` (introduced by this PR for #107990) and
the name-computation inliner `InlineAliasColumnsForNamingVisitor` added by #107913 in
`buildQueryTreeForShard`.

Unify them: the projection-aware inliner now lives in `buildQueryTreeForShard` and is exposed as
`inlineAliasColumnsForDistributed`. `StorageDistributed::buildQueryTreeDistributed` calls it, and the
name-computation path (`actionNameAfterAliasInlining`) reuses the same no-alias inliner. Aliasing is
irrelevant for name computation — action node names come from the column identifier / expression, not
the SQL alias — so the shared inliner yields the same name the shard assigns.

No behavior change: the duplicate-ALIAS column-count fix (#107913) and the same-named JOIN ALIAS
collision fix (#107990) both keep working.

Co-authored-by: Yakov Olkhovskiy <[email protected]>
@yakov-olkhovskiy
yakov-olkhovskiy marked this pull request as ready for review June 23, 2026 18:00
|| column_source->getNodeType() == QueryTreeNodeType::ARRAY_JOIN)
return nullptr;

return column_node->getExpression()->clone();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This still preserves aliases that were already present in the stored ALIAS expression. ClickHouse accepts definitions like foo UInt64 ALIAS (x AS v); after this clone, a non-projection use such as WHERE l.foo > 0 AND r.foo > 0 or JOIN ON l.foo = r.foo can still put two different expressions with alias v into the same remote-analysis scope, so the original MULTIPLE_EXPRESSIONS_FOR_ALIAS exception is still possible. Please clear aliases on the cloned expression before using it in expression clauses (recursively, with the same nested-scope boundaries as the analyzer alias cleanup), while still setting the output alias for the top-level projection case.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Such aliases don't survive resolution - they only serve as references inside the same column's defining expression and don't leak into the outer scope. By the time the inliner clones getExpression() it's already the resolved, alias-free expression ((x AS v) -> COLUMN x, and even (x AS v) + v -> plus(x, x)), so there's no alias left to collide.

The PR covers same-named ALIAS columns referenced in JOIN ON, but the test only
referenced them in WHERE/GROUP BY/ORDER BY/projection. Add a focused case
(ON l.id = r.id AND l.foo > 0 AND r.foo > 0) so the join-tree branch of the
inliner is exercised.

Co-authored-by: Yakov Olkhovskiy <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.40% 85.30% -0.10%
Functions 92.60% 92.50% -0.10%
Branches 77.60% 77.60% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 41/43 (95.35%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

cursor Bot pushed a commit that referenced this pull request Aug 5, 2026
Inlining an `ALIAS` column by mutating its stored expression and stamping the column's name on it puts
the same alias on two different bodies whenever two `JOIN` sides declare a same-named `ALIAS` column,
and the remote side then throws `MULTIPLE_EXPRESSIONS_FOR_ALIAS`. With the shipped query converted back
to SQL this surfaces through `ORDER BY`, which keeps both references:

    ORDER BY __table1.v * 2 AS a_v DESC, __table2.v * 2 AS a_v DESC

Clone the defining expression per occurrence and set the alias only on top-level projection items, where
it is needed to keep the mergeable-state output column's name. References inside `WHERE` / `GROUP BY` /
`ORDER BY` / `HAVING` / `JOIN ON` are inlined bare. Nested subqueries and unions are recursed into as
queries so their own projections keep their names. This is the inliner from
#108025, which becomes redundant once this lands.

Closes: #107990

Co-authored-by: Yakov Olkhovskiy <[email protected]>
cursor Bot pushed a commit that referenced this pull request Aug 5, 2026
`04757` grows the shapes it was missing relative to #113364's own matrix: two `ALIAS` columns with
identical bodies, `ARRAY JOIN` on either side, `GLOBAL RIGHT JOIN`, and `GLOBAL JOIN ... USING` both
selecting the key and selecting an `ALIAS` column beside it.

`04758` is the #107990 regression test from #108025,
covering the same-named `ALIAS` column referenced from `JOIN ON` / `WHERE` / `GROUP BY` / `ORDER BY` /
a projection expression / a `GLOBAL JOIN` subquery over real `Distributed` tables. It reports six
`MULTIPLE_EXPRESSIONS_FOR_ALIAS` on master.

`04759` is the laziness test from #113364: an `ALIAS`
column of a shipped table expression must be computed once per row on every dispatch path. Inlining
keeps that property, so the reference is identical to that pull request's. On master the
`parallel_replicas_local_plan=1` arm throws instead of reporting a count.

Co-authored-by: Yakov Olkhovskiy <[email protected]>
@yakov-olkhovskiy

Copy link
Copy Markdown
Member Author

closing in favor of #107700

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

MULTIPLE_EXPRESSIONS_FOR_ALIAS on Distributed JOIN when both tables have an ALIAS column with the same name

3 participants