Skip to content

Check the aggregates of deserialized query plan steps against their input - #131789

Merged
alexey-milovidov merged 15 commits into
masterfrom
fix-aggregating-step-argument-types
Nov 20, 2026
Merged

alexey-milovidov merged 15 commits into
masterfrom
fix-aggregating-step-argument-types

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Nov 15, 2026 •

Copy link
Copy Markdown
Member

The aggregate functions of a deserialized Aggregating step are resolved from the argument types written in the plan, but the Aggregator executes them on the input columns found by name. A plan with other types (or without the column) made a function interpret a column of another type. Likewise, the steps that merge states (Aggregating with only_merge, MergingAggregated, Rollup, Cube) merged the input columns with the functions from the plan.

Such plans are now refused with INCORRECT_DATA. checkDeserializedAggregateArguments requires the arguments to be in the input with the types the function is resolved for (ignoring LowCardinality, which both AggregateFunctionFactory and the Aggregator remove). The merging steps read the keys and then the states by position, so checkDeserializedMergedAggregatesLayout requires their input to start with the keys and then the states in the order of the plan, with distinct names and states of the same representation (for MergingAggregated with grouping sets, per set, after the reordering done by MergingAggregatedTransform). TotalsHaving finalizes the states it finds by name, so checkDeserializedFinalizedAggregates requires each of its aggregates to name an input column holding a state of the same representation.

Rollup and Cube always finalize and address the whole input with a mask for the keys and the states, and they finalize a single input chunk with the functions of its own columns. So checkDeserializedGroupByModifierInput requires final, an input of exactly the keys and the states, and states that finalize to the result types of the plan. The merge-only Aggregating step also requires an exact layout, because AggregatingInOrderTransform uses the same mask. The ordinary Aggregating step requires distinct key and aggregate names, because the finalization finds the states by name.

States of functions that share a state representation (like quantile and quantiles) have equal types, so a Union can pass a column of one under the header of the other, and the finalization used the function of the column. finalizeChunk (used by Rollup, Cube, TotalsHaving and the in-order aggregation) now checks that every state finalizes to the type of the expected header, and throws ILLEGAL_COLUMN otherwise. A deserialized MergingAggregated step with grouping sets and distributed_aggregation_memory_efficient (never produced by the planners) is refused instead of throwing a LOGICAL_ERROR.

Changelog category (leave one):

  • Critical Bug Fix (crash, data loss, RBAC)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fix type confusion when deserializing a query plan whose aggregate functions do not match the types of their input columns. Now such a plan is rejected with INCORRECT_DATA.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.12.1.19-master (included in 26.12 and later)
  • Backported to: 26.11.1.2916, 26.10.11.12, 26.9.37.4, 26.8.42.21, 26.3.67.32

…nput

The aggregate functions of a deserialized `Aggregating` step are resolved from the argument types written
in the plan, but the `Aggregator` executes them on the input columns found by name. A plan with other
types (or a missing column) made a function interpret a column of another type. Likewise, the steps that
merge states (`Aggregating` with `only_merge`, `MergingAggregated`, `Rollup`, `Cube`) merged the input
columns with the functions from the plan.

`checkDeserializedAggregatesMatchHeader` refuses such plans with `INCORRECT_DATA`: arguments must be in
the input with the types the function is resolved for (`LowCardinality` aside, which the factory and the
`Aggregator` both remove), and merged columns must be states of the same representation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov alexey-milovidov self-assigned this Nov 15, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f50f0b3]

Summary: ✅


AI Review

Summary

Validates aggregate argument types and merge layouts in deserialized query plans, and checks runtime aggregate finalization against the expected result types. The earlier findings are addressed in the current code; no additional actionable findings remain. The focused 05791_aggregating_step_argument_types regression passed in Fast test at f50f0b3e18e833601e2adf422c90e2c855591aab.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! labels Nov 15, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). label Nov 15, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f50f0b3e1 with master 49ab4c4d9 (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

14 object files changed (+142.48 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/AggregateDescription.cpp.o 134.00 KiB 201.52 KiB +67.52 KiB (+50.39%)
src/CMakeFiles/dbms.dir/Processors/Transforms/finalizeChunk.cpp.o 27.29 KiB 55.34 KiB +28.06 KiB (+102.83%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/MergingAggregatedStep.cpp.o 347.23 KiB 371.91 KiB +24.68 KiB (+7.11%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/AggregatingStep.cpp.o 1.10 MiB 1.12 MiB +20.75 KiB (+1.84%)

716 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.

Compile time of recompiled translation units

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

Job report

alexey-milovidov and others added 2 commits November 16, 2026 17:40
Address review: the `Aggregator` looks up the types of the keys and the
states by name, but merges the columns by position (`makeAggregateColumnsData`
reads `columns[keys_size + i]`). A plan whose input had the right states in
another order, or that repeated an aggregate, passed the by-name check and
merged a state with the function of another one.

Now `checkDeserializedMergedAggregatesLayout` requires the input of the
merging steps (`Aggregating` with `only_merge`, `MergingAggregated`, `Rollup`,
`Cube`) to start with the keys and then the states, in the order of the plan,
with distinct names. For `MergingAggregated` with grouping sets, the layout is
checked per set as `MergingAggregatedTransform` reorders it. The merge-only
`Aggregating` with grouping sets, which the planner never produces, is refused.

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

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=131789&sha=8475b70149712863b7f4d424e1b30b336415a0f7&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20sequential%2C%201%2F2%29 (02385_profile_events_overflow: OverflowAny grew by 3 instead of 1 with max_threads 3 and group_by_two_level_threshold 1; it failed the same way on 2026-11-15 in unrelated #120438) and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. Reproduced on master (fdc4389), also with max_threads=1: with group_by_two_level_threshold_bytes=1, max_bytes_before_external_group_by=2880163 the query has ExternalAggregationWritePart = 3, AggregationSharedKeptKeysSpillReseeds = 2 and OverflowAny grows by 3; without the spill it grows by 1.

The extra two come from the post-spill re-seed that #126249 enabled for max_rows_to_group_by with group_by_overflow_mode = 'any': reseedKeptKeysAfterSpill re-inserts the spilled keys through mergeOnBlock with a fresh no_more_keys = false, so checkLimits counts the overflow again after every re-seed. No fix is in progress yet; I'll follow up here with a PR.

`Aggregator::Params::getHeader` builds the header of the merge-only steps from the whole input,
so a later column with the name of a key or a state would be there, but not in the merged chunks.
Addresses the review comment in #131789.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Interpreters/AggregateDescription.h Resolved
@groeneai

Copy link
Copy Markdown
Collaborator

The fix is in #132141: merges that only put the kept keys back into the table (the re-seed after a spill, and the kept-keys rebuild) no longer count as a new max_rows_to_group_by overflow, so OverflowAny grows by 1 again. 05401_external_aggregation_overflow_any_keeps_kept_keys gets a check for it (50/50 fail on master, 50/50 pass with the fix), and 02385 with the CI settings forced passes 20/20.

…s input

Address review: `TotalsHavingStep::deserialize` accepted `AggregateDescriptions`
without checking them against the input header, and `TotalsHavingTransform`
finalizes the columns named by them, assuming they are states. Now every
aggregate must name an input column holding a state of the same
representation (`checkDeserializedFinalizedAggregates`), otherwise the plan is
refused with `INCORRECT_DATA`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…d` step

With grouping sets, `MergingAggregatedTransform` reads `__grouping_set` as `ColumnUInt64` and the output
header takes its type from the input. A forged plan with another type or several such columns was accepted
and then hit an exception in `MergingAggregatedTransform::addChunk`, or produced chunks that disagreed with
the output header. Require exactly one `UInt64` `__grouping_set` column during deserialization.

#131789 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ated` step without grouping sets

`appendGroupingIfNeeded` copies a `__grouping_set` column of the input into the output header, but the merge without grouping sets does not produce it, so the chunks would not match the header.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Processors/QueryPlan/CubeStep.cpp Resolved
alexey-milovidov and others added 3 commits November 17, 2026 09:01
… and distinct aggregate names

- `Rollup` and `Cube` always finalize their states and address the whole input with a mask built
  for the keys and the states only, and finalize a single input chunk with the functions of its
  columns. `checkDeserializedGroupByModifierInput` now requires `final`, an input of exactly the keys
  and the states, and states whose functions finalize to the result types of the plan (functions
  with the same state representation, like `quantile` and `quantiles`, may finalize differently).
- The merge-only `Aggregating` step requires an input of exactly the keys and the states, because
  `AggregatingInOrderTransform` addresses the whole input with the mask too.
- The ordinary `Aggregating` step requires distinct key and aggregate names, because the
  finalization finds the states by name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits November 17, 2026 10:04
… sort descriptions

The merge-only `Aggregating` step (also in order) finalizes the states with the functions of its input,
while its header takes the result types from the plan, so require them to agree, as for `Rollup` and `Cube`.

`AggregatingInOrderTransform` takes the first columns of `group_by_sort_description` as the ones the input is
sorted by and compares the key columns at their positions, so require `sort_description_for_merging` to be
a prefix of `group_by_sort_description`, and the latter to name only keys.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`DataTypeAggregateFunction::equals` considers the states of functions with the same
state representation (like `quantile` and `quantiles`) equal, so a `Union` can pass
a column of `quantile` states under a header of `quantiles` states. `finalizeChunk`
finalized it with the column's own function, producing `Float64` under an advertised
`Array(Float64)`. The header checks of the deserialized steps cannot see this, so
`finalizeChunk` now takes the expected finalized header and throws `ILLEGAL_COLUMN`
if a state finalizes to another type (as `checkAggregateStateCanBeFinalized` does for
`finalizeAggregation`). This covers `Rollup`, `Cube`, `TotalsHaving` and the in-order
aggregation.

The test now also reads the packets after the plan is built, so it sees the exceptions
of the execution. That exposed a `LOGICAL_ERROR` for a deserialized `MergingAggregated`
step with grouping sets and `distributed_aggregation_memory_efficient` (which is on by
default in the step settings): the planners never combine them, so such a plan is now
refused with `INCORRECT_DATA`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits November 19, 2026 19:33
…d grouping-sets merge

A deserialized `MergingAggregated` step with grouping sets now refuses an input in which a key occurs more
than once (the output header and `makeCreatingMissingKeysForGroupingSetDAG` take keys by name), and the
memory-bound merge with grouping sets, which threw a `LOGICAL_ERROR` in `transformPipeline`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 20, 2026
Merged via the queue into master with commit 4c8deb4 Nov 20, 2026
196 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-aggregating-step-argument-types branch November 20, 2026 09:24
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 20, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 20, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 20, 2026
Backport #131789 to 26.11: Check the aggregates of deserialized query plan steps against their input
alexey-milovidov added a commit that referenced this pull request Nov 20, 2026
Adapt the backport of #131789 to 26.3:
- 26.3 has no serialization of `Rollup` and `Cube` steps, and no merge-only
  or in-order `Aggregating` step in a serialized plan, so their checks
  (`checkDeserializedGroupByModifierInput`, `checkDeserializedMergeOnlyInput`,
  the sort description checks) are dropped. The `finalizeChunk` check in the
  `Rollup` and `Cube` transforms is kept.
- `deserializeAggregateDescriptions` has no `max_type_complexity` on 26.3.
- `AggregateDescription.h` forward-declares `Block`.
- The test uses query plan serialization version 0 and `ReadFromTable` leaves
  reading from tables created by the test; the `Rollup`, `Cube`, merge-only
  and in-order cases are removed. The byte layout was checked against the
  `clickhouse/clickhouse-server:26.3` image: the well-formed plans are
  accepted there, and the broken ones hit `LOGICAL_ERROR` and other errors
  without the fix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robot-ch-test-poll added a commit that referenced this pull request Nov 20, 2026
Cherry pick #131789 to 26.3: Check the aggregates of deserialized query plan steps against their input
robot-clickhouse added a commit that referenced this pull request Nov 20, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 20, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 20, 2026
Backport #131789 to 26.8: Check the aggregates of deserialized query plan steps against their input
alexey-milovidov added a commit that referenced this pull request Nov 20, 2026
Backport #131789 to 26.3: Check the aggregates of deserialized query plan steps against their input
clickhouse-gh Bot added a commit that referenced this pull request Nov 22, 2026
Backport #131789 to 26.9: Check the aggregates of deserialized query plan steps against their input
clickhouse-gh Bot added a commit that referenced this pull request Nov 23, 2026
Backport #131789 to 26.10: Check the aggregates of deserialized query plan steps against their input
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! 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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants