Skip to content

Keep injective GROUP BY optimization under modifiers with correct defaults - #110953

Closed
groeneai wants to merge 13 commits into
ClickHouse:masterfrom
groeneai:fix-groupby-injective-optimization-modifiers-defaults
Closed

groeneai wants to merge 13 commits into
ClickHouse:masterfrom
groeneai:fix-groupby-injective-optimization-modifiers-defaults

Conversation

@groeneai

@groeneai groeneai commented Jul 18, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #110715
Related: #110721
Related: #107535

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):

Re-enables optimize_injective_functions_in_group_by under GROUPING SETS, CUBE and ROLLUP while emitting the correct value on rows where a grouping key is absent. For example SELECT toString(number), count() FROM numbers(3) GROUP BY CUBE(toString(number)) no longer needs the optimization disabled to return the empty string on the rolled-up level.

Description

Follow-up to #110721, which fixed #110715 by disabling the optimization under every GROUP BY modifier. As requested there, this keeps it enabled and substitutes the correct defaults instead.

The setting rewrites an injective key f(g) out of the GROUP BY list to g and recomputes f(g) in the projection, which is only valid while every output row carries g. On a row where the key is absent g holds its column default, so the projection computes f(default), for example toString(0) = '0', not ''.

Where a __grouping_set column exists on every row, each eliminated output is now wrapped in a grouping conditional emitting the type default on absent-key rows. That correction lives in the query tree, so a shard re-analyzing the query reproduces it. Covered: GROUPING SETS, CUBE, ROLLUP, ROLLUP ... WITH TOTALS.

Plain WITH TOTALS keeps its keys wrapped, as on master: its grand-total row carries no __grouping_set column, so any correction would live outside the query tree and be lost when the tree becomes an AST again.

Corrections use the aggregation layer's own key identity, so a self-join grouping by both sides keeps each side's value. The corrected clauses are the projection, ORDER BY, HAVING, LIMIT BY and INTERPOLATE.

The key is instead left wrapped, behaving as on master, whenever a correction cannot reach it or would change the output: an occurrence under a window function, in QUALIFY or in a named WINDOW, reached through any clause; a correlated subquery in a corrected clause, which the rewriter cannot descend into; a conditional that would not preserve the key's type, since if cannot return LowCardinality; a constant key, whose removal by the planner depends on flags this pass cannot see; and any unwrap merging two keys of the lattice. OptimizeGroupByFunctionKeysPass and the legacy TreeOptimizer path stay disabled under modifiers.

groeneai and others added 2 commits July 18, 2026 19:33
…with correct defaults

Re-enable OptimizeGroupByInjectiveFunctionsPass for GROUP BY modifiers that
produce absent-key rows (CUBE/ROLLUP subtotals, GROUPING SETS non-member sets)
instead of disabling it. An injective key f(g) is unwrapped to g only when the
rewrite is cardinality-preserving (single non-constant leaf) and g does not
collide with another key, so the final key layout is exactly the original with
f(g) replaced by g. Each output occurrence of f(g) is then guarded with
if(groupingForKind(__grouping_set, g) == present, f(g), defaultOf(typeOf(f(g))))
so absent-key rows emit the correct output-type default rather than f(default).

See ClickHouse#110715. WITH TOTALS handled in a follow-up commit.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…otals defaults

Extends the previous commit (GROUPING SETS/CUBE/ROLLUP) to plain WITH TOTALS.

The optimize_injective_functions_in_group_by pass rewrites an injective key f(g)
in the GROUP BY key list to g and recomputes f(g) in the projection. The WITH
TOTALS grand-total row fills g with its type default and has no __grouping_set
column, so the projection recomputes f(default) instead of defaultOf(typeOf(f(g)))
(e.g. '0' instead of '' for toString). See ClickHouse#110715.

The pass now unwraps f(g) under a plain WITH TOTALS and records the eliminated
projection output positions on the query node; the planner inserts a step after
the projection that overwrites those columns with their type default on the
totals stream only. A key is only unwrapped when every occurrence of f(g) in the
output is a whole top-level projection column (so the whole-column overwrite is
sufficient); otherwise the key is left as is.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse-local -q "SELECT toString(number) AS s, count() c FROM numbers(3) GROUP BY toString(number) WITH TOTALS FORMAT JSON" returns the totals s='0' on master (opt on) and s='' with the fix, every time.
b Root cause explained? The pass rewrites injective f(g) out of the GROUP BY key list to g and recomputes f(g) in the projection. On absent-key rows (WITH TOTALS grand-total, non-member GROUPING SETS rows, rolled-up CUBE/ROLLUP levels) g is filled with its column type default, so the projection computes f(default) (toString(0)='0') instead of defaultOf(resultType(f(g))) ('').
c Fix matches root cause? Yes. It emits the correct output-type default on exactly the absent-key rows: a grouping conditional over __grouping_set for CUBE/ROLLUP/GROUPING SETS rows, and a totals-stream-only column overwrite for the WITH TOTALS grand-total row. The optimization stays enabled.
d Test intent preserved / new tests added? New test 04547_group_by_injective_optimization_modifiers_defaults asserts both the correct values AND that the optimization still fires (EXPLAIN PLAN key is the unwrapped column). No existing test weakened.
e Both directions demonstrated? Yes. Surgical negative control: with the totals-port step disabled, the unwrapped-key WITH TOTALS row returns '0' (the bug); with it enabled, ''. Proves the step is what corrects it.
f Fix is general across code paths? Yes. Both correction mechanisms cover all four modifiers. Cases that cannot be safely fixed are explicitly kept disabled (function-keys pass under all modifiers = lattice change / per-set hazard; cardinality-changing unwrap under CUBE/ROLLUP; legacy TreeOptimizer), with reasons in the PR body.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Verified String, FixedString(4) (default \0\0\0\0, not '0\0\0\0'), LowCardinality(String), reinterpretAsString; numeric injective (negate) where defaultOf==f(default)=0 stays correct; aliased key, two injective keys, duplicate top-level columns. Both force_grouping_standard_compatibility modes covered.
h Backward compatible? Yes. No setting default change, no on-disk/wire/metadata format change. It corrects a wrong result under an already-default-on optimization; behavior is still fully recoverable with optimize_injective_functions_in_group_by=0. No SettingsChangesHistory.cpp change needed.
i Invariants and contracts preserved? Yes. The new QueryNode field is included in isEqualImpl + updateTreeHashImpl + cloneImpl (required: the unwrapped-key+channel tree and a plain same-key tree are otherwise identical but need different totals; the query cache must not conflate them). The new step preserves header/rows/sorting and only rewrites values on the 1-row totals chunk. The channel carries stable projection positions (RemoveUnusedProjectionColumnsPass runs before this pass; nothing reorders projection columns after).

Session id: cron:clickhouse-author-slot-0:20260718-202900

@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review — adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 findings; bounded: 1 full pass + 1 fix round + 1 delta recheck, which found 0 new findings).

# Sev Finding Verdict Evidence / action
1 ❌ Diff includes generated runtime artifacts (access/*.list, preprocessed_configs/config.xml, .meta.json) DISAGREE Those are untracked working-tree artifacts from the local test server; git ls-tree on the commit shows they are NOT in it. The branch contains exactly 10 files (8 src + 2 test). Removed from the worktree as hygiene; no commit change needed.
2 ⚠️ Test uses a blanket no-random-settings tag instead of pinning result-affecting settings; missing force_grouping_standard_compatibility branch coverage AGREE — fixed Dropped the tag; pinned optimize_injective_functions_in_group_by, group_by_use_nulls, force_grouping_standard_compatibility per query; added explicit coverage for force_grouping_standard_compatibility=0 and group_by_use_nulls=1. Re-verified 30-run stability with optimize_group_by_function_keys and other execution settings randomized = 0 failures.

Severity: ❌ blocker / ⚠️ major / 💡 nit. The DISAGREE verdict carries recorded evidence and is terminal.

Session id: cron:clickhouse-author-slot-0:20260718-202900

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @yakov-olkhovskiy @davenger — could you review this? It re-enables the injective-function GROUP BY optimization under GROUPING SETS/CUBE/ROLLUP/WITH TOTALS (which #110721 disabled) and instead substitutes the correct output-type default on the absent-key rows: a grouping conditional over __grouping_set for the subtotal rows, and a small totals-stream-only step for the WITH TOTALS grand-total row.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 18, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e60072c]

Summary: ✅


AI Review

Summary

This PR re-enables the injective GROUP BY rewrite for CUBE, ROLLUP, and GROUPING SETS when the correction can stay inside the query tree, while keeping the unsafe plain WITH TOTALS cases declined. I did not find a remaining correctness, distributed-analysis, or compatibility issue on the current head.

Final Verdict

✅ No new findings.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 18, 2026
Two follow-up fixes on top of the injective GROUP BY optimization under
GROUP BY modifiers (ClickHouse#110715):

1. The grouping conditional built for GROUPING SETS/CUBE/ROLLUP used the
   original key f(g) as the grouping function's argument, but f(g) is no
   longer a GROUP BY key after the unwrap (g is). The value is unaffected
   (FunctionGroupingBase computes only from __grouping_set plus the argument
   index), but ValidateGroupByColumnsVisitor requires every grouping()
   argument to be a current key, and a distributed shard re-analyzes the
   serialized query from scratch and rejected grouping(f(g)) with
   BAD_ARGUMENTS. Pass the unwrapped key as the argument instead.

2. For plain WITH TOTALS, the key is now unwrapped even when it is also
   referenced in ORDER BY. The grand-total row is produced on a separate
   totals stream and is never sorted, so the totals-column overwrite is
   independent of ORDER BY. HAVING remains a bail-out.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed 3ca5db0 fixing the two Fast-test failures on the prior head (both PR-caused):

  1. 02165_replicated_grouping_sets (Code 36 BAD_ARGUMENTS): the grouping conditional synthesized for GROUPING SETS/CUBE/ROLLUP passed f(g) as the grouping() argument, but after the unwrap only g is a GROUP BY key. The value was unaffected (the grouping function computes from __grouping_set plus the precomputed key index), but a distributed shard re-analyzes the serialized query and ValidateGroupByColumnsVisitor rejected grouping(f(g)). Now passes the unwrapped key g.

  2. 02969_analyzer_eliminate_injective_functions: relaxed the WITH TOTALS bail so the key is unwrapped even when it also appears in ORDER BY. The grand-total row is on a separate totals stream and is never sorted, so the totals-column default overwrite is independent of ORDER BY (verified: EXPLAIN PLAN shows DefaultTotalsColumns below Sorting, totals value stays correct). HAVING remains a bail-out. The reference update is the #110715 fix itself: the totals row of GROUP BY val WITH TOTALS ORDER BY val goes from 0 to the correct String default.

Verified locally on the fixed binary: 02165, 02969, and 04547 pass (30-run randomized stability, 0 failures); distributed remote() GROUPING SETS re-analysis works.

…rack leaves across eliminations

Two correctness gaps in the modifier-aware injective optimization:

- Window arguments, window PARTITION BY / ORDER BY and QUALIFY are materialized
  post-aggregation (after Totals/Rollup/Cube, before the projection), so an
  eliminated key referenced from any of them still evaluated f(column-default) on
  subtotal / totals rows even though the projected key column was corrected. Keep
  the key wrapped (unoptimized but correct) whenever it reaches a window/QUALIFY
  consumer, in both the grouping-conditional path and the WITH TOTALS path.

- The collision guard only compared each leaf to the original keys, so two
  different injective keys could unwrap to the same leaf (e.g.
  CUBE(toString(number), negate(number)) -> both number). analyzeAggregation then
  deduplicates them into one aggregation key, shrinking the CUBE/ROLLUP grouping
  lattice (missing subtotal levels, wrong GROUPING arity). Track leaves chosen by
  earlier eliminations and reject a later unwrap onto an already-claimed leaf.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Both addressed in fd0acb0.

  1. Window / QUALIFY consumers: an eliminated key is now kept wrapped (optimization declined for that key, correct but unoptimized as before) whenever it is reached by a window function (arguments or OVER clause) in the projection / ORDER BY / HAVING, by QUALIFY, or by a named WINDOW clause. Applied to both the grouping-conditional path and the WITH TOTALS path (reachesPostAggregationWindowOrQualify). Verified first_value(toString(number)) OVER () and QUALIFY under GROUPING SETS / WITH TOTALS now return the type default on the special row (result matches optimize_injective_functions_in_group_by=0).

  2. Collision guard: it now tracks leaves chosen by earlier eliminations across all sets and rejects a later unwrap onto an already-claimed leaf (only the same original key repeated across sets, e.g. GROUPING SETS ((k),(k,k)), may reuse a leaf). CUBE(toString(number), negate(number)) keeps the full lattice again (7 rows vs the previous 3), same for ROLLUP.

Regressions for both added to 04547 (assert opt on == off; deterministic ORDER BY / windows). 30x randomized runs clean; 02165 (distributed remote GROUPING SETS) and 02969 pass.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — fd0acb0

CI fully finished and clean on this head. Finish Workflow: pass. Mergeable Check: pass. CH Inc sync: pass. No failing tests or jobs (CIDB: 0 FAIL/ERROR on this commit). The earlier 02165_replicated_grouping_sets / 02969_analyzer_eliminate_injective_functions Fast-test failures were PR-caused and fixed by the pushes leading to this head.

Check / test Reason Owner / fixing PR
(none) — all green on this head

Session id: cron:our-pr-ci-monitor:20260719-073000

groeneai and others added 2 commits July 31, 2026 16:57
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master to clear the conflict. The conflict was with #110721, which merged on 2026-07-30 and disables this optimization under GROUPING SETS / WITH TOTALS / CUBE / ROLLUP. This branch keeps the optimization and corrects the absent-key rows instead, so I took this branch's version of the pass. #110721's other files are untouched here and its test 04546 passes unchanged.

Two adaptations were needed: ColumnNode's column-source parameter was renamed to TableExpressionNodeWeakPtr on master, and 02969's reference auto-merged to the variant recording the tree with the unwrap disabled, so I restored the unwrapped tree (verified byte-identical to the merged build's actual output; the data assertion that the totals row prints the String default is unchanged).

Validation: 304 semantically related stateless tests, identical selection on two arms built from this worktree with only the pass reverted, gave 0 regressions and 2 improvements (this PR's own tests); 12 failures are shared by both arms and environmental. 75/75 under randomized settings.

While reviewing the merge I found three wrong-result paths that are not merge fallout, they are already reachable on the previous head, and I do not think the current approach can cover them. Please hold off reviewing until I have pushed a fix.

  1. Two same-named keys from different sources. The key identity used for the correction ignores the column source, so in a self-join GROUP BY CUBE(toString(l.number), toString(r.number)) both keys share one grouping index. Rows are duplicated and every mixed subtotal is lost against the same query at optimize_injective_functions_in_group_by = 0.

  2. Distributed queries projecting grouping(). The correction is written into the grouping function's argument, and serialization generalizes the resolved specialization back to grouping, whose argument must still be a GROUP BY key. SELECT toString(number), grouping(toString(number)) FROM remote('127.0.0.{1,2}', numbers(3)) GROUP BY CUBE(toString(number)) fails with BAD_ARGUMENTS when the optimization is on and succeeds when it is off.

  3. LIMIT BY. Only the projection, ORDER BY and HAVING are rewritten, so LIMIT BY still evaluates the uncorrected value on subtotal rows. For GROUP BY CUBE(toString(number)) over numbers(3), LIMIT 1 BY k must be a no-op because every k is distinct, but it drops the 0 row: the subtotal reaches LIMIT BY as '0' and merges with the real 0 group.

The common cause is that the correction keys on a source-unaware node identity and rewrites only three of the post-aggregation consumers, so fixing it properly is a change of approach rather than another patch. I will also trim the comment blocks in the pass in the same push.

groeneai and others added 7 commits July 31, 2026 22:35
The correction that keeps optimize_injective_functions_in_group_by enabled under
GROUP BY modifiers had four independently reachable defects. Three of them are
regressions of this PR: the pristine master snapshot is correct on all three.

Attribute each correction to the right aggregation key. AggredationKeyIndexMap
and the replacements map were keyed on QueryTreeNodePtrWithHashIgnoreAliases, but
ColumnNode::isEqualImpl and updateTreeHashImpl both take CompareOptions unnamed
and compare only the column name and type, so a self-join grouping by
toString(l.number) and toString(r.number) collapsed both corrections onto one
map entry and every mixed subtotal showed the left side's value. Switching to
compare_aliases = true would have been a no-op. The maps now use the same
source-aware identity the aggregation layer already applies, so the comparator
GroupingFunctionsResolvePass defines moves verbatim into a new header shared by
both passes; that relocation is behaviour-neutral.

Do not rewrite a GROUPING argument into the conditional. The rewrite descended
into resolved grouping specializations, so a user grouping(f(g)) had the
conditional substituted for its argument, and a distributed shard rejected the
query with BAD_ARGUMENTS once removeGroupingFunctionSpecializations generalized
the call back to grouping. The eliminated argument is replaced by its unwrapped
key instead, which is the rule this pass already documents for the grouping node
it synthesizes itself. The resolved function must then be re-resolved: an
IFunctionBase records the argument types it was built for, and both
QueryTreePassManager's validator and PlannerActionsVisitor compare them against
the actual arguments. The grouping specializations are not registered in
FunctionFactory and carry per-query state, so the existing IFunction is
re-wrapped rather than looked up by name.

Correct the two missing post-aggregation carriers. Per Planner.cpp the carriers
are projection, ORDER BY, HAVING, LIMIT BY and INTERPOLATE; only the first three
were rewritten, so LIMIT BY merged a subtotal row with a real group and dropped
it, and an INTERPOLATE filled row carried f(default). On the plain WITH TOTALS
path, where the correction is a whole-column overwrite that cannot reach either
clause, the key is left wrapped instead.

The test gains rows for all four defects plus a per-modifier assertion that the
optimization actually fired, so the existing assertions can no longer pass on a
silent decline. Verbose comment blocks are trimmed to the local invariant.
The correction for a plain WITH TOTALS grand-total row was recorded beside
the query tree, as QueryNode::eliminated_totals_default_positions, and
applied by the planner on the totals stream. That field participates in
query-tree identity but QueryNode::toASTImpl does not emit it, and two
consumers key on the converted AST rather than on the tree, so both kept
the unwrap and lost the correction.

A distributed shard receives the query as text. For the query

  SELECT toString(number) AS s, count() FROM remote('127.0.0.1', numbers(3))
  GROUP BY toString(number) WITH TOTALS ORDER BY s

the shard was sent GROUP BY __table1.number WITH TOTALS with no marker, so
it added no correction while its projection still computed toString on the
totals row, and the totals value read 0 instead of the empty string. This
happened on all four combinations of prefer_localhost_replica and
serialize_query_plan, with no non-default setting.

The planner subquery result cache key is built from the converted AST too,
so GROUP BY toString(number) WITH TOTALS, which needs an empty totals
value, and GROUP BY number WITH TOTALS projecting toString(number), which
needs '0', converged on one byte-identical AST and shared an entry.
Whichever ran first returned its value for the other, in both orders.

Carrying the marker into the AST does not work. A field that is not
printed cannot reach a shard, and printing it would mean inventing
user-visible syntax for an internal correction. There is no
expression-level signal either: grouping() returns 0 on the
plain WITH TOTALS totals row, exactly as on a real group, so the grouping
conditional used for the other modifiers has nothing to branch on.

So plain WITH TOTALS keys stay wrapped, which is what master does today.
GROUPING SETS, CUBE and ROLLUP keep the optimization, including
ROLLUP(...) WITH TOTALS, because their correction is a grouping
conditional inside the query tree and therefore survives conversion.

With nothing writing the marker, the field, its participation in equality,
tree hash and clone, the planner insertion site, DefaultTotalsColumnsStep
and DefaultTotalsColumnsTransform are all unreachable and removed. This
also removes a latent failure: that step implemented neither serialize()
nor isSerializable() and was not registered, so had the marker ever
reached a shard plan the query would have failed outright.

The test gains the two cells that would have caught this, one distributed
and one over the subquery cache, a structural assertion that the converted
AST still carries the wrapped key, and firing assertions for the four
shapes that previously had result-comparison oracles only. The
02969 reference returns to the unmodified upstream file.
…AVING

Round 3 of the review cycle. Four fixes.

The blocker: a constant GROUP BY key made the grouping conditional emit the
wrong value. buildAndApplyCorrections numbers every GROUP BY node, constants
included, and hands that count to the grouping function as its set-space base.
The planner removes a constant key when the query has aggregates
(PlannerExpressionAnalysis.cpp, the check_constants_for_group_by_key branches),
so execution has fewer keys than the pass counted. That count is the mask base
in Functions/grouping.h, so an off-by-N mis-decides present-versus-absent and
the conditional emits the type default on rows where the key is present.
GROUP BY CUBE(toString(number), toUInt8(7)) returned subtotal 0 instead of the
empty string, at default settings, and the same for the ROLLUP equivalent.

The pass cannot mirror the planner's predicate: whether a constant is pruned
depends on is_secondary_query and isDistributed, so it differs between the
initiator and a shard for the same query, and a conditional baked into the tree
on the initiator would be re-derived differently on the shard. So the pass now
declines to unwrap anything when any GROUP BY key is a constant. That is no
worse than master, which skips the whole modifier family, and a constant GROUP
BY key is a degenerate query.

HAVING had no coverage although the pass rewrites it, so deleting that rewrite
left the suite green while a HAVING predicate over an eliminated key filtered
subtotal rows using f(column-default). Four cells added, each mutation-proven
and each carrying a label literal: the two CUBE cells are complementary, so
unlabelled their diffs cancelled and only half the breakage was visible.

The LIMIT BY firing assertion explained a query with no LIMIT BY clause, making
it a near-duplicate of the CUBE assertion. Both explained queries now carry
LIMIT 1 BY k.

Four stale comments corrected, including a reference to a declineWithTotals
symbol that never existed and two describing the totals-port mechanism that
the previous round deleted.
…would change the key type

The correction built for an eliminated key f(g) under CUBE / ROLLUP / GROUPING SETS is
if(equals(grouping(...), present), f(g), default). FunctionIf reports
canBeExecutedOnLowCardinalityDictionary() = false, and the LowCardinality re-wrap in
IFunctionOverloadResolver::getReturnType is gated on exactly that, so the conditional can
never return LowCardinality for any argument shape. Replacing a LowCardinality key with it
narrowed the declared column type: a query with an enclosing function resolved against the
original type failed to analyze, and one without still silently changed the type reported by
DESC depending on optimize_injective_functions_in_group_by.

Check whether the conditional preserves the key's result type and decline the key otherwise,
following the shape IfChainToMultiIfPass and three other analyzer passes already use. The
check is expressed on the type rather than on isLowCardinality so it also covers any other
type family that later stops round-tripping through if.

It has to run before the unwrap: the key is replaced in the GROUP BY in place and the
correcting conditional is only built afterwards, so a late decline would leave the key
unwrapped with no correction applied, which is the f(column-default) wrong-results bug this
optimization path exists to avoid.

Also adds the FixedString-under-CUBE wrapper cell, whose subtotal must be four NUL bytes
rather than toFixedString('0', 4), and a firing assertion covering the
force_grouping_standard_compatibility = 0 branch of the grouping conditional, which no
existing assertion reached.

Co-Authored-By: Claude Fable 5 <[email protected]>
… them

A key referenced from inside a window function is not fixed by the grouping conditional: the
rewrite deliberately stops at window and aggregate nodes, because their arguments are
evaluated pre-aggregation where __grouping_set does not exist. Such a key is therefore kept
wrapped instead.

The guard scanned the projection, ORDER BY, HAVING, QUALIFY and the named WINDOW clause, but
not LIMIT BY or INTERPOLATE, which are also rewritten. A key occurring inside a window
function in either of those two was neither declined nor corrected and kept computing
f(column-default) on subtotal rows: a LIMIT BY query lost a real group whose window value
collided with the subtotal's, and an INTERPOLATE query filled '0' where '' belongs.

Scan both, using the same accessors the rewrite uses so the two lists cannot drift apart
again, and state in the comment that every rewritten carrier has to appear here.

Co-Authored-By: Claude Fable 5 <[email protected]>
… correlated subquery

A correlated subquery is not a separate GROUP BY scope: it reads a column of the
enclosing query. The output rewriter stops at every nested query, so an eliminated
key occurring inside one was neither corrected nor declined, and the subquery still
computed f(column-default) on an absent-key row. The reported shape disagreed with
itself about a single alias:

  SELECT toString(number) AS k, (SELECT k) AS kk, kk = k AS same, count()
  FROM numbers(3) GROUP BY CUBE(toString(number))

On the subtotal row k was corrected to '' while kk stayed '0'.

reachesPostAggregationWindowOrQualify now scans the same seven clauses for a
correlated subquery and keeps the key wrapped when it finds one, which restores
master's behaviour exactly. The unwrap is in fact what made the subquery planable
at all - decorrelation looks for the correlated leaf column, which only reaches the
aggregation header once the key is unwrapped - so with the key wrapped these shapes
return the same NOT_IMPLEMENTED they return on master.

Declining rather than correcting is the right shape here because a correlated
subquery is planned from the correlated leaf column, not from the outer projection
expression, so there is no node in this tree for the conditional to wrap. The test
is deliberately whole-clause rather than contains-the-key: the correlated column
names the leaf, so a containment test would not match it. That coarseness is
measurably free, since a correlated subquery reading a different key produces
byte-identical results either way.
…unify the test anchors

The placeholder comment credited FunctionIf::getReturnTypeImpl only type-checking the
first argument as UInt8. That is true but not load-bearing: the type the pass observes
comes from IFunctionOverloadResolver::getReturnType, whose LowCardinality re-wrap
classifies each argument by whether its column is const and counts full-vs-const
columns, and constness is exactly what a placeholder changes. The gate is sound because
FunctionIf::canBeExecutedOnLowCardinalityDictionary() is false and short-circuits that
condition, so the placeholder and the real conditional land on the same type.

Six firing assertions still used the original unbounded window, matching the words
GROUP BY anywhere and running to the end of the dump rather than to the next section
header. Those six shapes have no ORDER BY today so they were not wrong, but the
correction deliberately puts the injective function back into ORDER BY and the
projection, so adding one later would have silently inverted them. All 31 now use the
same section-scoped anchor and read the same values as before.
@groeneai groeneai changed the title Keep injective GROUP BY optimization under modifiers with correct defaults Closes: https://github.com/ClickHouse/ClickHouse/issues/110715 Aug 1, 2026
@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review, rounds 3-5 on e60072ce (final round clean; 3 blockers and 5 more findings fixed since the last log)

Three further rounds of independent cold review plus a second-model gate since the round-2 log
above. The final round on e60072ce returned no findings from either party, so the PR is ready
for review. Every finding was verified against the source before it was accepted; the ones I
rejected are recorded with the evidence that killed them.

Finding Verdict
❌ The correcting conditional cannot return LowCardinality, so it silently narrowed the declared type of an LC key. FunctionIf hard-codes canBeExecutedOnLowCardinalityDictionary() = false while inheriting useDefaultImplementationForLowCardinalityColumns() = true, so IFunctionOverloadResolver::getReturnType strips LC from both branches and its re-wrap gate refuses to put it back. Any enclosing function already resolved against the original type then disagrees with its own argument. AGREE, fixed
❌ Two of the five corrected clauses were not scanned for window-bound keys. Corrections are applied to the projection, ORDER BY, HAVING, LIMIT BY and INTERPOLATE, but only the first three plus QUALIFY/WINDOW were checked for an occurrence under a window function, and the output rewriter stops at a window function. A key bound inside a window function in LIMIT BY or INTERPOLATE was therefore neither declined nor corrected, and the LIMIT BY case lost a real group. AGREE, fixed
❌ A correlated subquery in a corrected clause is an eighth carrier, missed by my own clause enumeration and found by the gate. The output rewriter stops at every nested query, which is right for an uncorrelated subquery (its own GROUP BY scope) and wrong for a correlated one, which reads a column of this query. Measured pre-fix: SELECT toString(number) AS k, (SELECT k) AS kk, kk = k FROM numbers(3) GROUP BY CUBE(toString(number)) made the query disagree with itself about one alias on the subtotal row. AGREE, fixed
⚠️ The wrapper-type matrix could not detect the LowCardinality defect: every wrapper cell used plain WITH TOTALS, which this change declines outright, so those cells asserted existing behaviour. AGREE, respecified and fixed
⚠️ No firing assertion ran with force_grouping_standard_compatibility = 0, although the conditional's expected value is setting-dependent. A silent decline there still yields correct results, so the reference diff alone cannot catch it. AGREE, fixed
💡 The type gate's comment credited its own soundness to the wrong fact. FunctionIf::getReturnTypeImpl being indifferent to argument 0's value is true but not load-bearing; the operative fact is that canBeExecutedOnLowCardinalityDictionary() is the first term of the resolver's LowCardinality re-wrap condition, so the chain short-circuits. The rest of that re-wrap does depend on argument constness, which is exactly what the gate's placeholder condition changes. Raised independently by both parties. AGREE, fixed
💡 Two anchor conventions coexisted across the firing assertions: six still matched GROUP BY anywhere in the tree dump with no upper bound, so an occurrence in ORDER BY or the projection counted, which is precisely what the correction deliberately puts back. Not wrong today, since those six shapes have no ORDER BY. Raised independently by both parties. AGREE, all 31 converted
💡 One of my own earlier requests was itself wrong: I asked for CUBE/ROLLUP cells covering reinterpretAsString and toLowCardinality, but neither is injective, so the pass never unwraps them and those cells would have asserted master behaviour. Only toFixedString is a genuine carrier. Recorded; my request corrected

Two findings I raised and then refuted myself, recorded so they are not re-litigated. The
conditional takes its absent-key value from IDataType::getDefault while the CUBE/ROLLUP
transforms build theirs through insertDefaultInto, which looked like a divergence for an
Enum-typed key; reading both paths shows they agree for every type the key filter admits. And the
used_in_set guard looked like it should stay key-identity-blind, but it is part of the aggregation
key attribution it wraps, so leaving it blind would have collapsed two sides of a self-join inside
one grouping set.

One acceptance criterion of mine turned out to be unsatisfiable by construction, and that is worth
stating plainly rather than burying. I asked for the correlated-subquery query to agree with itself
on the fixed build. It cannot: the unwrap is what made that subquery planable at all, because the
correlated column names the leaf and the aggregation header carries the bare leaf only after the
unwrap. With the key left wrapped the query returns NOT_IMPLEMENTED, byte-identically to master,
so the wrong row and the unwrap are the same event and there are no rows left to compare. The
decline is instead proven by a tree-level firing pair (the correlated shape declines while an
otherwise identical shape using a plain alias reference still fires, and an uncorrelated subquery
correctly does not decline), plus self-consistency rows for the one shape of that family which does
return rows. No oracle was substituted silently.

Validation on the final head: the new test passes 50 out of 50 randomized runs; a 300-test A/B
sweep against the same tree with only the last hunk reverted shows no regressions and one
improvement, which is this test; and deleting the new decline reddens exactly one assertion.

@groeneai groeneai changed the title Closes: https://github.com/ClickHouse/ClickHouse/issues/110715 Keep injective GROUP BY optimization under modifiers with correct defaults Aug 1, 2026
@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, exact commands, each deterministic rather than a failure rate. SELECT toString(number) AS k, count() FROM numbers(3) GROUP BY CUBE(toString(number), toUInt8(7)) ORDER BY k returned subtotal 0 where the optimize_injective_functions_in_group_by = 0 oracle returns the empty string, at default settings with no fuzzing, and the same for the ROLLUP equivalent. This round added two more, both deterministic at default settings: SELECT reverse(lc) AS k, length(k) FROM u GROUP BY CUBE(reverse(lc)) over a LowCardinality(String) column, which failed to analyze before the fix, and ... GROUP BY CUBE(toString(x)) LIMIT 1 BY first_value(toString(x)) OVER (PARTITION BY toString(x)), which returned three rows against the oracle's four. This round adds one more, deterministic at default settings: SELECT toString(number) AS k, (SELECT k) AS kk, kk = k AS same, count() FROM numbers(3) GROUP BY CUBE(toString(number)) returned same = 0 on the subtotal row, i.e. the query disagreed with itself about one alias, because the correlated subquery still computed toString(0) while k was corrected to the empty string. Earlier rounds' repros are unchanged: the distributed remote('127.0.0.1', numbers(3)) ... WITH TOTALS query on all four combinations of prefer_localhost_replica and serialize_query_plan, and the planner-subquery-cache pair whose two members legitimately need different totals values.
b Root cause explained? Yes. buildAndApplyCorrections numbers every GROUP BY node, constants included, and hands that count to the grouping function as its set-space base. The planner removes a constant key when the query has aggregates (PlannerExpressionAnalysis.cpp, the check_constants_for_group_by_key branches, one per GROUP BY shape), so execution has fewer keys than the pass counted. That count is the mask base in Functions/grouping.h (set_mask = (1 << N) - 1 - set_index for CUBE, arg_index < N - set_index for ROLLUP), so an off-by-N mis-decides present-versus-absent and the conditional emits the type default on rows where the key IS present. Modelled at N=2 versus N=1 and it predicts the observed value exactly.
c Fix matches root cause? Yes, and it deliberately does not mirror the planner's predicate: check_constants_for_group_by_key is is_secondary_query || is_distributed_query, so whether a constant is pruned differs between the initiator and a shard for the same query, and a conditional baked into the tree on the initiator would be re-derived differently on the shard. Instead the pass declines to unwrap anything when any GROUP BY key is a constant, which is no worse than master (it skips the whole modifier family) and costs nothing in practice, since a constant GROUP BY key is a degenerate query. No bound widened, no test weakened, no no-random-* tag.
d Test intent preserved / new tests added? Yes. Every pre-existing assertion is kept and all four per-modifier firing assertions still read 1. New rows: four constant-key result cells with their oracles, covering both planner pruning branches (flat and GROUPING SETS, the latter twice: constant beside the key, and constant alone in its own set); a decline/fire pair proving the decline is targeted; four HAVING cells with oracles plus a HAVING firing pair, closing a rewrite that previously had zero coverage. The two explained LIMIT BY queries now actually carry LIMIT 1 BY k, so that assertion is the shape it names. This round adds: two window-bound cells (LIMIT BY and INTERPOLATE) with their oracles, each row carrying its own label so complementary arms cannot cancel in the line diff, each paired with a firing assertion reading 0 (declined) plus a no-window sibling reading 1 so the decline is proven targeted; a LowCardinality carrier cell with both DESC arms asserted; the FixedString-under-CUBE wrapper cell; and a firing assertion on the force_grouping_standard_compatibility = 0 branch, which no existing assertion reached. This round adds a three-way firing group for the correlated-subquery decline (the correlated shape reads 0, an otherwise identical shape with the subquery replaced by a plain reference to the same alias reads 1, and an UNcorrelated subquery reads 1, so the decline is proven targeted in both directions), plus a labelled result pair for the one shape of that family which produces rows at all with its optimize_injective_functions_in_group_by = 0 arm. It also unifies the six remaining loose firing assertions onto the section-scoped anchor the other 25 already use, a pure tightening that moved no reference line.
e Both directions demonstrated? Yes, on Build-ID-verified binaries (fix 4a4a36ae, pristine HEAD 753e3c45, mutants 5edd0d69 and 6c736695), each arm asserting the served buildId() equals its own readelf -n. The pristine arm fails on exactly the four new constant-key cells. Deleting the HAVING rewrite breaks all four HAVING cells, measured per cell (three lose their row, one gains a wrong one). Deleting the LIMIT BY rewrite reddens the 0\t1 row of each of the three LIMIT BY result cells. This round: the fix arm is 55dbc0ba. Moving the type check after the unwrap makes a LowCardinality(UInt8) key's subtotal read 0 where the oracle reads the empty string, so the check is proven to be a pre-check rather than a plausible-looking late one; removing it entirely restores the original analysis failure; removing the two new carrier lines reddens exactly the two new cells and their two firing assertions, four diff lines and nothing else; and declining on the non-compatibility grouping branch reddens exactly the one new compatibility assertion. This round: the fix arm is 27d192be. Removing exactly the fourteen new correlated-subquery lines (e30b8577) reddens exactly one row and nothing else, two diff lines. The pre-fix arm 55dbc0ba produces the self-disagreeing subtotal row. One acceptance oracle could not be measured as written and is disclosed rather than manufactured: once the key stays wrapped, that query returns the same NOT_IMPLEMENTED it returns on pristine master (verified on the master snapshot, both setting values, its copy of the carrier md5-identical to master), because the unwrap is what made the correlated column reachable in the aggregation header at all. The load-bearing test for the decline is therefore the EXPLAIN firing group, which needs no rows. Every restore relinked bit-identically to the fix arm with the source md5 restored, so no mutation residue ships.
f Fix is general across code paths? Yes. The decline is applied over the flattened key space the collision guard already walks, so GROUPING SETS is covered by construction rather than as a second case, and it fires before any key is mutated, so nothing is left half-unwrapped. Both planner pruning branches are covered by tests. The identical constant-key miscount in upstream's own resolveGroupingFunctions is pre-existing and independent of this PR, so it is deliberately left alone (one concern per PR). This round also closed a carrier-enumeration gap: the guard that declines a key referenced from a window function scanned three of the five clauses the correction rewrites, missing LIMIT BY and INTERPOLATE, so a window-bound key there was neither declined nor corrected and kept computing f(column-default) (a LIMIT BY query lost a real group, an INTERPOLATE query filled 0 where the empty string belongs). Both are now scanned, using the same accessors the rewrite uses so the two lists cannot drift apart again. This round closed the last member of that enumeration: a correlated subquery in any of those clauses is also an uncorrected carrier, because it is not a separate GROUP BY scope (it reads a column of this query) yet the output rewriter stops at every nested query. It is declined via the existing containsCorrelatedSubquery helper, matching the in-tree precedent that declines ConvertQueryToCNFPass on the same predicate; all seven scanned clauses are covered by one list.
g Fix generalizes across inputs (params/datatypes/wrappers)? The decline is type-independent by construction, and the surviving optimization is still exercised across CUBE, ROLLUP, GROUPING SETS and ROLLUP ... WITH TOTALS, both force_grouping_standard_compatibility branches, and the self-join, user grouping(), HAVING, LIMIT BY and INTERPOLATE shapes, plus the type matrix where defaultOf(type) differs from f(default). The LowCardinality gap disclosed in earlier rounds is now CLOSED rather than disclosed: FunctionIf reports canBeExecutedOnLowCardinalityDictionary() = false and the LowCardinality re-wrap in IFunctionOverloadResolver::getReturnType is gated on exactly that, so the conditional can never return LowCardinality for any argument shape; such a key is now declined by a general type-preservation check rather than an isLowCardinality special case, so any other type family that later stops round-tripping through if is covered too. Measured across twelve type families, LowCardinality was the only one affected. New cells cover the LowCardinality carrier (rows and the DESC-visible declared type, identical on both setting values) and the FixedString-under-CUBE wrapper, whose subtotal must be four NUL bytes rather than toFixedString('0', 4).
h Backward compatible? (maintainer-approved exception only) Yes, and no SettingsChangesHistory.cpp entry is owed: no setting is added or changed and optimize_injective_functions_in_group_by keeps its default. No format or protocol change. Where the pass now declines, behaviour matches master exactly, which is why 02969_analyzer_eliminate_injective_functions passes against master's own unmodified reference.
i Invariants and contracts preserved? Yes. The invariant is that a key is only unwrapped when the correction lives in the query tree and therefore survives conversion to an AST, and when the pass can know the key count execution will use. A constant key breaks the second half, so such a query is declined outright; plain WITH TOTALS breaks the first half and is likewise left wrapped. Both are correct but unoptimized. No plan step, header or stream contract changes; QueryNode equality, tree hash and clone keep their base semantics.

Also verified this round: a 281-test feature-scoped A/B sweep whose baseline reverts only this change, identical selection in both arms with ran_only_in_base and ran_only_in_fix both empty, giving 0 regressions; the 49 shared failures are bare-sandbox classes (cluster, ZooKeeper, distributed) present in both arms. The baseline arm aborts on this test, which is the reproduction, so it was run in two passes to cover the full selection; the one apparent improvement besides this test failed on the baseline with (ABORTED), i.e. collateral of that abort rather than a real gain. 50 of 50 passes in a randomized 50-run, tag-free. Every mutation restore relinked bit-identically to the fix arm with the source md5 restored. Re-run for this round on the current head: a 300-test A/B sweep with the identical selection in both arms and a per-arm server restart (a .sql test is served by whichever server is listening, not by --binary), ran_only_in_fix empty, giving 0 regressions, 52 shared bare-sandbox failures and one improvement which is this test itself; and 50 of 50 passes in a fresh randomized 50-run.

Session id: cron:clickhouse-impl-slot-44:20260801-084700

@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.80% +0.10%

Changed lines: Changed C/C++ lines covered: 231/249 (92.77%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - e60072c

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

All 174 checks completed with no failures (156 success, 18 skipped, Finish Workflow success).

Check / test Reason Owner / fixing PR
- no failures -

Session id: cron:our-pr-ci-monitor:20260801-163000

@PedroTadim

Copy link
Copy Markdown
Member

The issue has been fixed

@PedroTadim PedroTadim closed this Aug 7, 2026
@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks for looking. One check on scope before I drop this, because I think the close may be reading two separate things as one.

#110715 was closed by #110721 (merged 2026-07-31), which fixes it by disabling the injective-key and function-key GROUP BY optimizations whenever a modifier is present. That guard is on master today: OptimizeGroupByInjectiveFunctionsPass.cpp:52, OptimizeGroupByFunctionKeysPass.cpp:55 and TreeOptimizer.cpp:114 / :626 (master 1c39bbe4e7df) all return early on CUBE, ROLLUP, GROUPING SETS and WITH TOTALS.

This PR is the follow-up @alexey-milovidov asked for on #110721: "can we keep the optimization while fixing the values for rolled-up keys at the same time? ... If you do, send another PR for that." It re-enables the optimization under those modifiers and emits the correct type default on rows where a key is absent, so the bug stays fixed either way.

What is still on master is the cost. SELECT toString(number), count() FROM numbers(3000000) GROUP BY CUBE(...), single thread, aggregating with the key in the two forms the pass chooses between (toString(number) as master leaves it, against the bare number the optimization would use): peak memory 1117 MiB against 672 MiB, and 1.39 s against 0.85 s median over 5 interleaved runs, ranges disjoint. Those two arms also return different values, which is the bug this PR corrects while keeping the cheaper key.

So my question is whether you want the optimization to stay disabled under modifiers. If yes, I will leave this closed and record that as the outcome. If not, this head was green (174 check runs, 156 success and 18 skipped, 0 failures) and carries no human review objection, so it can be reopened, or I can open a fresh PR from the same tree.

cc @alexey-milovidov, since this PR exists only because you asked for it and your call is the one that settles it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

optimize_injective_functions_in_group_by changes the WITH TOTALS row value of a computed grouping key

3 participants