Skip to content

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

Closed
yakov-olkhovskiy wants to merge 8 commits into
masterfrom
fix-columns-order
Closed

yakov-olkhovskiy wants to merge 8 commits into
masterfrom
fix-columns-order

Conversation

@yakov-olkhovskiy

@yakov-olkhovskiy yakov-olkhovskiy commented May 23, 2026 •

Copy link
Copy Markdown
Member

Closes #81631

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. 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)) and flag_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:

  1. Before cloneAndReplace, register the StorageDummy replacement in the planner context with the same column identifiers as the original table expression (e.g. __table1.col_name). This allows calculateActionNodeName to resolve column identifiers correctly on the cloned tree.

  2. ReplaseAliasColumnsVisitor now records each replaced alias column's expanded action name via calculateActionNodeName, building a map from alias column name to the identifier the remote planner assigns to the inlined expression.

  3. 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 an ExpressionStep that reorders columns so that the downstream positional rename in PlannerJoinTree maps them correctly.

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.

  • Documentation is written / is not needed

@clickhouse-gh

clickhouse-gh Bot commented May 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c20202d]

Summary: ✅


AI Review

Summary

This PR fixes wrong results for Distributed queries with ALIAS columns by recording the remote action names produced after alias expansion and adding a reorder step before PlannerJoinTree performs positional renaming. The direction matches the reported ORDER BY ... LIMIT bug, but the current implementation still has correctness holes in the alias-name mapping and a user-triggerable non-terminating substitution path, so I do not think it is safe to merge yet.

Findings

❌ Blockers

  • [src/Storages/StorageDistributed.cpp:1168, src/Storages/StorageDistributed.cpp:1230] alias_column_expanded_names is resolved with raw substring replacement instead of column-identifier replacement. A valid table with a regular column like ab, an alias a ALIAS ab + 1, and a nested alias c ALIAS a + 1 keeps finding __table1.a inside __table1.ab, so the fixpoint loop can grow the string forever; the later expected-name transformation has the same token-boundary problem and can corrupt unrelated identifiers or string-literal names. Replace aliases on the query tree, or at least replace only whole column-identifier tokens with explicit boundaries, before doing any fixpoint expansion.
  • [src/Storages/StorageDistributed.cpp:1242] Failed matching still falls through to the downstream MatchColumnsMode::Position rename. That is the same fail-open behavior that caused the original wrong results: if any expected column cannot be mapped, the code just skips the reorder step and lets PlannerJoinTree map by position. This path should throw with the unmatched expected column and remote header, or otherwise fail closed, rather than continuing with potentially misordered data.
  • [src/Storages/StorageDistributed.cpp:797] The recorded alias map is keyed only by bare column name while ReplaseAliasColumnsVisitor traverses the whole cloned query tree. If another table expression or subquery has an ALIAS with the same name, the first entry wins and this Distributed table can use an expanded expression from the wrong source. Scope the map to query_info.table_expression, or key it by the table-qualified column identifier/source plus column name.
Tests

⚠️ Please add focused coverage for the unresolved edge cases above: a regular column whose identifier has an alias identifier as a prefix, nested aliases over that column to prove the fixpoint terminates, and a query with two table expressions/subqueries that have same-named ALIAS columns so the mapping is proven table-scoped. Also cover the fail-closed path so an unmappable remote header cannot silently reach positional renaming.

Final Verdict

Status: ❌ Block

Minimum required actions: make alias substitution token-safe or AST-based, fail closed when the remote header cannot be matched, scope alias_column_expanded_names to the current table expression, and add regression tests for those cases.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 23, 2026
@yakov-olkhovskiy
yakov-olkhovskiy marked this pull request as draft May 23, 2026 08:22
Comment thread src/Planner/PlannerJoinTree.cpp Resolved
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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

addressed

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

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))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
Comment thread src/Storages/StorageDistributed.cpp Resolved
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.
Comment thread src/Storages/StorageDistributed.cpp Resolved
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

@filimonov

Copy link
Copy Markdown
Contributor

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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@alexey-milovidov

Copy link
Copy Markdown
Member

The failures of 00175_obfuscator_schema_inference and 00096_obfuscator_save_load in Stateless tests (amd_tsan, parallel) are NOT caused by this PR.

They were introduced by #104690 ("Add UntrackedMemory asynchronous metric"), which made clickhouse-obfuscator abort (SIGABRT) on process teardown: the query results are correct, but the Aborted line on stderr fails the test. #104690 has now been reverted (#106365).

#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.

@clickhouse-gh

clickhouse-gh Bot commented Jun 3, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.40% 84.40% +0.00%
Functions 92.40% 92.40% +0.00%
Branches 77.00% 77.00% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 117/120 (97.50%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@yakov-olkhovskiy

Copy link
Copy Markdown
Member Author

...trying alternative solution here:
#106398
approach - to fix order on remote

@filimonov

filimonov commented Jun 3, 2026 •

Copy link
Copy Markdown
Contributor

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

@yakov-olkhovskiy

Copy link
Copy Markdown
Member Author

@filimonov we will consider your PR too, don't worry

@yakov-olkhovskiy

Copy link
Copy Markdown
Member Author

closing in favor of #106398

@yakov-olkhovskiy

Copy link
Copy Markdown
Member Author

closing in favor of #106398

zeekay added a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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]>
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

3 participants