Skip to content

Resolve JOIN USING identifier from aliases nested in the SELECT list - #110739

Merged
novikd merged 25 commits into
masterfrom
fix-analyzer-join-using-nested-alias
Jul 31, 2026
Merged

novikd merged 25 commits into
masterfrom
fix-analyzer-join-using-nested-alias

Conversation

@novikd

@novikd novikd commented Jul 16, 2026 •

Copy link
Copy Markdown
Member

Related: https://github.com/ClickHouse/clickhouse-private/issues/55715

The USING clause of a JOIN can reference an identifier defined as an expression alias inside a SELECT-list expression, typically inside an aggregate function:

SELECT uniqExact(lower(if(platform = 'android', advertising_id, idfv)) AS id) AS users_pay
FROM events AS iap
INNER JOIN (SELECT lower(...) AS id, min(event_date) AS InstallDate FROM events ...) AS sub
USING (id)

The old analyzer resolves id from the alias. The analyzer rejected it with an UNKNOWN_IDENTIFIER exception even with analyzer_compatibility_join_using_top_level_identifier = 1, because QueryAnalyzer::resolveJoin scanned only top-level projection aliases when resolving a USING identifier from the projection. The error hint suggesting the setting did not fire either, for the same reason.

Changes

  • QueryAnalyzer::resolveJoin now falls back to searching aliases defined on subexpressions of the SELECT list, reusing QueryExpressionsAliasVisitor (so lambda aliases and aliases inside nested subqueries are correctly excluded). The pre-existing top-level scan still runs first and keeps its pick-first behavior. The alias map is computed lazily, at most once per join.
  • The hint message (You may try to SET analyzer_compatibility_join_using_top_level_identifier = 1 ...) now also fires when the alias is nested. This is the only change visible with default settings.
  • The resolved node goes through the existing synthetic-subquery machinery unchanged, so all its guards (single source expression, name-conflict avoidance, JOIN-source restrictions) apply to nested aliases too.

Behavior notes

  • With the setting enabled, a nested alias takes priority over a real left-table column with the same name, matching the old analyzer. As a consequence, if such an alias expression cannot be resolved from the left table, the query now throws instead of silently falling back to the column (also matching the old analyzer); this shape is pinned by a test case.
  • Duplicated alias names in the SELECT list make the fallback bail out rather than pick an arbitrary expression, so repeated identical expr AS alias occurrences still throw under the setting (they did before this change as well).
  • Aliases defined outside the SELECT list (e.g. in WHERE), which the old analyzer treated as global, remain out of scope.

Distributed queries and parallel replicas

A USING key resolved from a nested alias cannot be re-resolved by a remote server: the query text sent to shards is rendered from the resolved tree, which keeps only top-level projection aliases (as projection names), so the shipped SQL says USING (id) with nothing named id. Instead of repairing shipped queries (an earlier attempt was reverted after it broke a top-level case under join_use_nulls), the analyzer now handles this at resolution time:

  • When a USING key is resolved from a nested SELECT-list alias and task-based parallel replicas would be used, the analyzer disables parallel replicas for every query on the scope chain containing that JOIN (allow_experimental_parallel_reading_from_replicas = 0 on the corresponding query contexts, with a LOG_DEBUG message). The whole chain is mutated because subqueries are planned independently with their own context copies. Sibling subqueries that do not contain the JOIN keep parallel replicas.
  • In force mode (enable_parallel_replicas = 2) the analyzer throws a SUPPORT_IS_DISABLED exception, mirroring the FINAL convention (including the canUseTaskBasedParallelReplicas gate, so configured-but-inert parallel replicas, e.g. max_parallel_replicas = 1, are not affected). Note this fires at analysis time, so EXPLAIN of such a query in force mode throws as well.
  • Top-level aliases are unaffected and keep parallel replicas (their names survive in the shipped SQL as projection names).
  • Over Distributed/remote (where the query must be shipped in some form), the initiator throws a clear UNSUPPORTED_METHOD exception when a nested-alias USING key cannot be resolved on the remote server at all (instead of a confusing shard-side UNKNOWN_IDENTIFIER). When the nested alias shadows a real column of the left table, the query is shipped and the remote server joins by that column, so the result may differ from local execution — this is deliberate, documented behavior (the setting description states it), pinned by a test. Top-level aliases and table ALIAS columns keep working over Distributed (their names survive in the shipped SQL). These are documented limitations vs the old analyzer, which shipped the alias definition inside the USING clause itself (USING (x + 10 AS id)); supporting that form in the new analyzer would be a separate feature.

