Repository navigation
Fix constant-condition if/multiIf GROUP BY keys with the identifier resolve cache and group_by_use_nulls - #122512
Conversation
…onPass
The pass folded in `enterImpl`. `InDepthQueryTreeVisitorWithContext::visit`
then descends into the children of the replacement without entering the
replacement itself, so one visit folded only every other level of a chain of
constant conditions: `if(0, n, if(0, n, if(0, n, if(0, n, n))))` became
`if(0, n, if(0, n, n))`.
With `enable_identifier_resolve_cache` (on by default since 26.6) every later
lookup of a GROUP BY alias returns the node already resolved for it, so the
GROUP BY key and its ORDER BY / HAVING / LIMIT BY / GROUPING SETS references
are one shared node, while the projection is a separate copy. The visitor does
not deduplicate, so it reaches the shared node once per referencing slot, and
the second visit folds one more level in place, inside the shared parent. The
key then no longer matches the projection by action name, the planner tries to
recompute the projection from a column that aggregation has consumed, and the
query fails with NOT_FOUND_COLUMN_IN_BLOCK, e.g.
SELECT if(0, s, if(0, s, if(0, s, if(0, s, s)))) AS r FROM t GROUP BY r ORDER BY r
Folding in `leaveImpl` decides a node after its arguments, so a chain
collapses completely in one visit, visiting an already folded node again is a
no-op, and every copy of the expression converges to the same result with the
cache on or off. The fold rule itself is unchanged. The old analyzer's
equivalent, `OptimizeIfWithConstantConditionVisitor`, was bottom-up as well.
Closes: ClickHouse#122404
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…p_by_use_nulls
`IfConstantConditionPass` runs after analysis and rewrites a GROUP BY key that
is an `if`/`multiIf` with a constant condition to the branch it always takes,
through every nested constant condition. When that branch is a column, the
aggregation groups by the column, and ROLLUP/CUBE/GROUPING SETS output it as
Nullable under `group_by_use_nulls`. A correlated reference to the column
matched no registered key, so it kept its non-Nullable type while its
placeholder was bound to the Nullable header column. For a `Bool` column the
cast wrapper then received a `ColumnNullable` and failed with
`Bad cast from type DB::ColumnNullable to DB::ColumnVector<char8_t>`:
SELECT (SELECT c0) FROM (SELECT 1::Bool) t0(c0)
GROUP BY if(1, c0, false) WITH ROLLUP SETTINGS group_by_use_nulls = 1
The analyzer now registers every column such a key may collapse to, through
the branches of nested `if`/`multiIf`, without checking the conditions: one
can become constant only in a later pass, for example when
`optimize_inverse_dictionary_lookup` replaces a dictionary lookup that matches
no key with `0`. The correlated-column lookup converts a reference to such a
column to Nullable, as it does for a reference to a key. A column the
aggregation does not group by is not in its output, so such a reference is
rejected as before. The column is registered for correlated references only,
since for other expressions it is not a key.
The test of the bottom-up fold is renumbered from 05267 to 05272, since 05267
is used by another open PR.
Related: ClickHouse#106377
Related: ClickHouse#100173
Co-Authored-By: Claude Opus 5.5 <[email protected]>
With `group_by_use_nulls` and ROLLUP/CUBE/GROUPING SETS, the analyzer
replaces an expression equal to a GROUP BY key with a copy of the key made
Nullable. `IfConstantConditionPass` folded a constant-condition key to its
branch but never such a copy, whose type is the Nullable form of the branch
type, so the copy no longer matched the key by name and was computed from
the aggregation output, which lacks the other branch's columns:
SELECT if(0, b, a) AS k, count() FROM t GROUP BY k WITH ROLLUP
SETTINGS group_by_use_nulls = 1
failed with NOT_FOUND_COLUMN_IN_BLOCK. With the bottom-up fold this also
broke keys such as `if(0, b, if(0, b, a))`, which the top-down fold left
matching the copy.
The pass now folds such a copy to its branch made Nullable, as
`ComparisonTupleEliminationPass` does (ClickHouse#96426). Constant branches are left
as they were.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
ROLLUP, CUBE and GROUPING SETS take their grouping sets from the distinct
GROUP BY keys: the planner merges keys with the same action name, and
grouping() is resolved against the keys before the pass runs. Folding
every level of a constant-condition chain can make two different keys
equal:
SELECT a, if(0, b, if(0, b, a)) AS k, count() FROM t
GROUP BY ROLLUP(a, k)
lost the grouping set that rolls up only `k`. A single level such as
`if(0, b, a)` was merged the same way before.
The pass now leaves a query unfolded when folding would make two of its
ROLLUP/CUBE/GROUPING SETS keys equal.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten the nullable_collapsed_group_by_key_columns and registerConstantConditionBranchColumns comments to one line each; the reasons are in the commit messages above. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review: my own cold review plus an independent model (engine: codex), both on the tree before publication. Bounce cap reached - published as-is; residual findings listed below (rows 14-15).
Severity: ❌ blocker / |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-5:20260926-192300 |
|
Workflow [PR], commit [a72a6b0] Summary: ❌
AI ReviewSummaryThis PR fixes the original constant-condition Findings❌ Blockers
Final Verdict❌ Changes needed before merge: the collapsed-key registration still over-approximates what the later passes and planner can actually expose, so the new analyzer path accepts unsupported correlated-column shapes. |
The skip for a query whose folded keys would merge did not match the
merge it guards against.
It stopped the traversal at the skipped query, so its subqueries were not
folded either. A correlated subquery under `group_by_use_nulls` inside such
a subquery then failed with NOT_IMPLEMENTED (can't find correlated column),
where master returns rows. The skip now covers only the query's own
expressions, and each nested query decides for itself.
It also fired when the keys that become equal are in the same grouping
sets:
SELECT (SELECT c0) FROM t0
GROUP BY GROUPING SETS ((if(1, c0, 0), if(1, c0, 2)), ())
Merging such keys changes neither the grouping sets nor any value, and
without the fold the correlated read of c0 failed with NOT_IMPLEMENTED
where master returns rows. The skip now requires two keys that become
equal to be in different grouping sets, which any two ROLLUP or CUBE keys
are.
It compared keys without aliases, while the planner tells apart the
columns of two sources that differ only in alias. With `s2` and `s3` the
same subquery under two aliases, it took
if(0, s2.b, if(0, s2.b, s1.a)), if(0, s3.b, if(0, s3.b, s1.a))
for one key, so folding both to `s1.a` lost CUBE and ROLLUP grouping sets,
and it took the folded keys `s1.a` and `s2.a` for one key, so it skipped a
query that merges nothing. Keys are now compared as the planner compares
them: without the aliases in the expression, and with each column named
after the unique alias of its source.
Hashing a column hashed its whole source as well, so the check made the
analysis of 1200 keys from one subquery take 0.91 s instead of 0.61 s
(2.76 s instead of 1.57 s for 2400). Naming the columns after their
sources removes that: 0.62 s and 1.58 s, also when the keys can fold.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Build profile diff (arm_release)Commit See the job log for details. |
…tiIfPass
With `group_by_use_nulls`, a clause that reads a ROLLUP/CUBE/GROUPING SETS
key after the aggregation reads a copy of the key that is made Nullable.
IfChainToMultiIfPass compared the type of the `multiIf` with that Nullable
type, so it rewrote an `if` chain in the key but not in the copy. The copy
then has another name than the key and is computed from the columns it
reads instead of being read from the aggregation: the query fails with
NOT_FOUND_COLUMN_IN_BLOCK, or, when those columns are other keys, returns
the value of the chain where the key is rolled up:
SELECT a, b, if(a = 'x', a, if(b = 'y', b, a)) AS k, count()
FROM (SELECT 'x' AS a, 'w' AS b) GROUP BY ROLLUP(a, b, k) ORDER BY ALL
SETTINGS group_by_use_nulls = 1, optimize_if_chain_to_multiif = 1
returned `x w x` twice and `x \N x` instead of `x w \N` and `x \N \N`
(26.3 to 26.9 and master). The pass now compares with the type of the
function itself and keeps the copy Nullable, as ComparisonTupleEliminationPass
does since ClickHouse#96426.
The ROLLUP/CUBE/GROUPING SETS skip in IfConstantConditionPass leaves such a
chain in place when folding it would merge two keys, so without this
`ROLLUP(a, if(0, b, if(0, b, a)))` failed with NOT_FOUND_COLUMN_IN_BLOCK
under optimize_if_chain_to_multiif = 1, where master returns rows.
This is the `if` chain query of ClickHouse#103419; its `multiIf` query
(MultiIfToIfPass) is not changed.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ToIfPass`
With `group_by_use_nulls`, a clause that reads a `ROLLUP`/`CUBE`/`GROUPING SETS`
key after the aggregation reads a copy of the key that is made `Nullable`.
`MultiIfToIfPass` compared the type of the new `if` with that `Nullable` type,
so it rewrote a three-argument `multiIf` key but not its copy. The copy then
has another name than the key and is computed again from its arguments: the
query fails with `NOT_FOUND_COLUMN_IN_BLOCK`, or, when those arguments are
other keys, returns their value where the key is rolled up:
SELECT number, multiIf(number > 0, number, 0) AS k, count()
FROM numbers(3) GROUP BY ROLLUP(number, k) ORDER BY ALL
SETTINGS group_by_use_nulls = 1
returned `0 0` twice and `\N 0` instead of `0 \N` and `\N \N` (26.3 to
26.9 and master). The pass now compares with the type of the function
itself; the node is rewritten in place, so the copy stays `Nullable`, as
`ComparisonTupleEliminationPass` does since ClickHouse#96426. ClickHouse#122512 does the same
for `IfChainToMultiIfPass`, the `if` chain query of ClickHouse#103419.
Part of ClickHouse#103419.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tantConditionPass` folds the keys, renumber tests
| registerNullableGroupByKeys(nullable_group_by_keys, scope); | ||
| /// Only if `IfConstantConditionPass` folds the keys of this query, so that the collapsed columns exist after aggregation. | ||
| if (!ifConstantConditionFoldingMergesGroupingKeys(query_node_typed, scope.context)) | ||
| registerCollapsedGroupByKeyColumns(nullable_group_by_keys, scope); |
There was a problem hiding this comment.
This guard only rules out the "folding would merge grouping sets" case; it still registers collapsed columns for keys that IfConstantConditionPass never folds at all because the condition is not constant. For example, with group_by_use_nulls = 1:
SELECT (SELECT c0)
FROM (SELECT 1::Bool AS c0, 1::UInt8 AS c1) t0
GROUP BY if(c1 = 0, c0, false) WITH ROLLUP;registerConstantConditionBranchColumns still adds c0, resolveExpressionNode converts the correlated c0 to Nullable, and the query only dies later in PlannerCorrelatedSubqueries because the outer header still contains only the written key if(c1 = 0, c0, false), not c0. So the analyzer is still promising a collapsed-key output that the pass does not produce. The registration here needs a per-key proof that the condition will actually fold, or the unfolded path needs to materialize the collapsed column explicitly.
| for (size_t i = 1; i < 3; ++i) | ||
| { | ||
| if (arguments[i]->getNodeType() == QueryTreeNodeType::COLUMN) | ||
| scope.nullable_collapsed_group_by_key_columns.insert(arguments[i]->clone()); |
There was a problem hiding this comment.
nullable_collapsed_group_by_key_columns is keyed by QueryTreeNodePtrWithHashIgnoreAliases, and ColumnNode::isEqualImpl compares only column name and type, not source identity. That means this new path will treat same-scope columns from different sources as the same collapsed key. A query like
SELECT (SELECT s2.a)
FROM (SELECT 1::UInt8 AS a) AS s1, (SELECT 2::UInt8 AS a) AS s2
GROUP BY if(1, s1.a, 0) WITH ROLLUP
SETTINGS group_by_use_nulls = 1;now matches the s1.a entry here when resolving the correlated s2.a, even though aggregation never groups by s2.a. The planner later still cannot supply s2.a and rejects the query. This needs a source-aware key (for example the same source-renaming trick used in cloneForComparison, or a container keyed by source pointer + name/type) instead of a source-blind ColumnNode set.
CI finish ledger - a72a6b0Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
CIDB has no other Session id: cron:our-pr-ci-monitor:20261013-063008 |
852cfef
|
@groeneai @fm4v — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
After `GROUP BY` only the keys and the aggregates exist, and the planner matches a subexpression to a key column by its action name. Two passes dissolved a key node into its arguments in such an expression, so the planner recomputed it from the arguments: those either do not exist after aggregation (`NOT_FOUND_COLUMN_IN_BLOCK`), or, under `group_by_use_nulls`, are not `NULL` on the subtotal rows where the key is `NULL` (wrong results). - `IfChainToMultiIfPass` spliced every nested 3-argument `if` of an else branch into one `multiIf`, also a key or its `group_by_use_nulls` copy. - `OrderByTupleEliminationPass` split every `ORDER BY tuple(...)`, also a tuple key. The analyzer expands top-level tuple keys, so such a key comes from `IfConstantConditionPass` folding `if(1, tuple(a), tuple(0))`. ClickHouse#122512 made `IfConstantConditionPass` also fold the `Nullable` copy of a constant-condition key, so the constant-condition forms of ClickHouse#125803 and ClickHouse#125804 regressed on master; a bare `if` key nested in a chain, and the `group_by_use_nulls = 0` forms, were already broken on 26.3 - 26.9. Both passes now ask `isGroupByKeyAfterAggregation`: the node is a copy on which `convertToNullable` was called (new `FunctionNode::isConvertedToNullable`, which also covers an `Array` copy whose type cannot become `Nullable`), or equal to a key by `compareGroupByKeys`. `IfChainToMultiIfPass` rewrites nodes while it walks the query, and with the identifier resolve cache a key node is shared with its references, so it classifies the query's `if` nodes by pointer when it enters the query, before rewriting it, and only when the setting is on and the query has an `if` key. The check for the copy's own rewrite now uses the same flag instead of comparing result types. Closes ClickHouse#125803 Closes ClickHouse#125804 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Backport #122512 to 26.9: Fix constant-condition `if`/`multiIf` GROUP BY keys with the identifier resolve cache and `group_by_use_nulls`
Resolve the 26.3 conflicts of the cherry-pick of #125828: - IfChainToMultiIfPass.cpp: keep the 26.3 "result type changed" return. The conflicting master hunk changes the `group_by_use_nulls` multiIf rewrite that #122512 added; 26.3 does not have #122512, so there is nothing to change there. All other hunks of #125828 apply as is. - OptimizeKeyExpressionsUtils.{h,cpp}: the files do not exist on 26.3 (master added them in the GROUP BY passes refactor). Add them with only the two helpers #125828 introduces, getGroupByKeys and isGroupByKeyAfterAggregation; compareGroupByKeys already exists in Analyzer/ValidationUtils.h on 26.3. - 05397 test: `SET enable_analyzer = 1` for the 26.3 old analyzer jobs, and drop `enable_identifier_resolve_cache = 1` from one statement (the setting does not exist on 26.3). The reference is unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Closes: #122404
Related: #106377
Related: #100173
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
NOT_FOUND_COLUMN_IN_BLOCKfor a constant-conditionif/multiIfGROUP BYkey reused through an alias withenable_identifier_resolve_cache(default since 26.6) or read back undergroup_by_use_nulls, lost grouping sets when such a key collapses to another key, aBad castlogical error for a correlated subquery reading the column a key collapses to, andNOT_FOUND_COLUMN_IN_BLOCKor wrong values for anifchain key undergroup_by_use_nullsandoptimize_if_chain_to_multiif. Closes #122404.Description
On 26.6.8.7 to 26.9,
SELECT <nested constant-condition multiIf> AS r1 ... GROUP BY r1 ORDER BY r1fails withNOT_FOUND_COLUMN_IN_BLOCK. On 26.3 to 26.9, a correlated(SELECT c0)withGROUP BY if(1, c0, false) WITH ROLLUPandgroup_by_use_nulls = 1throws theBad castlogical error (STID 1499-5613).Cause.
IfConstantConditionPassfolded top-down, every other level of a chain per visit, and the identifier resolve cache shares one node between theGROUP BYkey and itsORDER BY/HAVINGreferences, folded once per reference. Undergroup_by_use_nullsit collapsed a key but not itsNullablecopies, and a correlated reference to the branch column stayed non-Nullable.Change. The pass folds bottom-up (idempotent) and folds a key's
Nullablecopy like the key (as #96426 did), except where that would mergeROLLUP/CUBE/GROUPING SETSkeys of different grouping sets (#117904).IfChainToMultiIfPassnow rewrites such a copy too; rewriting only anifchain key fails (#103419) or returns wrong values (26.3 to 26.9). The analyzer makes a correlated reference to the collapsed columnNullable. It supersedes #117241. Sibling passes (e.g.SumIfToCountIf) need their own fixes (#108553 declined cloning).Validation.
05386(the issue's query) and05385(#117241's test plus 22 statements) fail on master and pass 50 randomized runs; no new failures in 1050 related tests.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/122512]
Version info
26.10.1.2367-master(included in26.10and later)26.9.33.14