Skip to content

Fix wrong column order in distributed queries with ALIAS columns - #106398

Closed
yakov-olkhovskiy wants to merge 11 commits into
masterfrom
cursor/fix-distributed-alias-column-order-cb73
Closed

yakov-olkhovskiy wants to merge 11 commits into
masterfrom
cursor/fix-distributed-alias-column-order-cb73

Conversation

@yakov-olkhovskiy

@yakov-olkhovskiy yakov-olkhovskiy commented Jun 3, 2026 •

Copy link
Copy Markdown
Member

Closes: #81631
Related: #105690

Problem

When querying a Distributed table with ALIAS columns and ORDER BY ... LIMIT (which triggers WithMergeableState processing stage), the remote planner expands alias column references into their underlying expressions via ReplaseAliasColumnsVisitor in buildQueryTreeDistributed. 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 PlannerJoinTree renames remote columns using MatchColumnsMode::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') and flag_b ALIAS toString(x), the remote planner inlines both aliases. Since toString(x) is a subexpression of concat(toString(x), '_suffix'), CSE creates the shared node first, reversing the output order. The positional rename then swaps the values.

Root cause

ActionsChainStep::initialize builds available_output_columns by 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 their input_columns, ultimately determining the shard's output header.

Solution

After analyzeProjection returns and before analyzeSort runs, compare the projection columns in available_output_columns against the recorded projection_column_names (captured in projection order by analyzeProjection). If they diverge, reorder both the DAG outputs and available_output_columns to match, and propagate the corrected order into current_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 getAvailableOutputColumns is added to ActionsChainStep to allow the reorder.

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 when querying ALIAS columns from a Distributed table with ORDER BY ... LIMIT, caused by CSE in the action DAG reordering projection outputs during chain construction. Fixes #81631.

Open in Web Open in Cursor 

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]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1b79dd8]

Summary: ❌

job_name test_name status info comment
Stress test (arm_msan) FAIL
MemorySanitizer (STID: None) FAIL cidb
Performance Comparison (arm_release, master_head, 2/6) FAIL Performance dashboard
aggregation_by_partitions #2::old FAIL query history
aggregation_by_partitions #2::new FAIL query history
aggregation_by_partitions #5::old FAIL query history
aggregation_by_partitions #5::new FAIL query history
aggregation_by_partitions #8::old FAIL query history
aggregation_by_partitions #8::new FAIL query history
formats_columns_nullable #2::old FAIL query history
formats_columns_nullable #2::new FAIL query history
hash_table_sizes_stats #2::old FAIL query history
hash_table_sizes_stats #2::new FAIL query history
6 more test cases not shown

AI Review

Summary

This PR fixes the projection-order invariant for Distributed queries with ALIAS columns by reordering the projection ActionsDAG outputs and the current ActionsChainStep available columns before downstream ORDER BY and LIMIT stages are built. The regression test now covers the original CSE-induced swap, nested/shared alias expressions, duplicate projection names, and the previously discussed duplicate-interleaving case. I did not find unresolved correctness issues in the current diff.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 3, 2026
@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

cursoragent and others added 2 commits June 3, 2026 16:44
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]>
cursoragent and others added 3 commits June 3, 2026 17:28
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]>
@yakov-olkhovskiy
yakov-olkhovskiy marked this pull request as ready for review June 4, 2026 19:33
cursoragent and others added 2 commits June 15, 2026 13:03
…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]>
@vdimir vdimir self-assigned this Jun 15, 2026
cursoragent and others added 2 commits June 15, 2026 20:21
…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]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 16, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.10% 85.20% +0.10%
Functions 92.30% 92.30% +0.00%
Branches 77.40% 77.40% +0.00%

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

Full report · Diff report

@yakov-olkhovskiy

Copy link
Copy Markdown
Member Author

closing in favor of #107675

zeekay added a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

4 participants