Skip to content

Cherry pick #111191 to 26.5: Fix block structure check for aggregate-state columns nested in containers - #113566

Merged
robot-ch-test-poll4 merged 24 commits into
backport/26.5/111191from
cherrypick/26.5/111191
Aug 6, 2026
Merged

robot-ch-test-poll4 merged 24 commits into
backport/26.5/111191from
cherrypick/26.5/111191

Conversation

@robot-ch-test-poll

Copy link
Copy Markdown
Contributor

Original pull-request #111191

Do not merge this PR manually

This pull-request is a first step of an automated backporting.
It contains changes similar to calling git cherry-pick locally.
If you intend to continue backporting the changes, then resolve all conflicts if any.
Otherwise, if you do not want to backport them, then just close this pull-request.

The check results does not matter at this step - you can safely ignore them.

Troubleshooting

If the conflicts were resolved in a wrong way

If this cherry-pick PR is completely screwed by a wrong conflicts resolution, and you want to recreate it:

  • delete the pr-cherrypick label from the PR
  • delete this branch from the repository

You also need to check the Original pull-request for pr-backports-created label, and delete if it's presented there

The PR source

The PR is created in the CI job

alexey-milovidov and others added 23 commits July 21, 2026 08:57
…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]>
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]>
…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`.
…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.
…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]>
… 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]>
`checkColumnStructure` unwraps a top-level `ColumnSparse` because `Sparse(T)`
and `T` are structurally interchangeable, but the recursive
`haveCompatibleColumnStructure` returns `false` on `typeid(actual) != typeid(expected)`
before any sparse-specific handling. So nested shapes such as
`Tuple(Sparse(T))` versus `Tuple(T)` - real today, see `recursiveRemoveSparse`
and `01780_column_sparse_materialize` - still reported
`Block structure mismatch` when one branch materialized a nested subcolumn
while another kept it sparse.

Unwrap `Sparse` on either side independently at the top of
`haveCompatibleColumnStructure` (and drop it from the generic compositional
whitelist, which is now unreachable for it), mirroring the top-level unwrap.

Added a unit test `gtest_block_nested_sparse_structure`: the nested sparse
versus full case is accepted symmetrically, and a structurally different
nested column is still rejected. Verified A/B - the first test fails without
this change.
… comparison

The relaxed comparison of constant aggregate-state values (compare only the
serialized state, because compatible states are allowed to have different
aggregate function names) is only sound while the type of a value is fully
determined by the column type.

Under `Variant` it is not: `ColumnVariant::operator []` flattens a row to the
`Field` of its active alternative, and `DataTypeVariant::equals` allows a
`Variant` to hold several aggregate-state alternatives that are compatible by
state representation. Two constants on different alternatives with the same
serialized state would then compare equal, although the active alternative is a
part of the value and is observable, e.g. by `variantType`. `Dynamic` and `JSON`
hide the value type in the same way.

Compare the aggregate function names as well for constants of such types (field
by field, because `Field::operator ==` throws when the names differ).

Unit test `BlockStructure.ConstantVariantKeepsTheActiveAggregateStateAlternative`,
which fails without this change.
`typeCanHideTheValueType` used `IDataType::hasDynamicSubcolumns`, which is
also `true` for a plain `Map` (`DataTypeMap::hasDynamicSubcolumnsData`
returns `true` unconditionally, because of the `m.keys` and `m.values`
virtual subcolumns) even though the type of every value a `Map` holds is
fixed by the declared `Map(K, V)`.

As a result `strict_aggregate_states` was set for any constant containing
a `Map` with aggregate states (and for `Tuple` / `Nullable` / `Array`
wrappers around such a `Map`), so `haveCompatibleConstantValues` fell back
to the name-sensitive comparison of the aggregate-state leaves and
rejected constants that `DataTypeMap::equals` accepts.

Check only `Variant`, `Dynamic` and `JSON` (`Object`) — the types whose
value type is genuinely not fixed by the column type; nested occurrences
are still found by the existing `IDataType::forEachChild` recursion.

New unit test `gtest_block_map_aggregate_state_constant.cpp`:
`ConstantMapRelaxesTheNestedAggregateState` fails without this change,
and `ConstantMapKeepsComparingTheOtherValues` pins that the rest of the
constant is still compared strictly. A stateless test is not possible
here: `sameConstants` in `getLeastSuperColumn` materializes any constant
that contains an aggregate state, so planning never reaches the constant
comparison in `checkColumnStructure` for such a `Map`.
…e-state-header

Fix block structure check for aggregate-state columns nested in containers
@robot-ch-test-poll robot-ch-test-poll added pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only! do not test disable testing on pull request pr-bugfix Pull request with bugfix, not backported by default labels Aug 5, 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
robot-ch-test-poll4 merged commit c724007 into backport/26.5/111191 Aug 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

do not test disable testing on pull request pr-bugfix Pull request with bugfix, not backported by default pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only!

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants