Repository navigation
Fix wrong column order in distributed queries with ALIAS columns - #106398
yakov-olkhovskiy wants to merge 11 commits into
Conversation
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 #81631 Related: #105690 Co-authored-by: Yakov Olkhovskiy <[email protected]>
|
Workflow [PR], commit [1b79dd8] Summary: ❌
AI ReviewSummaryThis PR fixes the projection-order invariant for Final VerdictStatus: ✅ Approve |
|
|
The previous commit reordered the Projection DAG outputs after `actions_chain.finalize`, but by that time the Before ORDER BY step had already been built from the wrong `available_output_columns` order. The shard's output header was still determined by the sort DAG, not the Projection DAG, so the positional rename still swapped values. Move the reorder to right after `analyzeProjection` returns and before `analyzeSort` runs. Reorder both the DAG outputs and `available_output_columns` (via a new mutable accessor on `ActionsChainStep`) so that downstream steps inherit the correct projection order. Co-authored-by: Yakov Olkhovskiy <[email protected]>
Skip the projection output reorder when `projection_column_names` contains duplicates (e.g. two ALIAS columns expanding to the same expression). In that case, the columns are interchangeable and reordering with a name-keyed map would corrupt the output structure. Update reference files for two EXPLAIN tests whose output changed because the projection column order is now corrected: - `04105_limit_by_into_sort_explain`: input positions in Project names and Before LIMIT BY steps reflect the corrected projection order. - `03928_deferred_filters_after_final_in_explain`: input positions in Project names step reflect the corrected projection order. Co-authored-by: Yakov Olkhovskiy <[email protected]>
Replace the duplicate-name guard (which disabled the entire reorder) with a position-based approach: build a list of positions per name so that duplicate projection names (e.g. two aliases expanding to the same expression) each consume the next available position. If there are more occurrences in the projection than in `available_output_columns`, fall back gracefully (`can_reorder = false`). Update `03928_deferred_filters_after_final_in_explain` reference: the "both deferred" section also has reordered projection columns, matching the "nothing deferred" section already updated. Adjust `04305_distributed_alias_column_order` test: keep the local `same_expr` case (two aliases with identical expressions) but remove its distributed variant. When both aliases inline to the same expression, CSE on the shard deduplicates them into a single output column, causing a column count mismatch -- a separate pre-existing issue unrelated to column ordering. Co-authored-by: Yakov Olkhovskiy <[email protected]>
Restore the distributed variant of the same-expression alias test to let CI determine whether it passes or fails, rather than assuming it is a pre-existing issue. Co-authored-by: Yakov Olkhovskiy <[email protected]>
When the projection has more occurrences of a name than `available_output_columns` has entries (because `initialize` deduplicates by name), reuse the last available position instead of aborting the entire reorder. The columns are identical (same CSE node), so reusing is safe, and this ensures unique columns that need reordering still get fixed. Add a regression test for `SELECT flag_a, flag_b, flag_b` where `flag_a` and `flag_b` have a CSE relationship and `flag_b` is duplicated in the projection. Co-authored-by: Yakov Olkhovskiy <[email protected]>
…on aliases
Fix the reorder logic to not abort when the projection has more
occurrences of a name than `available_output_columns` has entries:
reuse the last available position (the columns are identical CSE nodes).
This ensures unique columns that need reordering still get fixed even
when other columns in the same projection are duplicated.
The `distributed_same_expr` test case (two ALIAS columns expanding to
the identical expression) fails with `NUMBER_OF_COLUMNS_DOESNT_MATCH`
because `ActionsChainStep::initialize` deduplicates
`available_output_columns` by name, producing fewer columns than the
initiator expects. This is a pre-existing issue on master: the
deduplication in `initialize` and the `MatchColumnsMode::Position`
rename in `PlannerJoinTree` are unchanged by this PR. Mark the query
with `-- { serverError NUMBER_OF_COLUMNS_DOESNT_MATCH }` to document
this known limitation.
Co-authored-by: Yakov Olkhovskiy <[email protected]>
…ted-alias-column-order-cb73 Co-authored-by: Yakov Olkhovskiy <[email protected]>
PR #106404 fixed the column count mismatch for identical-expression ALIAS columns in distributed queries. The `distributed_same_expr` query now returns `7 7` successfully instead of throwing `NUMBER_OF_COLUMNS_DOESNT_MATCH`. Co-authored-by: Yakov Olkhovskiy <[email protected]>
…n order Address review feedback on PR #106398 (#106398 (comment)). The reviewer asked to cover an interleaved duplicate case such as `SELECT flag_b, flag_b, flag_a`, where a duplicated alias occurrence precedes a later distinct alias column. Empirically the duplicate `flag_b` is deduplicated at the mergeable-state boundary (the shard returns the distinct columns `dt, flag_b, flag_a` and the duplicate is reconstructed on the initiator by the `Project names` step), so this query already returns correct results with the fix. The test locks in that behavior and documents the deduplication. Co-authored-by: Yakov Olkhovskiy <[email protected]>
Co-authored-by: Yakov Olkhovskiy <[email protected]>
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 50/54 (92.59%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 1 line(s) · Uncovered code |
|
closing in favor of #107675 |
…n order Address review feedback on PR ClickHouse#106398 (ClickHouse#106398 (comment)). The reviewer asked to cover an interleaved duplicate case such as `SELECT flag_b, flag_b, flag_a`, where a duplicated alias occurrence precedes a later distinct alias column. Empirically the duplicate `flag_b` is deduplicated at the mergeable-state boundary (the shard returns the distinct columns `dt, flag_b, flag_a` and the duplicate is reconstructed on the initiator by the `Project names` step), so this query already returns correct results with the fix. The test locks in that behavior and documents the deduplication. Co-authored-by: Yakov Olkhovskiy <[email protected]>
Closes: #81631
Related: #105690
Problem
When querying a
Distributedtable withALIAScolumns andORDER BY ... LIMIT(which triggersWithMergeableStateprocessing stage), the remote planner expands alias column references into their underlying expressions viaReplaseAliasColumnsVisitorinbuildQueryTreeDistributed. CSE (Common Subexpression Elimination) in the action DAG can then reorder the output columns compared to what the initiator's planner expects.The initiator's
PlannerJoinTreerenames remote columns usingMatchColumnsMode::Position, so when the remote returns columns in a different order, the wrong values get assigned to the wrong column names — producing silently incorrect query results.For example, given
flag_a ALIAS concat(toString(x), '_suffix')andflag_b ALIAS toString(x), the remote planner inlines both aliases. SincetoString(x)is a subexpression ofconcat(toString(x), '_suffix'), CSE creates the shared node first, reversing the output order. The positional rename then swaps the values.Root cause
ActionsChainStep::initializebuildsavailable_output_columnsby iterating the internal node list (getNodes), whose order reflects DAG construction order rather than the original 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. This wrong order propagates to downstream steps (Before ORDER BY, sorting) as theirinput_columns, ultimately determining the shard's output header.Solution
After
analyzeProjectionreturns and beforeanalyzeSortruns, compare the projection columns inavailable_output_columnsagainst the recordedprojection_column_names(captured in projection order byanalyzeProjection). If they diverge, reorder both the DAG outputs andavailable_output_columnsto match, and propagate the corrected order intocurrent_output_columns. This ensures downstream steps (Before ORDER BY, etc.) inherit the correct projection order.For the common case where CSE does not affect order, the comparison finds everything in place and no mutation occurs — making this a zero-cost no-op for unaffected queries.
A mutable accessor
getAvailableOutputColumnsis added toActionsChainStepto allow the reorder.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix wrong results when querying
ALIAScolumns from aDistributedtable withORDER BY ... LIMIT, caused by CSE in the action DAG reordering projection outputs during chain construction. Fixes #81631.