Skip to content

Cherry pick #110739 to 26.7: Resolve JOIN USING identifier from aliases nested in the SELECT list - #112772

Merged
robot-clickhouse merged 27 commits into
backport/26.7/110739from
cherrypick/26.7/110739
Aug 3, 2026
Merged

robot-clickhouse merged 27 commits into
backport/26.7/110739from
cherrypick/26.7/110739

Conversation

@robot-ch-test-poll

Copy link
Copy Markdown
Contributor

Original pull-request #110739

Do not merge this PR manually

This pull-request is a first step of an automated backporting.
It contains changes similar to calling git cherry-pick locally.
If you intend to continue backporting the changes, then resolve all conflicts if any.
Otherwise, if you do not want to backport them, then just close this pull-request.

The check results does not matter at this step - you can safely ignore them.

Troubleshooting

If the conflicts were resolved in a wrong way

If this cherry-pick PR is completely screwed by a wrong conflicts resolution, and you want to recreate it:

  • delete the pr-cherrypick label from the PR
  • delete this branch from the repository

You also need to check the Original pull-request for pr-backports-created label, and delete if it's presented there

The PR source

The PR is created in the CI job

novikd and others added 26 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]>
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]>
… 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]>
`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]>
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]>
…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]>
…sted-alias

Resolve JOIN USING identifier from aliases nested in the SELECT list
@robot-ch-test-poll robot-ch-test-poll added pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only! do not test disable testing on pull request pr-bugfix Pull request with bugfix, not backported by default labels Jul 31, 2026
@robot-clickhouse
robot-clickhouse merged commit faff6ac into backport/26.7/110739 Aug 3, 2026
1 check passed
@robot-clickhouse
robot-clickhouse deleted the cherrypick/26.7/110739 branch August 3, 2026 12:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

do not test disable testing on pull request pr-bugfix Pull request with bugfix, not backported by default pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only!

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants