Repository navigation
Conversation
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
|
Workflow [PR], commit [3d8914a] Summary: ✅
AI ReviewSummaryThis PR rewrites duplicate Missing context / blind spots
Findings
Final Verdict❌ Request changes. The distributed LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 112/112 (100.00%) · Uncovered code |
…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.
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.
…licate-alias-columns
|
Merged current
Root cause (reproduced on Design note. The current fix disambiguates by wrapping later occurrences in I've held off on further changes to the |
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
|
I reworked the fix to address the review feedback (commits
The test now covers three duplicates, Note: a |
|
@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 ( |
|
@alexey-milovidov Confirmed: this is the known Fix PR (in progress): #107086 (test-only, CI clean, awaiting review). Root cause. CIDB (30d). 14 Fix in #107086. Replace the one-shot KILL + bare join with a bounded loop that re-issues |
…licate-alias-columns
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]>
|
Merged
One unresolved review thread remains (the generated |
…licate-alias-columns
|
Merged |
…licate-alias-columns
…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]>
|
Merged current
|
…licate-alias-columns
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]>
|
Merged current
Verified locally (own server, ports 19607/18627): The The two unresolved review threads (wrapper-name collision with a real column named |
…licate-alias-columns
…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.
|
Merged current Neither reproduces. Both rest on the assumption that a name spelled in the query can be reused for the
A forged name can collapse onto another expression when it spells out a genuine internal action name, but that is pre-existing on Added the regressions the review asked for (commit
Verified locally against this build (server on a private port): 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 |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 94/94 (100.00%) · Uncovered code |
…licate-alias-columns
…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]>
…licate-alias-columns
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); |
There was a problem hiding this comment.
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.
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]>
What this PR does
When several
ALIAScolumns 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 withNUMBER_OF_COLUMNS_DOESNT_MATCH.The fix wraps such expansions into the internal function
__actionName(expression, 'name'), which exists exactly for pinning planner action names (seePlannerActionsVisitor) and is a no-op at runtime. EveryALIAScolumn gets its own action name, so any number of duplicates stay distinct, while all occurrences of oneALIAScolumn 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. AnALIASexpansion is also wrapped when its inlined expression coincides with a physical column (d String ALIAS bnext to a selectedb, issue #108291) or with an explicit expression of the query itself (SELECT a * 10, ewheree UInt64 ALIAS a * 10), so the shard never collapses anALIAScolumn onto anything and the block sent over the network always has one column per column the initiator expects.ALIAScolumns referencing otherALIAScolumns are inlined recursively down to physical columns, and duplicates are detected on the fully inlined expressions, soe Float64 ALIAS dcollides withd Float64 ALIAS b + cthe same way a literal duplicate would. Occurrences inWHERE/PREWHEREare 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, genuineString.Closes: #85895
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):
Fix
NUMBER_OF_COLUMNS_DOESNT_MATCHerror when querying a Distributed table with severalALIAScolumns sharing the same expression.Documentation entry for user-facing changes