Repository navigation
Fix optimize_injective_functions_in_group_by changing results with GROUPING SETS and WITH TOTALS - #110721
Conversation
…ITH TOTALS OptimizeGroupByInjectiveFunctionsPass rewrites an injective f(g) to g in the GROUP BY key list and recomputes f(g) in the output projection. This relies on every output row still carrying g, which does not hold when a grouping modifier emits rows where the key is absent from the aggregated set: those rows output the key column default. For such a row the projection then computes f(defaultOf(g)) instead of defaultOf(typeOf(f(g))), changing the result even though optimize_injective_functions_in_group_by is documented as result-preserving. The pass already bails on CUBE/ROLLUP and group_by_use_nulls for the same reason. Extend that to GROUPING SETS (non-member set rows) and WITH TOTALS (the totals row). Closes: ClickHouse#110715 Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-3:20260716-160700 |
|
cc @vdimir @novikd — could you review this? OptimizeGroupByInjectiveFunctionsPass rewrites injective f(g) to g in the GROUP BY keys and recomputes f(g) in the output; this is wrong for rows where the key is absent from the aggregated set (GROUPING SETS non-member sets, the WITH TOTALS row), which output the key default. The pass already bails on CUBE/ROLLUP and group_by_use_nulls for the same reason; this extends the guard to GROUPING SETS and WITH TOTALS. |
|
Workflow [PR], commit [082731b] Summary: ✅
AI ReviewSummaryThis PR closes the result-changing Final VerdictStatus: ✅ Approve |
The WITH TOTALS EXPLAIN QUERY TREE in 02969 asserted the (incorrect)
unwrapping of the injective function in the totals row. With the pass now
skipping WITH TOTALS, the totals-key column is no longer unwrapped and the
totals-row value is the String default ('') instead of toString(0)='0'.
Plain GROUP BY and GROUP BY ALL sections are unchanged (optimization still
fires there).
Co-Authored-By: Claude Opus 4.8 <[email protected]>
OptimizeGroupByFunctionKeysPass drops a GROUP BY key that is a function of other keys and lets the output projection recompute it. Like the sibling OptimizeGroupByInjectiveFunctionsPass, this is only valid when every output row still carries those other keys. For WITH TOTALS and GROUPING SETS the non-member/totals rows output the keys as their column defaults, so the dropped key gets recomputed from those defaults (e.g. toString(number) from number = 0 yields '0' instead of the String default ''), changing results. Extend the CUBE/ROLLUP guard to GROUPING SETS and WITH TOTALS, mirroring the injective-functions pass. Add regression cases for optimize_group_by_function_keys to 04546. See ClickHouse#110715. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Good catch. Fixed in 14c68bc. `OptimizeGroupByFunctionKeysPass` relied on the same "every output row still carries the key" contract and only guarded CUBE/ROLLUP. Extended its early-return guard to `isGroupByWithGroupingSets()` and `isGroupByWithTotals()`, mirroring the injective-functions pass. Confirmed your reproducer on the pre-fix binary returns `v = '0'` in the totals row and `v = ''` after the guard. Added regression cases (WITH TOTALS + GROUPING SETS, plus a plain-GROUP BY case proving the optimization still applies) for `optimize_group_by_function_keys` to `04546_injective_functions_in_group_by_modifiers`. |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-1:20260716-190800 |
The new GROUPING SETS / WITH TOTALS guard in OptimizeGroupByFunctionKeysPass correctly stops rewriting function keys under grouping sets, so the query-tree in 02481_analyzer_optimize_grouping_sets_keys changes. Regenerated from the fixed binary (Build ID f40246858). Co-Authored-By: Claude Opus 4.8 <[email protected]>
optimizeGroupBy and optimizeGroupByFunctionKeys in TreeOptimizer.cpp (enable_analyzer=0) had no group_by_with_totals / grouping_sets bail-out, so the totals/non-member rows recomputed a dropped function key from other keys' defaults (toString(0)='0' instead of the String default ''). Mirror the analyzer-pass guard and extend 04546 with enable_analyzer=0 cases. Co-Authored-By: Claude Opus 4.8 <[email protected]>
GROUP BY GROUPING SETS ((v, number), (number)) with ORDER BY number, v is not a total order: for each number the member-set row (real v) and the non-member-set row (v = default '') tie on both number and v, so they interleaved nondeterministically between runs. Add GROUPING(v) as a final ORDER BY key so the member-set row is always emitted before the non-member row, yielding a stable result. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Covers the group_by_with_grouping_sets bail-out in the legacy TreeOptimizer::optimizeGroupBy (injective path), mirroring the top-of-file query-tree GROUPING SETS reproducer at enable_analyzer=0. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Single-set GROUPING SETS ((...)) never produces a non-member row: it is collapsed to an ordinary GROUP BY by GroupingFunctionsResolvePass before OptimizeGroupByFunctionKeysPass / OptimizeGroupByInjectiveFunctionsPass run, so every output row still carries the key and the rewrite is safe. Both passes must still fire for it, not be blocked by the GROUPING SETS guard added for the multi-set case in ClickHouse#110715. Add two single-set queries proving the redundant function-of-key is removed and the injective function is unwrapped. Co-Authored-By: Claude Opus 4.8 <[email protected]>
optimize_aggregators_of_group_by_keys eliminates min/max/any of a GROUP BY key to the bare key. On the legacy AST path (enable_analyzer=0) the call site skipped this only for WITH TOTALS / ROLLUP / CUBE, not GROUPING SETS, and getGroupByKeysInfo unions all set members. So for GROUP BY GROUPING SETS ((a,b),(a)), max(b) was dropped to bare b and the (a)-set rows emitted b's default 0 instead of the real aggregate. Add the group_by_with_grouping_sets guard, matching the query-tree pass and the sibling optimizeGroupBy / optimizeGroupByFunctionKeys guards. Add an enable_analyzer=0 regression. Co-Authored-By: Claude Opus 4.8 <[email protected]>
The legacy-optimizer GROUP BY modifier guard (this PR) stops optimizeGroupBy from eliminating the constant array key under WITH ROLLUP. Preserving the heterogeneous array literal key makes the old analyzer validate it as a Variant/Dynamic GROUP BY key and raise ILLEGAL_COLUMN (code 44) before the function-argument type error. With allow_suspicious_types_in_group_by=1 the same query still reaches ILLEGAL_TYPE_OF_ARGUMENT (43), confirming 44 is the correct, more precise error, not a regression. Accept it alongside 43/386. Co-Authored-By: Claude Opus 4.8 <[email protected]>
CI finish ledger - 0d80e27Every failure below has an owner. Only
CI fully finished on this head: Config Workflow, Finish Workflow, Mergeable Check, CH Inc sync all green; zero check-level FAIL/ERROR rows. The prior PR-caused Fast-test / 00390 failures on earlier heads are resolved on 0d80e27. Session id: cron:our-pr-ci-monitor:20260717-193000 |
|
This is ok, but can we keep the optimization while fixing the values for rolled-up keys at the same time? |
|
Will do - sending a separate follow-up PR that keeps the optimization and substitutes the correct type-defaults for the rolled-up / absent-key output rows (non-member GROUPING SETS rows, the WITH TOTALS row, CUBE/ROLLUP levels) instead of disabling it, across both analyzer passes and the legacy TreeOptimizer path. This PR stays as-is. |
|
@alexey-milovidov For
Proposal: a follow-up PR re-enabling the optimization for |
Can we use ChunkInfo for that? |
|
Yes, ChunkInfo works. Verified:
One mechanic: the projection is an So the full scope is feasible and I will build it in the follow-up PR, keeping the optimization enabled: |
|
Follow-up PR opened: #110953. It keeps For GROUPING SETS / CUBE / ROLLUP the correction is a grouping conditional over Scope is the injective pass only; the function-keys pass stays disabled under the modifiers (removing a key changes the CUBE/ROLLUP lattice), as this PR does. |
…y path Address review: the new `optimize_aggregators_of_group_by_keys` guard in `TreeOptimizer` also disabled the optimization for single-set `GROUPING SETS ((...))`, although `ExpressionAnalyzer` classifies that form as `GroupByKind::ORDINARY` (it is executed as a plain `GROUP BY` and emits no rows with a key absent from the aggregated set), so the min/max/any elimination is safe there. Narrow the guard to the multi-set form and add an `enable_analyzer = 0` regression proving both the unchanged result and that the `max(number) -> number` rewrite still fires for the single-set form. Co-Authored-By: Claude Fable 5 <[email protected]>
| (number / 2, number / 3) | ||
| ); | ||
|
|
||
| -- A single-set GROUPING SETS ((...)) never produces a non-member row: it is collapsed to an |
There was a problem hiding this comment.
GROUPING SETS ((...)) is only collapsed to an ordinary GROUP BY when group_by_use_nulls = 0 (GroupingFunctionsResolvePass.cpp:182-188). With group_by_use_nulls = 1, the query still stays a grouping-sets query, resolveGroupByNode registers the key in nullable_group_by_keys, and the projection is re-resolved after GROUP BY to that Nullable key shape (QueryAnalyzer.cpp:3965-4016). AggregateFunctionOfGroupByKeysPass still rewrites max/min/any/anyLast to the bare key for grouping sets (AggregateFunctionOfGroupByKeysPass.cpp:38-86), so a query like SELECT toTypeName(max(number)) FROM numbers(1) GROUP BY GROUPING SETS ((number)) SETTINGS group_by_use_nulls = 1 can change from UInt64 to Nullable(UInt64).
So the new “single-set form is safe” proof is incomplete: it holds for group_by_use_nulls = 0, but not for the nullable-key path. This needs either a group_by_use_nulls bail-out in AggregateFunctionOfGroupByKeysPass for grouping sets, or a focused regression that proves max(key) keeps its original type under GROUPING SETS ((key)) SETTINGS group_by_use_nulls = 1.
There was a problem hiding this comment.
Verified on the current head (5cc0338): this type change is pre-existing master behavior, not something this PR introduces or that alexey's single-set narrowing affects.
AggregateFunctionOfGroupByKeysPass.cppis byte-identical to master here (git diff master HEAD= 0 lines); it was last touched in Jan 2026. This PR does not modify it, and alexey's 5cc0338 only narrowed the legacyTreeOptimizerguard (enable_analyzer=0), while your repro is the analyzer path (enable_analyzer=1).- The flip reproduces with this PR's own passes disabled (
optimize_injective_functions_in_group_by=0, optimize_group_by_function_keys=0), so those passes are not involved. - It is also arguably not a correctness bug: under
group_by_use_nulls=1the grouping keynumberis itselfNullable(UInt64)(SELECT toTypeName(number) ... GROUP BY GROUPING SETS ((number)) SETTINGS group_by_use_nulls=1), so rewritingmax(number)to the bare key inherits that nullable type. Values are identical with the optimization on and off (0,1,2); only the declared type differs.
So there is no gap in the single-set narrowing on this PR's paths. Any change to AggregateFunctionOfGroupByKeysPass's group_by_use_nulls handling would be an independent, out-of-scope change to stock master code. Deferring to alexey, who is actively iterating on this PR.
There was a problem hiding this comment.
Confirmed and out of scope for this PR. Reproduced on this head with clickhouse local:
SELECT toTypeName(max(number)) FROM numbers(1) GROUP BY GROUPING SETS ((number)) SETTINGS group_by_use_nulls=1, optimize_aggregators_of_group_by_keys=0 -- UInt64
... optimize_aggregators_of_group_by_keys=1 -- Nullable(UInt64)
SELECT toTypeName(number) FROM numbers(1) GROUP BY GROUPING SETS ((number)) SETTINGS group_by_use_nulls=1 -- Nullable(UInt64)
The values are identical with the optimization on and off (0,1,2); only the declared type differs, and it differs because the grouping key number is itself Nullable(UInt64) under group_by_use_nulls=1, so rewriting max(number) to the bare key inherits that type. AggregateFunctionOfGroupByKeysPass is not modified by this PR (byte-identical to master), and the flip also reproduces with this PR's own passes (optimize_injective_functions_in_group_by, optimize_group_by_function_keys) disabled. So this is pre-existing master behavior, not a regression introduced here, and it does not block this PR. If the Nullable-key type under group_by_use_nulls=1 is deemed worth changing, it should be a separate change to AggregateFunctionOfGroupByKeysPass.
CI finish ledger - 5cc0338Every failed check below has an owner. Only CI is fully finished on this head (Finish Workflow SUCCESS 2026-07-19 21:40:29Z; Config Workflow + CH Inc sync green; 0 queued/in-progress; >20 min buffer). No PR-caused failure remains on this head.
Session id: cron:clickhouse-maint-slot-8:20260719-223800 |
…ions-group-by-modifiers
CI finish ledger - 24535c9CI is fully finished on this head (Finish Workflow SUCCESS, CH Inc sync green, 0 queued/in-progress, >20 min buffer). No PR-caused failure remains:
Session id: cron:our-pr-ci-monitor:20260722-200000 |
…ions-group-by-modifiers
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 39/39 (100.00%) · Uncovered code |
CI finish ledger - 082731bCI is fully finished on this head (Finish Workflow success, 156 success / 18 skipped, zero failures). Session id: cron:our-pr-ci-monitor:20260726-163000 |
|
Hi — this looks like a backport candidate for |
Resolves the conflict in OptimizeGroupByInjectiveFunctionsPass.cpp. Master gained a87ae3f (ClickHouse#110721), which disables the injective GROUP BY unwrap under GROUPING SETS / WITH TOTALS / CUBE / ROLLUP because the rewrite makes the output projection recompute f(defaultOf(g)) on rows where the key is absent from the set being aggregated. This branch supersedes that guard: it keeps the unwrap under those modifiers and corrects the absent-key output rows instead, via a grouping conditional for CUBE / ROLLUP / GROUPING SETS and a totals-stream overwrite for plain WITH TOTALS. Master's whole change to this file is the guard inside the conflicting hunk, so the resolution takes this branch's version of the pass unchanged. ClickHouse#110721's other files (OptimizeGroupByFunctionKeysPass.cpp, TreeOptimizer.cpp and its tests, including 04546) are untouched by this branch and are preserved as merged on master. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…2969 reference Two post-merge corrections, both verified against a build of the merged tree. ColumnNode's column-source parameter type was renamed from QueryTreeNodeWeakPtr to TableExpressionNodeWeakPtr on master (88b22b8, "Introduce ITableExpressionNode in the query tree"), so the __grouping_set column this pass synthesizes no longer compiled. GroupingFunctionsResolvePass, which this code mirrors, uses the new name in the same position. 02969's reference was auto-merged to master's variant, which records the query tree with the injective unwrap DISABLED (the state ClickHouse#110721 produced). This branch keeps the unwrap and corrects the totals row instead, so the tree dump has to show the unwrapped GROUP BY key again. The restored file is byte-identical to the merged build's actual output. Only the tree dump differs from master; the data assertion that the WITH TOTALS row prints the String default rather than '0' is unchanged and is what both branches fix. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Closes: #110715
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
optimize_injective_functions_in_group_bychanging query results forGROUP BY GROUPING SETSandGROUP BY ... WITH TOTALS. The setting is documented as result-preserving, but eliminating an injective function of a grouping key produced a wrong value (or dropped a row) for rows where that key is absent from the aggregated set (aGROUPING SETSnon-member set) or for theWITH TOTALSrow. The wrong value could coincide with a genuine key value, making a super-aggregate row indistinguishable from a real group in the same result set.Description
OptimizeGroupByInjectiveFunctionsPassrewrites an injectivef(g)in theGROUP BYkey list togand recomputesf(g)in the output projection. That is only valid when every output row still carriesg. It does not hold when aGROUP BYmodifier emits rows where the key is absent from the aggregated set: such a row outputs the key column default, so the projection computesf(defaultOf(g))instead ofdefaultOf(typeOf(f(g))).The pass already bails on
CUBE/ROLLUPandgroup_by_use_nullsfor the same reason. This extends the guard toGROUPING SETS(non-member set rows) andWITH TOTALS(the totals row).Reproducers from the issue, now returning identical output with the setting on and off:
A reported consequence of the same defect: the value the projection computes for an absent key can collide with a genuine key value, so the two row classes stop being distinguishable rather than merely rendering differently.
The optimization still applies to plain
GROUP BY.