Skip to content

Fix duplicate ALIAS columns causing column count mismatch in Distributed - #101789

Closed
Onyx2406 wants to merge 25 commits into
ClickHouse:masterfrom
Onyx2406:fix/distributed-duplicate-alias-columns
Closed

Onyx2406 wants to merge 25 commits into
ClickHouse:masterfrom
Onyx2406:fix/distributed-duplicate-alias-columns

Conversation

@Onyx2406

@Onyx2406 Onyx2406 commented Apr 4, 2026 •

Copy link
Copy Markdown
Contributor

What this PR does

When several ALIAS columns of one table share the same expression (e.g. d Float64 ALIAS b + c, e Float64 ALIAS b + c), the query rewrite for Distributed tables expanded them into identical expression trees with identical action names, the planner collapsed them into a single column of the block sent over the network, and the positional conversion against the header expected by the initiator failed with NUMBER_OF_COLUMNS_DOESNT_MATCH.

The fix wraps such expansions into the internal function __actionName(expression, 'name'), which exists exactly for pinning planner action names (see PlannerActionsVisitor) and is a no-op at runtime. Every ALIAS column gets its own action name, so any number of duplicates stay distinct, while all occurrences of one ALIAS column resolve to the same name and are correctly recognized as one column. The duplicate detection is a deterministic two-pass traversal scoped per column source. An ALIAS expansion is also wrapped when its inlined expression coincides with a physical column (d String ALIAS b next to a selected b, issue #108291) or with an explicit expression of the query itself (SELECT a * 10, e where e UInt64 ALIAS a * 10), so the shard never collapses an ALIAS column onto anything and the block sent over the network always has one column per column the initiator expects. ALIAS columns referencing other ALIAS columns are inlined recursively down to physical columns, and duplicates are detected on the fully inlined expressions, so e Float64 ALIAS d collides with d Float64 ALIAS b + c the same way a literal duplicate would. Occurrences in WHERE/PREWHERE are expanded bare, so primary key and skipping index analysis on the shards is unaffected. The first argument of __actionName (returned unchanged) may now have any type; the name argument must still be a constant, non-empty, genuine String.

Closes: #85895

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 to CHANGELOG.md):

Fix NUMBER_OF_COLUMNS_DOESNT_MATCH error when querying a Distributed table with several ALIAS columns sharing the same expression.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Onyx2406 added 3 commits April 4, 2026 18:47
When two ALIAS columns share the same expression, the Planner
deduplicated them causing a column count mismatch. Wrap duplicate
ALIAS expressions in `identity()` to keep them distinct while
preserving semantics.

Fixes ClickHouse#85895
Rename `04073_distributed_duplicate_alias_columns` to `04079` since
number 04073 is already taken on master by other tests.
… avoid number collision with upstream master
Comment thread src/Storages/StorageDistributed.cpp Resolved
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Apr 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Apr 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3d8914a]

Summary: ✅


AI Review

Summary

This PR rewrites duplicate ALIAS expansions in Distributed queries to __actionName(...) so shard-side planning no longer collapses them into fewer columns than the initiator expects. The main rewrite is much more complete than the earlier versions, but one new namespace collision remains: the generated wrapper names are predictable user-spellable strings, so a direct __actionName call can still collapse onto the synthetic wrapper and return wrong results.

Missing context / blind spots
  • ⚠️ I could not execute a targeted SQL repro in this workspace because there is no built clickhouse server/binary available here; the finding is based on tracing the current PlannerActionsVisitor name-resolution path against the new wrapper-name generation.
Findings
  • ❌ [src/Storages/StorageDistributed.cpp:1068] The synthetic __aliasColumn_<source>_<name> namespace is forgeable from SQL. PlannerActionsVisitor takes the second __actionName argument as the action name, and addFunctionIfNecessary reuses an existing function node purely by result_name, so SELECT __actionName('x', '__aliasColumn_0_d'), d, e FROM dist_alias_name_collision can make the user call and the synthetic wrapper for d alias the same DAG node. That reintroduces wrong results even though the physical-column and query-alias collision cases were tested. Suggested fix: generate wrapper names from an unforgeable planner-private namespace / identifier scheme, or reject direct __actionName names in the reserved wrapper namespace before DAG construction.
Final Verdict

❌ Request changes. The distributed ALIAS rewrite itself looks close, but the new wrapper-name namespace is still forgeable and can collapse with a user-written __actionName, which is a wrong-result risk.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 112/112 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Apr 5, 2026
Comment thread src/Storages/StorageDistributed.cpp Resolved
…NS_FOR_ALIAS`

The previous revision decided per *visit* whether to wrap an expanded
`ALIAS` column in `identity`: the first time an expression hash was seen
it stayed bare, and every later visit wrapped. That broke ordinary
queries that reference the same `ALIAS` column more than once (e.g.
`SELECT user_level, grouping(user_level) GROUP BY user_level`), because
the SELECT occurrence expanded to `multiIf(...)` while the GROUP BY
occurrence expanded to `identity(multiIf(...))`, and the Planner raised
`MULTIPLE_EXPRESSIONS_FOR_ALIAS` for the single alias now bound to two
different expressions. Regressions were visible on
`03259_grouping_sets_aliases`, `02494_optimize_group_by_function_keys_and_alias_columns`,
`00594_alias_in_distributed`, and `03034_normalized_ast`.

Key the wrap decision on the alias name, not the visit order. The first
visit of a new alias decides `wrap` vs `no-wrap` based on whether the
expression hash was already used by another alias, and every subsequent
visit of the same alias reuses that decision. Different aliases that
share an expression still get `identity` on the later one, which is the
behavior ClickHouse#85895 requires.
The previous revision set the alias on `column_expression` up-front and
then, when it decided to wrap, passed the already-aliased expression into
`identity`. That produced `identity(X AS e) AS e` — the same alias on both
the inner expression and the outer wrapper. The analyzer later saw two
distinct expressions for alias `e` and threw
`MULTIPLE_EXPRESSIONS_FOR_ALIAS` on `04090_distributed_duplicate_alias_columns`
and `00594_alias_in_distributed`.

Factor the expansion tail into `finalizeExpansion`, which either:
  - attaches the alias to the bare expression (when the alias is seen for
    the first time), or
  - strips any lingering alias from the inner expression and attaches the
    alias only to the `identity` wrapper.
The alias is therefore bound to exactly one node, matching what the
Planner and analyzer expect.
Comment thread src/Storages/StorageDistributed.cpp Resolved
Audit of the `identity()` cache fix pointed out that the regression test
only exercised the original bug (two distinct aliases that share one
expression). The class of query the cache specifically guards against —
the *same* ALIAS column referenced from more than one clause — wasn't
covered, so a regression of that logic would slip through.

Add four queries that each reference the same ALIAS column from multiple
positions:

- SELECT + GROUP BY
- SELECT + GROUP BY + HAVING
- SELECT + ORDER BY
- Two aliases `d` and `e`, each referenced more than once in the output,
  so the visitor both hits the cache *and* the identity wrap in the same
  query.

If the visitor ever returns a mismatched expansion between visits of the
same alias, these cases raise MULTIPLE_EXPRESSIONS_FOR_ALIAS and fail.
Comment thread src/Storages/StorageDistributed.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member

Merged current master (branch was ~1537 commits behind); the merge is conflict-free and the three red checks were not caused by this PR:

  • 00096_obfuscator_save_load and 00175_obfuscator_schema_inference — flaky (3/12 and 2/10 reruns), unrelated to a StorageDistributed change.
  • Unit tests (asan_ubsan) — job-level only; the detailed report shows 0 failing tests (the UntrackedMemoryRegistry UBSan issue was reverted on master, now in this branch via the merge).

Root cause (reproduced on master). Plain SELECT d, e FROM dist already works; only the aggregate case fails. After ReplaseAliasColumnsVisitor expands sum(d)/sum(e) into sum(b + c)/sum(b + c), the planner deduplicates the identical aggregate action node into a single column, so the shard produces 1 column while the Distributed header expects 2 → NUMBER_OF_COLUMNS_DOESNT_MATCH.

Design note. The current fix disambiguates by wrapping later occurrences in identity. As flagged in review, this wrapping is applied to every occurrence of the duplicate alias, including WHERE/PREWHERE. Since identity disables index analysis, a table like d ALIAS key, e ALIAS key with SELECT d, e FROM dist WHERE e = 42 would lose primary-key/skip-index pruning on the shards. So the column-count bug is fixed, but at the cost of pruning in predicate contexts.

I've held off on further changes to the identity mechanism pending a decision on direction (refine to keep predicate expansions bare and disambiguate only projected/aggregate action names, vs. a root-cause fix such as not expanding a duplicate ALIAS for shards that already expose the column). Happy to implement whichever you prefer.

The internal function `__actionName(expression, 'name')` overrides the action
name of `expression` with the constant 'name' (see `PlannerActionsVisitor`).
The 2024 hardening against direct calls restricted both arguments to `String`,
which was fine while the function was generated only for constants. To reuse it
for keeping duplicate `ALIAS` column expansions distinct in queries sent to
shards of Distributed tables, the first argument (the renamed expression, which
is returned unchanged) may now have any type. The second argument (the name)
must still be a genuine `String`, constant and non-empty, so the protection
against malformed direct calls is preserved.

Related: ClickHouse#85895
Related: ClickHouse#101789
Replace the `identity` wrapping of duplicate `ALIAS` column expansions in
`ReplaceAliasColumnsVisitor` (also fixing the `Replase` typo in its name) with
the internal function `__actionName(expression, 'name')`, which exists exactly
for pinning planner action names and is a no-op at runtime:

- Any number of `ALIAS` columns sharing one expression stay distinct, because
  every column gets its own name. The `identity` approach kept only two:
  the third and subsequent duplicates produced identical `identity(...)` trees
  that were collapsed again, and the query failed with the same
  `NUMBER_OF_COLUMNS_DOESNT_MATCH` exception.
- The wrap decision is computed by a deterministic two-pass traversal scoped
  per column source instead of a visit-order-dependent cache keyed by alias
  name alone, so equal alias names of different tables cannot be conflated.
- Occurrences in WHERE and PREWHERE are expanded bare: filters are computed
  entirely on the shards, and an opaque wrapper would prevent primary key and
  skipping index analysis there. `identity` disables index analysis by design,
  so the previous approach pessimized filtering by a duplicate `ALIAS` column
  to a full scan.

The test now also covers three duplicates, GROUP BY keys, subqueries, GLOBAL
JOIN of two distributed tables, `ALIAS` columns missing on the shard table,
equal alias names with different expressions in two sources, and verifies that
primary key analysis still prunes granules when filtering by a duplicate
`ALIAS` column.

Closes: ClickHouse#85895
@alexey-milovidov

Copy link
Copy Markdown
Member

I reworked the fix to address the review feedback (commits 3f5995f1c5f, dfd7798ef2e):

  • Instead of identity, duplicate ALIAS column expansions are wrapped into the internal function __actionName(expression, 'name'), which exists exactly for pinning planner action names (see PlannerActionsVisitor) and is a no-op at runtime. Its first argument may now have any type (previously restricted to String); the name argument must still be a constant, non-empty, genuine String.
  • Every ALIAS column gets its own action name, so any number of duplicates stay distinct. The identity version handled only two: with three duplicates (d, e, f all ALIAS b + c) the second and third wraps produced identical identity(b + c) trees, which were collapsed again, and the query kept failing with the same NUMBER_OF_COLUMNS_DOESNT_MATCH exception (verified).
  • The wrap decision is a deterministic two-pass traversal scoped per column source instead of a visit-order-dependent cache keyed by alias name, so equal alias names of different tables cannot be conflated, and the MULTIPLE_EXPRESSIONS_FOR_ALIAS workarounds are unnecessary by construction.
  • WHERE/PREWHERE occurrences are expanded bare, so primary key and skipping index analysis on the shards is unaffected (identity disables index analysis by design). Verified: filtering 2M rows by a duplicate ALIAS of the sorting key expression reads 16384 rows, not 2M.

The test now covers three duplicates, GROUP BY keys, subqueries, GLOBAL JOIN, ALIAS columns missing on the shard table, equal alias names with different expressions in two sources, and asserts granule pruning via read_rows. All of 00594_alias_in_distributed, 01576_alias_column_rewrite, 01923_different_expression_name_alias, 02008_aliased_column_distributed_bug, 02517_wrong_total_structure_crash, 03035_alias_column_bug_distributed, 03402_join_using_alias, 03035_internal_functions_direct_call, and 04201_action_name_lowcardinality_args pass locally against the patched build.

Note: a GLOBAL JOIN of two different distributed tables that both define the same alias name fails with MULTIPLE_EXPRESSIONS_FOR_ALIAS — that is a pre-existing problem on master (the expansion binds the same alias to two different trees) and is independent of this fix.

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=101789&sha=9761f4206efb6c6de7509e18e9beef83c44444f2&name_0=PR&name_1=Integration%20tests%20%28amd_msan%2C%204%2F6%29 (test_profile_max_sessions_for_user/test.py::test_profile_max_sessions_for_user_postgres timed out after 900 s under MSan) and provide a fix in a separate PR. If the fix is already in progress, link it here. It is unrelated to this PR, which only changes the ALIAS column rewrite for Distributed tables.

Comment thread src/Storages/StorageDistributed.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator

@alexey-milovidov Confirmed: this is the known test_profile_max_sessions_for_user_postgres flaky timeout under MSan, unrelated to your ALIAS column rewrite. Already root-caused, and a separate fix is in progress.

Fix PR (in progress): #107086 (test-only, CI clean, awaiting review).

Root cause. threaded_run_test starts 3 postgres sessions (limit 2), waits for the "overflown session count" log (which fires at session acquisition, before query execution), then issues a single KILL QUERY WHERE user='test_user' SYNC plus a bare thread.join(). If an accepted session's infinite SELECT ... FROM system.numbers has not yet registered in system.processes when that one-shot KILL snapshots the process list, it is never killed and runs forever. psycopg2 has no client-side query timeout, so the worker thread blocks in fetchall() until the pytest 900s test-level limit. The native variants (tcp/http/mysql/grpc) are masked by the 600s query timeout in helpers/client.py; postgres has none, and MSan widens the connect-to-execute window, which is why it is postgres+MSan specific.

CIDB (30d). 14 _postgres timeouts across 13 distinct PRs plus master, 11/14 on amd_msan; 1 each for tcp/http/mysql/grpc. No regression (test.py unchanged since 2024).

Fix in #107086. Replace the one-shot KILL + bare join with a bounded loop that re-issues KILL QUERY ... SYNC while any session thread is still alive. The session-overflow assertion is unchanged.

alexey-milovidov and others added 2 commits June 12, 2026 20:09
The fix for issue ClickHouse#85895 lives entirely in the new analyzer's distributed
query-tree rewrite (`buildQueryTreeDistributed`, wrapping duplicate `ALIAS`
expansions into the internal `__actionName` function). The old analyzer uses a
separate AST-based path that cannot resolve `ALIAS` columns of a `GLOBAL JOIN`
right-hand table (`UNKNOWN_IDENTIFIER` in `ExpressionAnalyzer` /
`GlobalSubqueriesVisitor`), which is an unrelated, pre-existing limitation. Tag
the test `no-old-analyzer` so it runs only where the fix applies.

Failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=101789&sha=dfd7798ef2e74556fed1933e5f312fd160322ac2&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20old%20analyzer%2C%20s3%20storage%2C%20DatabaseReplicated%2C%20WasmEdge%2C%20parallel%29

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

Merged master and fixed the one real CI failure.

  • 04090_distributed_duplicate_alias_columns (old analyzer config): the fix lives entirely in the new analyzer's distributed query-tree rewrite (buildQueryTreeDistributed, wrapping duplicate ALIAS expansions into __actionName). On the old analyzer the GLOBAL JOIN case fails with UNKNOWN_IDENTIFIER: Unknown column: e deep in ExpressionAnalyzer/GlobalSubqueriesVisitor — a separate, pre-existing old-analyzer limitation unrelated to this PR. Tagged the test no-old-analyzer so it runs only where the fix applies (commit 448cd3503ac).
  • BuzzHouse (amd_debug) — Inconsistent AST formatting (STID: 1941-1bfa): unrelated known flake (emoji literals + tupleElement/arrayElement), tracked in Logical error: 'Inconsistent AST formatting: the original AST: (STID: 1941-1bfa) #106850.

One unresolved review thread remains (the generated __actionName action name __aliasColumn_<n>_<name> could in principle collide with a physical column of the same name) — left for @alexey-milovidov as a design call on the naming scheme.

Comment thread src/Storages/StorageDistributed.cpp Resolved
Comment thread src/Functions/identity.h Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member

Merged master again. The only red check, Build (arm_tidy), was a stale base: the branch still carried the pre-fix applyHistogramQuantile.cpp with an uninitialized out_of_range_value (cppcoreguidelines-init-variables), which has since been fixed on master. After the merge the variable is initialized and the tidy build is unblocked. The merge is conflict-free and the PR diff is unchanged (8 files).

alexey-milovidov and others added 3 commits July 15, 2026 03:00
…ons`

