Skip to content

Fix an ALIAS column read as a default through Merge over Distributed - #119561

Merged
alexey-milovidov merged 2 commits into
masterfrom
fix-merge-over-distributed-alias-119374
Sep 12, 2026
Merged

alexey-milovidov merged 2 commits into
masterfrom
fix-merge-over-distributed-alias-119374

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 11, 2026 •

Copy link
Copy Markdown
Member

An ALIAS column whose expression is a bare reference to another column read back as the default value of its type through a Merge table over a Distributed table with a remote shard:

CREATE TABLE t (a UInt64, b UInt64 ALIAS a, c UInt64 ALIAS b, d UInt8 ALIAS a > 0) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t SELECT number + 1 FROM numbers(4);
CREATE TABLE t_dist AS t ENGINE = Distributed(test_cluster_two_shards, currentDatabase(), t);
CREATE TABLE t_merge AS t ENGINE = Merge(currentDatabase(), '^t_dist$');

SELECT a, b, c, d FROM t_dist ORDER BY a LIMIT 1;   -- 1 1 1 1
SELECT a, b, c, d FROM t_merge ORDER BY a LIMIT 1;  -- 1 0 0 0  <-- b, c and d are defaults

The whole query is delegated to the shards there, and Distributed inlines the ALIAS columns of the child table into their expressions before sending it, so b UInt64 ALIAS a selected next to a becomes the same expression as a and the child's ActionsDAG deduplicates the two into one column. The name of the collapsed column is gone from the child's header, and neither the name nor the position matching in convertAndFilterSourceStream can rebuild it, so addMissingDefaults filled the column Merge was still expecting with the default value of its type. An ALIAS column with a function in it (d UInt8 ALIAS a > 0) survived, because its expression has an action name of its own and nothing to collapse onto — until a bare alias was selected next to it and the whole reconciliation fell back to defaults.

The fix fans the collapsed columns back out before the reconciliation, with buildShardCollapseFanOut — the same helper the planner already uses for a direct read of a Distributed table, which is why reading t_dist itself was correct all along.

One divergence in this area is older than this change and not addressed by it: when a child table defines the alias differently from the Merge table (b ALIAS a * 100 in the child, b ALIAS a in the Merge table), a delegated stage evaluates the Merge table's definition, while reading the same tables through Merge at the FetchColumns stage evaluates each child's own. Before this change that shape returned the default value as well.

Closes: #119374

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 to CHANGELOG.md):

Fix an ALIAS column that references another column (b UInt64 ALIAS a) reading back as the default value of its type when the table is read through a Merge table over a Distributed table with a remote shard.


Workflow [PR]
Sync PR [sync-upstream/pr/119561]

Version info

  • Merged into: 26.9.1.1276 (included in 26.9 and later)

…uted`

An `ALIAS` column whose expression is a bare reference to another column read
back as the default value of its type through a `Merge` table over a
`Distributed` table with a remote shard:

    CREATE TABLE t (a UInt64, b UInt64 ALIAS a, c UInt64 ALIAS b, d UInt8 ALIAS a > 0) ENGINE = MergeTree ORDER BY tuple();
    CREATE TABLE t_dist AS t ENGINE = Distributed(test_cluster_two_shards, currentDatabase(), t);
    CREATE TABLE t_merge AS t ENGINE = Merge(currentDatabase(), '^t_dist$');

    SELECT a, b, c, d FROM t_dist;   -- 1 1 1 1
    SELECT a, b, c, d FROM t_merge;  -- 1 0 0 0

The whole query is delegated to the shards there, and `Distributed` inlines the
`ALIAS` columns of the child table into their expressions before sending it, so
`b UInt64 ALIAS a` selected next to `a` becomes the same expression as `a` and
the child's `ActionsDAG` deduplicates the two into one column. The name of the
collapsed column is gone from the child's header, and neither the name nor the
position matching in `convertAndFilterSourceStream` can rebuild it, so
`addMissingDefaults` filled the column `Merge` was still expecting with the
default value of its type. An `ALIAS` column with a function in it survived,
because its expression has an action name of its own and nothing to collapse
onto - until a bare alias was selected next to it and the whole reconciliation
fell back to defaults.

Fan the collapsed columns back out before the reconciliation, with
`buildShardCollapseFanOut` - the same helper the planner already uses for a
direct read of a `Distributed` table, which is why reading `t_dist` itself was
correct all along.

Closes: #119374
@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [577d1e0]

Summary: ✅


AI Review

Summary

This PR fixes the header-reconciliation bug for plain SELECT/single-key cases where a Merge table reads a Distributed child whose bare ALIAS columns collapse onto the same shard expression. I do not think it closes the aggregation variant of the same invariant yet: Merge now reconstructs the missing header columns locally, but it still does not propagate the duplicate-key collapse metadata that the outer aggregation merge needs to bucket two-level states correctly.

Findings

❌ Blockers

  • [src/Storages/StorageMerge.cpp:2248, src/Planner/Planner.cpp:1020-1075, src/Planner/Planner.cpp:2891, src/Planner/Planner.cpp:3004] The new buildShardCollapseFanOut call only repairs the child header shape. For Merge over Distributed, the outer planner still receives an empty shard_collapse_duplicate_keys map, so under two-level aggregation it buckets and merges by both a and b even when the distributed shard already collapsed b ALIAS a onto a before computing bucket numbers. That is the same wrong-results invariant the direct Distributed path had to fix in addMergingAggregatedStep, and it also leaves the GROUPING SETS rejection path unreachable here. A focused GROUP BY a, b or GROUP BY GROUPING SETS ((a, b), (a)) repro over Merge(currentDatabase(), '^t_dist$') with duplicate ALIAS keys should still split states per shard instead of producing one merged result.
    Suggested fix: propagate the duplicate-to-representative mapping out of ReadFromMerge the same way buildJoinTreeQueryPlan does for direct Distributed reads, and feed it into the outer addMergingAggregatedStep; if that is too invasive, force this shape down to FetchColumns or disable shipped aggregation for now.
Tests
  • ⚠️ [tests/queries/0_stateless/05209_merge_over_distributed_alias_column.sql:19] The new test only exercises the header-reconstruction cases (SELECT, WHERE, sum, GROUP BY b). Please add a focused regression for duplicate-key aggregation over Merge-over-Distributed under two-level aggregation, plus the unsafe GROUPING SETS shape, so the remaining wrong-results path is covered once fixed.
Final Verdict

Changes requested: the patch fixes the projection/header mismatch, but grouped Merge reads over Distributed can still mis-merge duplicate-ALIAS aggregate states under two-level aggregation.

LLVM Coverage Report

Measured on commit 577d1e0.

Metric Baseline Current Δ
Lines 89.00% 89.00% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.30% 81.30% +0.00%

Changed lines: Changed C/C++ lines covered: 8/8 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 11, 2026
/// The translation between an `ALIAS` column's own name and its inlined expression is read from
/// the outer query tree and its planner context: those are what the expected `header` is named
/// after, and the child's derived planner context holds no column identifiers of its own.
if (auto fan_out_actions_dag = buildShardCollapseFanOut(

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 only repairs the header shape. The direct Distributed path also feeds the duplicate -> representative map from buildShardCollapseFanOut into addMergingAggregatedStep, because once the shard has collapsed GROUP BY a, b with b ALIAS a to one key it also buckets its partial states by that collapsed key set.

Here ReadFromMerge fans b back out, but the aggregation merge above this step still sees both keys, so under two-level aggregation it can bucket the same logical group differently from the shard and never merge the states. Unsafe GROUPING SETS shapes stay affected for the same reason. The new test only exercises the single-key GROUP BY b case, which does not hit this.

I think this needs the same metadata flow as the plain Distributed path (shard_collapse_duplicate_keys in Planner.cpp), or shipped aggregation has to be disabled for this shape. A focused repro would be a Merge-over-Distributed copy of the two-level GROUP BY a, b / GROUPING SETS cases from 04357_distributed_alias_same_expression.sql.

@clickhouse-gh clickhouse-gh Bot added the comp-storage-merge Merge table engine (logical union over tables) and related mechanics. label Sep 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 577d1e0aa with master 30c98e714 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

16 translation units recompiled, 123 s compile time in total, 16 of them have a recent master baseline.

Job report

With `optimize_respect_aliases = 0` the old analyzer refuses a `Merge` table over
a `Distributed` table with `ALIAS` columns outright - `Missing columns: 'b' 'c'
'd'` - because it asks the `Merge` table for the source column alone while the
query still references the alias columns. That happens on master as well, so the
old-analyzer control of this test pins the setting instead of tripping over it
when the randomized-settings run turns it off.

@alexey-milovidov alexey-milovidov left a comment

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.

Ok.

@clickgapai

Copy link
Copy Markdown
Contributor
Reproducer
-- on a server with the standard test clusters (test_cluster_two_shards has a remote shard)
CREATE TABLE t (a UInt64, b UInt64 ALIAS a) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t VALUES (1);
CREATE TABLE t_dist AS t ENGINE = Distributed(test_cluster_two_shards, currentDatabase(), t);
CREATE TABLE t_merge AS t ENGINE = Merge(currentDatabase(), '^t_dist$');

SELECT a, b FROM t_dist  ORDER BY a LIMIT 1;  -- 1  1
SELECT a, b FROM t_merge ORDER BY a LIMIT 1;  -- 1  0  <-- ALIAS column b reads back as the default

Results:

  • Reproduces on: 26.8, 26.7, 26.6, 26.3
  • Does not reproduce on: master
  • Tested versions: master, 26.8, 26.7, 26.6, 26.3
  • Also tested (unsupported, context only): 26.2 reproduces
  • ✓ Fix is on master — this PR's change fixes the bug on master. The releases listed above still have the bug and need the backport.

Backport the fix to 26.8, 26.7, 26.6, 26.3.

CC component owner: @alexey-milovidov @CurtizJ

Analysis metadata

comp-storage-merge · Severity P2 · Finding phase_d_pr119561

  • Verified against master build 1e691b7ed280 (aarch64)
Introducing change: not identified
  • The introducing change was not identified.
  • Walked 6 release(s) below the supported window: still reproduces down to 25.8.
  • Secondary components: comp-testing

pull Bot pushed a commit to admariner/ClickHouse that referenced this pull request Sep 27, 2026
… EXPLAIN or a subquery

A correlated subquery is planned with its own `GlobalPlannerContext`, and
`collectTableExpressionDataForCorrelatedColumns` stores raw pointers to the
enclosing query's `TableExpressionData` in it, without keeping the enclosing
`PlannerContext` alive. Every context derived from the subquery falls back to
that map when it looks up the correlated column's source.

`ReadFromMerge` plans its source tables lazily (from `applyFilters` during
`QueryPlan::optimize`, or from `initializePipeline`). For a non-empty source
table narrower than the `Merge` header, `convertAndFilterSourceStream` builds
the fan-out added in ClickHouse#119561 and names the correlated column through that map.
`EXPLAIN`, a subquery in `FROM`, a view and an `IN` subquery destroy the
enclosing `Planner` before that point, so the lookup reads freed memory
(AST fuzzer, arm_asan_ubsan, STID 4877-28b1).

`GlobalPlannerContext` now holds a `PlannerContextPtr` to every planner context
whose data it points into. It is the only writer of the map, so this covers all
readers and every place that drops the enclosing planner early, without
changing each of them. No reference cycle: the subquery's plan is united into
the enclosing `QueryPlan`, never stored in the enclosing `PlannerContext`
(correlated subqueries are neither `IN` set sources nor materialized CTEs).

Related: ClickHouse#115238 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-storage-merge Merge table engine (logical union over tables) and related mechanics. pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ALIAS column referencing another column reads back as the default value through Merge over a multi-shard Distributed table (analyzer)

3 participants