Related: #111276

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, an identifier in JOIN ... USING can now be resolved from an alias defined on a subexpression inside the SELECT list (for example, SELECT uniqExact(lower(x) AS id) FROM t1 JOIN t2 USING (id)), matching the old analyzer behavior. Previously only top-level projection aliases were considered, and such queries failed with an UNKNOWN_IDENTIFIER exception even with the setting enabled. The error hint suggesting the setting is now also produced when the matching alias is nested.

Version info

  • Backported to: 26.7.3.11, 26.6.3.10, 26.5.7.5

novikd and others added 3 commits July 16, 2026 19:50
… list

The `USING` clause could reference an identifier defined as an expression
alias nested inside a SELECT-list expression (for example inside `uniqExact`),
which the old analyzer resolved but the new analyzer rejected with an
`UNKNOWN_IDENTIFIER` exception, even with
`analyzer_compatibility_join_using_top_level_identifier = 1`.

`QueryAnalyzer::resolveJoin` scanned only top-level projection nodes when
looking up a `USING` identifier by alias. Extract a shared helper that first
keeps the existing top-level pick-first scan, then falls back to
`QueryExpressionsAliasVisitor` over a clone of the projection list to find
aliases attached to subexpressions. The helper is used both for resolution and
for the hint message, so nested aliases now also get the
`analyzer_compatibility_join_using_top_level_identifier` suggestion. Lambda
aliases are excluded and duplicated aliases bail out to avoid picking an
arbitrary expression.

Related: ClickHouse/clickhouse-private#55715

Co-Authored-By: Claude Fable 5 <[email protected]>
Regression test for resolving `JOIN USING` identifiers from aliases nested
inside `SELECT`-list expressions under
`analyzer_compatibility_join_using_top_level_identifier = 1`.

Related: ClickHouse/clickhouse-private#55715

Co-Authored-By: Claude Fable 5 <[email protected]>
Hoist the SELECT-list alias collection out of the per-identifier loop in
`QueryAnalyzer::resolveJoin`: the map does not depend on the `USING`
identifier, so it is now computed lazily at most once per join and reused,
instead of cloning the projection list and running
`QueryExpressionsAliasVisitor` for every `USING` identifier. Pure refactor,
no behavior change.

Also add a test case pinning the priority semantics under
`analyzer_compatibility_join_using_top_level_identifier = 1` when a real
left-table column and a nested alias share the name and the alias expression
cannot be resolved from the left table: the alias wins and the query throws
an `UNKNOWN_IDENTIFIER` exception (old-analyzer-compatible), while without
the setting the column resolves.

Related: ClickHouse/clickhouse-private#55715

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

clickhouse-gh Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e8170ae]

Summary: ✅


AI Review

Summary

This PR extends analyzer_compatibility_join_using_top_level_identifier so JOIN USING can resolve aliases nested inside SELECT-list expressions, and it adds remote / parallel-replica handling for the cases that cannot be shipped verbatim. The local alias-resolution part looks directionally right, but the shipped-query guard still misses some real paths and the public docs still promise broader compatibility than the implementation now provides, so I would not merge it as-is.

Documented surface
  • docs/en/operations/analyzer.md:90-104 still tells users that setting analyzer_compatibility_join_using_top_level_identifier = true makes JOIN USING interpret the key from the projection expression, matching earlier versions.
  • This PR adds three user-visible exceptions under that same setting: nested subexpression aliases are special-cased, task-based parallel replicas are downgraded or rejected in force mode, and queries shipped through remote / Distributed can now either throw or join by a different left-side column.
  • gh search code --repo ClickHouse/clickhouse-docs 'analyzer_compatibility_join_using_top_level_identifier' only finds the mirrored analyzer page / translations, so updating docs/en/operations/analyzer.md here is the source-of-truth fix for the documented contract.
Findings
  • ❌ [src/Storages/buildQueryTreeForShard.cpp:719-720] [dismissed by author -- https://github.com/Resolve JOIN USING identifier from aliases nested in the SELECT list #110739#discussion_r3629326104] This branch knowingly ships a query after the initiator has already resolved USING (id) to the nested alias body, as soon as any real left-side id exists. 04604_join_using_nested_projection_alias_remote now pins the remote result as 0 where the same query returns 11 locally, so the PR still contains a silent wrong-result path rather than an unsupported-case guard.
  • ❌ [src/Storages/buildQueryTreeForShard.cpp:636-720] leftTableHasColumn is only a descendant-name scan, not a real "can the shard resolve this USING key from the left table expression?" check. A left subtree such as a CROSS JOIN b makes this guard return true as soon as some descendant exposes id, even when the shard can only re-analyze USING (id) as ambiguous or against the wrong descendant. That still violates the intended initiator-side UNSUPPORTED_METHOD contract for unshippable nested-alias keys.
  • ❌ [src/Storages/buildQueryTreeForShard.cpp:872-873] Gating rejectUnshippableJoinUsingKeys off planner_context->getQueryContext() misses subqueries with their own SETTINGS analyzer_compatibility_join_using_top_level_identifier = 1. Subquery SETTINGS survive in QueryNode ASTs, and resolveJoin uses each subquery's own context, so an unshippable nested-alias USING key inside such a subquery bypasses the shipping guard entirely.
  • ❌ [src/Core/Settings.cpp:7860] The public docs page docs/en/operations/analyzer.md:90-104 still states that enabling analyzer_compatibility_join_using_top_level_identifier makes JOIN USING follow the projection expression, matching the old analyzer. This PR adds remote / distributed and parallel-replica exceptions, including the accepted divergent-key case, but updates only the internal setting help text. Because this is a documented compatibility setting, the docs/en page needs the same limitation and migration guidance in the same PR.
Final Verdict

❌ Changes requested.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 16, 2026
novikd and others added 4 commits July 17, 2026 13:34
When a `JOIN USING` key is resolved from a SELECT-list alias (the
`analyzer_compatibility_join_using_top_level_identifier` mechanism, extended to
nested aliases), the query shipped to shards/replicas loses the alias name.
`resolveQuery` erases expression aliases from the resolved tree, and
`QueryNode::toAST` re-emits only top-level projection aliases from projection
names. A nested alias such as `uniqExact(lower(...) AS id)` is not a projection
name, so the shipped SQL reads `USING (id)` with nothing named `id`, and the
shard fails re-analysis with an `UNKNOWN_IDENTIFIER` exception.

Add a repair pass in `buildQueryTreeForShard` (the single choke point every
shipping path goes through, on an already-cloned tree) that walks each query's
own join tree and, for every USING key marked as resolved from a projection
alias, re-attaches the key's name to the matching projection subexpression. The
shipped SQL then reads `... AS id ... USING (id)` again, which the shard
re-resolves through the same nested-alias path (the setting travels with the
query). Plain-column USING keys carry no marker and are left untouched.

Related: ClickHouse/clickhouse-private#55715
CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110739&sha=e8c7068c16ee47f7e4c24044a786921612418ded&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel%29

Co-Authored-By: Claude Fable 5 <[email protected]>
The repair pass added for shipped-query `USING` keys assumed the shape
`resolveJoin` builds: a `ColumnNode` wrapping the alias body. By the time
`buildQueryTreeForShard` runs, the planner has inlined such alias columns,
so the left element of the `USING` key is the body itself carrying the key
name as its alias. Handle both shapes.

Also fail close when the alias body was rewritten out of the projection by an
optimization pass (e.g. `sum(x + 1 AS id)` into `sum(x) + count()`) while the
key shadows a real column of the left table: the shipped query would silently
join by that column instead of the alias expression. Throw an
`UNSUPPORTED_METHOD` exception on the initiator instead. Without shadowing the
shard keeps failing loudly on re-analysis, as before.

Related: ClickHouse/clickhouse-private#55715

Co-Authored-By: Claude Fable 5 <[email protected]>
Pins that `JOIN USING` keys resolved from nested SELECT-list aliases work
over `remote()` (the CI ParallelReplicas failure shape), plus the
fail-close behavior when an optimization pass rewrites the alias body out
of the projection so it cannot be restored in the query shipped to shards
(an exception on the initiator instead of a silent wrong join).

Related: ClickHouse/clickhouse-private#55715
CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110739&sha=e8c7068c16ee47f7e4c24044a786921612418ded&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel%29

Co-Authored-By: Claude Fable 5 <[email protected]>
…NG remote test

Cases R3 and R5 in 04604_join_using_nested_projection_alias_remote.sql
depend on RewriteSumFunctionWithSumAndCountPass rewriting
sum(x + 10) out of the projection, so that the JOIN key alias body
is dropped and an error is thrown. That pass is gated on
optimize_arithmetic_operations_in_aggregate_functions, which
clickhouse-test randomizes to 0 with probability 0.05. When
randomized off, the alias body survives and both queries succeed,
making the expected -- { serverError ... } annotations fail ~5% of
CI runs. Pin the setting explicitly to keep the test deterministic.

Related: ClickHouse/clickhouse-private#55715

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/Storages/buildQueryTreeForShard.cpp Resolved
@novikd
novikd requested review from KochetovNicolai and vdimir July 17, 2026 13:50
novikd and others added 6 commits July 21, 2026 19:32
… alias

When `analyzer_compatibility_join_using_top_level_identifier` is enabled, a
`JOIN USING` key can be resolved from an alias defined on a subexpression
nested inside the SELECT list. Such queries cannot be shipped to remote
servers: the rendered SQL keeps only top-level projection aliases, so a
replica re-analyzing `USING` cannot find the nested alias.

Instead of repairing shipped queries, `QueryAnalyzer::resolveJoin` now disables
parallel replicas for such a query at analysis time. `find_aliased_node_in_projection`
reports whether the match came from the nested branch via a per-identifier flag;
when a nested match is used, the hook walks to the root scope's mutable query
context (the same context `Planner::buildPlannerContext` uses to gate
`canUseTaskBasedParallelReplicas`) and, guarded by `INITIAL_QUERY`, clears
`allow_experimental_parallel_reading_from_replicas`, logging at debug level.
Top-level aliases become projection names in the rendered SQL and are unaffected.

In force mode (`allow_experimental_parallel_reading_from_replicas >= 2`) it throws
`SUPPORT_IS_DISABLED`, mirroring the `FINAL` convention, because silent downgrade
would violate an explicit request for parallel replicas.

Related: ClickHouse/clickhouse-private#55715
CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110739&sha=5e645254f315331a695ef749da81655f90b3da28&name_0=PR

Co-Authored-By: Claude Fable 5 <[email protected]>
…grade

The shard-repair approach was reverted; the analyzer now downgrades
parallel replicas (with a debug log) when a `JOIN USING` key resolves
from a nested SELECT-list alias, and throws `SUPPORT_IS_DISABLED` in
force mode. Nested-alias keys over `Distributed`/`remote` remain a
documented loud limitation (`UNKNOWN_IDENTIFIER` from the shard). The
test `04604_join_using_nested_projection_alias_remote` is reworked in
place to pin this contract (P1 downgrade, P2 force-mode exception,
R1/R2 loud remote errors, T1 top-level-alias control).

Related: ClickHouse/clickhouse-private#55715
CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110739&sha=5e645254f315331a695ef749da81655f90b3da28&name_0=PR

Co-Authored-By: Claude Fable 5 <[email protected]>
Addresses the final-review findings on the nested-alias `USING` parallel
replicas downgrade hook in `resolveJoin`.

- Gate the hook on `canUseTaskBasedParallelReplicas`, mirroring the `FINAL`
  precedent in the planner, instead of branching on the raw
  `allow_experimental_parallel_reading_from_replicas` value. Without the gate a
  user with `enable_parallel_replicas = 2` but `max_parallel_replicas = 1`
  (parallel replicas configured but inert) got a spurious `SUPPORT_IS_DISABLED`
  for nested-alias `USING` queries. The gate also means custom-key
  parallel-replicas modes are not downgraded - they ship full SQL and fail
  loudly on the nested alias, consistent with the accepted `Distributed`
  limitation. The redundant `== 1` value check is dropped since the gate
  already requires the setting to be positive.
- Guard the hook by intent: skip only `SECONDARY_QUERY` (replica-side) contexts
  rather than requiring `INITIAL_QUERY`, so `NO_QUERY` contexts are handled too.
- Make test case P1 self-contained: add
  `parallel_replicas_for_non_replicated_merge_tree = 1` so parallel replicas
  does not trivially skip the plain `MergeTree`, and pin
  `automatic_parallel_replicas_mode = 0` on P1 and P2 so the new gate
  deterministically exercises the downgrade / force-mode paths regardless of
  suite settings randomization. Reference values unchanged.

Related: ClickHouse/clickhouse-private#55715

Co-Authored-By: Claude Fable 5 <[email protected]>
The previous hook in `QueryAnalyzer::resolveJoin` walked to the root scope
and disabled `allow_experimental_parallel_reading_from_replicas` only on the
root query node's context. But subqueries (an `IN`, `FROM`, or `JOIN`
right-side subquery) are planned independently from their own pre-analysis
context copies. When the unshippable nested-alias `USING` JOIN sits inside
such a subquery, mutating only the root left that subquery's context free to
ship the JOIN to replicas - reproduced on a bare server as a
`CLUSTER_DOESNT_EXIST` attempt where the same JOIN at the top level was
correctly downgraded.

Every query node that CONTAINS the JOIN lies on the scope chain from the
current scope up to the root, so the hook now walks that chain and applies
the FINAL-convention downgrade to each `QueryNode`/`UnionNode` context on it.
The per-node `canUseTaskBasedParallelReplicas` check matters because
subquery-level `SETTINGS` clauses produce distinct contexts (including force
mode `>= 2`, where the throw is still correct for that subquery). Sibling
subqueries not on the chain do not hold the JOIN and keep parallel replicas.

Adds a `FROM`-subquery pin to `04604_join_using_nested_projection_alias_remote`.

Related: ClickHouse/clickhouse-private#55715

Co-Authored-By: Claude Fable 5 <[email protected]>
/// and fail loudly on the nested alias, consistent with the accepted `Distributed` limitation.
/// It is checked per node because subquery-level `SETTINGS` clauses produce distinct contexts.
if (chain_context->getClientInfo().query_kind == ClientInfo::QueryKind::SECONDARY_QUERY
|| !chain_context->canUseTaskBasedParallelReplicas())

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.

canUseTaskBasedParallelReplicas only covers the read-tasks path, so after this block the query is still free to ship to an ordinary remote/Distributed execution with a nested USING alias. That is not always a loud failure: if the left source really has a physical id column, the initiator resolves USING (id) to the nested alias, but the SQL sent to the shard no longer contains that alias, so the shard re-analyzes USING (id) against the real column and joins on a different key. This turns the change into a silent wrong-result regression for distributed queries that used to fail with UNKNOWN_IDENTIFIER.

