Skip to content

Fix NUMBER_OF_COLUMNS_DOESNT_MATCH for Distributed table with duplicate ALIAS expressions - #106404

Merged
vdimir merged 15 commits into
masterfrom
cursor/fix-distributed-duplicate-alias-columns-6333
Jun 15, 2026
Merged

vdimir merged 15 commits into
masterfrom
cursor/fix-distributed-duplicate-alias-columns-6333

Conversation

@yakov-olkhovskiy

@yakov-olkhovskiy yakov-olkhovskiy commented Jun 3, 2026 •

Copy link
Copy Markdown
Member

Closes: #105689
Related: #81631

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:

Code: 20. DB::Exception: Number of columns doesn't match (source: 2 and result: 3). (NUMBER_OF_COLUMNS_DOESNT_MATCH)

Root cause

ReplaseAliasColumnsVisitor in buildQueryTreeDistributed inlines both ALIAS expressions into the shard query tree. Since the expressions are structurally identical, calculateActionNodeName produces the same DAG node name for both. Downstream removeUnusedActions(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). The MatchColumnsMode::Position rename in PlannerJoinTree throws 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's getTreeHash({.compare_aliases = false}) before ReplaseAliasColumnsVisitor inlines ALIAS columns. After inlining, group projection items by their post-inlining structural hash and within each group partition by the original hash:

  • the first partition in each post-inlining bucket keeps its natural DAG name;
  • every subsequent partition (i.e. a new original identity that only became structurally identical via inlining) gets a fresh __actionName(expr, '<unique_name>') wrap;
  • items inside the same partition share the same wrap.

This guarantees the shard emits exactly as many distinct DAG output names as the outer planner's NameSet deduplication collapses to, regardless of whether the collision was introduced by inlining (e.g. SELECT a1, a2 with both ALIAS 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 on SELECT a1, toString(x) (the user-written expression has no alias matching an ALIAS column) and could false-positive on SELECT 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):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fix NUMBER_OF_COLUMNS_DOESNT_MATCH exception when querying a Distributed table that has two or more ALIAS columns expanding to the same expression (e.g. both defined as toString(x)), or when the same expression is written both as an ALIAS column reference and directly in the SELECT list, with an ORDER BY clause.

Open in Web Open in Cursor 

Version info

  • Merged into: 26.6.1.809

…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]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [653e3b5]

Summary: ✅


AI Review

Summary

This PR targets a real Distributed planning bug where different ALIAS projections can become the same expression after alias inlining and then collapse in the shard-side ActionsDAG. The hash-based pre/post-inlining approach addresses the earlier alias-tracking holes, but the synthetic __actionName names are still not proven fresh against the actual ActionsDAG scope, so the fix can return wrong data when a legal column/action name collides with the generated name.

Findings

❌ Blockers

  • [src/Storages/StorageDistributed.cpp:1005] The disambiguation contract requires each synthetic __actionName result to be distinct from every name already visible to the shard projection ActionsDAG, but wrap_name is only __distributed_alias_dedup_<n> and is never checked against that scope. A valid table can have a material column named __distributed_alias_dedup_1; when a query like SELECT a1, a2, __distributed_alias_dedup_1 ... needs the first duplicate a2 wrapper, PlannerActionsVisitorImpl::visitFunction computes the same result name and ActionsScopeNode::addFunctionIfNecessary returns the existing input node instead of creating the wrapper. That makes the a2 output slot read the unrelated column, producing wrong results instead of preserving the inlined ALIAS expression.
    Suggested fix: make the generated name fresh at the point where the current ActionsDAG scope is known, or make __actionName insertion fail/retry when the chosen name is already bound to a different node. Reusing an existing node should only be allowed when it is the same synthetic wrapper for the same children.
Tests
  • ⚠️ Add a focused regression with a real column whose name collides with the generated internal prefix, for example __distributed_alias_dedup_1, and a Distributed query that selects both duplicate ALIAS projections and that real column. The test should prove the duplicate ALIAS output still returns the alias expression value, not the colliding column.
Final Verdict

Status: ❌ Block

Minimum required actions: prove synthetic __actionName names are fresh or fail-close on collisions, and add the collision regression above.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 3, 2026
Comment thread src/Planner/PlannerActionsVisitor.cpp Resolved
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]>
@CLAassistant

CLAassistant commented Jun 3, 2026 •

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
1 out of 2 committers have signed the CLA.

✅ alexey-milovidov
❌ cursoragent
You have signed the CLA already but the status is still pending? Let us recheck it.

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]>
Comment thread src/Storages/StorageDistributed.cpp Resolved
cursoragent and others added 2 commits June 4, 2026 02:06
…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]>
Comment thread src/Planner/PlannerActionsVisitor.cpp Resolved
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]>
Comment thread src/Storages/StorageDistributed.cpp Resolved
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]>
Comment thread src/Storages/StorageDistributed.cpp Resolved
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]>
Comment thread src/Storages/StorageDistributed.cpp Resolved
cursoragent and others added 2 commits June 4, 2026 14:38
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]>
Comment thread src/Storages/StorageDistributed.cpp Outdated
if (!col_default || col_default->kind != ColumnDefaultKind::Alias)
continue;

auto unique_name = node_alias + "_" + std::to_string(i);

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.

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.

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.

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.

cursoragent and others added 2 commits June 4, 2026 15:18
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]>
@filimonov

Copy link
Copy Markdown
Contributor

very similar #106402

@yakov-olkhovskiy
yakov-olkhovskiy marked this pull request as ready for review June 4, 2026 19:33
alexey-milovidov pushed a commit to evillique/ClickHouse that referenced this pull request Jun 6, 2026
…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)
alexey-milovidov pushed a commit to jh0x/ClickHouse that referenced this pull request Jun 6, 2026
…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)
alexey-milovidov pushed a commit to adityachopra29/ClickHouse that referenced this pull request Jun 6, 2026
…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)
alexey-milovidov pushed a commit to abonander/ClickHouse that referenced this pull request Jun 6, 2026
…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)
alexey-milovidov pushed a commit to melvynator/ClickHouse that referenced this pull request Jun 6, 2026
…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)
@clickhouse-gh

clickhouse-gh Bot commented Jun 13, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.70% 84.70% +0.00%
Functions 92.30% 92.30% +0.00%
Branches 77.30% 77.30% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 63/63 (100.00%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@vdimir
vdimir added this pull request to the merge queue Jun 15, 2026
Merged via the queue into master with commit eb2c089 Jun 15, 2026
166 checks passed
@vdimir
vdimir deleted the cursor/fix-distributed-duplicate-alias-columns-6333 branch June 15, 2026 10:37
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 15, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @yakov-olkhovskiy @vdimir — while reviewing this PR I found the following:

Happy to discuss — close anything that's wrong or already addressed.

cursor Bot pushed a commit that referenced this pull request Jun 15, 2026
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]>
@filimonov

Copy link
Copy Markdown
Contributor

I was already fighting the same problems... #106402

pull Bot pushed a commit to CrazyForks/ClickHouse that referenced this pull request Jun 23, 2026
… 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]>
cursor Bot pushed a commit that referenced this pull request Aug 5, 2026
…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]>
pull Bot pushed a commit to peijunlin2008/ClickHouse that referenced this pull request Aug 10, 2026
…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]>
zeekay added a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
… 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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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)
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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)
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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)
zeekay added a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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]>
zeekay added a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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]>
zeekay added a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Wrong results / exception querying multiple ALIAS columns with identical expressions from Distributed table with ORDER BY LIMIT

8 participants