Skip to content

Resolve JOIN USING identifier from aliases defined in WITH and other clauses - #121975

Merged
vdimir merged 4 commits into
masterfrom
vdimir/join-using-with-clause-alias
Oct 1, 2026
Merged

vdimir merged 4 commits into
masterfrom
vdimir/join-using-with-clause-alias

Conversation

@vdimir

@vdimir vdimir commented Sep 24, 2026 •

Copy link
Copy Markdown
Member

Closes: #121401
Related: #110739

With analyzer_compatibility_join_using_top_level_identifier = 1 the USING identifier was looked up among the aliases of the SELECT list only: top-level aliases and, since #110739, aliases nested in SELECT list expressions. An alias defined in the WITH clause was not found, so the query from the issue failed with UNKNOWN_IDENTIFIER while the old analyzer accepted it:

WITH lower(if(platform = 'ios', idfv, advertising_id)) AS id, dateDiff('day', InstallDate, event_date) AS lifetime
SELECT lifetime, count() AS users
FROM events
INNER JOIN (WITH lower(if(platform = 'ios', idfv, advertising_id)) AS id SELECT id, event_date AS InstallDate FROM installs) USING (id)
GROUP BY lifetime ORDER BY lifetime;

The WITH section is removed from the query node before the join tree is resolved, but the scope alias table already holds an unresolved clone of every aliased expression of the query, WITH included: identifiers are resolved through fresh clones of these entries, so they stay unresolved at that point. The lookup now uses that table after the top-level SELECT list check, instead of re-collecting the SELECT list aliases per join. As a consequence an alias defined in any clause is considered, which is what the old analyzer did: SELECT sum(x) FROM t1 JOIN t2 USING (id) WHERE (x + 1 AS id) > 0 joins by x + 1. Test 04603 pinned the opposite for a WHERE alias and is updated.

Duplicated aliases are now refused only when their definitions differ. Identical definitions, for example WITH x + 1 AS id SELECT sum(x + 1 AS id) FROM t1 JOIN t2 USING (id), were refused before and are accepted by the old analyzer.

A key resolved this way is treated like a nested SELECT list alias for shipping: parallel replicas are disabled for the query, and Distributed tables and remote reject it on the initiator unless the key is also a top-level SELECT list column. The behaviour was compared against the old analyzer (26.3 with enable_analyzer = 0). The remaining known difference is prefer_column_name_to_alias = 1, which the old analyzer honoured inside USING and the compatibility setting never did, for SELECT list aliases as well.

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

With analyzer_compatibility_join_using_top_level_identifier = 1, a JOIN USING identifier is now also resolved from an alias defined in the WITH clause or in another clause of the query, not only from the SELECT list, and duplicated aliases with identical definitions no longer prevent the resolution. Closes #121401.

🤖 Generated with Claude Code


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

Version info

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

vdimir and others added 3 commits September 23, 2026 18:06
With `analyzer_compatibility_join_using_top_level_identifier = 1` the `USING`
identifier was looked up among `SELECT` list aliases only, so an alias defined
in the `WITH` clause was not found and the query failed with
`UNKNOWN_IDENTIFIER`. The `WITH` section is removed from the query node before
the join tree is resolved; keep its nodes in the scope and include their
aliases in the lookup. Such a key is treated like a nested `SELECT` list alias
for parallel replicas and remote shipping, since the rendered query loses it.

Closes: #121401

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The alias lookup for `analyzer_compatibility_join_using_top_level_identifier`
refused an alias with several definitions even when all of them are the same
expression, while the old analyzer accepted such queries, for example
`WITH x + 1 AS id SELECT sum(x + 1 AS id) FROM t1 JOIN t2 USING (id)`.
Compare the definitions and refuse only conflicting ones.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…py of the `WITH` section

The scope already holds an unresolved clone of every aliased expression of the
query, the `WITH` section included: identifiers are resolved through fresh
clones of these entries, so they stay unresolved while the join tree is
resolved. Use it for the `analyzer_compatibility_join_using_top_level_identifier`
lookup instead of keeping the `WITH` nodes in the scope and re-collecting the
`SELECT` list aliases per join.

As a consequence an alias defined in any clause, not only in `WITH` or the
`SELECT` list, is considered, which is what the old analyzer did: for example
`SELECT sum(x) FROM t1 JOIN t2 USING (id) WHERE (x + 1 AS id) > 0` joins by
`x + 1`. Test 04603 pinned the opposite for a `WHERE` alias and is updated.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [672ecfe]

Summary: ✅


AI Review

Summary

This PR expands analyzer_compatibility_join_using_top_level_identifier so JOIN USING can resolve keys from WITH and other query-clause aliases and updates the remote-shipping / parallel-replica handling for those keys. The compatibility path is still incomplete: chained aliases still lose their enclosing alias scope, semantically identical duplicate aliases are still compared in unresolved form, and conflicting non-top-level aliases can silently fall back to a same-named real left-table column instead of being refused.

Findings

