Repository navigation
Fix wrong column order in distributed queries with ALIAS columns - #105690
yakov-olkhovskiy wants to merge 8 commits into
Conversation
|
Workflow [PR], commit [c20202d] Summary: ✅
AI ReviewSummaryThis PR fixes wrong results for Findings❌ Blockers
Tests
Final VerdictStatus: ❌ Block Minimum required actions: make alias substitution token-safe or AST-based, fail closed when the remote header cannot be matched, scope |
When querying a Distributed table with ALIAS columns and ORDER BY ... LIMIT (which triggers WithMergeableState stage), ReplaseAliasColumnsVisitor in buildQueryTreeDistributed inlines alias expressions. CSE in the action DAG can then reorder output columns compared to what the initiator planner expects. The existing positional rename silently mapped columns wrong, producing incorrect results. Fix the divergence at its source in StorageDistributed: 1. Register the StorageDummy replacement in the planner context with the original table expression's column identifiers so that calculateActionNodeName resolves identifiers correctly on the cloned tree. 2. ReplaseAliasColumnsVisitor now records each replaced alias column's expanded action name via calculateActionNodeName. 3. After ClusterProxy::executeQuery, compute the expected header from the original query tree, build a precise permutation using the alias map, and add an ExpressionStep that reorders columns so the downstream positional rename in PlannerJoinTree maps them correctly. Closes #81631
|
|
||
| if (it == remote_name_to_pos.end()) | ||
| { | ||
| can_match = false; |
There was a problem hiding this comment.
When we cannot match one expected column, this path silently skips reordering and continues.
That is fail-open for correctness: downstream still performs positional rename, which is exactly the mechanism that produced wrong results in #81631 when remote output order diverged.
A concrete class that still hits this: expected outputs that are expressions containing alias identifiers (for example plus(__table1.flag_zero, 1)), where getColumnNameOrNull cannot map the full expression string, so can_match becomes false and we continue without reordering.
If matching fails, we should throw instead of proceeding with potentially misordered columns.
There was a problem hiding this comment.
I re-checked the current code and this is still fail-open.
At src/Storages/StorageDistributed.cpp:1194-1197, an unmatched expected column only sets can_match = false and breaks. Then src/Storages/StorageDistributed.cpp:1205 skips the reorder step without throwing.
So we still continue with potentially misordered columns, which keeps the original correctness risk.
7fea245 to
6e4920e
Compare
Skip registering the replacement table expression in the shared planner context for tables without ALIAS columns. The unconditional registration was polluting the planner context and affecting downstream pipeline construction (GroupingAggregated->MergingAggregated, missing AddSequenceNumber).
| if (planner_context) | ||
| { | ||
| const auto & column_name = node->as<ColumnNode &>().getColumnName(); | ||
| if (!alias_column_expanded_names.contains(column_name)) |
There was a problem hiding this comment.
alias_column_expanded_names is keyed only by bare column_name and this visitor runs over the whole cloned query tree, not just the current distributed table expression.
If another table/subquery has an ALIAS with the same name, the first one wins because of contains(column_name), so the mapping for this table can point to a different expression. Then the reorder lookup later (table_data->getColumnNameOrNull -> alias_column_expanded_names) misses or resolves to the wrong remote position, which can silently skip reordering and fall back to positional renaming.
Please key this map by table-qualified identifier (for example the column identifier from TableExpressionData) or by (column_source, column_name), and record entries only for aliases from query_info.table_expression.
When the expected column name is an expression containing alias identifiers (e.g. ORDER BY flag_a || '_extra'), the reorder logic now replaces embedded alias identifiers with their expanded action names to find the matching remote column. Added a test case for this scenario.
When replacing alias identifiers within expression names, sort by identifier length descending so longer identifiers (e.g. __table1.flag1) are replaced before shorter ones that share a prefix (e.g. __table1.flag). Without this, replacing the shorter identifier first corrupts the longer one. Added a test case for ORDER BY over aliases with prefix-related names.
add4e8c to
4171dd3
Compare
For nested aliases (e.g. a2 ALIAS a1 + 1, a1 ALIAS x + 1), the expanded names recorded by the visitor may reference other alias identifiers. When identifiers have equal length, the single-pass replacement order is unspecified and can leave values partially expanded. Expand identifier_to_expanded values until fixpoint so every entry is fully resolved to base-column expressions. Also propagate the resolved values back to alias_column_expanded_names so the direct alias lookup (strategy 2) benefits. Added a test case with deeply nested aliases (aa, ac, ab) whose identifiers all have the same length.
| for (const auto & [id, expanded] : identifier_to_expanded) | ||
| { | ||
| size_t pos = 0; | ||
| while ((pos = transformed.find(id, pos)) != std::string::npos) |
There was a problem hiding this comment.
This replacement is still substring-based, so it can rewrite identifiers that only start with an alias identifier.
Concrete case: table has alias a and regular column ab, and expected expression name is like plus(__table1.a, __table1.ab). Replacing __table1.a also mutates the __table1.ab token into <expanded_a>b, so lookup misses and reorder is skipped.
Could we restrict replacement to whole identifier tokens (for example AST-level substitution or explicit identifier-boundary checks) instead of raw find/replace?
|
I have a different fix for the same - more invasive, but covering much more cases. In short - it introduces marker function to pass down to the shards the intent of injecting alias. IMHO it's more robust than trying to deduct on the initiator what exactly arrived from the shards and how to map it to what was requested (because sometimes even the number of columns can be different - when 2 aliases use the same expression). I'll send PR today to show it. |
| if (&id == &other_id) | ||
| continue; | ||
| size_t pos = 0; | ||
| while ((pos = expanded.find(other_id, pos)) != std::string::npos) |
There was a problem hiding this comment.
This fixpoint expansion can fail to terminate because it uses raw substring replacement.
Concrete case: regular column ab, alias a ALIAS ab + 1, and nested alias c ALIAS a + 1. identifier_to_expanded contains __table1.a -> plus(__table1.ab, 1) and __table1.c -> plus(__table1.a, 1). Replacing __table1.a in c produces a string that still contains __table1.a as the prefix of __table1.ab, so the outer while (changed) repeats and the string grows every pass.
Please only replace whole column identifiers, or do this on the query tree instead of action-name strings, before using a fixpoint loop.
|
The failures of They were introduced by #104690 ("Add #104690 was merged in violation of the ClickHouse team rules: its own CI already showed these two tests failing (10 times between May 12 and June 1) before it was merged. Please update your branch to pick up the revert; the tests should pass again. |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 117/120 (97.50%) | Lost baseline coverage: none · Uncovered code |
|
...trying alternative solution here: |
|
Please check #106402 It also introduces few tests which this PR fails (i didn't check #106398 yet). I'm not too happy about intoducing that extra 'technical' function there (similar to __actionName), but that was the only path which worked for me when schema on shards differ and which worked for distributed-over-distributed |
|
@filimonov we will consider your PR too, don't worry |
|
closing in favor of #106398 |
|
closing in favor of #106398 |
When querying a Distributed table with ALIAS columns and ORDER BY ... LIMIT (triggering `WithMergeableState` processing stage), the remote planner inlines alias expressions via `ReplaseAliasColumnsVisitor`. CSE in the action DAG can then reorder the output columns compared to what the initiator expects. The initiator's `PlannerJoinTree` renames columns using `MatchColumnsMode::Position`, so reordered columns produce silently wrong results. Root cause: `ActionsChainStep::finalizeInputAndOutputColumns` appends child-required columns by iterating `getNodes` (internal DAG construction order) rather than `getOutputs` (projection order). When CSE shares a node between two projection expressions, the shared node appears earlier in the node list than the containing expression, reversing their relative order in the outputs. Fix: after `actions_chain.finalize` in `buildExpressionAnalysisResult`, compare the first N outputs of the Projection DAG against the recorded `projection_column_names` (captured in projection order before finalization). If they diverge, reorder the outputs to match. For the common case where CSE does not affect order, the comparison finds everything in place and no mutation occurs. Closes ClickHouse#81631 Related: ClickHouse#105690 Co-authored-by: Yakov Olkhovskiy <[email protected]>
Closes #81631
Problem
When querying a Distributed table with ALIAS columns and
ORDER BY ... LIMIT(which triggersWithMergeableStateprocessing stage), the remote planner expands alias column references into their underlying expressions viaReplaseAliasColumnsVisitorinbuildQueryTreeDistributed. This changes both the names and order of columns in the remote header compared to what the local planner expects.For example, given two ALIAS columns
flag_zero ALIAS toBool(bitTest(flags_bitmap, 0))andflag_one ALIAS toBool(bitTest(flags_bitmap, 1)), the remote planner inlines them into expression-based identifiers and CSE in the action DAG may reorder them — particularly when one alias expression contains a subexpression of another, which the planner extracts as a dependency.The existing code used
makeConvertingActions(MatchColumnsMode::Position)which silently mapped columns by position, producing wrong query results.Solution
The fix is entirely in
StorageDistributed.cpp, at the source of the divergence:Before
cloneAndReplace, register theStorageDummyreplacement in the planner context with the same column identifiers as the original table expression (e.g.__table1.col_name). This allowscalculateActionNodeNameto resolve column identifiers correctly on the cloned tree.ReplaseAliasColumnsVisitornow records each replaced alias column's expanded action name viacalculateActionNodeName, building a map from alias column name to the identifier the remote planner assigns to the inlined expression.After
ClusterProxy::executeQuery, compute the expected header from the original query tree. Using the alias-to-expanded-name map, build a precise permutation and add anExpressionStepthat reorders columns so that the downstream positional rename inPlannerJoinTreemaps them correctly.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix wrong results when querying ALIAS columns from a Distributed table with
ORDER BY ... LIMIT.