Master commit 59583e1 made tree comparison always exact (types are
always part of the hash), which is exactly what this code requested with
`.compare_types = true`, so the field can simply be dropped.

Co-Authored-By: Claude Fable 5 <[email protected]>
The expression of an ALIAS column may itself reference other ALIAS
columns (e.g. `d Float64 ALIAS b + c, e Float64 ALIAS d`), and none of
them can be assumed to exist on the shard tables. Previously such a
reference was expanded only once, so the query sent to the shard kept
the bare column reference (`__table1.d AS e`) and failed with
UNKNOWN_IDENTIFIER when the alias column is missing on the shard table.

Expansions are now inlined recursively down to physical columns, and
the duplicate detection compares the fully inlined expressions, so the
chained `e ALIAS d` collides with `d ALIAS b + c` the same way a
literal `e ALIAS b + c` would, and gets its own `__actionName` wrapper
instead of being collapsed by the planner.

Addresses the second finding of the automated review.

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

Copy link
Copy Markdown
Member

Merged current master (the branch was a month behind) and reworked the branch to reconcile with it:

  • master removed compare_types from IQueryTreeNode::CompareOptions (59583e1) — tree comparison is now always exact, which is what this code requested with .compare_types = true, so the field is simply dropped.
  • Fixed the nested-alias review finding: ALIAS columns referencing other ALIAS columns (d Float64 ALIAS b + c, e Float64 ALIAS d) are now inlined recursively down to physical columns, and the duplicate detection compares the fully inlined expressions. Previously the shard query kept a bare reference to the intermediate alias and failed with UNKNOWN_IDENTIFIER when it does not exist on the shard table. Regression cases added to 04090_distributed_duplicate_alias_columns.
  • Verified locally against this build: 04090_distributed_duplicate_alias_columns, 03035_internal_functions_direct_call, 04201_action_name_lowcardinality_args, master's 04357_distributed_alias_same_expression and 04357_distributed_alias_query_clauses, 03726/04305_distributed_alias_column_order, and a wider distributed-alias sweep — all pass. This confirms the shard-side __actionName rewrite of this PR and the initiator-side buildShardCollapseFanOut of Fix NUMBER_OF_COLUMNS_DOESNT_MATCH for duplicate ALIAS expressions on Distributed tables #107913 (which meanwhile fixed the same issue Duplicate alias does not work with distributed table #85895 on master by reconstructing the collapsed duplicates) coexist correctly: with this rewrite active, nothing collapses, and the fan-out is a no-op.

alexey-milovidov and others added 3 commits July 19, 2026 12:03
The duplicate detection only compared ALIAS columns of one table against
each other, so an ALIAS column whose inlined expression coincides with a
physical column (`d String ALIAS b`, issue ClickHouse#108291) or with an explicit
expression of the query (`SELECT a * 10, e` with `e UInt64 ALIAS a * 10`)
was still expanded bare and collapsed on the shard, while the wrapped
duplicates in the same query prevented the initiator-side fan-out
reconstruction (`buildShardCollapseFanOut`) from recognizing the collapsed
header, failing with `NUMBER_OF_COLUMNS_DOESNT_MATCH` in
`04493_distributed_alias_column_reference`.

Now the collection pass also remembers the inlined-form hashes of all other
expressions of the query (outside ALIAS expansions), and an ALIAS expansion
is wrapped into `__actionName` whenever it collides with another ALIAS
column of the same table or with any other expression, so the shard never
collapses an ALIAS column onto anything and the header column count always
matches what the initiator expects.

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=101789&sha=747f7516de301f5aa842adb878d8949af3efd66d&name_0=PR&name_1=Fast%20test
PR: ClickHouse#101789

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

Copy link
Copy Markdown
Member

Merged current master (clean merge) and fixed the two real CI failures on 747f7516de3:

  • Style check: the test comment said "new analyzer"; reworded to "the analyzer" (c6e9e0d5f4b).
  • Fast test, 04493_distributed_alias_column_reference (NUMBER_OF_COLUMNS_DOESNT_MATCH, source: 5, result: 6): a real regression of this branch, fixed in fd4f5ec1d70. The duplicate detection only compared ALIAS columns of one table against each other, so d String ALIAS b was still expanded bare and collapsed onto the physical column b on the shard — and the __actionName wrappers on the duplicates c/f in the same query prevented the initiator-side fan-out reconstruction (buildShardCollapseFanOut, Fix NUMBER_OF_COLUMNS_DOESNT_MATCH for duplicate ALIAS expressions on Distributed tables #107913) from recognizing the collapsed header, because its naming mirror (InlineAliasColumnsForNamingVisitor) predicts the bare inlined names, not the wrapped ones. The fix extends the collection pass to also remember the inlined-form hashes of all other expressions of the query (outside ALIAS expansions) and wraps an ALIAS expansion whenever it collides with another ALIAS column of the same table or with any other expression (a physical column, or an explicit expression such as SELECT a * 10, e with e UInt64 ALIAS a * 10). The shard then never collapses an ALIAS column onto anything, the header column count always matches what the initiator expects, and the fan-out path is never needed for these queries. Regression cases added to 04090_distributed_duplicate_alias_columns (asterisk expansion with plain-reference aliases, plain-reference alias next to its source column, function alias next to the same explicit expression, and both mixed with wrapped duplicates).

Verified locally (own server, ports 19607/18627): 04090, 04493, 04357_distributed_alias_same_expression, 04357_distributed_alias_query_clauses, 03726/04305_distributed_alias_column_order, 04103_fuse_quantiles_distributed_alias_clash, 03035_internal_functions_direct_call, 04201_action_name_lowcardinality_args, plus a wider alias sweep (00594, 03035_alias_column_bug_distributed, 01923, 02008, 01576, 03402) — all pass.

The Finish Workflow red (new_tests_check.py: no per-arch Bugfix validation passed) was cascading — the Bugfix validation jobs were DROPPED because Fast test failed; the nested-ALIAS-chain cases of 04090 still fail on master (UNKNOWN_IDENTIFIER), so the gate should pass on the next run.

The two unresolved review threads (wrapper-name collision with a real column named __aliasColumn_*, and the relaxed first argument of __actionName) remain open design questions for @alexey-milovidov.

…rapper

The AI review asked for regressions covering the two reported wrong-result
scenarios of the `__actionName` wrapper generated by the `Distributed`
rewrite of duplicate `ALIAS` columns.

Neither reproduces, and the new tests lock that in:

- `04652_distributed_alias_action_name_collision`: a physical column, a
  query alias, and an `ALIAS` column all named exactly like the generated
  wrapper name `__aliasColumn_0_d`, next to the duplicate `ALIAS` columns
  it could collide with. Column action names in the plan are column
  identifiers (`__table1.__aliasColumn_0_d`) and a query alias is not an
  action name at all, so the namespaces do not intersect.
- `04653_action_name_forged_name_over_input`: direct `__actionName` calls
  requesting the name of an input column or of an explicit alias of the same
  query, in both visiting orders and inside an aggregate function. The
  requested name never shadows the input, for the same reason.
@alexey-milovidov

Copy link
Copy Markdown
Member

Merged current master (the branch was 8 days behind; clean merge, PR diff unchanged) and investigated the two blockers of the AI review's Request changes verdict against a build of the merged head.

Neither reproduces. Both rest on the assumption that a name spelled in the query can be reused for the __actionName wrapper's node, but column action names in the plan are column identifiers (__table1.x), and an explicit alias of the query is not an action node name at all, so the namespaces do not intersect:

  • __aliasColumn_0_d as a physical column, as a query alias, and as an ALIAS column, next to the duplicate ALIAS columns it could collide with — correct values in every order.
  • SELECT __actionName(number + 1, 'number') FROM numbers(3) and its variants (with number selected before and after, with a query alias as the forged name, inside an aggregate) — correct values throughout.

A forged name can collapse onto another expression when it spells out a genuine internal action name, but that is pre-existing on master and independent of this PR: it needs only a constant first argument, which master already allows. SELECT number + 1 AS z, __actionName('aaa', 'plus(__table1.number, 1_UInt8)') AS y FROM numbers(3) returns 1 1 / 2 2 / 3 3 on the released 26.7 binary as well. Details and reproducers are in the two review threads.

Added the regressions the review asked for (commit 49791f55783):

  • 04652_distributed_alias_action_name_collision — the wrapper-name collision cases above.
  • 04653_action_name_forged_name_over_input — direct __actionName calls requesting the name of an input column or of a query alias.

Verified locally against this build (server on a private port): 04652, 04653, 04090_distributed_duplicate_alias_columns, 04493_distributed_alias_column_reference, 04305_distributed_alias_column_order, 04357_distributed_alias_query_clauses, 03035_internal_functions_direct_call, 04201_action_name_lowcardinality_args all pass. 04357_distributed_alias_same_expression fails locally only on its remote('127.0.0.2', ...) queries, which target the default port 9000 — an artifact of the private-port setup, not of the branch.

Still open for @alexey-milovidov as design/product calls, unchanged by this pass: whether to move the generated wrapper names into the planner's unique-identifier namespace, and whether to keep this shard-side rewrite alongside the initiator-side buildShardCollapseFanOut of #107913 (with this rewrite active nothing collapses, so the fan-out is a no-op for these queries).

Comment thread src/Storages/StorageDistributed.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.40% 78.40% +0.00%

Changed lines: Changed C/C++ lines covered: 94/94 (100.00%) · Uncovered code

Full report · Diff report

alexey-milovidov and others added 4 commits August 4, 2026 05:26
…essions

The duplicate detection collected every descendant COLUMN/FUNCTION/CONSTANT
node of the query as a collision candidate, so harmless matches forced
`__actionName` wrappers and pessimized shard-side planning: a sibling
literal inside one expression (`d UInt8 ALIAS 1` in `SELECT d + 1`) or a
column referenced only by the filter (`d String ALIAS b` in
`SELECT d FROM dist WHERE b = 'x'`) made the expansion opaque to constant
folding and other optimizations for no reason.

A collapse can only drop a column of the block sent over the network when
two whole expressions of the query clauses that the initiator distinguishes
become identical on the shard after inlining. So the collision candidates
are now the whole clause expressions (projection entries, GROUP BY keys,
ORDER BY expressions, ...) excluding filters, limits and join conditions,
compared at that granularity: an ALIAS occurrence is wrapped when it lies
inside a whole expression whose fully inlined form is also produced by
another whole expression that differs before inlining. Expressions equal
before inlining collapse the same way on the initiator and need no wrapper.
This also moves the detection to the right granularity for expansions
nested inside larger expressions (`SELECT sum(d), sum(b + c)` with
`d Float64 ALIAS b + c` still gets the wrapper), which the per-node hash
check only caught by accident of collecting every subtree.

The new test pins both the results and the presence/absence of the wrapper
in the query the initiator sends to the shard, read back from
system.query_log.

Co-Authored-By: Claude Fable 5 <[email protected]>
The Style check requires every test reading system.query_log to carry a
current_database = currentDatabase() condition. Scope the shard-side
entries through the initial_query_id of the initiator queries, which ran
with current_database = currentDatabase() - stronger isolation than the
previous match of the database name inside the shard query text.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=101789&sha=3f402bfeecc80d6d2197de6712b98b8e6208c340&name_0=PR&name_1=Style%20check
PR: ClickHouse#101789

column_expression->removeAlias();

auto action_name = fmt::format("__aliasColumn_{}_{}", source_ordinals.at(column_source), column_name);

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 generated __aliasColumn_<source>_<column> names are still forgeable from SQL. PlannerActionsVisitor takes the second __actionName argument verbatim as the DAG node name, and addFunctionIfNecessary deduplicates purely by that name, so a query like

SELECT __actionName('x', '__aliasColumn_0_d'), d, e FROM dist_alias_name_collision;

puts the user-written call and the synthetic wrapper for d in the same namespace. Whichever node is visited first is then reused for both, so one of the result columns can silently return the other expression's value.

This is new to this PR because the wrapper names are deterministic and public. Please move them into an unforgeable planner-private namespace, or reject direct __actionName requests that target the reserved wrapper-name prefix.

cursor Bot pushed a commit that referenced this pull request Aug 6, 2026
An `ALIAS` column defined over another one has to be inlined all the way down to physical columns
before the query is shipped. One level of inlining leaves the intermediate alias in the shipped SQL,
and a shard that does not know it fails:

    Identifier '__table1.d' cannot be resolved from table with name __table1 (UNKNOWN_IDENTIFIER)

That is what the chain-declared-only-on-the-`Distributed`-table shape from
#101789 exercises, and it still reproduces on master:
the inliner there replaces a column with its body once, so a chain stops after the first link. The
inliner here unwraps until the body no longer resolves to an `ALIAS` column, which fixes it. The
duplicate-`ALIAS` half of that pull request needs no test here, as it is already fixed on master by
#107913 - the shapes from its issue
#85895 produce identical results on master and here.

The test reports eight `UNKNOWN_IDENTIFIER` on master. Its last section declares the same chain on
both tables, where the shard can resolve it unaided, and passes either way.

Related: #101789

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

Copy link
Copy Markdown
Member

covered by #107700 and #107913

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 pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Duplicate alias does not work with distributed table

4 participants