Please either reject nested SELECT-list aliases whenever the query can be shipped to another server, or preserve enough metadata to rebuild the alias on the shard. At minimum, the shadowing case needs to throw instead of silently falling back to the physical column.

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.

Confirmed — the shadowing case produced silently wrong results over Distributed/remote (verified: 22 on the old analyzer vs a silent 0), a regression vs the previous loud UNKNOWN_IDENTIFIER. Fixed in f01148c by not supporting nested-alias USING keys for queries sent to remote servers at all: buildQueryTreeForShard now throws a clear UNSUPPORTED_METHOD exception on the initiator for both the shadowing and non-shadowing shapes. Top-level aliases (re-emitted as projection names in the shipped SQL) and table ALIAS columns are excluded and keep working; both exclusions and the rejection are pinned in 04604_join_using_nested_projection_alias_remote (722c525).

One note on scope: custom-key parallel-replicas modes were already covered — the planner disables custom-key parallel replicas for any query with more than one table expression, which every JOIN USING query has.

Rebuilding the alias on the shard (the old analyzer ships USING (x + 10 AS id) — the alias definition inside the USING clause) would be the full-support alternative, but the new analyzer's USING resolution does not accept aliased expressions; left as a possible future feature.

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.

src/Storages/buildQueryTreeForShard.cpp:699-705 still lets the original wrong-result case through when the same query also projects any top-level output named like the USING key. hasProjectionColumn(query_node, name) is true for an ordinary projected id, so the visitor treats the nested-alias key as safe and skips the UNSUPPORTED_METHOD exception.

