Skip to content

Inline ALIAS columns on the parallel-replicas shipping paths - #107700

Merged
yakov-olkhovskiy merged 26 commits into
masterfrom
cursor/fix-distributed-dup-alias-parallel-replicas-3628
Aug 10, 2026
Merged

yakov-olkhovskiy merged 26 commits into
masterfrom
cursor/fix-distributed-dup-alias-parallel-replicas-3628

Conversation

@yakov-olkhovskiy

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

Copy link
Copy Markdown
Member

Closes: #112246
Closes: #107990
Related: #113364
Related: #108025
Related: #101789
Related: #107913

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):

Fixed NO_SUCH_COLUMN_IN_TABLE when a query with parallel replicas selects an ALIAS column of a table shipped as a GLOBAL JOIN temporary table, MULTIPLE_EXPRESSIONS_FOR_ALIAS when both sides of a distributed JOIN declare an ALIAS column with the same name, and UNKNOWN_IDENTIFIER when a Distributed table declares an ALIAS column over another ALIAS column, including as a JOIN USING key.

Description

A query tree that is about to be shipped goes through buildQueryTreeForShard, which rebuilds the shipped table expression from column names and types only. That drops an ALIAS column's resolved body, so the remote side asks storage for a column it does not have:

Code: 16. DB::Exception: There is no column or subcolumn a_v in table. (NO_SUCH_COLUMN_IN_TABLE)

The Distributed/remote path never hit this because it inlines ALIAS columns into their bodies beforehand. Neither parallel-replicas caller did. This makes all the shipping callers inline, which is what the rest of the code already assumes, so the alias is computed by the replica that reads the real table.

Inlining alone is not enough, though: the existing inliner mutates the column's stored body in place and stamps the column's name on it. When two JOIN sides declare a same-named ALIAS column, one alias ends up on two different bodies, and once the shipped query is converted back to SQL the remote analyzer sees

ORDER BY __table1.v * 2 AS a_v DESC, __table2.v * 2 AS a_v DESC

