Repository navigation
Conversation
…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]>
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.
Severity: ❌ blocker / Session id: cron:clickhouse-review-self-slot-58:20261006-010800 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-self-slot-57:20261005-235400 |
|
Workflow [PR], commit [97eb79a] Summary: ❌
AI ReviewSummaryThe PR preserves expressions over columns missing from a The affected consumers traced were Findings
Final Verdict
|
CI finish ledger - d8fd487Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
All 146 check runs completed (120 pass, 25 not selected, 1 red), last completion 08:03:28Z, and Session id: cron:our-pr-ci-monitor:20261006-083231 |
|
One more shape of this bug is not covered here: 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 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
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]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes150 object files changed (+23.01 KiB total), 0 added.
711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Slowest function optimization changes (ThinLTO)Median per-function time ratio to the master baseline:
Compile time of recompiled translation units624 translation units recompiled, 5902 s compile time in total, 624 of them have a recent master baseline. |
…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]>
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]>
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]>
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]>
CI finish ledger - 11eb34dEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
All 179 check runs completed and Session id: cron:our-pr-ci-monitor:20261028-203004 |
|
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(); |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
[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.
…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]>
Related: #99833
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed wrong results of
merge()andMergetables whose children have different columns when one child is aDistributedtable: 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 withTHERE_IS_NO_COLUMN(e.g.min(a)returned the other child's minimum instead of0, andidwas read as0).Description
On 26.8.10.6, with
p_a (id, a, b)holding(1, 5, 5)and aDistributedtable overp_b (id)holding10, 11,SELECT min(a), min(b), count() FROM merge(currentDatabase(), '^p_(a|dist_b)$')returns5 5 3instead of0 0 3,and
SELECT id, a FROM merge(...)in a subquery returns ids0, 0instead of10, 11. 26.3 threwUNKNOWN_IDENTIFIER; the default substitution came with #99833.Root cause: a
Distributedchild lifts the read aboveFetchColumns, and each child computes the query with amissing column replaced by its default constant. The child's header then stops matching the
Mergeheader: equalconstant aggregates are deduplicated (
min(a), min(b)become onemin(0)), constant columns are not returned, anda 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:
WHERE/PREWHEREthe default is wrapped intoidentity(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
Mergequery does. Filters keep the bare default for pruning.buildShardCollapseFanOuttranslates theMergeheader through the same replacement (long constants named asthe child names them) and fans out the columns the child deduplicated, as for duplicate
ALIAScolumns.Buffer's buffers plan runs only the resolve passes, asmaster does for
Mergechildren, and an inlined view resolves_shard_num. Nested reads inherit it, viewbodies do not.
Validation: the new test compares every query with the same query without
Distributed; it fails on master andpasses with the fix, also with
prefer_localhost_replica = 0andserialize_query_plan = 1, 50 randomized runs.Each hunk removed turns named rows red. 265 related
Merge/Distributedtests pass.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/124125]