Minimal shape:

SELECT id, sum(x + 10 AS id)
FROM remote('127.0.0.{1,2}', currentDatabase(), t_shadow2) AS tsh
JOIN (SELECT 11 AS id) t2 USING (id);

The initiator still resolves USING (id) to the nested alias body x + 10, but the shipped query no longer contains that nested alias. src/Analyzer/QueryNode.cpp:509-517 reattaches every projection output name as a top-level alias when serializing, so the shard sees a top-level id again and re-resolves USING (id) against the projected/physical id column instead of x + 10. That is the same silent divergence as the original thread, just with an extra projected id column in the SELECT list.

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.

Update after an owner decision: the guard was simplified in db0addb. The initiator now throws UNSUPPORTED_METHOD only when the USING key cannot be resolved on the remote server at all (no top-level alias in the shipped SQL and no left-table column). The shadowing case is shipped again: the remote server joins by the real column, so the result may differ from local execution — this divergence is accepted, documented in the setting description, and pinned by a test case in 04604_join_using_nested_projection_alias_remote (505e2f8). #111276 stays open to document it.

novikd and others added 7 commits July 21, 2026 21:52
`JOIN USING` keys resolved from an alias nested in the SELECT list (the
`analyzer_compatibility_join_using_top_level_identifier` mechanism, extended to
nested aliases) are not supported for queries sent to remote servers
(`Distributed` tables, the `remote` table function). The rendered SQL keeps only
top-level projection aliases, so a shard cannot re-resolve such a key: today it
either fails re-analysis with `UNKNOWN_IDENTIFIER` or, when the nested alias
shadows a real left-table column, silently returns wrong results.

Add a small visitor in `buildQueryTreeForShard` (run right after
`createUniqueAliasesIfNecessary`, on the already-cloned shipping tree) that walks
each query's own join tree and throws `UNSUPPORTED_METHOD` for a USING key marked
as resolved from a nested alias. Two exclusions keep it precise:

- Top-level aliases become projection names in the rendered SQL and re-resolve on
  the shard, so a key whose name is in the enclosing query's projection columns is
  spared (this is the old-analyzer wire behavior).
- A genuine table `ALIAS` column used in USING is spared: its wrapper name equals
  the key name AND the key name is a real column of the JOIN's left table
  expression. A shadowing nested alias is `_`-prefixed (wrapper name differs) and a
  non-shadow nested alias is not a real left column, so neither is spared.

Also shorten the comments this branch added to `QueryAnalyzer.cpp` (comment-only
change there) to one line each, keeping only the load-bearing fact, and extend the
`analyzer_compatibility_join_using_top_level_identifier` description to note the
remote-server limitation.

Related: ClickHouse/clickhouse-private#55715
Related: #111276

Co-Authored-By: Claude Fable 5 <[email protected]>
The initiator-side guard now throws `UNSUPPORTED_METHOD` for every
nested-alias `USING` key in a query shipped to `Distributed`/`remote`
(top-level aliases and table `ALIAS` columns excluded). Update
`04604_join_using_nested_projection_alias_remote` to pin that contract:
retarget R1/R2 to the loud initiator-side rejection, add the owner's
minimal repro, the shadowing variant that used to return silently wrong
data (now an exception, not a crash), and an `ALIAS`-column positive
control that still ships and returns.

Related: ClickHouse/clickhouse-private#55715
Related: #111276

Co-Authored-By: Claude Fable 5 <[email protected]>
`leftTableHasColumn` in `buildQueryTreeForShard.cpp` only recognized
`TableNode` when checking whether a `USING` key is a genuine table
`ALIAS` column; add a matching `TableFunctionNode` branch so the check
stays symmetric when a table function survives into the shipped join
tree. Also clarify two nearby comments: name the `Distributed`-path
alias-inlining visitor (`ReplaseAliasColumnsVisitor`, misspelling
verified in `StorageDistributed.cpp`), and spell out that the
`leftTableHasColumn` doc comment means "not a query-level alias".
Reword a test comment to attribute the repro to the PR review rather
than "the owner".

Related: ClickHouse/clickhouse-private#55715

Co-Authored-By: Claude Fable 5 <[email protected]>
Owner-requested pure refactor of `RejectNestedAliasJoinUsingKeyVisitor` in
`buildQueryTreeForShard.cpp`; no behavior change.

Rebase the visitor on `InDepthQueryTreeVisitorWithContext` and let the standard
DFS traversal do the walking: an enter/leave stack of enclosing `QueryNode`s
binds each `JoinNode` to its nearest `QueryNode` ancestor (the same association
the recursive `walkJoinTree` computed), so the explicit
`CrossJoinNode`/`ArrayJoinNode`/terminator dispatch is deleted. Convert
`leftTableHasColumn` from self-recursion to a flat worklist loop with identical
node-kind coverage. `checkJoin`, `hasProjectionColumn`, the exclusion logic, and
the throw message are unchanged.

Related: ClickHouse/clickhouse-private#55715

Co-Authored-By: Claude Fable 5 <[email protected]>
Rewrite the shipping guard for `JOIN USING` keys resolved from an alias
nested in the `SELECT` list. The guard is now a plain `while()` loop
(`rejectUnshippableJoinUsingKeys`) instead of a visitor class; the enclosing
query travels with each node so a `JOIN USING` is checked against its own
projection, which keeps top-level-alias keys (case B) working.

Owner decision: throw only when nothing on the remote server can resolve the
key. A key that names a real column of the left table is now shipped even when
an alias shadows that column (case E) — the shard joins by the shadowed column,
so results may differ from local execution. This is accepted, documented
behavior, not a bug fix. The wrapper-name extraction and the shadow
discriminator are deleted; the marker shrinks to a boolean entry filter.

The setting description for `analyzer_compatibility_join_using_top_level_identifier`
is updated accordingly: the remote-server exception is raised only when the
identifier cannot be resolved on the remote server at all.

Related: ClickHouse/clickhouse-private#55715
Related: #111276

Co-Authored-By: Claude <[email protected]>
The `R4` shadowing case in `04604_join_using_nested_projection_alias_remote`
no longer throws `UNSUPPORTED_METHOD`: when the nested alias in `USING`
shadows a real left-table column, the shard resolves the shadowed column
and ships the query, so the result deliberately differs from the local
execution result.

Related: ClickHouse/clickhouse-private#55715
Related: #111276

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/Storages/buildQueryTreeForShard.cpp Resolved
@vdimir vdimir self-assigned this Jul 22, 2026
Unshippable `USING` keys can only be produced by the projection-alias
resolution, which is gated by
`analyzer_compatibility_join_using_top_level_identifier`. Skip the
`rejectUnshippableJoinUsingKeys` walk entirely when the setting is off.

Related: ClickHouse/clickhouse-private#55715

Co-Authored-By: Claude Fable 5 <[email protected]>

/// Reject `JOIN USING` keys that no remote server can resolve; keys the shard can re-resolve are shipped.
/// Such keys can only be produced by the projection-alias resolution, so check only when it is enabled.
if (planner_context->getQueryContext()->getSettingsRef()[Setting::analyzer_compatibility_join_using_top_level_identifier])

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.

rejectUnshippableJoinUsingKeys cannot be gated off the root planner_context setting here. A nested SELECT ... SETTINGS analyzer_compatibility_join_using_top_level_identifier = 1 still goes through the new nested-alias resolution inside resolveJoin, but planner_context->getQueryContext() stays at the outer query's value. In that shape we will synthesize an unshippable nested-alias USING key inside the subquery and then skip this check entirely, so the serialized query sent to shards loses the nested alias and gets re-analyzed there with different semantics (or a shard-side exception).

This should either run unconditionally, or consult each walked QueryNode / UnionNode context instead of the root query context.

novikd and others added 2 commits July 30, 2026 17:38
…sing-nested-alias

# Conflicts:
#	src/Analyzer/Resolve/QueryAnalyzer.cpp
The accessor renames for the `ITableExpressionNode` API landed in the
working tree during the merge conflict resolution but were not staged into
the merge commit (`git merge` had already auto-staged the auto-merged file).

Related: ClickHouse/clickhouse-private#55715

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/Core/Settings.cpp
)", IMPORTANT, enable_analyzer) \
DECLARE(Bool, analyzer_compatibility_join_using_top_level_identifier, false, R"(
Force to resolve identifier in JOIN USING from projection (for example, in `SELECT a + 1 AS b FROM t1 JOIN t2 USING (b)` join will be performed by `t1.a + 1 = t2.b`, rather then `t1.b = t2.b`).
Force to resolve identifier in JOIN USING from projection (for example, in `SELECT a + 1 AS b FROM t1 JOIN t2 USING (b)` join will be performed by `t1.a + 1 = t2.b`, rather then `t1.b = t2.b`). Aliases defined on subexpressions inside the SELECT list are also considered (for example, in `SELECT uniqExact(a + 1 AS b) FROM t1 JOIN t2 USING (b)` the join is performed by `t1.a + 1 = t2.b`). When the matching alias is defined on a subexpression inside the SELECT list rather than as a top-level alias, parallel replicas are disabled for the query. For queries sent to remote servers (`Distributed` tables, the `remote` table function), such a query is rejected with an exception only when the identifier cannot be resolved on the remote server at all; if the alias shadows a real column of the left table, the remote server joins by that column instead, so the results may differ from local execution.

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.

docs/en/operations/analyzer.md:90-104 is still the public contract for analyzer_compatibility_join_using_top_level_identifier, and it currently says that enabling the setting makes JOIN USING use the projection expression, matching the old analyzer. This PR adds material exceptions under the same setting: nested aliases inside subexpressions only work locally, task-based parallel replicas are downgraded or rejected in force mode, and remote / Distributed may either throw or even join by a different left-side column.

Updating only the Settings.cpp help text leaves the documented flow in docs/en contradicted. Please update docs/en/operations/analyzer.md in the same PR with the new remote / parallel-replica limitations and the accepted divergence case.

@clickhouse-gh

clickhouse-gh Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.40% 86.50% +0.10%
Functions 91.80% 91.90% +0.10%
Branches 78.50% 78.60% +0.10%

Changed lines: Changed C/C++ lines covered: 155/182 (85.16%) · Uncovered code

Full report · Diff report

@novikd
novikd added this pull request to the merge queue Jul 31, 2026
Merged via the queue into master with commit 62574fc Jul 31, 2026
351 of 352 checks passed
@novikd
novikd deleted the fix-analyzer-join-using-nested-alias branch July 31, 2026 15:38
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Jul 31, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 31, 2026
robot-clickhouse added a commit that referenced this pull request Aug 3, 2026
Cherry pick #110739 to 26.5: Resolve JOIN USING identifier from aliases nested in the SELECT list
robot-clickhouse added a commit that referenced this pull request Aug 3, 2026
robot-clickhouse added a commit that referenced this pull request Aug 3, 2026
Cherry pick #110739 to 26.6: Resolve JOIN USING identifier from aliases nested in the SELECT list
robot-clickhouse added a commit that referenced this pull request Aug 3, 2026
robot-clickhouse added a commit that referenced this pull request Aug 3, 2026
Cherry pick #110739 to 26.7: Resolve JOIN USING identifier from aliases nested in the SELECT list
robot-clickhouse added a commit that referenced this pull request Aug 3, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 3, 2026
clickhouse-gh Bot added a commit that referenced this pull request Aug 4, 2026
Backport #110739 to 26.7: Resolve JOIN USING identifier from aliases nested in the SELECT list
novikd added a commit that referenced this pull request Aug 4, 2026
Backport #110739 to 26.5: Resolve JOIN USING identifier from aliases nested in the SELECT list
novikd added a commit that referenced this pull request Aug 6, 2026
Backport #110739 to 26.6: Resolve JOIN USING identifier from aliases nested in the SELECT list
cursor Bot pushed a commit that referenced this pull request Aug 6, 2026
When a `USING` key resolves to an alias nested in the `SELECT` list and the left table also has a real
column of that name, only top-level aliases survive into the shipped SQL, so the shard cannot see the
nested one and joins by the real column instead. The key is shipped rather than rejected by an explicit
owner decision recorded at
#110739 (comment), with
#111276 left open to document it.

`04604` already pins that decision on the query level. Pinning it here on the values as well - 11 local
against 0 distributed for the same data - so that revisiting the decision shows up as a diff rather than
as a silent change. The section behaves identically on master.

Co-authored-by: Yakov Olkhovskiy <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.4-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants