Repository navigation
Fix NUMBER_OF_COLUMNS_DOESNT_MATCH for Distributed table with duplicate ALIAS expressions - #106404
Conversation
…te ALIAS expressions
When a Distributed table has two ALIAS columns expanding to the same
expression (e.g. both are `toString(x)`), querying them with ORDER BY
fails because the planner's ActionsDAG deduplicates the projection
items by their action node name, shrinking the output column count.
The initiator then throws:
Code: 20. Number of columns doesn't match (source: 2 and result: 3)
Root cause: `ReplaseAliasColumnsVisitor` inlines both alias
expressions into the shard query tree. Since the expressions are
structurally identical, `calculateActionNodeName` produces the same
DAG node name for both. `addFunctionIfNecessary` returns the same
node, and downstream `removeUnusedActions` / `finalizeInputAndOutputColumns`
deduplicates outputs by name -- producing fewer columns than expected.
Fix: In `PlannerActionsVisitorImpl::visit`, when processing an
expression list (projection), detect when multiple items resolve to the
same DAG node. For duplicates, add an ALIAS node with a unique
suffix so that each projection item has a distinct output name in the
DAG. This prevents deduplication while preserving the correct
projection semantics (the final rename step maps internal names to
display names anyway).
Closes: #106403
Co-authored-by: Yakov Olkhovskiy <[email protected]>
|
Workflow [PR], commit [653e3b5] Summary: ✅
AI ReviewSummaryThis PR targets a real Findings❌ Blockers
Tests
Final VerdictStatus: ❌ Block Minimum required actions: prove synthetic |
Fix the generated unique name to be truly unique in the current scope: loop with incrementing suffix until `containsNode` confirms the name is fresh. This prevents silently resolving to an unrelated column if the naive suffix name already exists (e.g. a column named `x_1`). Also fix test references: - 04305: correct expected output (4 lines, not 6) - 03777: update EXPLAIN output to reflect the additional alias nodes now visible in intermediate plan headers Co-authored-by: Yakov Olkhovskiy <[email protected]>
|
|
The previous approach (adding alias nodes in `PlannerActionsVisitorImpl::visit` for all expression lists) was too broad and broke unrelated tests: - `02369_analyzer_array_join_function`: interfered with arrayJoin semantics - `03631_select_replace_comprehensive`: broke PREWHERE with duplicate columns - `04145_multiple_expressions_for_alias_parallel_replicas`: changed projection handling for parallel replicas - `03777_join_runtime_filter_duplicate_columns`: changed EXPLAIN output New approach: apply the fix only in `buildQueryTreeDistributed` after `ReplaseAliasColumnsVisitor` inlines ALIAS columns. Scan the projection for structurally identical expressions (same tree hash ignoring aliases) and wrap subsequent duplicates in `identity()` — a no-op function that creates a distinct action-node name without affecting query results. This is targeted to the distributed query path and does not affect local queries or other expression lists like ORDER BY, GROUP BY, etc. Co-authored-by: Yakov Olkhovskiy <[email protected]>
…xpressions Use a while loop: keep wrapping in identity() until the resulting tree hash is unique among all previously-seen projection hashes. This handles: - 3+ ALIAS columns expanding to the same expression (each gets an additional layer of identity() nesting) - A projection that already contains identity(expr) alongside ALIAS columns expanding to the same expr Co-authored-by: Yakov Olkhovskiy <[email protected]>
Revert the `identity()` wrapper approach in `StorageDistributed.cpp` (it cannot handle 3+ duplicates or existing `identity()` projections). Instead, fix in `PlannerActionsVisitorImpl::visit` with a precise condition: add a DAG ALIAS node only when a later list item resolves to the same DAG node as an earlier item AND the two items carry different non-empty query-tree aliases. This targets the distributed ALIAS column case (where `ReplaseAliasColumnsVisitor` inlines identical expressions under different aliases like "a1" and "a2") without affecting: - `arrayJoin` duplicates (second item has no alias → skipped) - `SELECT x, x` (column refs have no alias on the tree node → skipped) - `SELECT * REPLACE(a AS b)` producing same-alias duplicates (same alias → condition false → skipped) - JOIN projections with duplicate columns (same alias → skipped) The generated alias name incorporates the query-tree alias for readability (e.g. `toString(__table1.x)_a2`) and loops with a suffix until fresh in the scope to avoid collisions. Co-authored-by: Yakov Olkhovskiy <[email protected]>
Relax the type restriction on __actionName's first argument: the original all-arguments-must-be-String guard (added in #62287 as a fuzzer crash workaround) was overly broad — the actual bug was empty action names from the second argument, not a type mismatch on the first. Now only the second argument (the desired name) is required to be String; the first argument (the wrapped expression) can be any type. In buildQueryTreeDistributed, after ReplaseAliasColumnsVisitor inlines ALIAS columns, scan the projection for structurally identical expressions (same tree hash ignoring aliases). Wrap subsequent duplicates in __actionName(expr, 'column_alias') which forces the planner to use the column alias as the action-node name — guaranteed unique since column aliases within a table are unique by definition. No nesting, no collisions, works on both initiator and shard. Also fix typo: "nad" → "and" in error messages. Closes: #106403 Co-authored-by: Yakov Olkhovskiy <[email protected]>
Fix three issues:
1. Empty alias: use `projection_columns[i].name` from `QueryNode::getProjectionColumns()`
instead of `getAlias()` which can be empty after analyzer resolution.
2. MULTIPLE_EXPRESSIONS_FOR_ALIAS on shard: call `removeAlias()` on the
inner expression before wrapping in `__actionName`, so only the wrapper
carries the alias in the serialized AST.
3. False positives: only wrap projection items that correspond to ALIAS
columns in the storage metadata (`ColumnDefaultKind::Alias`). This
prevents wrapping unrelated duplicate expressions like `SELECT 1 x, x y`
or `SELECT toString(x), toString(x)` that happen to share a tree hash.
Update tests for relaxed `__actionName` first-argument type:
- 03035: `__actionName(materialize('aaa'), 'aaa')` now succeeds
- 04201: rewritten to test current semantics (any first arg type,
String-only second arg)
Co-authored-by: Yakov Olkhovskiy <[email protected]>
Fix two gaps: 1. Renamed projections (`SELECT a1 AS first, a2 AS second`): use the node alias (set by `ReplaseAliasColumnsVisitor` to the original ALIAS column name) instead of projection display name for the `getDefault` lookup. This correctly identifies ALIAS columns even after user renames. 2. Repeated projections (`SELECT a1, a2, a2`): generate the action name as `column_name + "_" + position` (e.g. `a2_1`, `a2_2`) to guarantee uniqueness per projection position, preventing collisions when the same ALIAS column appears multiple times. Add regression tests for both cases. Co-authored-by: Yakov Olkhovskiy <[email protected]>
The repeated-same-ALIAS-column case (SELECT a1, a2, a2) requires deeper planner changes to handle correctly — the initiator and shard disagree on how many distinct columns to produce because the planner merges identical logical columns. This is a separate issue from the original bug (two DIFFERENT ALIAS columns with the same expression body). The bot's concern about nested ALIAS usage like `SELECT concat(a1, ''), concat(a2, '')` is also noted as a known limitation — it would require tracking inlined positions through the visitor, which is out of scope for this fix. Co-authored-by: Yakov Olkhovskiy <[email protected]>
Each duplicate ALIAS projection position needs its own unique action name — even repeated references to the same column. The position-based suffix (`a2_1`, `a2_2`) guarantees each wrapped item is distinct. The `getSampleBlock` (modified tree) and `expected_header` (original tree) both produce the same column count because the original tree also preserves all projection positions (with Position-based matching, column count must agree — names are irrelevant). `SELECT a1, a2, a2` is a valid query that exercises this: positions 1 and 2 both collide with position 0 and both get wrapped uniquely. Co-authored-by: Yakov Olkhovskiy <[email protected]>
| if (!col_default || col_default->kind != ColumnDefaultKind::Alias) | ||
| continue; | ||
|
|
||
| auto unique_name = node_alias + "_" + std::to_string(i); |
There was a problem hiding this comment.
unique_name is not guaranteed fresh in the current ActionsDAG scope. Projection actions are initialized with the input columns, and addFunctionIfNecessary returns an existing node when the __actionName result name already exists. A valid table can have a material column named a2_1; for SELECT a1, a2, a2_1 ..., the duplicate a2 at position 1 gets unique_name == "a2_1", so the wrapper can resolve to the real a2_1 input instead of toString(x), returning wrong data under the display name a2.
Please generate a name that is fresh against the current action scope, or use an internal namespace that user columns cannot collide with and verify it before planning. Add a regression with a column whose name collides with the generated suffix.
There was a problem hiding this comment.
This is still present in the current code at src/Storages/StorageDistributed.cpp:999. The __distributed_alias_ prefix only reduces accidental collisions; it is still a legal column/action name and is not checked against the current ActionsDAG scope. For example, a query that also projects a real column named __distributed_alias_a2_2 can make the duplicate a2 wrapper at position 2 use that same action name. addFunctionIfNecessary will then return the existing node instead of creating the __actionName wrapper, so the a2 output can read the unrelated column.
Please keep generating until the name is proven fresh in the current action scope, or use another mechanism that fails instead of reusing an existing node.
Two fixes: 1. Repeated same-alias references (`SELECT a1, a2, a2`): only wrap the first occurrence of each distinct ALIAS column name. Repeated references share one identifier in the original tree — wrapping both produces more unique columns than the initiator expects. 2. Name collision safety: use `__distributed_alias_` prefix for generated action names to avoid collisions with real columns (e.g. a table having a column literally named `a2_1`). Co-authored-by: Yakov Olkhovskiy <[email protected]>
Co-authored-by: Yakov Olkhovskiy <[email protected]>
|
very similar #106402 |
…rg::alter PR ClickHouse#106102 (merged 2026-06-05 17:43 UTC) refactored Iceberg::alter to declare last_version and compression_method outside an if/else that assigns them in both branches. Clang-tidy cppcoreguidelines-init-variables flags the bare declarations and Build (arm_tidy) is built with -warnings-as-errors, so the build fails for every PR whose CI ran on master after this commit. CIDB shows 30+ unrelated PRs hitting this in the last 2 days (e.g. ClickHouse#89360, ClickHouse#103540, ClickHouse#106120, ClickHouse#106386, ClickHouse#106404, ClickHouse#106522, ClickHouse#105102, ClickHouse#106590). Initialize both variables to safe defaults at declaration. They are unconditionally overwritten in both if and else branches before use, so behavior is unchanged. The new defaults are only relevant if a future code path skips both assignments, in which case last_version=0 and compression_method=CompressionMethod::None are sane no-op values (the same defaults the old structured-binding form would produce through default-construction of the destructured aggregate). Co-Authored-By: Claude Opus 4.8 <[email protected]> (cherry picked from commit d72cac5)
…rg::alter PR ClickHouse#106102 (merged 2026-06-05 17:43 UTC) refactored Iceberg::alter to declare last_version and compression_method outside an if/else that assigns them in both branches. Clang-tidy cppcoreguidelines-init-variables flags the bare declarations and Build (arm_tidy) is built with -warnings-as-errors, so the build fails for every PR whose CI ran on master after this commit. CIDB shows 30+ unrelated PRs hitting this in the last 2 days (e.g. ClickHouse#89360, ClickHouse#103540, ClickHouse#106120, ClickHouse#106386, ClickHouse#106404, ClickHouse#106522, ClickHouse#105102, ClickHouse#106590). Initialize both variables to safe defaults at declaration. They are unconditionally overwritten in both if and else branches before use, so behavior is unchanged. The new defaults are only relevant if a future code path skips both assignments, in which case last_version=0 and compression_method=CompressionMethod::None are sane no-op values (the same defaults the old structured-binding form would produce through default-construction of the destructured aggregate). Co-Authored-By: Claude Opus 4.8 <[email protected]> (cherry picked from commit d72cac5)
…rg::alter PR ClickHouse#106102 (merged 2026-06-05 17:43 UTC) refactored Iceberg::alter to declare last_version and compression_method outside an if/else that assigns them in both branches. Clang-tidy cppcoreguidelines-init-variables flags the bare declarations and Build (arm_tidy) is built with -warnings-as-errors, so the build fails for every PR whose CI ran on master after this commit. CIDB shows 30+ unrelated PRs hitting this in the last 2 days (e.g. ClickHouse#89360, ClickHouse#103540, ClickHouse#106120, ClickHouse#106386, ClickHouse#106404, ClickHouse#106522, ClickHouse#105102, ClickHouse#106590). Initialize both variables to safe defaults at declaration. They are unconditionally overwritten in both if and else branches before use, so behavior is unchanged. The new defaults are only relevant if a future code path skips both assignments, in which case last_version=0 and compression_method=CompressionMethod::None are sane no-op values (the same defaults the old structured-binding form would produce through default-construction of the destructured aggregate). Co-Authored-By: Claude Opus 4.8 <[email protected]> (cherry picked from commit d72cac5)
…rg::alter PR ClickHouse#106102 (merged 2026-06-05 17:43 UTC) refactored Iceberg::alter to declare last_version and compression_method outside an if/else that assigns them in both branches. Clang-tidy cppcoreguidelines-init-variables flags the bare declarations and Build (arm_tidy) is built with -warnings-as-errors, so the build fails for every PR whose CI ran on master after this commit. CIDB shows 30+ unrelated PRs hitting this in the last 2 days (e.g. ClickHouse#89360, ClickHouse#103540, ClickHouse#106120, ClickHouse#106386, ClickHouse#106404, ClickHouse#106522, ClickHouse#105102, ClickHouse#106590). Initialize both variables to safe defaults at declaration. They are unconditionally overwritten in both if and else branches before use, so behavior is unchanged. The new defaults are only relevant if a future code path skips both assignments, in which case last_version=0 and compression_method=CompressionMethod::None are sane no-op values (the same defaults the old structured-binding form would produce through default-construction of the destructured aggregate). Co-Authored-By: Claude Opus 4.8 <[email protected]> (cherry picked from commit d72cac5)
…rg::alter PR ClickHouse#106102 (merged 2026-06-05 17:43 UTC) refactored Iceberg::alter to declare last_version and compression_method outside an if/else that assigns them in both branches. Clang-tidy cppcoreguidelines-init-variables flags the bare declarations and Build (arm_tidy) is built with -warnings-as-errors, so the build fails for every PR whose CI ran on master after this commit. CIDB shows 30+ unrelated PRs hitting this in the last 2 days (e.g. ClickHouse#89360, ClickHouse#103540, ClickHouse#106120, ClickHouse#106386, ClickHouse#106404, ClickHouse#106522, ClickHouse#105102, ClickHouse#106590). Initialize both variables to safe defaults at declaration. They are unconditionally overwritten in both if and else branches before use, so behavior is unchanged. The new defaults are only relevant if a future code path skips both assignments, in which case last_version=0 and compression_method=CompressionMethod::None are sane no-op values (the same defaults the old structured-binding form would produce through default-construction of the destructured aggregate). Co-Authored-By: Claude Opus 4.8 <[email protected]> (cherry picked from commit d72cac5)
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 63/63 (100.00%) | Lost baseline coverage: none · Uncovered code |
|
Hi @yakov-olkhovskiy @vdimir — while reviewing this PR I found the following:
Happy to discuss — close anything that's wrong or already addressed. |
PR #106404 fixed the column count mismatch for identical-expression ALIAS columns in distributed queries. The `distributed_same_expr` query now returns `7 7` successfully instead of throwing `NUMBER_OF_COLUMNS_DOESNT_MATCH`. Co-authored-by: Yakov Olkhovskiy <[email protected]>
|
I was already fighting the same problems... #106402 |
… Distributed tables
When a Distributed query is executed up to `WithMergeableState`, the shard's
query tree has its `ALIAS` columns inlined into their defining expressions. If
several projection/sort/group items expand to the same expression, the shard's
`ActionsDAG` deduplicates them into a single output column, so the shard header
has fewer columns than the header the initiator expects (the initiator keeps the
columns distinct, because there the `ALIAS` columns are not inlined).
The reconciliation in `buildQueryPlanForTableExpression` only renamed columns by
position via `ActionsDAG::makeConvertingActions` with `MatchColumnsMode::Position`,
which requires an equal number of columns and therefore threw
`NUMBER_OF_COLUMNS_DOESNT_MATCH`, e.g.:
SELECT a1, a2 FROM dist_same_expr ORDER BY dt DESC;
where `a1` and `a2` are both `ALIAS toString(x)`.
This adds `buildShardCollapseFanOut`, which reconstructs the initiator's expected
header from the deduplicated shard header by fanning out each collapsed shard
column back to every expected column that maps onto it. The mapping is computed
exactly: for every expression node in the query tree we compute both its
identifier-based action name (matching the initiator header) and its action name
after inlining `ALIAS` columns (matching the shard header), and use this
translation to resolve which shard column feeds each expected column. The helper
returns `std::nullopt` (and the caller falls back to the previous behaviour) when
the situation is not a recognized projection collapse.
This replaces the reverted ClickHouse#106404 approach (which disambiguated expressions on
the shard with a wrapper function) with a boundary-only reconciliation that does
not change shard-side naming.
Closes: ClickHouse#106403
Co-authored-by: Yakov Olkhovskiy <[email protected]>
…ning The disambiguation half of this pull request wrapped duplicate projection items in `__actionName(expr, '<unique>')`. It relied on the relaxation of `FunctionActionName` that #106404 made, which #107846 reverted the day after this branch was cut, so on current master that wrapper rejects every argument that is not a `String` constant: SELECT __actionName(materialize(1) + 1, 'dedup_1'); -- Code: 36. BAD_ARGUMENTS: Function __actionName is internal nad should not be used directly SELECT __actionName(toString(materialize(1)), 'dedup_1'); -- Code: 44. ILLEGAL_COLUMN: Argument at index 0 for function __actionName must be constant The duplicate-column reconciliation that superseded it now lives on the initiator, in `buildShardCollapseFanOut` (#107913). What remains here is the half that does not depend on any of that: the parallel-replicas entry points now inline `ALIAS` columns before `buildQueryTreeForShard`, exactly as the Distributed/`remote` path already does. `ReplaseAliasColumnsVisitor` moves out of `StorageDistributed.cpp` into `buildQueryTreeForShard.cpp` so all four callers share it, which also removes the byte-identical copy `InlineAliasColumnsForNamingVisitor` that landed on master in the meantime. Related: #112246 Co-authored-by: Yakov Olkhovskiy <[email protected]>
…parallel replicas Querying two ALIAS columns that expand to the same expression (e.g. both toString(x)) with GROUP BY over a Distributed/remote() table while parallel replicas are enabled threw NUMBER_OF_COLUMNS_DOESNT_MATCH (source: 1 and result: 2). The same query works without parallel replicas. The duplicate-ALIAS disambiguation added in ClickHouse#106404 lived only in StorageDistributed's buildQueryTreeDistributed and was never applied on the parallel-replicas query-preparation path. Extract that logic into a reusable inlineAndDisambiguateAliasColumns helper (in buildQueryTreeForShard) and call it from both ClusterProxy::executeQueryWithParallelReplicas and Planner::buildQueryPlanForParallelReplicas before buildQueryTreeForShard. Wrapping only the projection is not enough for parallel replicas: the per-replica query runs up to WithMergeableState, whose output cardinality is driven by the GROUP BY keys. With analyzer identifier-resolution node reuse a GROUP BY / ORDER BY / HAVING key is the same node object as the projection item, so after the projection item is wrapped the matching clause keys must be rewritten to the same __actionName wrapper (matched by node pointer, since the alias on the shared node has been cleared). Otherwise the duplicate keys collapse by name and the position-based column match throws. Closes: ClickHouse#107696 Related: ClickHouse#106404 Co-authored-by: Yakov Olkhovskiy <[email protected]>
… Distributed tables
When a Distributed query is executed up to `WithMergeableState`, the shard's
query tree has its `ALIAS` columns inlined into their defining expressions. If
several projection/sort/group items expand to the same expression, the shard's
`ActionsDAG` deduplicates them into a single output column, so the shard header
has fewer columns than the header the initiator expects (the initiator keeps the
columns distinct, because there the `ALIAS` columns are not inlined).
The reconciliation in `buildQueryPlanForTableExpression` only renamed columns by
position via `ActionsDAG::makeConvertingActions` with `MatchColumnsMode::Position`,
which requires an equal number of columns and therefore threw
`NUMBER_OF_COLUMNS_DOESNT_MATCH`, e.g.:
SELECT a1, a2 FROM dist_same_expr ORDER BY dt DESC;
where `a1` and `a2` are both `ALIAS toString(x)`.
This adds `buildShardCollapseFanOut`, which reconstructs the initiator's expected
header from the deduplicated shard header by fanning out each collapsed shard
column back to every expected column that maps onto it. The mapping is computed
exactly: for every expression node in the query tree we compute both its
identifier-based action name (matching the initiator header) and its action name
after inlining `ALIAS` columns (matching the shard header), and use this
translation to resolve which shard column feeds each expected column. The helper
returns `std::nullopt` (and the caller falls back to the previous behaviour) when
the situation is not a recognized projection collapse.
This replaces the reverted ClickHouse#106404 approach (which disambiguated expressions on
the shard with a wrapper function) with a boundary-only reconciliation that does
not change shard-side naming.
Closes: ClickHouse#106403
Co-authored-by: Yakov Olkhovskiy <[email protected]>
…rg::alter PR ClickHouse#106102 (merged 2026-06-05 17:43 UTC) refactored Iceberg::alter to declare last_version and compression_method outside an if/else that assigns them in both branches. Clang-tidy cppcoreguidelines-init-variables flags the bare declarations and Build (arm_tidy) is built with -warnings-as-errors, so the build fails for every PR whose CI ran on master after this commit. CIDB shows 30+ unrelated PRs hitting this in the last 2 days (e.g. ClickHouse#89360, ClickHouse#103540, ClickHouse#106120, ClickHouse#106386, ClickHouse#106404, ClickHouse#106522, ClickHouse#105102, ClickHouse#106590). Initialize both variables to safe defaults at declaration. They are unconditionally overwritten in both if and else branches before use, so behavior is unchanged. The new defaults are only relevant if a future code path skips both assignments, in which case last_version=0 and compression_method=CompressionMethod::None are sane no-op values (the same defaults the old structured-binding form would produce through default-construction of the destructured aggregate). Co-Authored-By: Claude Opus 4.8 <[email protected]> (cherry picked from commit d72cac5)
…rg::alter PR ClickHouse#106102 (merged 2026-06-05 17:43 UTC) refactored Iceberg::alter to declare last_version and compression_method outside an if/else that assigns them in both branches. Clang-tidy cppcoreguidelines-init-variables flags the bare declarations and Build (arm_tidy) is built with -warnings-as-errors, so the build fails for every PR whose CI ran on master after this commit. CIDB shows 30+ unrelated PRs hitting this in the last 2 days (e.g. ClickHouse#89360, ClickHouse#103540, ClickHouse#106120, ClickHouse#106386, ClickHouse#106404, ClickHouse#106522, ClickHouse#105102, ClickHouse#106590). Initialize both variables to safe defaults at declaration. They are unconditionally overwritten in both if and else branches before use, so behavior is unchanged. The new defaults are only relevant if a future code path skips both assignments, in which case last_version=0 and compression_method=CompressionMethod::None are sane no-op values (the same defaults the old structured-binding form would produce through default-construction of the destructured aggregate). Co-Authored-By: Claude Opus 4.8 <[email protected]> (cherry picked from commit d72cac5)
…rg::alter PR ClickHouse#106102 (merged 2026-06-05 17:43 UTC) refactored Iceberg::alter to declare last_version and compression_method outside an if/else that assigns them in both branches. Clang-tidy cppcoreguidelines-init-variables flags the bare declarations and Build (arm_tidy) is built with -warnings-as-errors, so the build fails for every PR whose CI ran on master after this commit. CIDB shows 30+ unrelated PRs hitting this in the last 2 days (e.g. ClickHouse#89360, ClickHouse#103540, ClickHouse#106120, ClickHouse#106386, ClickHouse#106404, ClickHouse#106522, ClickHouse#105102, ClickHouse#106590). Initialize both variables to safe defaults at declaration. They are unconditionally overwritten in both if and else branches before use, so behavior is unchanged. The new defaults are only relevant if a future code path skips both assignments, in which case last_version=0 and compression_method=CompressionMethod::None are sane no-op values (the same defaults the old structured-binding form would produce through default-construction of the destructured aggregate). Co-Authored-By: Claude Opus 4.8 <[email protected]> (cherry picked from commit d72cac5)
…S referenced in GROUP BY/ORDER BY/HAVING When buildQueryTreeDistributed disambiguates a duplicate-ALIAS projection item by wrapping it in __actionName(expr, '<unique_name>') and moving the alias onto the wrapper, GROUP BY / ORDER BY / HAVING / WINDOW keys that referenced the same alias still pointed at a sibling node carrying the bare inlined expression with that alias. On shard re-analysis two structurally different nodes shared one alias in the same scope, throwing MULTIPLE_EXPRESSIONS_FOR_ALIAS. Rewrite those sibling nodes to the wrapper as well, so a single structurally identical expression carries the alias throughout the scope. Closes: ClickHouse#107507 Related: ClickHouse#106404 Co-authored-by: Yakov Olkhovskiy <[email protected]>
…parallel replicas Querying two ALIAS columns that expand to the same expression (e.g. both toString(x)) with GROUP BY over a Distributed/remote() table while parallel replicas are enabled threw NUMBER_OF_COLUMNS_DOESNT_MATCH (source: 1 and result: 2). The same query works without parallel replicas. The duplicate-ALIAS disambiguation added in ClickHouse#106404 lived only in StorageDistributed's buildQueryTreeDistributed and was never applied on the parallel-replicas query-preparation path. Extract that logic into a reusable inlineAndDisambiguateAliasColumns helper (in buildQueryTreeForShard) and call it from both ClusterProxy::executeQueryWithParallelReplicas and Planner::buildQueryPlanForParallelReplicas before buildQueryTreeForShard. Wrapping only the projection is not enough for parallel replicas: the per-replica query runs up to WithMergeableState, whose output cardinality is driven by the GROUP BY keys. With analyzer identifier-resolution node reuse a GROUP BY / ORDER BY / HAVING key is the same node object as the projection item, so after the projection item is wrapped the matching clause keys must be rewritten to the same __actionName wrapper (matched by node pointer, since the alias on the shared node has been cleared). Otherwise the duplicate keys collapse by name and the position-based column match throws. Closes: ClickHouse#107696 Related: ClickHouse#106404 Co-authored-by: Yakov Olkhovskiy <[email protected]>
PR ClickHouse#106404 fixed the column count mismatch for identical-expression ALIAS columns in distributed queries. The `distributed_same_expr` query now returns `7 7` successfully instead of throwing `NUMBER_OF_COLUMNS_DOESNT_MATCH`. Co-authored-by: Yakov Olkhovskiy <[email protected]>
Closes: #105689
Related: #81631
When a
Distributedtable has two ALIAS columns expanding to the same expression (e.g. both aretoString(x)), querying them withORDER BYfails:Root cause
ReplaseAliasColumnsVisitorinbuildQueryTreeDistributedinlines both ALIAS expressions into the shard query tree. Since the expressions are structurally identical,calculateActionNodeNameproduces the same DAG node name for both. DownstreamremoveUnusedActions(NameSet)then collapses outputs by name and the shard returns fewer columns than the outer initiator planner expects (the outer planner sees the un-inlined tree, where the two columns have distinct identifiers). TheMatchColumnsMode::Positionrename inPlannerJoinTreethrows because the source column count from the shard does not match the result column count expected by the initiator.Fix
In
buildQueryTreeDistributed, snapshot each projection item'sgetTreeHash({.compare_aliases = false})beforeReplaseAliasColumnsVisitorinlines ALIAS columns. After inlining, group projection items by their post-inlining structural hash and within each group partition by the original hash:__actionName(expr, '<unique_name>')wrap;This guarantees the shard emits exactly as many distinct DAG output names as the outer planner's
NameSetdeduplication collapses to, regardless of whether the collision was introduced by inlining (e.g.SELECT a1, a2with bothALIAS toString(x)), by mixing inlined and user-written expressions (e.g.SELECT a1, toString(x)), or by pure user duplication (SELECT toString(x), toString(x)).The earlier revision of this PR keyed the wrap decision off "projection node alias matches the name of an ALIAS column in
ColumnsDescription". That predicate was an unreliable proxy: it false-negatived onSELECT a1, toString(x)(the user-written expression has no alias matching an ALIAS column) and could false-positive onSELECT a1 AS a2, a2. The structural-hash predicate above is what actually distinguishes "inlining created the collision" from "user wrote the duplicate".Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix
NUMBER_OF_COLUMNS_DOESNT_MATCHexception when querying aDistributedtable that has two or more ALIAS columns expanding to the same expression (e.g. both defined astoString(x)), or when the same expression is written both as an ALIAS column reference and directly in the SELECT list, with anORDER BYclause.Version info
26.6.1.809