❌ Blockers

  • [src/Analyzer/Resolve/QueryAnalyzer.cpp:6052] Chained query aliases still stop working once the alias body is re-resolved inside the synthetic left-side subquery. WITH x + 1 AS a, a AS id SELECT ... USING (id) clones a AS id, then resolves it in a new scope created with parent_scope = nullptr, so alias a is lost and the query still fails (or binds to a real a column if one exists). Carry the current alias environment into that synthetic scope and add a regression test for chained aliases in WITH / other clauses.
  • [src/Analyzer/Resolve/QueryAnalyzer.cpp:6060] The duplicate-alias compatibility check still compares unresolved trees, so semantically identical definitions such as WITH x + 1 AS id, x + 1 AS a, a AS id ... USING (id) are rejected even though the canonical duplicate-alias pass would resolve both sides to x + 1 and accept them. Normalize both sides the same way as the main duplicate-alias validation before deciding that the alias is conflicting.
  • [src/Analyzer/Resolve/QueryAnalyzer.cpp:6060] Conflicting non-top-level aliases are only treated as “no alias found”, which lets the resolver fall through to the plain left-column lookup. With WITH x + 1 AS id, x + 2 AS id SELECT ... FROM (SELECT 1 AS x, 5 AS id) t1 JOIN (SELECT 2 AS id) t2 USING (id), the query now joins by t1.id instead of refusing the ambiguous alias, violating the PR’s contract that differing duplicate aliases must still be rejected. Once a conflicting alias match is detected, suppress the left-column fallback (or throw immediately) and add a regression test with a real same-named left column.
Tests
  • ⚠️ Missing regression coverage for chained aliases (WITH x + 1 AS a, a AS id ... USING (id)) and for conflicting duplicate aliases when the left table also has a real column with that name.
Final Verdict

Changes requested.

LLVM Coverage Report

Measured on commit 672ecfe.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.60% 79.60% +0.00%

Changed lines: Changed C/C++ lines covered: 60/61 (98.36%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 24, 2026
/// A lambda alias must not become a USING column.
auto it = select_list_aliases->alias_name_to_expression_node.find(identifier_full_name_);
if (it == select_list_aliases->alias_name_to_expression_node.end())
const auto & aliases = scope.aliases;

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.

Pulling an unresolved node straight out of scope.aliases is only half of the fix here. The matched body is still re-resolved inside the synthetic subquery created a few lines below with parent_scope = nullptr, so chained query aliases are still lost. A query like WITH x + 1 AS a, a AS id SELECT sum(x) FROM (SELECT 1 AS x) t1 JOIN (SELECT 2 AS id) t2 USING (id) reaches this branch, clones a AS id, and then the synthetic subquery no longer has alias a, so it throws UNKNOWN_IDENTIFIER (or silently binds to a real a column if one exists). Since the PR now says aliases from WITH and other clauses are supported, I think this needs the current alias environment carried into that synthetic resolution path, plus a regression test for alias chaining.

for (const auto & duplicated_node : aliases.nodes_with_duplicated_aliases)
{
if (duplicated_node->hasAlias() && duplicated_node->getAlias() == identifier_full_name_)
if (duplicated_node->hasAlias() && duplicated_node->getAlias() == identifier_full_name_ && !duplicated_node->isEqual(*it->second))

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 duplicate check is stricter than the normal duplicate-alias validation later in resolveQuery, because here we compare the unresolved trees directly. A case like WITH x + 1 AS id, x + 1 AS a, a AS id SELECT sum(x) FROM (SELECT 1 AS x) t1 JOIN (SELECT 2 AS id) t2 USING (id) will pick the first id, see the duplicate a AS id, and reject it here even though the end-of-query duplicate pass would resolve a to x + 1 and accept the definitions as identical. That contradicts the new "identical duplicated aliases are accepted" behavior from the PR description and tests, so this path needs to normalize/resolve both sides the same way as the canonical duplicate check.

@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 24, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 672ecfe95 with master 5353f5fc0 (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

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

Job report

@novikd novikd self-assigned this Sep 25, 2026
@vdimir
vdimir force-pushed the vdimir/join-using-with-clause-alias branch from b451812 to 672ecfe Compare September 30, 2026 13:06
for (const auto & duplicated_node : aliases.nodes_with_duplicated_aliases)
{
if (duplicated_node->hasAlias() && duplicated_node->getAlias() == identifier_full_name_)
if (duplicated_node->hasAlias() && duplicated_node->getAlias() == identifier_full_name_ && !duplicated_node->isEqual(*it->second))

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.

The duplicate-alias guard only returns nullptr, so this path can still fall through to the plain left-column lookup below. With analyzer_compatibility_join_using_top_level_identifier = 1, WITH x + 1 AS id, x + 2 AS id SELECT sum(x) FROM (SELECT 1 AS x, 5 AS id) t1 JOIN (SELECT 2 AS id) t2 USING (id) now joins by t1.id instead of refusing the ambiguous alias, even though the PR contract says differing duplicate aliases should still be rejected. This needs to suppress the left-table fallback (or throw immediately) once a conflicting non-top-level alias was found, and it needs a regression test with a real id column on the left side.

@vdimir
vdimir added this pull request to stack #123104 September 30, 2026 16:21
@vdimir
vdimir added this pull request to the merge queue Oct 1, 2026
Merged via the queue into master with commit 4e72b65 Oct 1, 2026
150 checks passed
@vdimir
vdimir deleted the vdimir/join-using-with-clause-alias branch October 1, 2026 08:55
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... 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.

Analyzer: UNKNOWN_IDENTIFIER when alias is defined in WITH clause and analyzer_compatibility_join_using_top_level_identifier=1

3 participants