Repository navigation
Fix NUMBER_OF_COLUMNS_DOESNT_MATCH for duplicate ALIAS expressions on Distributed tables - #107913
Conversation
… 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 #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: #106403
Co-authored-by: Yakov Olkhovskiy <[email protected]>
|
|
|
Workflow [PR], commit [af08c2d] Summary: ✅
AI ReviewSummaryThis PR fixes Final VerdictStatus: ✅ Approve |
…s-shard-collapse-reconcile-3628 Co-authored-by: Yakov Olkhovskiy <[email protected]>
…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]>
…columns
`buildQueryTreeForShard` runs `ReplaceLongConstWithScalarVisitor` after inlining
ALIAS columns, turning over-threshold constants into `__getScalar('<hash>')`
calls (controlled by `optimize_const_name_size`, default 256). The shard header
therefore names such a collapsed column after the scalar, not after the literal.
`buildShardCollapseFanOut` previously computed the inlined action name without
that rewrite, so the lookup missed for duplicate long-literal `ALIAS` columns and
the caller fell back to the positional conversion, again raising
`NUMBER_OF_COLUMNS_DOESNT_MATCH`.
Mirror the same constant-to-scalar rewrite (with the same `>= 0` guard) in
`actionNameAfterAliasInlining` so the computed name matches the shard header, and
add a focused regression with duplicate over-threshold constant `ALIAS` columns
to `04357_distributed_alias_same_expression`.
Co-authored-by: Yakov Olkhovskiy <[email protected]>
Set optimize_const_name_size explicitly so the over-threshold constant ALIAS columns are guaranteed to be scalarized into __getScalar regardless of any future change to the setting's default value, keeping the regression meaningful. Co-authored-by: Yakov Olkhovskiy <[email protected]>
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 85/90 (94.44%) | Lost baseline coverage: none · Uncovered code |
| /// columns expanding to the same expression), its header has fewer columns than the initiator expects. | ||
| /// Reconstruct the missing columns by fanning out the deduplicated shard columns before the positional | ||
| /// reconciliation below (which only handles renames, not different column counts). | ||
| if (auto fan_out_actions_dag = buildShardCollapseFanOut( |
There was a problem hiding this comment.
As I get buildShardCollapseFanOut matches columns to fan out by names, but step below does rename column, so it's not clear why here we can apply such transform if later we assume that position but not names matches.
There was a problem hiding this comment.
in general while we expect incoming columns to be ordered properly (though we have a case when this assumption is broken — case of #81631, which we address separately), we still need to put the duplicates of a collapsed column into their proper places, and for that we match by name. Downstream it's assumed the columns are already in order, and the only step left is to rename them to local names.
| auto node_clone = node->clone(); | ||
| InlineAliasColumnsForNamingVisitor visitor; |
There was a problem hiding this comment.
Why do we need to clone node and mutate it and process recursively? Is it because ALIAS column can other ALIASes, so they can be nested?
There was a problem hiding this comment.
we clone because we're operating on the live tree that downstream depends on and expects in its original (un-inlined, "local") form — so we mustn't mutate it. And yes, exactly: aliases can be nested, which is why the inlining is recursive — by recursively inlining the clone we just replicate the shard-side inlining to figure out the shard's side of the story, so we can build a matching map
|
|
||
| for (bool used : shard_column_used) | ||
| if (!used) | ||
| return {}; /// Some shard column is unaccounted for; fall back to be safe. |
There was a problem hiding this comment.
Do we know any case when this fall back happens?
There was a problem hiding this comment.
none that I can think of - it's just a precaution - if it ever happens, we let the downstream steps catch it, most likely as a NUMBER_OF_COLUMNS_DOESNT_MATCH exception
… helper After merging master (which brought in #107913), there were two copies of the ALIAS-column inliner: the shard-transport inliner in `StorageDistributed` (introduced by this PR for #107990) and the name-computation inliner `InlineAliasColumnsForNamingVisitor` added by #107913 in `buildQueryTreeForShard`. Unify them: the projection-aware inliner now lives in `buildQueryTreeForShard` and is exposed as `inlineAliasColumnsForDistributed`. `StorageDistributed::buildQueryTreeDistributed` calls it, and the name-computation path (`actionNameAfterAliasInlining`) reuses the same no-alias inliner. Aliasing is irrelevant for name computation — action node names come from the column identifier / expression, not the SQL alias — so the shared inliner yields the same name the shard assigns. No behavior change: the duplicate-ALIAS column-count fix (#107913) and the same-named JOIN ALIAS collision fix (#107990) both keep working. Co-authored-by: Yakov Olkhovskiy <[email protected]>
|
Hi — this looks like a backport candidate for |
|
@clickgapai we do not want to backport this fix since it covers a corner case that we don't think affects many users. It involves alias columns in the Distributed engine with duplicate expressions, which is not typical usage. |
|
Thanks for the clarification, @vdimir. I understand — this fix addresses a narrow edge case (duplicate ALIAS expressions in Distributed queries) that doesn't reflect typical usage patterns, so backporting it to stable branches isn't justified by the impact-to-risk ratio. I appreciate you being explicit about the scope decision. It helps me calibrate future triage: corner cases that are technically correct fixes but low-frequency in production warrant a different bar than widespread bugs. The fix itself is solid (the root cause — ALIAS inlining creating duplicate column references — is real), but I agree the backport threshold shouldn't be crossed for this one. Is there anything else you'd like me to verify or document about the fix before we close it out? |
…ubquery on a Distributed table buildShardCollapseFanOut (added in ClickHouse#107913) reconstructs duplicate-ALIAS columns that a shard deduplicates into one, matching the expected columns to the shard columns by their inlined action-node names. Those names embed a __tableN table alias. The shard query tree is renumbered independently from the initiator's: buildQueryTreeForShard runs createUniqueAliasesIfNecessary, which restarts the __tableN aliases at 1. When the distributed read is nested inside a subquery, the same source column is named __table1.x on the shard but __tableK.x (K > 1) in the initiator's tree, so the name match fails, the fan-out is skipped, and the positional fallback cannot reconcile the differing column counts, throwing NUMBER_OF_COLUMNS_DOESNT_MATCH. The top-level form works only because the distributed table is __table1 on both sides. Realign the two numberings before matching by zipping the distinct __tableN indices of each side in ascending order (both trees number tables in the same DFS pre-order) and rewriting the initiator indices to the shard ones. This is applied only when both sides expose the same number of table indices; otherwise the original names are kept and the existing bijection guard rejects any mismatch, so multi-table scopes are unchanged. Add subquery-wrapped regression cases to 04357_distributed_alias_same_expression. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ckHouse#108291) The NUMBER_OF_COLUMNS_DOESNT_MATCH error reported in ClickHouse#108291 for SELECT * with asterisk_include_alias_columns=1 over clusterAllReplicas / cluster plus an ORDER BY is already fixed on master by the shard collapse reconciliation (buildShardCollapseFanOut, ClickHouse#107913). The existing 04357 test only covers explicit column lists over a Distributed engine table, not the SELECT * + asterisk_include_alias_columns + cluster() path, so add a focused regression test for it. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ckHouse#108291) The NUMBER_OF_COLUMNS_DOESNT_MATCH error reported in ClickHouse#108291 for SELECT * with asterisk_include_alias_columns=1 over clusterAllReplicas / cluster plus an ORDER BY is already fixed on master by the shard collapse reconciliation (buildShardCollapseFanOut, ClickHouse#107913). The existing 04357 test only covers explicit column lists over a Distributed engine table, not the SELECT * + asterisk_include_alias_columns + cluster() path, so add a focused regression test for it. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…y with table-function argument The shard-collapse reconstruction added in ClickHouse#107913 walks the whole shard query tree (CollectAliasNameTranslationVisitor) to translate action names when duplicate-ALIAS columns are deduplicated on the shard. Its needChildVisit only skipped nested QUERY/UNION scopes, so it descended into table-function argument lists. A key = value named-collection override such as oss(s3_conn, filename = '...') leaves an unresolved identifier in the arguments; calculateActionNodeName has no case for IDENTIFIER and aborts the server with LOGICAL_ERROR Invalid action query tree node. Skip TABLE_FUNCTION and TABLE subtrees as well: their argument lists are not expression scopes whose names need translating. Co-Authored-By: Claude Opus 4.8 <[email protected]>
That specific case relies on fix #107913 which is not backported
That specific case relies on fix #107913 which is not backported
That specific case relies on fix #107913 which is not backported
That specific case relies on fix #107913 which is not backported
…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]>
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]>
…lias-shard-collapse-reconcile-3628 Fix NUMBER_OF_COLUMNS_DOESNT_MATCH for duplicate ALIAS expressions on Distributed tables
…ubquery on a Distributed table buildShardCollapseFanOut (added in ClickHouse#107913) reconstructs duplicate-ALIAS columns that a shard deduplicates into one, matching the expected columns to the shard columns by their inlined action-node names. Those names embed a __tableN table alias. The shard query tree is renumbered independently from the initiator's: buildQueryTreeForShard runs createUniqueAliasesIfNecessary, which restarts the __tableN aliases at 1. When the distributed read is nested inside a subquery, the same source column is named __table1.x on the shard but __tableK.x (K > 1) in the initiator's tree, so the name match fails, the fan-out is skipped, and the positional fallback cannot reconcile the differing column counts, throwing NUMBER_OF_COLUMNS_DOESNT_MATCH. The top-level form works only because the distributed table is __table1 on both sides. Realign the two numberings before matching by zipping the distinct __tableN indices of each side in ascending order (both trees number tables in the same DFS pre-order) and rewriting the initiator indices to the shard ones. This is applied only when both sides expose the same number of table indices; otherwise the original names are kept and the existing bijection guard rejects any mismatch, so multi-table scopes are unchanged. Add subquery-wrapped regression cases to 04357_distributed_alias_same_expression. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…y with table-function argument The shard-collapse reconstruction added in ClickHouse#107913 walks the whole shard query tree (CollectAliasNameTranslationVisitor) to translate action names when duplicate-ALIAS columns are deduplicated on the shard. Its needChildVisit only skipped nested QUERY/UNION scopes, so it descended into table-function argument lists. A key = value named-collection override such as oss(s3_conn, filename = '...') leaves an unresolved identifier in the arguments; calculateActionNodeName has no case for IDENTIFIER and aborts the server with LOGICAL_ERROR Invalid action query tree node. Skip TABLE_FUNCTION and TABLE subtrees as well: their argument lists are not expression scopes whose names need translating. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ckHouse#108291) The NUMBER_OF_COLUMNS_DOESNT_MATCH error reported in ClickHouse#108291 for SELECT * with asterisk_include_alias_columns=1 over clusterAllReplicas / cluster plus an ORDER BY is already fixed on master by the shard collapse reconciliation (buildShardCollapseFanOut, ClickHouse#107913). The existing 04357 test only covers explicit column lists over a Distributed engine table, not the SELECT * + asterisk_include_alias_columns + cluster() path, so add a focused regression test for it. Co-Authored-By: Claude Opus 4.8 <[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
Three of the staged regression tests expect a `serverError` that upstream fixes stopped raising, so each was asserting a bug that no longer exists. Replace the assertion with the result the query now returns, and fix the framing that went with it. `03934` claimed `enable_alias_marker` was a correctness toggle: with the marker off, a distributed-over-distributed read of a `String` ALIAS and a `UInt64` ALIAS swapped the two columns and failed with `CANNOT_PARSE_TEXT`. Upstream fixed the column ordering, so the setting is what it was always meant to be -- a way for an initiator to stop emitting `__aliasMarker` for a mixed-version cluster whose shards do not understand it. The test now runs the same query with the marker on and off and requires both to return the same rows. `05053` expected `NUMBER_OF_COLUMNS_DOESNT_MATCH` for two ALIAS columns over the same expression with the marker off. `buildShardCollapseFanOut` from ClickHouse#107913 reconstructs the column the shard deduplicated away whether or not a marker is present, so that variant returns the same single row as the other six. `05060` expected `UNKNOWN_IDENTIFIER` from a Hybrid/MergeTree/Iceberg join under `object_storage_cluster_join_mode = 'local'`. It now returns the same rows as the `'allow'` variant beside it, and is held to them. Each reference was taken from a sibling query in the same test that must produce identical output, so a wrong reference here would mean the test was already wrong. `05060` also gained a header note: it needs the stateless S3 mock on localhost:11111, it needs a server listening on `127.0.0.3` for `test_cluster_one_shard_three_replicas_localhost`, and it needs `enable_parallel_blocks_marshalling = 0` until the `DISTINCT` over `ColumnBLOB` abort is fixed. Related: #1844 Co-Authored-By: Claude Opus 5 <[email protected]>
Closes: #106403
When a Distributed query is executed up to
WithMergeableState, the shard's query tree has itsALIAScolumns inlined into their defining expressions. If several projection/sort/group items expand to the same expression, the shard'sActionsDAGdeduplicates them into a single output column, so the shard header ends up with fewer columns than the header the initiator expects (on the initiator theALIAScolumns are kept distinct, since they are not inlined there).The reconciliation in
buildQueryPlanForTableExpressiononly renamed columns by position viaActionsDAG::makeConvertingActionswithMatchColumnsMode::Position, which requires an equal number of columns and therefore threwNUMBER_OF_COLUMNS_DOESNT_MATCH, for example: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 rather than heuristically: 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 inliningALIAScolumns (matching the shard header), and use this translation to resolve which shard column feeds each expected column. The helper returnsstd::nullopt(and the caller falls back to the previous behaviour) when the situation is not a recognized projection collapse, so the common path with equal column counts is untouched.This replaces the reverted #106404 approach (which disambiguated expressions on the shard with a wrapper function and proved fragile for nested aliases / name collisions) with a boundary-only reconciliation that does not change shard-side naming.
The new stateless test
04357_distributed_alias_same_expressioncoversORDER BYon a non-projected column, renamed/repeated/interleaved projections, mixedALIAS/literal expressions, a third non-collapsingALIAScolumn,GROUP BY,HAVING, aggregates,DISTINCT, parallel replicas,Distributed-over-Distributed(multi-hop), theremote->Distributed-> parallel-replicas second hop, andserialize_query_plantransport variants.This is a focused fix for the column-count mismatch only. Column-order misalignment for distributed
ALIAScolumns is fixed separately in #107675, and theGLOBAL IN/JOINalias-name collision is tracked separately in #107990.Related: #106404
Related: #107675
Related: #107990
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix
NUMBER_OF_COLUMNS_DOESNT_MATCHerror when querying aDistributedtable (or using parallel replicas) that has severalALIAScolumns expanding to the same expression and referencing them together withORDER BY/GROUP BY/HAVING.Version info
26.6.1.1149