Repository navigation
Conversation
`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
|
Workflow [PR], commit [21f4ed9] Summary: ❌
AI ReviewSummaryThis PR fixes analyzer/planner Findings💡 Nits
Tests
Final VerdictChanges 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 |
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.
Build profile diff (arm_release)Comparing commit 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.
|
Both addressed in
On the serialization: Worth noting 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. |
`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.
|
Fixed in Both steps now throw when On the test you asked for: I could not exercise the branch. The version comes from the peer's advertised Separately, |
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.
|
Both done in The new gtest builds On Writing the round-trip case immediately caught a fixture bug of mine rather than a code bug: positions index the deduplicated key list, so |
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.
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.
|
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. |
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.
|
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.
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.
|
Closing to rework and resubmit. |
Related: #117904
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
GROUP BY CUBEandGROUP BY ROLLUPlosing 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.CUBEtakes the power set of the list andROLLUPits prefixes, but the list was deduplicated before either was expanded, soCUBE(x, x)produced the two grouping sets ofCUBE(x)andROLLUP(x, x)those ofROLLUP(x). The same sets written out asGROUPING SETSwere unaffected, so the two spellings of one query returned different results.Description
CUBEandROLLUPare defined over theGROUP BYlist as written -CUBEovernexpressions has2^ngrouping sets andROLLUPhasn + 1. The key list is deduplicated by result name inanalyzeAggregationbefore the expansion, andCubeTransform/RollupTransformthen took2^nandn + 1from the deduplicated count, so a repeated expression quietly cost grouping sets:docs/reference/statements/select/group-by.mdxstates that the modifiers "can be represented viaGROUPING 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 BYlist, the key it refers to, and the transforms iterate over those positions:CubeTransformtakes 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 forCUBE(x, x)rather than 7.RollupTransformshortens 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_setstill numbers the subsets of the deduplicated keys, so__groupingForCube/__groupingForRollupand their serialized arguments are untouched. Several emitted sets can now share a number, andGROUPING(x)reportsxas 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
CubeandRollupsteps, 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:
CUBE/ROLLUPkeys will explicitly fail closed (throwingSUPPORT_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)overnumbers(2)returns 3 there against 7 with the analyzer, so05077carriesno-old-analyzerand the changelog entry says which path it applies to. I have left #117904 asRelatedrather thanClosesfor that reason - happy to thread the same positions throughExpressionAnalyzerin 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", withGROUP 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, as02705_grouping_keys_equal_keyscovers.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), theGROUPING SETScontrol,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, andWITH 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 - theGROUPING SETSspelling 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]