Repository navigation
Conversation
…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]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-author-slot-0:20260718-202900 |
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).
Severity: ❌ blocker / Session id: cron:clickhouse-author-slot-0:20260718-202900 |
|
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 |
|
Workflow [PR], commit [e60072c] Summary: ✅
AI ReviewSummaryThis PR re-enables the injective Final Verdict✅ No new findings. |
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]>
|
Pushed 3ca5db0 fixing the two Fast-test failures on the prior head (both PR-caused):
Verified locally on the fixed binary: 02165, 02969, and 04547 pass (30-run randomized stability, 0 failures); distributed |
…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]>
|
Both addressed in fd0acb0.
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. |
CI finish ledger — fd0acb0CI 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
Session id: cron:our-pr-ci-monitor:20260719-073000 |
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]>
|
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: 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.
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. |
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.
Internal second-model review, rounds 3-5 on
|
| 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.
Pre-PR validation gate (click to expand)
Also verified this round: a 281-test feature-scoped A/B sweep whose baseline reverts only this change, identical selection in both arms with |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 231/249 (92.77%) · Uncovered code |
CI finish ledger - e60072cEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task All 174 checks completed with no failures (156 success, 18 skipped,
Session id: cron:our-pr-ci-monitor:20260801-163000 |
|
The issue has been fixed |
|
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: 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. 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. |
Closes: #110715
Related: #110721
Related: #107535
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Re-enables
optimize_injective_functions_in_group_byunderGROUPING SETS,CUBEandROLLUPwhile emitting the correct value on rows where a grouping key is absent. For exampleSELECT 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 BYmodifier. As requested there, this keeps it enabled and substitutes the correct defaults instead.The setting rewrites an injective key
f(g)out of theGROUP BYlist togand recomputesf(g)in the projection, which is only valid while every output row carriesg. On a row where the key is absentgholds its column default, so the projection computesf(default), for exampletoString(0) = '0', not''.Where a
__grouping_setcolumn 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 TOTALSkeeps its keys wrapped, as on master: its grand-total row carries no__grouping_setcolumn, 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 BYandINTERPOLATE.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
QUALIFYor in a namedWINDOW, 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, sinceifcannot returnLowCardinality; a constant key, whose removal by the planner depends on flags this pass cannot see; and any unwrap merging two keys of the lattice.OptimizeGroupByFunctionKeysPassand the legacyTreeOptimizerpath stay disabled under modifiers.