Skip to content

Fix block structure check for aggregate-state columns nested in containers - #111191

Merged
CheSema merged 22 commits into
masterfrom
fix/lift-up-union-aggregate-state-header
Jul 30, 2026
Merged

CheSema merged 22 commits into
masterfrom
fix/lift-up-union-aggregate-state-header

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 21, 2026 •

Copy link
Copy Markdown
Member

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

Fixed a logical error Block structure mismatch (in debug and sanitizer builds) and an Illegal types of arguments error for set operations over compatible aggregate-state columns (e.g. quantileState and quantilesState(0.9)) nested inside container columns such as Tuple, Array, Map, Nullable, or Variant.

The aggregate-state carve-out in checkColumnStructure (aggregate functions with the same state representation compare equal, e.g. quantileState vs quantilesState(0.9)) applied only to a 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 (e.g. after the liftUpUnion optimization and in QueryPipeline) with a logical error Block structure mismatch in after optimization liftUpUnion stream: different columns. Constant aggregate-state columns additionally failed in release builds at planning time (getLeastSuperColumn) with Illegal types of arguments.

Make the comparison recursive: descend into plain container columns (Tuple, Array, Map, Nullable, Const, Sparse, and Variant alternatives by global discriminator; Replicated by 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

  • Backported to: 26.7.3.19, 26.6.3.7, 26.5.7.21

…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]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1ae813a]

Summary: ✅


AI Review

Summary

This PR correctly closes the previously reported Tuple / Variant / Sparse / Replicated aggregate-state header mismatches, but two JSON / Dynamic constant paths still escape the new handling in the latest head. Because of those remaining gaps, the change does not yet fully satisfy its contract for constant payloads that contain compatible aggregate states under hidden-type containers.

Findings
  • ⚠️ Major — src/Columns/getLeastSuperColumn.cpp:34, src/Processors/QueryPlan/UnionStep.cpp:78, src/Processors/QueryPlan/IntersectOrExceptStep.cpp:77: the new aggregate-state detection only walks physical subcolumns, so it misses JSON / Object values that have already spilled into ColumnObject shared_data. In that layout the guard stays false, the code falls back to raw Field equality, and constants like JSON(max_dynamic_paths=0) {k: quantileState(...)} vs {k: quantilesState(...)} still throw Comparing aggregate functions with different types instead of materializing the header.
  • ⚠️ Major — src/Core/Block.cpp:203, src/Planner/ActionsChain.cpp:61: the new constant comparators still omit Field::Types::Object. For strict Dynamic / JSON comparisons they fall back to raw Field::operator==, which recursively reaches AggregateFunctionStateData::operator== and throws on differing aggregate-function names instead of returning false. So hidden-type constants with object leaves still retain the original exception path.
Final Verdict

⚠️ Needs changes before merge. The latest head fixes the previously discussed container cases, but JSON / Dynamic constants with nested aggregate states are still not handled consistently and can still throw in the constant-comparison paths.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Jul 21, 2026
Comment thread src/Core/Block.cpp Resolved
alexey-milovidov and others added 3 commits July 21, 2026 21:07
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]>
…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]>
Comment thread src/Core/Block.cpp Resolved
alexey-milovidov and others added 4 commits July 23, 2026 01:13
…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`.
Comment thread src/Core/Block.cpp Resolved
…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.
Comment thread src/Core/Block.cpp Resolved
alexey-milovidov and others added 2 commits July 24, 2026 05:27
…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]>
@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default and removed pr-ci labels Jul 24, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

The stateless failures on e40e2f5 (03216_arrayWithConstant_limits, 03826_calculate_subcolumn_size_during_merge_tree_read, 02477_single_value_data_string_regression) all failed with MEMORY_LIMIT_EXCEEDED at a server RSS of ~44 GiB out of the 44.83 GiB total limit — shard-wide memory pressure on the amd_asan_ubsan runner, unrelated to this PR. The arrayWithConstant memory hog that drives it is addressed by #111705. The Upgrade check reds (settings changes history) were caused by the branch being behind master and are cleared by the merge of master pushed together with the review fix.

Comment thread src/Columns/getLeastSuperColumn.cpp Resolved
… 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.
Comment thread src/Columns/getLeastSuperColumn.cpp Resolved
alexey-milovidov and others added 2 commits July 25, 2026 13:03
…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]>
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 30, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Found via ClickGap automated review. Please close or comment if this is incorrect or needs adjustment.

TL;DR

Fix block structure check for aggregate-state columns nested in containers

ClickGap verified: reproduced it with the script below on 26.6; tested 7 version(s) — 6 affected, 1 clean (see Affects); long-standing (not a recent regression); introducing PR not yet pinned.

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.

▶ Run on ClickHouse Fiddle

Bisect

  • Reproduces on every release line tested down to v23.5.5.92 (the oldest with a downloadable binary for this repro). The introducing change predates v23.5.5.92, so it can't be pinned from release binaries — this is a long-standing issue, not a recent regression. A maintainer with full git history can git blame the relevant file/line to find the exact change.

Affects

  • ✓ Fix is on master — this PR's change fixes the bug on master. Branches below still have the bug and need the backport.
  • Reproduces on: 26.6, 26.5, 26.4, 26.3, 26.2, 26.1
  • Does NOT reproduce on: master
  • Backport needed: 26.6, 26.5, 26.4, 26.3, 26.2, 26.1

Suggested next step

The fix has landed on master; the affected release branches above still need the backport.

Component: comp-query-execution
Severity: P2

cc fix PR reviewer: @CheSema


ClickGap · Finding: phase_d_pr111191

Triage metadata

  • Primary component: comp-query-execution
  • Secondary components: comp-data-types

Blargian pushed a commit to cwurm/ClickHouse that referenced this pull request Aug 4, 2026
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]>
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Aug 5, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Aug 5, 2026
clickhouse-gh Bot added a commit that referenced this pull request Aug 5, 2026
Backport #111191 to 26.7: Fix block structure check for aggregate-state columns nested in containers
clickhouse-gh Bot pushed a commit that referenced this pull request Aug 6, 2026
clickhouse-gh Bot added a commit that referenced this pull request Aug 6, 2026
Backport #111191 to 26.6: Fix block structure check for aggregate-state columns nested in containers
alexey-milovidov added a commit that referenced this pull request Aug 6, 2026
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]>
robot-ch-test-poll4 added a commit that referenced this pull request Aug 6, 2026
Cherry pick #111191 to 26.5: Fix block structure check for aggregate-state columns nested in containers
robot-clickhouse added a commit that referenced this pull request Aug 6, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 6, 2026
fm4v added a commit that referenced this pull request Aug 7, 2026
Backport #111191 to 26.5: Fix block structure check for aggregate-state columns nested in containers
@fm4v fm4v added v26.2-must-backport and removed v26.4-must-backport pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore labels Aug 7, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 8, 2026
@nikitamikhaylov nikitamikhaylov removed the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 10, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.2-must-backport

Projects

None yet

9 participants