Skip to content

Fix wrong results for alias columns with functions over distributed tables (analyzer) - #107514

Closed
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-97899-distributed-alias-function-column-order
Closed

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-97899-distributed-alias-function-column-order

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

Closes: #97899

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 and CANNOT_PARSE_* exceptions when reading an ALIAS column from a distributed/remote table together with a function column (now(), generateUUIDv4(), rand(), ...) and ORDER BY with enable_analyzer = 1.

Description

With enable_analyzer = 1, a query that reads an ALIAS column from a remote/distributed table together with a function column and ORDER BY could throw CANNOT_PARSE_* or silently return wrong results:

CREATE TABLE t (x String, xx String ALIAS concat(x, 'aaa'))
ENGINE = MergeTree ORDER BY x AS SELECT 'x';

SELECT now(), x, xx FROM remote('127.0.0.{1,2}', currentDatabase(), t) ORDER BY x;
-- Cannot parse DateTime from String

Root cause: for a remote read the local/ReadFromRemote plan inlines ALIAS columns into their expressions and places them among the projection columns, while the outer planner keeps the ALIAS column next to the storage columns. When an ALIAS column coexists with a function column the two headers end up in different orders. getQueryPlanForTableExpression then renames the local header to the expected header with ActionsDAG::MatchColumnsMode::Position, which pairs columns by position and maps the shard's alias value into the function column slot (the alias string concat(x, 'aaa') gets CAST to the function's type). Position matching is used here because constant function columns get value-dependent names that differ between the two planner runs, so a pure name match would not work.

Fix: before the position-based convert, reorder the local source columns to the expected order. Storage and function columns share names across both lists and are matched by name; the leftover columns (the ALIAS columns, named differently on each side but in the same relative order) are paired positionally. The reorder is only applied for remote reads with size-matching headers and only when it makes the types line up with the expected header position by position, so already-matching plans get the identity permutation and are untouched. The reorder is safe for shard reconciliation because both shard paths match the shard block to the header by name, not by position.

Verified on a 2-shard remote('127.0.0.{1,2}', ...) setup: the new test 04339_distributed_alias_column_with_function fails before the change (CANNOT_PARSE_DATETIME / silent wrong results) and passes after it. This is a different root cause from the recently merged #106404 (shard-side buildQueryTreeDistributed name dedup): confirmed the repro still failed identically on a build containing #106404 before this change.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes, 10/10. SELECT now(), x, xx FROM remote('127.0.0.{1,2}', db, t) ORDER BY x with enable_analyzer=1 on a 2-shard remote where an ALIAS column coexists with a function column and ORDER BY. rand()/generateUUIDv4() fail identically; function-last, no-ORDER-BY, and single-shard all pass.
b Root cause explained? Yes. For a remote read the local/ReadFromRemote plan inlines the ALIAS column into its expression among the projection columns, while the outer planner keeps the ALIAS column next to the storage columns. The two headers differ in order when an ALIAS and a function column coexist. The rename at PlannerJoinTree.cpp uses MatchColumnsMode::Position, so it pairs the shard's alias value with the function column slot and CASTs the alias string to the function's type (CANNOT_PARSE_*), or silently corrupts values when the types happen to match.
c Fix matches root cause? Yes. The fix reorders the local source columns to the expected order before the position-based convert, so positions line up. It targets the order mismatch directly, not the symptom.
d Test intent preserved / new tests added? New test 04339_distributed_alias_column_with_function added, covering now()/rand()/generateUUIDv4(), the silent-wrong-result UInt32 case, two interleaved alias+function pairs, reverse alias order, alias between storage columns, and the function-last / no-ORDER-BY controls.
e Both directions demonstrated? Yes, on Build-ID-verified binaries. Unpatched master eb2c089 (build id 33cc7d73): test FAILS (CANNOT_PARSE_DATETIME). Patched (build id 6b2d52de): test PASSES (diff vs reference empty), values correct.
f Fix is general, not a narrow patch? The fix handles any count/order of alias and function columns (verified with multiple interleavings), and is gated to remote reads with size-matching headers where the reorder makes types line up position-by-position, so working plans are untouched (identity permutation). A separate, pre-existing bug (SELECT a1, a1 FROM remote(...) ORDER BY x -> NUMBER_OF_COLUMNS_DOESNT_MATCH for duplicate aliases, source/result size mismatch) fails identically on both patched and unpatched builds and is out of scope for this position-reorder fix; left for a follow-up.
session-id: cron:clickhouse-worker-slot-5:20260615-135600

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @vdimir, this implements the option you picked for #97899: the local/ReadFromRemote plan columns are reordered to the outer planner's expected order before the position-based convert, so the alias value no longer lands in the function column slot. Confirmed #106404 does not cover this case.

@alesapin alesapin added the can be tested Allows running workflows for external contributors label Jun 15, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8bb9f77]


AI Review

Summary

This PR tries to fix analyzer wrong results and CANNOT_PARSE_* exceptions when remote/distributed reads project table ALIAS columns together with function columns before the initiator-side position-based header conversion. The approach is directionally targeted, but one fallback path can still return to the exact broken positional mapping unless the original non-deterministic/value-named function cases are proven not to hit it.

Missing context / blind spots
  • ⚠️ I could not run the stateless regression locally because this checkout has no ClickHouse build directory or runnable clickhouse binary. The S3 PR report available from the robot comment currently contains no test-result rows.
Findings

⚠️ Majors

  • [src/Planner/PlannerJoinTree.cpp:849] The new alignment helper returns the original source order whenever an unmatched expected column is not a real ALIAS. If a function column's action-node name differs between the real and only_analyze plans, this branch is reached after recording the ALIAS leftover, and the following MatchColumnsMode::Position conversion can again pair the alias expression with the function slot. This is the PR's original CANNOT_PARSE_DATETIME/wrong-result failure mode. Either keep such unmatched non-ALIAS function positions in the permutation instead of falling back to the old order, or add a regression that proves the original now, generateUUIDv4, and rand cases cannot hit this path.
Tests
  • ⚠️ The added stateless test uses deterministic constants and materialize shapes, but it does not execute the original now, generateUUIDv4, and rand repros claimed by the PR description. Adding those queries with FORMAT Null would keep output stable while proving they no longer throw.
Final Verdict

Status: ⚠️ Request changes

Minimum required action: address or prove safe the unmatched non-ALIAS function fallback, with focused coverage for the original function-column repros.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 15, 2026
Comment thread src/Planner/PlannerJoinTree.cpp Resolved

-- A function column BEFORE a plain column and its alias used to throw CANNOT_PARSE_DATETIME.
-- materialize() keeps the function value out of the output so the reference stays stable.
SELECT materialize(toDateTime('2020-01-01 00:00:00')) AS f, x, xx

@den-crane den-crane Jun 15, 2026 •

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.

The same issue with constants, add more tests without materialize

SELECT toDateTime('2020-01-01 00:00:00') AS f, x, xx
FROM remote('127.0.0.{1,2}', currentDatabase(), t_04339) ORDER BY x;

SELECT 7 AS f, x, xx, y
FROM remote('127.0.0.{1,2}', currentDatabase(), t_04339) ORDER BY x;

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Added both, without materialize:

SELECT toDateTime('2020-01-01 00:00:00') AS f, x, xx FROM remote('127.0.0.{1,2}', currentDatabase(), t_04339) ORDER BY x;
SELECT 7 AS f, x, xx, y FROM remote('127.0.0.{1,2}', currentDatabase(), t_04339) ORDER BY x;

Both fail on the base (CANNOT_PARSE_DATETIME / CANNOT_PARSE_TEXT) and pass with the fix.

@groeneai
groeneai force-pushed the groeneai/fix-97899-distributed-alias-function-column-order branch 2 times, most recently from 9443b85 to f7e74f4 Compare June 15, 2026 16:23
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (updated after clickhouse-gh[bot] review)

# Question Answer
a Deterministic repro? Yes. 2 shards via remote('127.0.0.{1,2}', ...), enable_analyzer=1, ORDER BY, and a function column before a plain column and its ALIAS column. Fails 100% on the base; single shard / enable_analyzer=0 are correct.
b Root cause explained? The local plan inlines ALIAS columns into their expressions and orders them among the projection columns; the outer planner keeps the ALIAS column under its identifier next to the storage columns. The two headers carry the same columns in different orders, and the MatchColumnsMode::Position convert that renames the remote header paired the alias column into the function slot (so e.g. concat(x,'aaa') was CAST to DateTime).
c Fix matches root cause? Yes. Before the position-based convert, the source columns are reordered to the expected order: storage and function columns are matched by name, the leftover ALIAS columns are paired in relative order.
d Test intent preserved / new tests added? New test 04339_distributed_alias_column_with_function (now()/generateUUIDv4()/rand()/folded constants/silent-wrong UInt32/two-function/reverse-order/alias-between-storage). After the bot review, added a same-type value-named constant case and two plain (non-materialize) constant cases requested in review.
e Both directions demonstrated? Yes, on build-id-verified binaries: base 33cc7d73 fails the test 3/3; fix 5df6aa3f passes 20/20 with randomization.
f Fix is general, not a narrow patch? The reorder covers exception and silent-wrong-result shapes and any number of interleaved function/alias columns. The leftover pairing is restricted to columns provably known to be table ALIAS columns (their ALIAS identifier), so a column whose name differs for another reason (e.g. a function referencing an alias) is never mispaired; in that case the convert keeps its prior behavior. A final type check guards the reorder, so working plans are untouched.

Session id: cron:clickhouse-worker-slot-1:20260615-153400

…ables (analyzer)

With the analyzer, reading an ALIAS column from a remote/distributed table together
with a non-storage function column and ORDER BY (so the query runs to
WithMergeableState) could route the alias value into the wrong column slot, throwing
CANNOT_PARSE_* or silently returning wrong results.

The local plan inlines ALIAS columns into their defining expressions and orders them
among the projection columns, while the outer planner keeps the ALIAS column under its
identifier next to the storage columns. The headers then carry the same columns in a
different order, and the position-based convert that renames the remote header to the
expected header paired the wrong columns.

Fix: before that convert, reorder the local source columns to the expected order.
Storage and function columns share names across both lists and are matched by name; the
leftover columns are paired positionally, but only when every leftover expected column
is provably a table ALIAS column (its name is an ALIAS identifier). A column whose name
merely differs between the two plans for another reason (for example a function that
references an ALIAS column) is not paired positionally; in that case the source is left
unchanged and the convert keeps its prior behavior. A final type check guards the
reorder, so already-matching plans get the identity permutation and are untouched. The
reorder is safe for shard reconciliation because both shard paths match the shard block
to the header by name, not by position.

Closes: ClickHouse#97899

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai
groeneai force-pushed the groeneai/fix-97899-distributed-alias-function-column-order branch from f7e74f4 to 54fc2da Compare June 15, 2026 16:26
The test uses remote('127.0.0.{1,2}', ...) which needs two shards to reproduce
the analyzer alias-column ordering bug. macOS runners cannot bind the 127.0.0.2
loopback alias, so the second shard connection deterministically times out
(SOCKET_TIMEOUT) and the Fast test (arm_darwin) fails. Skip it there, matching
the existing remote('127.0.0.{1,2}') entries in ci/defs/darwin.skip.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Jun 15, 2026
@fm4v fm4v removed the manual approve Manual approve required to run CI label Jun 16, 2026
/// Only pair leftovers positionally when every leftover is a real ALIAS column;
/// otherwise the relative-order assumption does not hold and we must not reorder.
if (!alias_column_identifiers.contains(expected[i].name))
return source;

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 still falls back to the old positional conversion for the case the PR description calls out as the reason pure name matching was unsafe: a non-ALIAS function column whose action-node name differs between the real and only_analyze plans. With source [__table1.x, _CAST(now_src), concat(__table1.x, 'aaa')] and expected [__table1.x, __table1.xx, _CAST(now_expected)], __table1.x matches, __table1.xx is recorded as an ALIAS leftover, then the unmatched now column hits this branch and returns the original order. The following MatchColumnsMode::Position convert then pairs concat(...) with the now slot again, reproducing the CANNOT_PARSE_DATETIME/wrong-result path. Please either keep unmatched non-ALIAS function slots in the permutation instead of bailing back to position matching, or add a regression that executes the original now, generateUUIDv4, and rand cases. For unstable output, FORMAT Null is enough to prove they no longer throw.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The now/generateUUIDv4/rand columns do not reach this branch, so the original issue shapes are not reproduced on the fixed binary. The premise that _CAST(now_src) differs from _CAST(now_expected) does not hold: the constant is folded once in the shared analyzed query tree, so the function's action-node name is byte-identical in both the ReadFromRemote (source) and only_analyze (expected) headers. It is therefore matched by name in the first pass and the only leftover is the genuine table ALIAS.

EXPLAIN header=1 for SELECT now(), x, xx FROM remote('127.0.0.{1,2}', db, t) ORDER BY x (fixed binary):

Change remote column names to local column names
Header: __table1.x String
        __table1.xx String
        _CAST(1781600130_DateTime, 'DateTime'_String) DateTime
  ReadFromRemote
  Header: __table1.x String
          _CAST(1781600130_DateTime, 'DateTime'_String) DateTime
          concat(__table1.x, 'aaa'_String) String

_CAST(1781600130_DateTime, ...) is identical on both sides, so now is name-matched; __table1.xx (an alias identifier) is the sole leftover; the reorder maps concat(...) to the xx slot. rand() and generateUUIDv4() behave the same (rand() UInt32, generateUUIDv4() UUID identical in both headers).

EXPLAIN actions=1 confirms the final mapping Positions: 0 3 2 -> [__table1.x, __table1.xx, _CAST(now)DateTime], no concat fed into the DateTime slot.

Added the now/generateUUIDv4/rand regressions to 04339 with FORMAT Null per your suggestion. They throw CANNOT_PARSE_* on the base binary and pass on the fixed one (10/10 randomized).

The function-referencing-alias shape (e.g. ax + 1000 next to a same-type alias) does land in the leftover lists and is intentionally left to the position fallback by the alias-identifier guard. That is a separate pre-existing bug (identical wrong result on unmatched master, outside #97899) and is noted as out of scope.

Cover the original issue ClickHouse#97899 shapes where a non-deterministic function
(now(), generateUUIDv4(), rand()) sits before a plain column and its ALIAS
column over a two-shard remote read with ORDER BY. These used to throw
CANNOT_PARSE_DATETIME / CANNOT_PARSE_UUID / CANNOT_PARSE_TEXT under the
analyzer. FORMAT Null is used because the output is non-deterministic; it
still proves the queries run to completion instead of throwing.

These functions do not hit the positional-fallback path in
alignRemoteColumnsToExpectedOrder: their action-node name is folded once in
the shared analyzed query tree (e.g. _CAST(<epoch>_DateTime, 'DateTime'),
rand(), generateUUIDv4()), so it is byte-identical in the ReadFromRemote
(source) and only_analyze (expected) headers and is matched by name in the
first pass. The only leftover column is the genuine table ALIAS, so the
alias-identifier guard holds and the reorder is applied. Verified with
EXPLAIN header=1/actions=1.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Jun 16, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (updated: now/generateUUIDv4/rand regressions)

# Question Answer
a Deterministic repro? Yes. SELECT now(), x, xx FROM remote('127.0.0.{1,2}', db, t) ORDER BY x with enable_analyzer=1, 2 shards, ORDER BY, function before plain+alias. Throws CANNOT_PARSE_DATETIME (and CANNOT_PARSE_UUID/CANNOT_PARSE_TEXT for generateUUIDv4/rand) on the base binary, 10/10.
b Root cause explained? The initiator renames the local plan to the outer planner's expected header via MatchColumnsMode::Position. The ReadFromRemote header inlines the alias into a projection expr, putting it after the function column, while the expected header groups table-expression columns (storage+alias) before functions. The orders differ, so Position pairs concat(x,'aaa') into the function slot and CASTs the alias string to the function type.
c Fix matches root cause? Yes. alignRemoteColumnsToExpectedOrder reorders the source columns to the expected order before the Position convert: storage and function columns by name (identical in both plans), the residual genuine ALIAS columns by relative order. Gated on isRemote(), equal sizes, and every residual being a provable table ALIAS identifier.
d Test intent preserved / new tests added? New test 04339. This update adds the original-issue now()/generateUUIDv4()/rand() shapes (FORMAT Null, output is non-deterministic) requested by the review, alongside the constant and silent-wrong-result cases already present.
e Both directions demonstrated? Yes. Base binary 33cc7d73: test fails (CANNOT_PARSE_*). Fixed binary 5df6aa3f: test passes 10/10 with randomized settings; direct .sql run matches .reference exactly.
f Fix is general, not a narrow patch? The reorder covers every #97899 shape (now/rand/generateUUIDv4, constants, multi-alias, reverse-order, silent same-type wrong results). The function-referencing-alias shape (ax + 1000 next to a same-type alias) is a separate pre-existing bug (identical wrong result on unmatched master, outside #97899); the alias-identifier guard routes it to the position fallback rather than mis-reordering it, so the fix does not regress it and does not over-reach.

Session id: cron:clickhouse-worker-slot-4:20260616-083800

@groeneai

Copy link
Copy Markdown
Collaborator Author

Closing in favor of #107675, the consolidated fix for #97899 (also #81631, #106398).

Verified #107675 fixes every #97899 shape, including the function-referencing-alias case (ax+1000 AS f, a, ay) that this PR handled only via the positional fallback. Its ActionsChain.cpp approach (preserve DAG output order in ActionsChainStep::initialize) is more general than the PlannerJoinTree reorder here.

@groeneai groeneai closed this Jun 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors manual approve Manual approve required to run CI pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Errors with alias columns and distributed tables and functions

4 participants