Repository navigation
Conversation
`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]>
|
@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:
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. |
…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
|
Workflow [PR], commit [d182856] Summary: ❌
|
|
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. |
…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]>
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]>
Changelog category (leave one):
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_MATCHerrors when queryingALIAScolumns fromDistributedor parallel-replicas — especially withORDER BY ... LIMIT(mergeable-state hop) or when multiple aliases share subexpressions.Closes #81631, #79916.
Description
StorageDistributedexpandsALIAScolumns 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 withTHERE_IS_NO_COLUMN/NUMBER_OF_COLUMNS_DOESNT_MATCHwhen the count diverged.This PR introduces a two-phase
__aliasMarkerprotocol that preserves logical-column identity across the boundary so the reconciliation can match by name.Mechanism
ReplaseAliasColumnsVisitorwraps each ALIAS-expansion in__aliasMarker(expr, original_column_node).__aliasMarkeris a 2-argument pass-through identity; arg2 carries the original column identity.createUniqueAliasesIfNecessaryassigns stable__tableNaliases,finalizeAliasMarkersForDistributedSerializationmaterializes each marker's arg2 fromColumnNodeto aStringConstantNode("__tableN.col"). Lambda bodies are skipped (so user-typed markers inside lambdas don't trigger a logical error). Called frombuildQueryTreeDistributedand fromexecuteSubqueryNodeforGLOBAL IN/JOINmaterialized subqueries.PlannerActionsVisitoruses the materialized string id as the action node name, so the shard emits each value under the stable__tableN.colidentifier. A new helpermakeConvertingActionsPreferNameThenPositionroutes the remote-table boundary conversion (PlannerJoinTree) and the parallel-replicas-follower header conversion (findParallelReplicasQuery) toMatchColumnsMode::Namewhen the rename is unambiguous (set equality, no duplicates),MatchColumnsMode::Positionotherwise. The legacy non-analyzer path explicitly rejects direct__aliasMarkercalls.The Name-mode routing change is unconditional —
enable_alias_marker = falsedisables 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 settingenable_alias_marker = falseAND restoring the priorMatchColumnsMode::Positionat 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)
EXPLAIN header=1:The
Expression (Change column names)step is the helper's call site. Source carries the table's first column name (x) as its syntheticAggregateFunction(count, Int64)state header; result wantscount(). Name-mode cannot match these strings. Position-mode resolves it asALIAS x -> count(). The narrower correct fix (renaming theReadFromPreparedSourceoutput) lives at the source-step builder level — out of scope here.Setting
Adds
enable_alias_marker(defaultfalse). 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 totruein a later release.Regression tests
04278_alias_marker_internal_function.shDistributednoLOGICAL_ERROR, arg2 materialized as action node name across mergeable-state stages, non-analyzer rejection, escape-hatch reverses behavior04279_distributed_alias_planner_column_count.sqlDistributed-over-Distributed(column-count mismatch on master)04280_distributed_alias_column_order.sql04282_parallel_replicas_alias_second_hop.sql04283_distributed_alias_global_in_product_mode_local.sqlGLOBAL INwithdistributed_product_mode='local'(analyzer alias-uniquification)04284_distributed_alias_query_clauses.sqlWHERE+GROUP BYand inJOIN ON04285_alias_marker_array_join.sql__aliasMarkeroverARRAY JOINmust pass through (finalize-visitor unaliased-source branch)Out of scope
ReadFromPreparedSource (Optimized trivial count)output tocount()so the Name branch matches without Position fallback.LOGICAL_ERRORinfinalizeAliasMarkersForDistributedSerializationfor non-lambda user-reachable shapes.Workflow [PR]
Sync PR [sync-upstream/pr/106402]