Skip to content

Distributed ALIAS columns: introduce __aliasMarker reconciliation - #106402

Draft
filimonov wants to merge 3 commits into
ClickHouse:masterfrom
filimonov:alias_marker3
Draft

filimonov wants to merge 3 commits into
ClickHouse:masterfrom
filimonov:alias_marker3

Conversation

@filimonov

@filimonov filimonov commented Jun 3, 2026 •

Copy link
Copy Markdown
Contributor

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 wrong results and THERE_IS_NO_COLUMN / NUMBER_OF_COLUMNS_DOESNT_MATCH errors when querying ALIAS columns from Distributed or parallel-replicas — especially with ORDER BY ... LIMIT (mergeable-state hop) or when multiple aliases share subexpressions.

Closes #81631, #79916.

Description

StorageDistributed expands ALIAS columns to their underlying expressions for shard-side transport. This rewriting changes column names and order on the remote header, while the initiator's planner still expects the original logical-column header. The reconciliation step at the boundary historically matched by position, silently producing wrong results when the order diverged and failing loudly with THERE_IS_NO_COLUMN / NUMBER_OF_COLUMNS_DOESNT_MATCH when the count diverged.

This PR introduces a two-phase __aliasMarker protocol that preserves logical-column identity across the boundary so the reconciliation can match by name.

Mechanism

  1. Inject — ReplaseAliasColumnsVisitor wraps each ALIAS-expansion in __aliasMarker(expr, original_column_node). __aliasMarker is a 2-argument pass-through identity; arg2 carries the original column identity.
  2. Finalize — after createUniqueAliasesIfNecessary assigns stable __tableN aliases, finalizeAliasMarkersForDistributedSerialization materializes each marker's arg2 from ColumnNode to a String ConstantNode("__tableN.col"). Lambda bodies are skipped (so user-typed markers inside lambdas don't trigger a logical error). Called from buildQueryTreeDistributed and from executeSubqueryNode for GLOBAL IN/JOIN materialized subqueries.
  3. Consume — PlannerActionsVisitor uses the materialized string id as the action node name, so the shard emits each value under the stable __tableN.col identifier. A new helper makeConvertingActionsPreferNameThenPosition routes the remote-table boundary conversion (PlannerJoinTree) and the parallel-replicas-follower header conversion (findParallelReplicasQuery) to MatchColumnsMode::Name when the rename is unambiguous (set equality, no duplicates), MatchColumnsMode::Position otherwise. The legacy non-analyzer path explicitly rejects direct __aliasMarker calls.

The Name-mode routing change is unconditional — enable_alias_marker = false disables marker injection but leaves the boundary helper in place. Name-mode is at-least-as-correct as Position-mode when names form an unambiguous set; the routing change can be reverted by setting enable_alias_marker = false AND restoring the prior MatchColumnsMode::Position at the two call sites if needed.

The Position branch in the helper is structurally load-bearing — making it strict regresses every base SELECT count() FROM <MergeTree> query.

Why Position fallback is required (full repro on a plain local query, click to expand)
CREATE TABLE test_local (x Int64) ENGINE = MergeTree ORDER BY x AS SELECT * FROM numbers(10);
SELECT count() FROM test_local;

EXPLAIN header=1:

Expression ((Project names + Projection))   Header: count() UInt64
  MergingAggregated                          Header: count() UInt64
    Expression (Change column names)         Header: count() AggregateFunction(count, Int64)
      ReadFromPreparedSource (Optimized trivial count)
                                             Header: x AggregateFunction(count, Int64)

The Expression (Change column names) step is the helper's call site. Source carries the table's first column name (x) as its synthetic AggregateFunction(count, Int64) state header; result wants count(). Name-mode cannot match these strings. Position-mode resolves it as ALIAS x -> count(). The narrower correct fix (renaming the ReadFromPreparedSource output) lives at the source-step builder level — out of scope here.

Setting

Adds enable_alias_marker (default false). The setting is shipped off by default to avoid breaking rolling upgrades: a new initiator with the setting on would emit __aliasMarker(...) in shard SQL that old shards do not recognize (UNKNOWN_FUNCTION). Operators enable it per query or via profile once a cluster is uniformly upgraded; the default can flip to true in a later release.

Regression tests

File Scenario
04278_alias_marker_internal_function.sh Function registration, setting existence, lambda over Distributed no LOGICAL_ERROR, arg2 materialized as action node name across mergeable-state stages, non-analyzer rejection, escape-hatch reverses behavior
04279_distributed_alias_planner_column_count.sql Single-hop CSE collapse + multi-hop Distributed-over-Distributed (column-count mismatch on master)
04280_distributed_alias_column_order.sql Canonical #81631 reproducer
04282_parallel_replicas_alias_second_hop.sql Parallel-replicas follower header reconciliation
04283_distributed_alias_global_in_product_mode_local.sql GLOBAL IN with distributed_product_mode='local' (analyzer alias-uniquification)
04284_distributed_alias_query_clauses.sql Alias columns in WHERE+GROUP BY and in JOIN ON
04285_alias_marker_array_join.sql Direct user-written __aliasMarker over ARRAY JOIN must pass through (finalize-visitor unaliased-source branch)

Out of scope

  • Renaming ReadFromPreparedSource (Optimized trivial count) output to count() so the Name branch matches without Position fallback.
  • Demoting the residual LOGICAL_ERROR in finalizeAliasMarkersForDistributedSerialization for non-lambda user-reachable shapes.

  • Documentation is written / is not needed

Workflow [PR]
Sync PR [sync-upstream/pr/106402]

`StorageDistributed` expands `ALIAS` columns to their underlying expressions
before sending SQL to shards, which changes column names and order on the
remote header. The boundary reconciliation step previously matched by
position, silently producing wrong results when order diverged and failing
loudly with `THERE_IS_NO_COLUMN` / `NUMBER_OF_COLUMNS_DOESNT_MATCH` when
count diverged.

This change adds a two-phase `__aliasMarker(expr, id)` protocol:

  1. `ReplaseAliasColumnsVisitor` wraps each expanded ALIAS expression in
     `__aliasMarker(expr, original_column_node)`.
  2. `finalizeAliasMarkersForDistributedSerialization` materializes arg2
     from a `ColumnNode` into a `ConstantNode("__tableN.col")` after
     `createUniqueAliasesIfNecessary` assigns stable `__tableN` aliases,
     so the shard emits each value under the analyzer identifier. Lambda
     bodies are skipped; nested marker chains pass through.

`PlannerActionsVisitor` uses the materialized id as the action node name.
A new helper `makeConvertingActionsPreferNameThenPosition` routes the
boundary conversion at `PlannerJoinTree` and `findParallelReplicasQuery`
to `MatchColumnsMode::Name` when names form an unambiguous set,
`MatchColumnsMode::Position` otherwise. The Position branch is
structurally required for paths like `Optimized trivial count`. This
routing is unconditional - `enable_alias_marker = false` disables marker
injection but leaves the helper in place.

Gated by `enable_alias_marker` (default `false` for rolling-upgrade
safety; old shards do not recognize `__aliasMarker`). The non-analyzer
`ActionsVisitor` path rejects `__aliasMarker`.

Closes ClickHouse#81631, ClickHouse#79916.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@yakov-olkhovskiy

yakov-olkhovskiy commented Jun 19, 2026 •

Copy link
Copy Markdown
Member

@filimonov thank you for this work - it's a thorough, well-documented PR, and the __aliasMarker design clearly does address the whole family of distributed ALIAS-column problems in one place.

After careful consideration, though, we'd prefer not to adopt it, for a few reasons:

  • we try to avoid introducing new internal functions unless strictly necessary - they tend to leak into introspection and the user-facing surface, and add long-term maintenance cost;
  • the change is fairly invasive (spanning shard-side naming, transport, and boundary reconciliation); we lean toward more targeted, independently reviewable fixes.;
  • keeping duplicate columns distinct on the shard prevents their deduplication, which increases the amount of data transferred over the network;
  • because it bridges behavior across initiator and shards, it requires a careful, synchronized rollout (and is gated behind a default-off setting), which we'd rather avoid.

Given this, we'd suggest putting this on hold for now, unless a compelling need for the unified approach comes up. The underlying problems appear to be mostly covered already by #107913 (column-count mismatch) and #107675 (column order), with the remaining GLOBAL IN / JOIN alias collision tracked separately in #107990.

Thanks again for the effort and the detailed write-up - it made the trade-offs easy to evaluate.

cc @KochetovNicolai @vdimir

cursor Bot pushed a commit that referenced this pull request Jun 19, 2026
…rialize_query_plan cases

Broaden the duplicate-ALIAS column-count regression coverage to match the
distributed scenarios exercised by PR #106402:

- `Distributed`-over-`Distributed` (two transport hops), including over the
  query-plan-serialization transport (`serialize_query_plan = 1`);
- `remote` over a `Distributed` table with parallel replicas (the
  `remote` -> `Distributed` -> parallel-replicas second hop);
- single-hop `serialize_query_plan = 1` variant.

These all reproduce `NUMBER_OF_COLUMNS_DOESNT_MATCH` on master and are fixed by
the shard-collapse fan-out in this PR. Column-order scenarios remain covered by
the separate fix in PR #107675; the `GLOBAL IN`/`JOIN` alias-name collision is
tracked separately as a distinct issue.

Co-authored-by: Yakov Olkhovskiy <[email protected]>
# Conflicts:
#	src/Storages/buildQueryTreeForShard.h
@clickhouse-gh

clickhouse-gh Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d182856]

Summary: ❌

job_name test_name status info comment
Fast test FAIL
04279_distributed_alias_planner_column_count FAIL cidb
04278_alias_marker_internal_function FAIL cidb
03934_distributed_alias_marker_setting_effect FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/new_tests_check.py FAIL
Code Review DROPPED
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 1, 2026
@filimonov

filimonov commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor Author

Hard to disagree :)

But all those tiny header alignments and small patches here and there are also not great. They introduce tons of new states / new 'ifs', exceptions from exceptions.

The fundamental problem is that then query transferred from initiator to shard in SQL form it can't get a good control / deterministic way to force what will be returned.

The idea behind the __aliasMarker is to have such an instrument. Beside those bugs it also helps to inject some custom virtual columns (as 'aliases') - if you will check the machinery around shardNum() - that insane. Or giving names to constant sets . If that way to control headers deterministically would exists - those silly things can be thrown away (well, only theoretically - we still need to preserve compatibility :D). Additional challenges arrive if schemas on shards differ...

Anyway. I hope that once distributed plan will become mature all those things like __aliasMarker or like your fixes will become obsolete and will never be needed.

@yakov-olkhovskiy
yakov-olkhovskiy marked this pull request as draft August 6, 2026 02:10
@abashkeev abashkeev added the comp-distributed Distributed table engine & query routing across shards (sharding/load balancing). label Sep 4, 2026
zeekay added a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…rialize_query_plan cases

Broaden the duplicate-ALIAS column-count regression coverage to match the
distributed scenarios exercised by PR ClickHouse#106402:

- `Distributed`-over-`Distributed` (two transport hops), including over the
  query-plan-serialization transport (`serialize_query_plan = 1`);
- `remote` over a `Distributed` table with parallel replicas (the
  `remote` -> `Distributed` -> parallel-replicas second hop);
- single-hop `serialize_query_plan = 1` variant.

These all reproduce `NUMBER_OF_COLUMNS_DOESNT_MATCH` on master and are fixed by
the shard-collapse fan-out in this PR. Column-order scenarios remain covered by
the separate fix in PR ClickHouse#107675; the `GLOBAL IN`/`JOIN` alias-name collision is
tracked separately as a distinct issue.

Co-authored-by: Yakov Olkhovskiy <[email protected]>
mkmkme added a commit to Altinity/ClickHouse that referenced this pull request Sep 19, 2026
Tests only, no source changes. Purpose is to establish which of the
`__aliasMarker` regressions from
#1844 still reproduce on
`antalya-26.6`, which already carries the upstream fixes that landed after
that PR was written:

  * ClickHouse#94644  (ALIAS column order)
  * ClickHouse#107675 (distributed ALIAS column order)
  * ClickHouse#107913 (`buildShardCollapseFanOut`)

All 22 distinct test files from #1844 are staged: the 18 active ones plus the
4 unique files kept under `_local_files_and_notes/dropped_tests` there. The
six dropped-test files that duplicate active ones byte-for-byte are staged
once.

Slot numbers from the 26.3 branch that are already taken on 26.6 are
reassigned to the 05053-05063 range:

  03843 -> 05053   03923 -> 05056   04286 -> 05059   03926 -> 05062
  03920 -> 05054   03928 -> 05057   03924 -> 05060   03927 -> 05063
  03921 -> 05055   03930 -> 05058   03925 -> 05061

`03648_alias_marker_with_mergeable_state.sh` is updated to the #1844 revision.
It is a contract test for the reworked marker, not a bug reproducer, so it is
expected to fail until the source change lands.

Related: #1844
Related: ClickHouse#106402
Resolve the conflict with the move of the settings changes history into the setting declarations
(ee6b44f): the history records this PR added to `SettingsChangesHistory.cpp` now live as
trailing arguments of the `DECLARE` of each setting.

- retargeted PR record [email protected] to 26.10 (settings-history check rule)

Also resolved conflicts in:
- `docs/reference/engines/table-engines/special/distributed.mdx`
- `src/Planner/PlannerActionsVisitor.cpp`
- `src/Storages/StorageDistributed.cpp`
- `src/Storages/buildQueryTreeForShard.cpp`

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-distributed Distributed table engine & query routing across shards (sharding/load balancing). external Author is not a member of the ClickHouse organization pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Incorrect SELECT results due to mixed order of columns from Distributed engine

6 participants