and throws MULTIPLE_EXPRESSIONS_FOR_ALIAS (#107990, reproducible on master today through a plain remote() join). So the inliner now clones the body per occurrence and sets the alias only where it is needed: on top-level projection items, to keep the mergeable-state output column's name, and on the per-side entries of a JOIN USING key list, because the shipped SQL renders those entries rather than the key — an ALIAS column that exists only on the Distributed table has to arrive as USING (x AS a), since the shard's table has x and has never heard of a. References in WHERE / GROUP BY / ORDER BY / HAVING / JOIN ON are inlined bare. This is the inliner from #108025, which this supersedes.

It also unwraps a chain rather than one link. The old inliner replaced a column with its body once, so an ALIAS column defined over another ALIAS column kept the intermediate name in the shipped SQL and a shard that does not know it failed with Identifier '__table1.d' cannot be resolved from table with name __table1 (UNKNOWN_IDENTIFIER). That is visible whenever the chain is declared only on the Distributed table, including when the chain is used as a JOIN USING key, and still reproduces on master.

ReplaseAliasColumnsVisitor moves out of StorageDistributed.cpp into buildQueryTreeForShard.cpp so all four callers share one implementation; that also removes InlineAliasColumnsForNamingVisitor, a byte-identical copy that landed separately.

On the original scope of this pull request

This branch was opened against master of 2026-06-17 to fix a NUMBER_OF_COLUMNS_DOESNT_MATCH for duplicate ALIAS columns under parallel replicas, by extracting the __actionName disambiguation from #106404 and reusing it. #106404 was reverted the next day by #107846, and #107913 replaced it with initiator-side reconciliation (buildShardCollapseFanOut). Two consequences:

  • The disambiguation no longer works. The revert restored __actionName to accepting only constant String arguments, so wrapping a projection expression now throws BAD_ARGUMENTS, or ILLEGAL_COLUMN for a non-constant argument.
  • It is also no longer needed: 04341_distributed_alias_dedup_parallel_replicas, added here as the regression test for that bug, passes unmodified on current master.

The disambiguation is therefore dropped and only the inlining is kept. 04341 and the integration test are retained as coverage of the paths this still touches.

Tests

Test Origin On master
04757_parallel_replicas_shipped_alias_column new here; the type and clause matrix 13 NO_SUCH_COLUMN_IN_TABLE
04761_shipped_alias_column_join_shapes new here; the join shapes and dispatch modes 7 NO_SUCH_COLUMN_IN_TABLE, 2 MULTIPLE_EXPRESSIONS_FOR_ALIAS
04758_distributed_join_same_named_alias_column the #107990 test from #108025 6 MULTIPLE_EXPRESSIONS_FOR_ALIAS
04759_shipped_alias_column_evaluated_once the laziness test from #113364 the parallel_replicas_local_plan = 1 arm throws instead of reporting a count
04760_distributed_chained_alias_column the chained-ALIAS shape from #101789 8 UNKNOWN_IDENTIFIER
04762_distributed_using_key_alias_only_on_distributed new here, after review feedback 1 UNKNOWN_IDENTIFIER (the chained USING key)
04341_distributed_alias_dedup_parallel_replicas, test_parallel_replicas_alias_columns this branch, retained pass (their bug is already fixed on master)

04757 and 04761 are one matrix split in two: the flaky check timed the combined test at 192s against a 180s budget, since a debug build with randomized settings spends around seven seconds per parallel-replicas query.

The duplicate-ALIAS half of #101789 needs no test here: it is already fixed on master by #107913, and the shapes from its issue #85895 produce identical results on master and here.

04759 stays a shell test on purpose. Reading SleepFunctionCalls from system.query_log instead does not hold up: which entry carries the counter depends on the dispatch path (the initiator aggregates the replicas' events when shipping a plan but not when shipping SQL), so the replicas' own entries have to be summed, and in CI they are not reliably written by the time the initiator's query returns. The client's --print-profile-events aggregate is delivered in band with the query and has no such race.

Validation

Built and run against a three-replica localhost cluster, compared with a master build and with the #113364 build:

master #113364 this
#112246 reproducer NO_SUCH_COLUMN_IN_TABLE pass pass
#113364's own 30-shape test 24 exceptions pass pass, output byte-identical to its reference
#113364's laziness test one arm throws pass pass, reference identical
#108025's #107990 test 6 exceptions 6 exceptions pass
#101789's chained-ALIAS shapes 8 UNKNOWN_IDENTIFIER 8 UNKNOWN_IDENTIFIER pass
#101789's duplicate-ALIAS shapes (#85895) pass pass pass, identical output
USING key that is a Distributed-only ALIAS pass pass pass
USING key that is a Distributed-only ALIAS chain UNKNOWN_IDENTIFIER UNKNOWN_IDENTIFIER pass
04341 pass pass pass
04604_join_using_nested_projection_alias_remote pass pass pass
28 neighbouring alias/distributed tests pass pass pass

On the shapes it shares with #113364, that PR's independent implementation produces byte-identical values.

Open in Web Open in Cursor 

Version info

  • Merged into: 26.8.1.1128 (included in 26.8 and later)

cursoragent and others added 2 commits June 17, 2026 04:31
…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 #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: #107696
Related: #106404

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

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 sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@clickhouse-gh

clickhouse-gh Bot commented Jun 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1ca669d]

Summary: ✅


AI Review

Summary

This PR moves shipped-query ALIAS inlining into shared buildQueryTreeForShard helpers, applies it on the Distributed and parallel-replicas shipping paths, and adds focused regressions for shipped ALIAS columns, same-named join aliases, chained aliases, JOIN USING, and volatile bodies. After reviewing the current head diff and all prior discussion threads, I did not find a remaining correctness issue in the final code.

Missing context / blind spots
  • ⚠️ The latest Praktika link available from the bot only exposed the Build profile diff shard in this run, so I could not cross-check the stateless or integration job results from CI here.
Final Verdict
  • Status: ✅ Approve
  • No further changes required from review.

LLVM Coverage Report

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

Changed lines: Changed C/C++ lines covered: 72/77 (93.51%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 17, 2026
cursoragent and others added 2 commits June 17, 2026 05:13
…cas path too

The analyzer custom-key parallel-replicas path (PlannerJoinTree, reading a MergeTree table
directly with cluster_for_parallel_replicas and parallel_replicas_mode=custom_key_*) built the
per-replica query from the original, un-disambiguated query tree. Apply inlineAndDisambiguateAliasColumns
there as well, mirroring the task-based path, so duplicate ALIAS projection columns do not collapse
by name on the replicas. Addresses review feedback on the parallel-replicas fix.

Co-authored-by: Yakov Olkhovskiy <[email protected]>
cursoragent and others added 2 commits June 17, 2026 05:45
Real multi-node (4 replicas) coverage for duplicate-ALIAS GROUP BY under task-based,
custom_key_sampling and custom_key_range parallel replicas.

Co-authored-by: Yakov Olkhovskiy <[email protected]>
…n tests catch the bug in CI

This commit will be reverted. It disables inlineAndDisambiguateAliasColumns so that the new
stateless and integration regression tests fail in CI, proving the bug reproduces without the fix.

Co-authored-by: Yakov Olkhovskiy <[email protected]>
Comment thread src/Storages/buildQueryTreeForShard.cpp Resolved
…licas path

Reverts the global disable and instead disables the fix solely on the custom-key path, so that a
failure of the custom_key_sampling/custom_key_range integration cases proves the bug is reproduced
specifically through that path, while the task-based and Distributed paths stay fixed (their tests
must still pass). Will be reverted to re-enable the fix.

Co-authored-by: Yakov Olkhovskiy <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 17, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.20% 85.20% +0.00%
Functions 92.30% 92.30% +0.00%
Branches 77.50% 77.50% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 102/102 (100.00%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 2 line(s) · Uncovered code

Full report · Diff report

cursoragent and others added 5 commits August 5, 2026 02:28
…ted-dup-alias-parallel-replicas-3628

# Conflicts:
#	src/Planner/PlannerJoinTree.cpp
#	src/Storages/StorageDistributed.cpp

Co-authored-by: Yakov Olkhovskiy <[email protected]>
…eplicas path

Reverts the `TEMPORARY` CI-verification scaffolding of ea14e3e, which commented out the
`inlineAndDisambiguateAliasColumns` call on the custom-key path so that the `custom_key_sampling` /
`custom_key_range` integration cases would fail in CI and prove they reproduce the bug through that
path. The earlier global disable (8fcbbe7) was already undone by that same commit.

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]>
Inlining an `ALIAS` column by mutating its stored expression and stamping the column's name on it puts
the same alias on two different bodies whenever two `JOIN` sides declare a same-named `ALIAS` column,
and the remote side then throws `MULTIPLE_EXPRESSIONS_FOR_ALIAS`. With the shipped query converted back
to SQL this surfaces through `ORDER BY`, which keeps both references:

    ORDER BY __table1.v * 2 AS a_v DESC, __table2.v * 2 AS a_v DESC

Clone the defining expression per occurrence and set the alias only on top-level projection items, where
it is needed to keep the mergeable-state output column's name. References inside `WHERE` / `GROUP BY` /
`ORDER BY` / `HAVING` / `JOIN ON` are inlined bare. Nested subqueries and unions are recursed into as
queries so their own projections keep their names. This is the inliner from
#108025, which becomes redundant once this lands.

Closes: #107990

Co-authored-by: Yakov Olkhovskiy <[email protected]>
Covers the `NO_SUCH_COLUMN_IN_TABLE` this pull request fixes (an `ALIAS` column of the table expression
that parallel replicas ship as a `GLOBAL JOIN` temporary table) across both shipping callers, both
dispatch modes, `Nullable` / `LowCardinality` / narrower-declared-type / alias-on-alias /
alias-over-`MATERIALIZED` bodies, aliases used only in a clause, and `GLOBAL IN`. Also covers the
same-named `ALIAS` column on both `JOIN` sides, on the parallel-replicas and the Distributed path.

On master the test reports 16 `NO_SUCH_COLUMN_IN_TABLE` and 2 `MULTIPLE_EXPRESSIONS_FOR_ALIAS`.

Related: #112246
Related: #107990

Co-authored-by: Yakov Olkhovskiy <[email protected]>
@cursor cursor Bot changed the title Fix NUMBER_OF_COLUMNS_DOESNT_MATCH for duplicate ALIAS columns under parallel replicas Inline ALIAS columns on the parallel-replicas shipping paths Aug 5, 2026
cursoragent and others added 5 commits August 5, 2026 05:30
`access/*.list` and `preprocessed_configs/config.xml` are written by a running server into its working
directory. They were swept in while validating this branch against a local server that had been started
from the repository root, and are not part of the change.

Co-authored-by: Yakov Olkhovskiy <[email protected]>
The wording check for "new analyzer" landed on master after this branch was cut.

Co-authored-by: Yakov Olkhovskiy <[email protected]>
A `JOIN USING` key is a `ColumnNode` whose expression is a `ListNode` recording how the key resolves on
each side, and a side's entry can itself be a `ColumnNode` with an expression and a table source, so it
looks exactly like an inlineable `ALIAS` column:

    COLUMN id: 23, column_name: id, source_id: 17            -- the key, source is the JOIN
      EXPRESSION
        LIST id: 24, nodes: 2
          COLUMN id: 25, column_name: id, source_id: 9       -- source is the TABLE
            EXPRESSION
              FUNCTION id: 26, function_name: plus           -- x + 10, the nested SELECT-list alias

That list is analyzer bookkeeping rather than an expression to evaluate: the shipped SQL renders
`USING (name)`. `rejectUnshippableJoinUsingKeys` reads it to decide whether a remote server can resolve
the key, and accepts either shape - a `ColumnNode` with an expression, or a non-`ColumnNode` with an
alias. Inlining the entry produced the second shape without an alias, which the check reads as "nothing
to see here", so an unshippable key was shipped and the shard failed with `UNKNOWN_IDENTIFIER` instead
of the intended `UNSUPPORTED_METHOD`. Caught by `04604_join_using_nested_projection_alias_remote`.

Leaving the list alone gives the check the un-inlined shape, which is what it already sees on the
parallel-replicas path.

Co-authored-by: Yakov Olkhovskiy <[email protected]>
`04757` grows the shapes it was missing relative to #113364's own matrix: two `ALIAS` columns with
identical bodies, `ARRAY JOIN` on either side, `GLOBAL RIGHT JOIN`, and `GLOBAL JOIN ... USING` both
selecting the key and selecting an `ALIAS` column beside it.

`04758` is the #107990 regression test from #108025,
covering the same-named `ALIAS` column referenced from `JOIN ON` / `WHERE` / `GROUP BY` / `ORDER BY` /
a projection expression / a `GLOBAL JOIN` subquery over real `Distributed` tables. It reports six
`MULTIPLE_EXPRESSIONS_FOR_ALIAS` on master.

`04759` is the laziness test from #113364: an `ALIAS`
column of a shipped table expression must be computed once per row on every dispatch path. Inlining
keeps that property, so the reference is identical to that pull request's. On master the
`parallel_replicas_local_plan=1` arm throws instead of reporting a count.

Co-authored-by: Yakov Olkhovskiy <[email protected]>
…shell test

The laziness check does not need the shell harness: `log_comment` marks each arm, and the profile event
is available in `system.query_log`. The counter's location differs by dispatch path - the initiator
aggregates the replicas' events when shipping a plan but not when shipping SQL - so the entries of one
execution are summed by their shared `initial_query_id`, and only the latest execution of each arm is
kept so the test survives being re-run in one database, as the flaky check does.

Co-authored-by: Yakov Olkhovskiy <[email protected]>
cursoragent and others added 2 commits August 5, 2026 07:05
The SQL rewrite read `SleepFunctionCalls` from `system.query_log`, which does not hold up. Which entry
carries the counter depends on the dispatch path - the initiator aggregates the replicas' events when
shipping a plan but not when shipping SQL - so the replicas' own entries have to be summed, and in CI
they are not reliably in `query_log` by the time the initiator's query returns: the arm that ships SQL
reported 0 instead of 20. The runner also sets its own `log_comment` per test, which the prefix filter
picked up as a spurious extra row.

The client's `--print-profile-events` aggregate is delivered in band with the query, so it has neither
problem. Restore the shell form, which is the one #113364 has already had green in CI.

Co-authored-by: Yakov Olkhovskiy <[email protected]>
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]>
Comment thread src/Planner/PlannerJoinTree.cpp Resolved
That path does not need the inlining, so this drops the change to it and takes `PlannerJoinTree.cpp` out
of the diff entirely.

The bug this fixes is `buildQueryTreeForShard` rebuilding a shipped table expression from column names
and types, which loses the `ALIAS` body. The custom-key path does not do that: it ships SQL against the
real table, whose schema declares the `ALIAS` column, so the replica resolves it unaided. Master ships
`SELECT \`__table1\`.\`a_v\` AS \`a_v\` FROM ...` there and the replica is happy with it. A `GLOBAL JOIN`,
which is the shape that does ship a rebuilt table expression, never reaches this branch at all - it logs
no secondary queries under `parallel_replicas_mode = 'custom_key_range'`, while a plain query on the same
table logs three.

So the call only changed the shipped SQL, inlining the body where nothing needed it, with no failing case
behind it. Removing it also answers the review point that nothing covered it: there is nothing left to
cover.

Reported by the review bot on
#107700 (comment).

Co-authored-by: Yakov Olkhovskiy <[email protected]>
@novikd novikd self-assigned this Aug 6, 2026
The workflow for 4de7b96 stayed queued without ever starting, and the report offered no rerun.

Co-authored-by: Yakov Olkhovskiy <[email protected]>
Comment thread src/Storages/buildQueryTreeForShard.cpp Resolved
Inlining hands each reference its own copy of the body, so a volatile body would be drawn more than once
per row if the copies did not converge again on the remote side. They do, and for a reason worth
recording: an action node is named after the expression rather than the SQL alias - the same property
`actionNameAfterAliasInlining` relies on - so structurally identical copies map to one node.

Measured with `a UInt32 ALIAS rand()` over 2000 rows, on the Distributed path and on both
parallel-replicas dispatch modes: a filter and a projection on the alias agree, two projections of it
agree, and `WHERE a = a` keeps every row. Had the references come apart, about half the rows would
disagree. Two assertions are added here, both 0 whatever `rand()` returns, so the reference stays stable.

Reported by the review bot on
#107700 (comment).

Co-authored-by: Yakov Olkhovskiy <[email protected]>
Comment on lines +209 to +211
for (auto & child : query_node->getChildren())
if (child && child != query_node->getProjectionNode())
inlineAliasColumnsInExpression(child);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is the projection list now only inlined? What if it is used in the GROUP BY or filter condition (or other places)?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

projection list is inlined above in 193-207 (with alias), here we are inlining all other nodes

const String key_name = side_column->getColumnName();
inlineAliasColumnsInExpression(expression);
expression->setAlias(key_name);
side = expression;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure I understand how this expression is then transformed to the AST, but if tests cover it, I'm okay

@yakov-olkhovskiy yakov-olkhovskiy Aug 8, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

USING is converted into USING (<left side resolved> AS <right side resolved>) when the two sides resolve to different names

Comment thread src/Storages/buildQueryTreeForShard.cpp Resolved
@clickgapai

Copy link
Copy Markdown
Contributor

@yakov-olkhovskiy @novikd — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

mkmkme added a commit to Altinity/ClickHouse that referenced this pull request Sep 19, 2026
…ALIAS columns

A `Distributed` query that reads the same-named `ALIAS` column from two
`JOIN` sources fails on the shard:

    Multiple expressions __aliasMarker(__table2.x, '__table4.foo') AS foo
                     and __aliasMarker(__table1.x, '__table3.foo') AS foo
                     for alias foo

`ReplaseAliasColumnsVisitor` stamped `setAlias(column_name)` on every marker it
created, so two markers carrying different ids both ended up named `foo` in the
same scope. It also aliased `column_node->getExpression()` in place, which is
shared between occurrences, so aliasing one occurrence changed the others.

Set the alias only where it is read. A top-level projection item keeps it so
the mergeable-state output column keeps its name, and a `JOIN USING` key side
keeps it because the shipped SQL renders the side rather than the key and
`rejectUnshippableJoinUsingKeys` reads that shape. Everywhere else -- `WHERE`,
`GROUP BY`, `ORDER BY`, `HAVING`, `JOIN ON` -- no alias is set, which is what
removes the collision. Clone the defining expression per occurrence so setting
an alias on one no longer reaches another.

The pass moves from `StorageDistributed` to `buildQueryTreeForShard` as
`inlineAliasColumns`, matching the name, file and semantics of the shared
inliner upstream introduced in
ClickHouse#107700, which fixes the same
class of failure (ClickHouse#107990)
without markers. Writing it there keeps the next version bump a merge rather
than a rewrite. The signature takes a `ContextPtr` that upstream's does not,
because marker injection needs the `enable_alias_marker` setting and function
resolution; with the setting off, the pass behaves exactly as upstream's.

Not ported here: the parallel-replicas call sites ClickHouse#107700 adds. No staged test
needs them yet.

Verified against the 20 staged regression tests from
#1844:
`05054_distributed_global_alias_marker_matrix` now passes, and the other 19
are byte-identical to the run before this change -- same error codes, same
messages. `05061` covers `enable_alias_marker = 0`, and `03844` / `05055`
cover nested marker chains; all three still pass.

Related: #1844
Related: ClickHouse#107700

Co-Authored-By: Claude Opus 5 <[email protected]>
mkmkme added a commit to Altinity/ClickHouse that referenced this pull request Sep 19, 2026
A review of the three preceding commits turned up four things worth
changing.

`finalizeAliasMarkersForDistributedSerialization` refused to descend into
a lambda body, but the inliner has no such limit: `inlineExpression`
recurses through every child, so `arrayMap(x -> x + computed, dist)`
wrapped `computed` in a marker that nothing then materialized. Its id
stayed a `ColumnNode` and was rendered straight back into the shipped SQL
as `__table1.computed`, leaving the shard to resolve the very `ALIAS`
column the inlining exists to remove. Where the column is declared on the
`Distributed` table and not on the local one, the shard cannot.

The guard is gone. The case it was written for -- a hand-written
`__aliasMarker(x, x)` inside a lambda, whose id is the lambda parameter
-- is now handled by checking the id's column source instead. A lambda
parameter's source is the `LambdaNode`, which `createUniqueAliasesIfNecessary`
never aliases, so it is recognisable without refusing to look.

`makeConvertingActionsPreferNameThenPosition` is deleted. Its only call
site builds `converted_columns[i]` out of `current_step_columns[i]`, and
every branch of that loop either copies the source name through or --
in the one branch reachable only when the source name is absent from
`header` -- substitutes a name that cannot then appear anywhere in the
result set. So either every name matches its own position, in which case
`MatchColumnsMode::Name` and `::Position` pair the same columns, or the
two name sets differ and the helper falls back to position anyway. The
column swap in `05057` is fixed by emitting alias outputs under analyzer
identifiers, not by this. `src/Planner/Utils.{h,cpp}` are back to their
previous contents.

Finalization moved from `buildQueryTreeDistributed` into the end of
`buildQueryTreeForShard`. Four call sites build a shard tree and only one
finalized it; nothing is broken today, because only the `Distributed`
path injects markers at all, but wiring a second injection site would
have shipped markers nobody materializes. Last in the function rather
than straight after `createUniqueAliasesIfNecessary`, so a long id still
passes `ReplaceLongConstWithScalarVisitor` as a `ColumnNode` rather than
as a `String` that visitor could replace with a scalar.

The plain-name to analyzer-identifier mapping in
`ReadFromMerge::convertAndFilterSourceStream` now takes the longest
matching declared column name rather than the first. This is not a bug
fix: reintroducing the first-match behaviour leaves `05065` passing,
because an analyzer identifier backquotes a dotted name and the child
stream never emits a dotted identifier. It removes the mapping's
dependence on an invariant enforced two layers away.

Two review findings were not acted on. An assertion for an unfinalized
marker id cannot be written: nothing at the planner can tell an injected
marker that missed its boundary from one a user typed, and `03933` runs
exactly that shape on purpose. And `NormalizeAliasMarkerVisitor` does not
discard nested marker chains -- it never descends into a marker's own
arguments and collapses one only when the payload is itself a marker, so
the only id it drops names an intermediate action node. Both are recorded
as comments where a future reader will look.

Upstream ClickHouse#107700 also calls
`inlineAliasColumns` from `ClusterProxy/executeQuery.cpp` and
`findParallelReplicasQuery.cpp`, fixing `NO_SUCH_COLUMN_IN_TABLE` for an
`ALIAS` column on the shipped side of a parallel-replicas query. That bug
is real on this branch's base and predates this work. It is left alone:
this `inlineAliasColumns` injects markers when `enable_alias_marker` is
on, which is the default, so wiring those sites would put markers on two
paths that have never carried one.

New tests: `05064_alias_marker_in_lambda_over_distributed` covers the
lambda case, and `05065_shadowed_dotted_alias_merge_over_distributed`
guards the values for a `Merge` schema declaring both `b` and `` `a.b` ``.

Related: #1844
Related: ClickHouse#107700

Co-Authored-By: Claude Opus 5 <[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

7 participants