Skip to content

Expand CUBE and ROLLUP over the GROUP BY list as written - #118186

Closed
navneet83 wants to merge 18 commits into
ClickHouse:masterfrom
navneet83:fix-cube-rollup-duplicate-keys
Closed

navneet83 wants to merge 18 commits into
ClickHouse:masterfrom
navneet83:fix-cube-rollup-duplicate-keys

Conversation

@navneet83

@navneet83 navneet83 commented Sep 4, 2026 •

Copy link
Copy Markdown
Member

Related: #117904

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 into CHANGELOG.md):

Fixed GROUP BY CUBE and GROUP BY ROLLUP losing grouping sets when an expression is repeated in the list. Applies to the analyzer (enable_analyzer = 1, the default); the old analyzer still expands from the deduplicated key list. CUBE takes the power set of the list and ROLLUP its prefixes, but the list was deduplicated before either was expanded, so CUBE(x, x) produced the two grouping sets of CUBE(x) and ROLLUP(x, x) those of ROLLUP(x). The same sets written out as GROUPING SETS were unaffected, so the two spellings of one query returned different results.

Description

CUBE and ROLLUP are defined over the GROUP BY list as written - CUBE over n expressions has 2^n grouping sets and ROLLUP has n + 1. The key list is deduplicated by result name in analyzeAggregation before the expansion, and CubeTransform / RollupTransform then took 2^n and n + 1 from the deduplicated count, so a repeated expression quietly cost grouping sets:

SELECT number, count() AS c FROM numbers(2) GROUP BY CUBE(number, number) ORDER BY number;
-- 3 rows; the standard, and DuckDB, give 7

SELECT number, count() AS c FROM numbers(2) GROUP BY ROLLUP(number, number) ORDER BY number;
-- 3 rows; should be 5

SELECT number, count() AS c FROM numbers(2) GROUP BY GROUPING SETS ((number), (number)) ORDER BY number;
-- 4 rows, correct - the explicit spelling keeps the duplicate

docs/reference/statements/select/group-by.mdx states that the modifiers "can be represented via GROUPING SETS" and gives the expansion explicitly, so the two disagreeing is a documented equivalence that does not hold.

The deduplication has to stay - the key list becomes the aggregation key and the output header, and a repeated name would collide there. What was missing is that the shape of the expansion belongs to the list as written. The planner now also records, for each element of the GROUP BY list, the key it refers to, and the transforms iterate over those positions:

  • CubeTransform takes the power set of the positions and zeroes a key only when none of the positions it was written at is in the subset, so a repeated key survives until its last copy is dropped. Zeroing per position instead would blank the shared column on the first copy and give 5 rows for CUBE(x, x) rather than 7.
  • RollupTransform shortens the prefix one position at a time and drops a key only at the first position it was written at, because an earlier copy still holds it. Passing a later copy drops nothing and re-emits the same grouping set, which is what the list asks for.

__grouping_set still numbers the subsets of the deduplicated keys, so __groupingForCube / __groupingForRollup and their serialized arguments are untouched. Several emitted sets can now share a number, and GROUPING(x) reports x as present while any copy of it is - the same answer DuckDB gives.

This change introduces a new per-step serialization version (version 1) on the Cube and Rollup steps, rather than a global query plan version bump.

Key positions are serialized using this new step version. When interacting with an older peer that does not support it:

  • Plans that do not repeat a key are sent normally and execute with unchanged behavior.
  • Plans with repeated CUBE / ROLLUP keys will explicitly fail closed (throwing SUPPORT_IS_DISABLED). This prevents a mixed-version cluster from silently dropping the positions and computing incorrect grouping sets.

The old analyzer (enable_analyzer = 0) still deduplicates and is left alone, to keep this change to one path. CUBE(number, number) over numbers(2) returns 3 there against 7 with the analyzer, so 05077 carries no-old-analyzer and the changelog entry says which path it applies to. I have left #117904 as Related rather than Closes for that reason - happy to thread the same positions through ExpressionAnalyzer in a follow-up, or here if you would rather it land in one piece.

Standard conformance. PostgreSQL defines both over the list rather than a set - CUBE ( e1, e2, ... ) is "the given list and all of its possible subsets", ROLLUP "all prefixes of the list" - and documents that the resulting sets "might contain duplicates", with GROUP BY DISTINCT (optional SQL feature T434) as the way to remove them. That feature only makes sense if keeping duplicates is the default. DuckDB returns 7 and 5 for the queries above. Duplicates within one grouping set are a separate matter and are still collapsed, as 02705_grouping_keys_equal_keys covers.

Note this makes the collapsing implicit today something that has to be asked for, which is what #117911 proposes.

Tests

New: 05077_cube_rollup_repeated_keys - CUBE(n, n), ROLLUP(n, n), the GROUPING SETS control, GROUPING() over a repeated key, a key repeated among others (CUBE(a, b, a), ROLLUP(a, b, a)), the unrepeated cases, group_by_use_nulls = 1, and WITH TOTALS. Verified against a build of this branch and against the 26.9.1.714 release binary: every repeated-key case changes (3→7, 3→5, 7→15, 5→7) and both controls - the GROUPING SETS spelling and the unrepeated cases - are unchanged.

Three existing references change. All three are AST fuzzer regressions that happen to repeat a key and only ever asserted "does not crash"; the diffs are purely additional grouping sets, 2^(n-1) → 2^n. Two of them already carry the comment -- WITH CUBE (note that result is different with the analyzer (analyzer is correct including all combinations).

Ran locally, all passing: 00701_rollup, 00720_with_cube, 01883_with_grouping_sets, 02304_grouping_sets_with_rollup_cube, 02315_grouping_constant_folding, 02481_analyzer_optimize_grouping_sets_keys, 02705_grouping_keys_equal_keys, 03014_analyzer_groupby_fuzz_60317, 03015_analyzer_groupby_fuzz_60772, 03253_group_by_cube_too_many_keys, 03389_regexp_rewrite_nullable_group_by, 04001_logical_error_with_cube, 04046_rollup_cube_with_external_group_by, 05077_cube_rollup_repeated_keys.


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

`CUBE` takes the power set of the GROUP BY list and `ROLLUP` its prefixes, but the key
list is deduplicated by result name before either is expanded, and the number of grouping
sets was then computed from the distinct keys. A repeated expression silently lost sets:
`CUBE(number, number)` produced 3 rows over `numbers(2)` where the standard asks for 7,
and `ROLLUP(number, number)` 3 where it asks for 5. Written out by hand as
`GROUPING SETS ((number), (number))` the duplicate was kept, so the two spellings of the
same query disagreed - and the documented equivalence between them
(`docs/reference/statements/select/group-by.mdx`) did not hold.

The deduplication itself has to stay: the key list becomes the aggregation key and the
output header, where a repeated name would collide. What was missing is that the *shape*
of the expansion belongs to the list as written, not to the deduplicated keys. So the
planner now also records, for each element of the GROUP BY list, which key it refers to,
and the two transforms iterate over those positions:

  * `CubeTransform` takes the power set of the positions. A key is zeroed only when *none*
    of the positions it was written at is in the subset, so a repeated key survives until
    the last of its copies is dropped. Zeroing per position instead would blank the shared
    column on the first copy and yield 5 rows for `CUBE(x, x)` rather than 7.
  * `RollupTransform` shortens the prefix one position at a time and drops a key only at
    the *first* position it was written at, since an earlier copy still holds it. Passing a
    later copy drops nothing and re-emits the same grouping set, which is what the list
    asks for.

`__grouping_set` keeps numbering the subsets of the deduplicated keys, so the `GROUPING`
implementations and their serialized arguments are untouched; several emitted sets can now
share a number, and `GROUPING(x)` reports `x` as present while any copy of it is, which is
what DuckDB answers. `CubeTransform`'s key limit now counts the elements of the list, since
that is what it takes 2^n of.

The positions are added to the serialized `Cube` and `Rollup` steps behind a new query plan
serialization version. A peer too old to read them sees only the deduplicated key list and
so keeps the behaviour it had before, rather than misreading the payload.

Three existing references change, all of them AST fuzzer regressions that happen to repeat
a key and were only ever asserting "does not crash"; two carry a comment already calling
"all combinations" the correct answer. Their row counts go from 2^(n-1) to 2^n.

The old analyzer (`enable_analyzer = 0`) still deduplicates and is left alone.

Closes: ClickHouse#117904
@clickhouse-gh

clickhouse-gh Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [21f4ed9]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

This PR fixes analyzer/planner CUBE / ROLLUP expansion for repeated GROUP BY expressions by carrying written-list positions into CubeStep / RollupStep, versioning that payload for serialized plans, and extending both stateless and gtest coverage. I did not find a remaining code-level correctness or compatibility gap in the current head; the only issue left is that the PR description still describes the pre-fix mixed-version behavior.

Findings

💡 Nits

  • [src/Processors/QueryPlan/CubeStep.cpp:176] The code now fail-closes repeated-key CubeStep / RollupStep serialization toward older peers, but the PR description still says older peers quietly keep the previous behavior. Update that description text so the rollout contract matches the shipped code.
Tests
  • Not run locally in this review; assessment is based on code inspection and the added stateless / gtest coverage in the PR.
Final Verdict

Changes look correct at the current head. One non-blocking follow-up remains: update the PR description to match the final mixed-version behavior.

LLVM Coverage Report

⚠️ No coverage measurement for commit 21f4ed9: incomplete coverage measurement: 1 of 21 shard profiles are missing: LLVM_COVERAGE_FILE_it_8.profdata.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Sep 4, 2026
The new private helper declaration opened a `private:` section directly above the one the
members were already in, which `readability-redundant-access-specifiers` rejects in the
tidy build.
Both are AST fuzzer regressions whose GROUP BY list happens to repeat an expression, so
both gain the grouping sets the list asks for. `02802_with_cube_with_totals` repeats a key
under `WITH CUBE WITH TOTALS` and gains two rows; `02967_analyzer_fuzz` gains two.

Found by CI rather than locally: the run I did covered a hand-picked subset instead of the
184 tests that mention CUBE, ROLLUP or GROUPING SETS. Running all of them afterwards, and
against an unpatched build for comparison, `02802` is the only one of the four remaining
result diffs that this change causes - `03168_cld2_tsan`,
`04306_distributed_aggregation_correctness_guards` and `02967` fail the same way without
it on a single node, for want of remote shards.
Comment thread src/Planner/Planner.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing commit 21f4ed9a34befa99bc5918ebfbbadfbcf41102fe with master failed: RuntimeError: CI logs cluster query failed: SELECT count() AS c FROM binary_sizes W….

See the job log for details.

Master took query plan serialization versions 12 to 14 while this branch was open, so the
repeated-key positions on the Cube and Rollup steps become version 15.
Two things the review asked for.

The repeated-key positions are new payload on the serialized `Cube` and `Rollup` steps and
nothing exercised them, so `05078` runs the same repeated-key `CUBE`, `ROLLUP` and
`GROUPING` queries with and without `make_distributed_plan = 1,
distributed_plan_execute_locally = 1`. Losing the payload is not silent: it collapses the
grouping sets back onto the deduplicated keys, so the two counts stop agreeing - 13 and 5
for `CUBE(a, a)` over four distinct values.

`05077` gains `no-old-analyzer`. The fix is in the planner, and `enable_analyzer = 0` still
expands from the deduplicated key list: `CUBE(number, number)` over `numbers(2)` returns 3
there against 7 with the analyzer. Without the tag the test fails in the old-analyzer runs
rather than reporting that gap honestly.
@navneet83

Copy link
Copy Markdown
Member Author

Both addressed in 4e9b102, and you were right that the scope gap was going to bite rather than just read badly.

05077 now carries no-old-analyzer. Checking it properly: CUBE(number, number) over numbers(2) returns 3 with enable_analyzer = 0 against 7 with the analyzer, so without the tag the test would have failed in the old-analyzer runs. I have changed Closes: to Related: on #117904 and said in the changelog entry which path this applies to. Happy to thread the same positions through ExpressionAnalyzer — either as a follow-up or here, whichever you prefer.

On the serialization: 05078 runs the repeated-key CUBE, ROLLUP and GROUPING queries with and without make_distributed_plan = 1, distributed_plan_execute_locally = 1 and compares the counts. Dropping the payload is not silent — it collapses the sets back onto the deduplicated keys, so CUBE(a, a) over four distinct values gives 13 with the positions and 5 without, and the two arms stop agreeing. Both arms return 13 here.

Worth noting make_distributed_plan needs a server; under clickhouse local the plan comes back with Unknown query plan step: GatherReceive, so the test is no-fasttest.

Also merged master, which had taken query plan serialization versions 12 through 14 in the meantime, so the repeated-key positions are version 15 now.

Comment thread src/Processors/QueryPlan/CubeStep.cpp Resolved
`make_distributed_plan` rejects an aggregation that carries `max_rows_to_group_by`, and the
CI users profile sets it to 10G (`tests/config/users.d/limits.yaml`), so the new test threw
`SUPPORT_IS_DISABLED` in the runs that apply that profile while passing locally, where the
setting is at its default. Set it back to 0 for the test rather than drop the coverage.
The version gate made the payload optional, so a shard below the version simply read the
deduplicated key list - which is to say it answered a repeated-key CUBE or ROLLUP with
exactly the grouping sets this change corrects. Calling that "the behaviour it had before"
was the wrong way round: the behaviour it had before is the bug, and on a mixed-version
cluster the fix would disappear without a word.

Throw instead, the way the step already refuses a peer too old to know it at all. The check
is on `key_positions` being non-empty, so it fires only for a query whose GROUP BY list
actually repeats a key; every other plan still ships to an older peer unchanged.

The branch itself is not exercised locally: the version comes from the peer's advertised
`server_query_plan_serialization_version`, and there is no client setting to lower it, so a
single node cannot reach it. Verified instead that the normal path is unchanged - both cube
tests pass and the repeated-key distributed query still returns 13.
@navneet83

Copy link
Copy Markdown
Member Author

Fixed in a249217. You are right, and my framing of it was backwards — I wrote in the commit message that an older peer "keeps the behaviour it had before", but the behaviour it had before is the bug, so on a rolling upgrade the fix would have vanished silently.

Both steps now throw when key_positions is non-empty and the peer is below DBMS_MIN_QUERY_PLAN_SERIALIZATION_VERSION_WITH_REPEATED_GROUPING_KEYS, the same way each already refuses a peer too old to know the step at all. Gating on the payload being non-empty rather than on the version alone means only a query whose GROUP BY list actually repeats a key is affected; everything else still ships to an older peer as before.

On the test you asked for: I could not exercise the branch. The version comes from the peer's advertised server_query_plan_serialization_version and there is no client-side setting to lower it — serialize_query_plan_version does not exist, which I found out by trying it — so a single node cannot reach that path. Verified instead that the normal path is unchanged: both cube tests pass and the repeated-key distributed query still returns 13 with and without the plan being serialized. If there is an existing pattern for forcing a lower plan-serialization version in a test, point me at it and I will add the case.

Separately, 05078 was failing in the runs that apply tests/config/users.d/limits.yaml: make_distributed_plan rejects an aggregation carrying max_rows_to_group_by, which that profile sets to 10G. Pinned it back to 0 in the test (5367748).

Two gaps in the coverage, both pointed out in review.

The sender-side gate had no test at all - I had said it was unreachable without a
multi-node setup, which was wrong: `gtest_array_join_step_serialization_roundtrip` already
drives `serialize`/`deserialize` through the production path at a chosen `ctx.version`. The
new gtest builds `CubeStep` and `RollupStep` over `(a, b, a)` and asserts three things: the
positions survive a round trip byte-for-byte, serializing them below the minimum version
throws, and a step carrying no repeated keys still serializes to that same older version.
The last one is the point of gating on the payload rather than the version.

`05078` only exercised `key_positions = [0, 0]`, which proves a repetition survives but not
that the order does - a serializer that sorted or deduplicated the positions would have
passed it. It now runs `ROLLUP(a, b, a)` and `CUBE(a, b, a)` with `GROUPING(a, b)`, whose
positions are `[0, 1, 0]`, and compares rows rather than counts, since the grouping sets
differ in which columns they keep rather than only in how many rows they produce.

Writing the round-trip case immediately caught a fixture of my own: positions index the
deduplicated key list, so `[0, 1, 0]` needs two keys, and building the step with one made
the deserializer reject the stream as out of range. The guard was right and the test was
wrong, which is the direction I would rather find out in.
@navneet83

Copy link
Copy Markdown
Member Author

Both done in a600389, and thanks for the pointer — I was wrong that the gate needed a multi-node setup. gtest_array_join_step_serialization_roundtrip drives serialize/deserialize through the production path at a chosen ctx.version, which is all it takes.

The new gtest builds CubeStep and RollupStep over (a, b, a) and asserts three things: the positions survive a round trip byte-for-byte, serializing them below the minimum version throws, and a step carrying no repeated keys still serializes to that same older version — the last being the point of gating on the payload rather than on the version alone.

On 05078: you were right that [0, 0] proves only that a repetition survives. It now runs ROLLUP(a, b, a) and CUBE(a, b, a) with GROUPING(a, b), positions [0, 1, 0], comparing rows rather than counts.

Writing the round-trip case immediately caught a fixture bug of mine rather than a code bug: positions index the deduplicated key list, so [0, 1, 0] needs two keys, and building the step with one made the deserializer reject the stream as out of range. The range check was doing its job.

Master took query plan serialization version 15 for the LimitRange step while this branch
was claiming it for the repeated-key positions, so those move to version 16.
Comment thread src/Processors/QueryPlan/CubeStep.cpp Resolved
The deserializers validated each position against `keys.size()` and nothing else, so a
payload like `keys = [a, b]` with `positions = [0]` was accepted: key `b` ends up with an
empty position mask, the transforms execute an impossible state, and `__grouping_set` and
`GROUPING()` come out wrong instead of the stream being rejected.

The full invariant is stronger than per-entry range: the positions say where each element
of the GROUP BY list refers into the deduplicated key list, and every key got into that
list from the GROUP BY list, so every key is referenced at least once. A payload that
skips one is not a plan the sender could have built. Both deserializers now count the
distinct keys referenced while reading and throw INCORRECT_DATA when any is missing; an
empty vector stays legal, since it means the trivial one-to-one mapping.

The new test serializes exactly that impossible payload - the constructor does not
validate, which is what makes it constructible - and asserts both deserializers refuse
it. Verified in both directions: without this change the test fails because the stream is
accepted, with it all four serialization tests and both stateless tests pass.
@navneet83

Copy link
Copy Markdown
Member Author

Fixed in c68577c. Both deserializers now verify that positions references every key at least once, throwing INCORRECT_DATA if it doesn't. (Empty lists are still valid). I also added a test that drops a key from the payload to make sure it gets rejected properly.

Comment thread src/Processors/QueryPlan/RollupStep.cpp Resolved
The previous commit rejected payloads that skip a key; it still accepted orderings the
sender cannot produce, such as `keys = [a, b]` with `positions = [1, 0]`. The planner
assigns a new key index to each expression the first time it meets it while walking the
GROUP BY list, so in any real payload the first appearances arrive as 0, 1, 2, ... That
order carries semantics for Rollup: `__groupingForRollup` assumes the drop order is the
reverse of the key order, which only holds under first-occurrence ordering, so an
out-of-order payload executes with wrong `GROUPING()` bits instead of failing.

Rather than add a third condition, state the whole invariant once: a new index must equal
the count of distinct indexes seen so far, and at the end every key must have appeared.
Together these characterise the valid payloads exactly - any sequence passing both is
realisable from some GROUP BY list - so there is no further payload of this kind to
reject, and the bitmap from the previous commit becomes redundant and is removed.

The new test serializes `[1, 0]`, which covers every key so only the ordering rule can
reject it, and asserts both deserializers throw. Without the fix it fails because the
stream is accepted; with it, all five serialization tests and both stateless tests pass,
and the previous rounds' commitments hold: the empty payload stays legal, `[0, 1, 0]`
still round-trips byte for byte, `[0, 0]` is still rejected for coverage, and the
below-minimum-version gate is untouched.
The updated reference only holds where the fix applies. The second query's GROUP BY
constants fold to the same key, so the written list repeats it and the expansion gains
two grouping sets - but only in the planner. The old-analyzer CI configuration
(enable_analyzer = 0) still deduplicates before expanding and produced two fewer rows,
reproducibly failing that configuration alone. Same scoping decision as the
no-old-analyzer tag on 05077_cube_rollup_repeated_keys; pinning the setting instead of
tagging keeps the original ClickHouse#42691 queries running in every configuration.
@navneet83

Copy link
Copy Markdown
Member Author

Merged master. Pinned 02802_with_cube_with_totals to enable_analyzer = 1 (52270b1) since the GROUP BY constants fold to the same key. The updated reference now strictly requires the fix, just like the no-old-analyzer tags on the new tests.

Master claimed query-plan serialization versions 16 (JoinStepLogical row-estimate
decisions) and 17 (always_read_till_end on LimitByStep) after the previous merge, so
the repeated-grouping-keys format moves from 16 to 18. Every gate reads
DBMS_MIN_QUERY_PLAN_SERIALIZATION_VERSION_WITH_REPEATED_GROUPING_KEYS, and the tests
derive their below-minimum version from the same constant, so the renumbering is
confined to ProtocolDefines.h.
@clickhouse-gh clickhouse-gh Bot added the comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). label Sep 13, 2026
@clickhouse-gh clickhouse-gh Bot removed the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Sep 13, 2026
Master claimed query-plan serialization version 18 (Filling step and WITH FILL bounds)
so the repeated-grouping-keys format moves from 18 to 19. As before, every gate and both
below-minimum tests read DBMS_MIN_QUERY_PLAN_SERIALIZATION_VERSION_WITH_REPEATED_GROUPING_KEYS,
so the renumbering is confined to ProtocolDefines.h.
Master added a per-step serialization version to query plan steps (each step owns
a version on the wire, readers refuse an unknown one, and the global plan version
moves only once per release). It took global query-plan serialization version 19
for that mechanism - the same number this branch had taken for the repeated-key
positions - so the two collide, and resolving the collision by renumbering to a
global 20 would keep racing the next feature for the next number.

Resolve it by moving onto the new mechanism instead. `CubeStep` and `RollupStep`
now register step serialization version 1, which appends the GROUP BY positions,
and gate on `ctx.step_version` rather than the global version:

  - serialize writes the positions when step_version >= 1, and still fails closed
    (a repeated-key CUBE/ROLLUP toward a peer at step_version 0 would expand the
    wrong grouping sets) - the refusal is now keyed on the step version, not the
    global one;
  - deserialize reads them when step_version >= 1; an unknown step version is
    already refused by the registry before deserialize runs;
  - the global DBMS_QUERY_PLAN_SERIALIZATION_VERSION bump and the
    DBMS_MIN_QUERY_PLAN_SERIALIZATION_VERSION_WITH_REPEATED_GROUPING_KEYS constant
    are both gone.

The gtests drive `step_version` directly: the round-trip and payload-validation
cases at version 1, and the two below-version cases (repeated keys refused, no
repeated keys still shipped) at version 0.
Comment thread src/Processors/QueryPlan/CubeStep.cpp Resolved
@navneet83

Copy link
Copy Markdown
Member Author

Closing to rework and resubmit.

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-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant