Repository navigation
Fix block structure check for aggregate-state columns nested in containers - #111191
Conversation
…iners The aggregate-state carve-out in `checkColumnStructure` (functions with the same state representation compare equal, e.g. `quantileState` vs `quantilesState(0.9)`) applied only to top-level `ColumnAggregateFunction`. When an expression over a `UNION ALL` of such states wraps them into another column (e.g. `tuple(s)`), the nested columns fell into the strict `IColumn::getName` comparison, and debug and sanitizer builds failed the query plan and pipeline header checks with a logical error 'Block structure mismatch in after optimization liftUpUnion stream'. Make the comparison recursive: descend into plain container columns (Tuple, Array, Map, Nullable, Const, Sparse, Replicated) and apply the aggregate-state relaxation at any nesting depth; all other columns are still compared by full name, exactly as before. Found by AST fuzzer: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=102509&sha=06ec723ed42b84c7c77f932d8afb808060adca5c&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%29 (the failure was unrelated to #102509) Closes: #111185 Co-Authored-By: Claude Fable 5 <[email protected]>
|
Workflow [PR], commit [1ae813a] Summary: ✅
AI ReviewSummaryThis PR correctly closes the previously reported Findings
Final Verdict
|
The recursive aggregate-state relaxation in `checkColumnStructure` descended into plain container columns (`Tuple`, `Array`, `Map`, `Nullable`, `Const`, `Sparse`, `Replicated`) but deliberately left `Variant` strict. A set operation over two unrelated `Tuple` types (e.g. `tuple(3, s) EXCEPT ALL tuple(s, x)`) builds a `Variant` of both alternatives, with the aggregate state nested inside one of them. The per-branch `Variant` columns then differ only by the nested aggregate function (`quantile` vs `quantiles`), fell into the strict `IColumn::getName` comparison, and AST fuzzer failed the block structure check with a logical error `Block structure mismatch in UnionStep stream: different columns`. Descend into `Variant` too: its type equality (already checked before this point) fixes the set and order of alternatives, so the only thing that can differ between two structurally-equal-typed `Variant` columns is an aggregate state nested inside an alternative, which is exactly what the relaxation should allow. `Dynamic`/`Object` stay strict because their nested structure is not fixed by the type. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111191&sha=8d99bb9741c89be02182218243b701b42bb5e3b0&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ggregate-state-header
…ucture check The previous commit descended into `ColumnVariant` via the generic `forEachSubcolumn`, which iterates the nested variant columns in the local (storage) order, while `ColumnVariant::getName` lists them in the global (type) order. Two same-typed `Variant` columns with different local orders were then compared alternative-against-wrong-alternative and reported as a structure mismatch — a regression caught by test `04327_variant_map_statistics_merge_discriminator` in the Fast test: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111191&sha=7b909cd84079e1a0a42bb720ad48e539f3818584&name_0=PR&name_1=Fast%20test #111191 Compare the alternatives pairwise by global discriminator instead, as `getName` does. Co-Authored-By: Claude Fable 5 <[email protected]>
…ggregate-state-header
…in the block structure check The internal indexes column of `ColumnReplicated` is a variable-width encoding detail (`UInt8` .. `UInt64`, widened lazily) that `getName` does not include, yet `forEachSubcolumn` exposes. Descending into it made the check stricter than the name comparison and could reject a valid runtime replicated block against its header. Give `Replicated` a dedicated branch comparing only `getNestedColumn`, mirroring `ColumnReplicated::structureEquals`.
The `Variant`-building set operations over unrelated `Tuple` types work only with the new analyzer; the old one fails to find a common type for the branches (`NO_COMMON_TYPE`), which failed the test on the old-analyzer shard: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111191&sha=26f8470a010fd342d26ca88defb1db6920d2a576&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20old%20analyzer%2C%20s3%20storage%2C%20DBReplicated%2C%20WasmEdge%2C%20parallel%2C%201%2F3%29
The analyzer is enabled by default since 24.3 and is no longer new. Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111191&sha=363f52585f769e0b07e841abd4ec863095235f02&name_0=PR&name_1=Style%20check PR: #111191 Co-Authored-By: Claude Fable 5 <[email protected]>
…ggregate-state-header
…eld` The `Field` comparison of aggregate states throws `Comparing aggregate functions with different types` when the aggregate function type names differ, even when the states are compatible by `haveSameStateRepresentation` (e.g. `quantileState` vs `quantilesState(0.9)`). Two places compared constant columns this way: - `sameConstants` in `getLeastSuperColumn`: a `UNION ALL` of constant compatible aggregate states failed at planning time. Don't save constness for aggregate-state constants — materializing is always correct. - the constant-value check in `checkColumnStructure`: skip it for constants containing an aggregate-state column; the structural compatibility is already checked above with the state-representation relaxation. Regression cases added to test 04623.
…ggregate-state-header
…gregate-state leaves Skipping the whole constant-value comparison when the payload contains an aggregate state anywhere was too broad: a constant `Tuple` with a compatible aggregate-state element but a differing scalar element, or top-level constant aggregate states with different serialized state bytes, would silently pass `blocksHaveEqualStructure` / `assertCompatibleHeader`. Replace the shortcut with a recursive `Field` comparison that relaxes only the aggregate-state leaves: compare their serialized state data (the function names may legitimately differ when the states are compatible by `haveSameStateRepresentation`, which the type and column structure checks have already established), and compare everything else exactly as before. #111191 (comment) Co-Authored-By: Claude Fable 5 <[email protected]>
|
The stateless failures on e40e2f5 ( |
…ggregate-state-header
… in ActionsChainStep The COLUMN-to-INPUT replacement in ActionsChainStep::finalizeInputAndOutputColumns compared the constant values of same-name nodes with a plain Field comparison, which throws "Comparing aggregate functions with different types" for aggregate states whose function names differ, even though such types compare equal (they are compatible by the normalized state type, e.g. `quantile(0.5)` vs `quantiles(0.9)`). Compare the aggregate-state leaves by both the function name and the serialized state instead of throwing: unlike the block structure checks, this comparison drives a substitution, and substituting a state of a different aggregate function would change the downstream behavior (e.g. the result of `finalizeAggregation`), so the names must match exactly.
…peration step headers `UnionStep::checkHeaders` and `IntersectOrExceptStep::checkHeaders` decided whether to keep a top-level `Const` column in the common header by comparing the constant values with raw `Field` equality. For aggregate-state constants that comparison throws `Comparing aggregate functions with different types` when the aggregate function type names differ, and they may legitimately differ between branches when the functions have the same state representation (e.g. `quantileState` vs `quantilesState(0.9)`). These steps recompute their headers during later plan rewrites, so a branch-local constant fold could reintroduce such a header even though planning materializes it initially. Apply the same non-throwing rule as `sameConstants` in `getLeastSuperColumn`: never keep constness for columns containing an aggregate state, materialize them instead. Co-Authored-By: Claude Fable 5 <[email protected]>
…ggregate-state-header
|
Found via ClickGap automated review. Please close or comment if this is incorrect or needs adjustment. TL;DRFix block structure check for aggregate-state columns nested in containers ClickGap verified: reproduced it with the script below on Reproduction-- Fixed by PR #111191. Reproduces on release 26.1-26.6; returns 2 on fixed master.
SELECT count() FROM
(
SELECT tuple(s) FROM
(
SELECT quantileState(number) AS s FROM numbers(7)
UNION ALL
SELECT quantilesState(0.9)(number) FROM numbers(5)
)
);
-- Observed on affected releases: Code: 49. DB::Exception: Block structure mismatch in UnionStep stream: different columns (LOGICAL_ERROR). Expected: 2.Bisect
Affects
Suggested next stepThe fix has landed on master; the affected release branches above still need the backport. Component: cc fix PR reviewer: @CheSema ClickGap · Finding: Triage metadata
|
Issue ClickHouse#112018: repeating an identical INSERT ... SELECT with the same insert_deduplication_token, into a MergeTree table whose column is a Tuple with a sparse-serialized element, raised the logical error "Block structure mismatch in function connect between SourceFromSingleChunk and ConvertingTransform". DeduplicationInfo::recalculateBlock builds the retry header with cloneEmpty(), which preserves the column implementation, so the sparse Tuple element stays sparse in the header. The retry chain's ConvertingTransform input header comes from the storage metadata sample block and is never sparse, so connect asserted. The nested sparse column escaped the top-level-only ColumnSparse unwrap in checkColumnStructure because ColumnTuple::getName renders element names recursively. Both source fixes merged on 2026-07-30 by different mechanisms, ClickHouse#111103 (goRetry returns early on empty input, before the retry pipeline is built) and ClickHouse#111191 (haveCompatibleColumnStructure recurses into ColumnTuple). Neither shipped a test for the sparse shape, and no test on master combines insert deduplication with sparse serialization, so this adds the missing coverage. The test covers a sparse element in a Tuple, a doubly nested Tuple and a materialized-view target, with controls for a top-level sparse column, an insert without deduplication, sparse serialization surviving on disk after the retry, and deduplication having dropped the rows. It guards the end-to-end behaviour rather than either fix individually: every deduplicating case uses one token per insert, so on the repeat all tokens collide and goRetry receives an empty block, which means ClickHouse#111103's guard returns before ClickHouse#111191's structure check is consulted. Reverting either fix alone leaves the test green; reverting both reproduces the reported message exactly. A partial deduplication case, which would deliver a non-empty sparse block and pin the Block.cpp side alone, is left as a follow-up. All nine MergeTree tables pin ratio_of_defaults_for_sparse_serialization so the test needs no no-random-merge-tree-settings tag. Verified with the real test runner: 100/100 under randomization, and a control that removes the pin from the one table whose sparseness is asserted fails 27/50, which confirms the pins are load-bearing. The test is parallel-safe without a no-parallel tag because every object lives in its own currentDatabase(). Co-Authored-By: Claude Fable 5 <[email protected]>
…te columns nested in containers
Backport #111191 to 26.7: Fix block structure check for aggregate-state columns nested in containers
…te columns nested in containers
Backport #111191 to 26.6: Fix block structure check for aggregate-state columns nested in containers
Resolve conflicts in favor of the 26.5 release branch for `src/Planner/ActionsChain.cpp`, `src/Processors/QueryPlan/UnionStep.cpp` and `src/Processors/QueryPlan/IntersectOrExceptStep.cpp`: the hunks of #111191 in these files fix the constant-keeping loop in `checkHeaders` and the COLUMN-to-INPUT replacement in `ActionsChainStep::finalizeInputAndOutputColumns`, which do not exist on 26.5, so there is nothing to fix there. The core fix (`Block.cpp`, `getLeastSuperColumn.cpp`) and the tests are kept. Co-Authored-By: Claude Fable 5 <[email protected]>
Cherry pick #111191 to 26.5: Fix block structure check for aggregate-state columns nested in containers
…te columns nested in containers
Backport #111191 to 26.5: Fix block structure check for aggregate-state columns nested in containers
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):
Fixed a logical error
Block structure mismatch(in debug and sanitizer builds) and anIllegal types of argumentserror for set operations over compatible aggregate-state columns (e.g.quantileStateandquantilesState(0.9)) nested inside container columns such asTuple,Array,Map,Nullable, orVariant.The aggregate-state carve-out in
checkColumnStructure(aggregate functions with the same state representation compare equal, e.g.quantileStatevsquantilesState(0.9)) applied only to a top-levelColumnAggregateFunction. When an expression over aUNION ALLof such states wraps them into another column (e.g.tuple(s)), the nested columns fell into the strictIColumn::getNamecomparison, and debug and sanitizer builds failed the query plan and pipeline header checks (e.g. after theliftUpUnionoptimization and inQueryPipeline) with a logical errorBlock structure mismatch in after optimization liftUpUnion stream: different columns. Constant aggregate-state columns additionally failed in release builds at planning time (getLeastSuperColumn) withIllegal types of arguments.Make the comparison recursive: descend into plain container columns (
Tuple,Array,Map,Nullable,Const,Sparse, andVariantalternatives by global discriminator;Replicatedby its nested column) whose names are a pure composition of the nested column names, and apply the aggregate-state relaxation at any nesting depth. Constant values are compared recursively as well, relaxing only the aggregate-state leaves (comparing their serialized state). All other columns are still compared by full name, exactly as before.Found by AST fuzzer on an unrelated PR: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=102509&sha=06ec723ed42b84c7c77f932d8afb808060adca5c&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%29
Closes: #111185
Related: #102509
Version info
26.7.3.19,26.6.3.7,26.5.7.21