Skip to content

Fix constant-condition if/multiIf GROUP BY keys with the identifier resolve cache and group_by_use_nulls - #122512

Merged
fm4v merged 9 commits into
ClickHouse:masterfrom
groeneai:fix-if-constant-condition-fold-bottom-up
Oct 14, 2026
Merged

fm4v merged 9 commits into
ClickHouse:masterfrom
groeneai:fix-if-constant-condition-fold-bottom-up

Conversation

@groeneai

@groeneai groeneai commented Sep 27, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #122404
Related: #106377
Related: #100173

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

Fixed NOT_FOUND_COLUMN_IN_BLOCK for a constant-condition if/multiIf GROUP BY key reused through an alias with enable_identifier_resolve_cache (default since 26.6) or read back under group_by_use_nulls, lost grouping sets when such a key collapses to another key, a Bad cast logical error for a correlated subquery reading the column a key collapses to, and NOT_FOUND_COLUMN_IN_BLOCK or wrong values for an if chain key under group_by_use_nulls and optimize_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 r1 fails with NOT_FOUND_COLUMN_IN_BLOCK. On 26.3 to 26.9, a correlated (SELECT c0) with GROUP BY if(1, c0, false) WITH ROLLUP and group_by_use_nulls = 1 throws the Bad cast logical error (STID 1499-5613).

Cause. IfConstantConditionPass folded top-down, every other level of a chain per visit, and the identifier resolve cache shares one node between the GROUP BY key and its ORDER BY/HAVING references, folded once per reference. Under group_by_use_nulls it collapsed a key but not its Nullable copies, and a correlated reference to the branch column stayed non-Nullable.

Change. The pass folds bottom-up (idempotent) and folds a key's Nullable copy like the key (as #96426 did), except where that would merge ROLLUP/CUBE/GROUPING SETS keys of different grouping sets (#117904). IfChainToMultiIfPass now rewrites such a copy too; rewriting only an if chain key fails (#103419) or returns wrong values (26.3 to 26.9). The analyzer makes a correlated reference to the collapsed column Nullable. It supersedes #117241. Sibling passes (e.g. SumIfToCountIf) need their own fixes (#108553 declined cloning).

Validation. 05386 (the issue's query) and 05385 (#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

  • Merged into: 26.10.1.2367-master (included in 26.10 and later)
  • Backported to: 26.9.33.14

groeneai and others added 5 commits September 26, 2026 15:47
…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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
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).

# Sev Finding Verdict Evidence / action
1 ❌ A key whose condition is a constant-condition multiIf, e.g. GROUP BY if(multiIf(1, 1, c1), c0, false), collapsed to a column that was not registered, so a correlated (SELECT c0) still hit the Bad cast (own review) AGREE, fixed covered by registering every branch column (#6); the shape is in 05271
2 ⚠️ 05272 does not prove that the cache shares the node (Gate B) DISAGREE the full-fold statements do not depend on the cache and are red on master (2 instead of 0, 4 6 instead of 0 0); the issue query is red on master with the cache on and green with it off
3 ⚠️ 05271 pinned two wrong results of master (the constant ROLLUP key of #120835 on the super-aggregate row, a missing row under GROUPING SETS ((k), ())) and kept statements this change cannot affect (own review) AGREE, fixed those statements are removed; GROUPING SETS stays covered by the reported query
4 💡 comments in 05271 described the implementation instead of the tested behavior (own review) AGREE, fixed rewritten
5 💡 a comment on the pinned settings in 05271 claimed they decide whether a key collapses (own review) AGREE, fixed comment corrected
6 ❌ a condition can become constant in an earlier pass (optimize_inverse_dictionary_lookup replaces a dictionary lookup that matches no key with 0), so the key collapses to a column that was not registered and the correlated reference hits the Bad cast (Gate B) AGREE, fixed every branch column of the key's if/multiIf is registered, conditions ignored; dictionary shapes added to 05271
7 💡 the full-fold EXPLAIN count in 05272 misses a residual multiIf under the randomized optimize_if_chain_to_multiif (own review, Gate B) AGREE, fixed multiIf is counted too
8 💡 05271 sets the legacy alias allow_experimental_correlated_subqueries (own review, Gate B) AGREE, fixed canonical name
9 ❌ with group_by_use_nulls and ROLLUP, the bottom-up fold collapsed a key such as if(0, b, if(0, b, a)) to a but not the Nullable copies the projection and ORDER BY read, so master's rows became NOT_FOUND_COLUMN_IN_BLOCK (own review, Gate B, measured) AGREE, fixed the pass folds such a copy like the key and keeps it Nullable, as ComparisonTupleEliminationPass does (#96426); this also fixes the single-level key, and both shapes are in 05271
10 💡 four of the pinned settings at the top of 05271 cannot affect these statements; the NOT_IMPLEMENTED statements pin a planner limitation (own review) noted, not blocking left as they are
11 ❌ folding every level can make two ROLLUP/CUBE/GROUPING SETS keys equal, e.g. ROLLUP(a, if(0, b, if(0, b, a))), and the planner merges equal keys, so a grouping set was lost where master kept it (own review, Gate B, measured) AGREE, fixed the pass leaves a query unfolded when folding would make two of its keys equal; ROLLUP, CUBE, GROUPING SETS and group_by_use_nulls statements added to 05271, equal to master
12 ⚠️ 05271 asserted the merged two-row result of GROUP BY if(1, c0, false), c0 WITH ROLLUP (own review, Gate B) AGREE, fixed it now expects the three grouping sets, as with a key that does not fold
13 ⚠️ a key whose condition the pass folds first, e.g. if(multiIf(1, 1, c1), 'x', a), becomes a constant, which keeps its value on the ROLLUP super-aggregate row (Gate B) DISAGREE measured: master returns the same rows, since its plan folds that key to a constant too (the open #120835)
14 ⚠️ with the query left unfolded, a correlated read of the column that two keys collapse to (not itself a key) finds no key, e.g. SELECT (SELECT c0) FROM (SELECT 1::UInt8) t0(c0) GROUP BY GROUPING SETS ((if(1, c0, 0), if(1, c0, 2))): predicted NOT_IMPLEMENTED, where master returns the row (own review; predicted from the code, not measured) noted, not blocking bounce cap; needs two keys that collapse to one column that is not a key, plus a correlated read of it; under ROLLUP/CUBE master returns the merged rows of #117904
15 ⚠️ a query left unfolded reaches IfChainToMultiIfPass, which rewrites the key but not its Nullable copy: with the non-default optimize_if_chain_to_multiif = 1 and group_by_use_nulls = 1, ROLLUP(a, if(0, b, if(0, b, a))) returns rows on master, NOT_FOUND_COLUMN_IN_BLOCK here (own review, measured) noted, not blocking the pass-side defect is the open #103419 (master fails a 4-level chain the same way, which this change fixes); a fix task is created

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On master the issue query and SELECT if(0, s, if(0, s, if(0, s, if(0, s, s)))) AS r FROM t GROUP BY r ORDER BY r fail with Code: 10 on every run; SELECT (SELECT c0) FROM (SELECT 1::Bool) t0(c0) GROUP BY if(1, c0, false) WITH ROLLUP SETTINGS group_by_use_nulls = 1 fails with the Bad cast logical error on every run.
b Root cause explained? IfConstantConditionPass folded before visiting the arguments, so one visit folded every other level; the identifier resolve cache makes the GROUP BY key and its ORDER BY/HAVING references one node, visited once per reference, so it was folded deeper than the projection copy. Separately, the pass collapses such a key to its branch after analysis, so the aggregation outputs that column as Nullable while a correlated reference to it kept the plain type. With group_by_use_nulls, the pass also never folded the Nullable copies of a key that the other clauses read, so they stopped matching a folded key. Folding every level could also make two ROLLUP/CUBE/GROUPING SETS keys equal, which the planner merges.
c Fix matches root cause? Yes. The pass folds after the arguments (fixpoint in one visit, revisits are no-ops). A Nullable copy of a key is folded like the key and stays Nullable, as in ComparisonTupleEliminationPass (#96426). Every column a key may collapse to is registered for correlated references only; the general key map and every non-correlated resolution stay as on master (66 non-correlated probes are byte-identical with and without the Nullable-copy fold). A query whose ROLLUP/CUBE/GROUPING SETS keys folding would make equal is left unfolded.
d Test intent preserved / new tests added? 05272: the issue's reproducer on MergeTree plus the chain under ORDER BY, HAVING, LIMIT BY, GROUPING SETS and EXPLAIN fold counts. 05271: #117241's test, trimmed to what this change can affect, with the nested key positive, plus the repeated-column, multiIf-condition, dictionary-condition, not-taken-branch and key-onto-key statements. Each new assertion fails on master or on the fold alone.
e Both directions demonstrated? Yes. Master: 05272 fails (Code: 10), 05271 aborts the debug server (Bad cast), 16 of its row statements differ. Fix: both pass, 50/50 randomized runs each and 5/5 without randomization.
f Fix is general across code paths? The fold rule has one site. The collapsed column has one consumer, the correlated-column lookup. Other passes have the same interaction with the cache (for example SumIfToCountIf); they are separate sites, not changed here.
g Fix generalizes across inputs (params/datatypes/wrappers)? if, multiIf, multiIf kept, false branch, nested chains of 2-5 levels, a key whose condition is a constant-condition multiIf or becomes constant in optimize_inverse_dictionary_lookup; Bool, UInt8, UInt64, String, Nullable, LowCardinality (not collapsed); ROLLUP, CUBE, GROUPING SETS, WITH TOTALS, grouping(), two keys, two keys that fold onto each other; non-collapsing keys; an uncorrelated reference; a not-taken branch that reads a column that is not a key; cache on and off; a JOIN.
h Backward compatible? (maintainer-approved exception only) Yes, no setting or format change, with the two residual regressions listed in the review comment. Results also change for ROLLUP/CUBE/GROUPING SETS whose keys become equal when folded: every grouping set is kept (master merged a single-level key). Mixed-version remote() aggregation was measured for the fold, not for the queries the pass now skips.
i Invariants and contracts preserved? The fold keeps each node's result type, so every parent stays valid. The only in-place change to an existing node converts a correlated column node to Nullable at its source scope, the path already taken for a correlated reference to a written key. 877 related tests show no new failures.

Session id: cron:clickhouse-impl-slot-5:20260926-192300

@clickhouse-gh

clickhouse-gh Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a72a6b0]

Summary: ❌

job_name test_name status info comment
Integration tests (arm_binary, 1/4) FAIL
test_storage_iceberg_concurrent/test_concurrent_reads.py::test_concurrent_reads FAIL cidb IGNORED

AI Review

Summary

This PR fixes the original constant-condition if/multiIf alias/cache bug by folding bottom-up, keeping the group_by_use_nulls copies in sync, and avoiding the ROLLUP/CUBE/GROUPING SETS key-merge regression. The remaining problem is that the new correlated-column registration for collapsed keys is still too broad: it now blesses columns that the post-analysis passes do not actually materialize, so some queries are accepted during analysis and only fail later in decorrelation.

Findings

❌ Blockers

  • [src/Analyzer/Resolve/QueryAnalyzer.cpp:4901] registerCollapsedGroupByKeyColumns runs whenever the query is not in the grouping-set-merge skip case, but that is much weaker than “IfConstantConditionPass will fold this key”. Non-constant keys such as if(c1 = 0, c0, false) still register c0 as a collapsed key under group_by_use_nulls, so a correlated (SELECT c0) is accepted here even though the outer aggregation output still has only the written if(...) key and later decorrelation rejects it.
  • [src/Analyzer/Resolve/QueryAnalyzer.cpp:4828] nullable_collapsed_group_by_key_columns uses source-blind ColumnNode equality, so the new lookup cannot distinguish s1.a from s2.a when they have the same name and type in one scope. A key that collapses to s1.a therefore also authorizes correlated reads of unrelated s2.a, which the planner still cannot provide from the outer aggregation output.
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.

@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 27, 2026
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]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit a72a6b0781bf1803211e226f1313a9da3a9cce81 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

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]>
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
grantholly-clickhouse pushed a commit to grantholly-clickhouse/ClickHouse that referenced this pull request Oct 10, 2026
…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]>
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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a72a6b0

Every failure below has an owner: a fixing PR (mine 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.

Check / test Reason Owner / fixing PR
Integration tests (arm_binary, 1/4) / test_storage_iceberg_concurrent/test_concurrent_reads.py::test_concurrent_reads not from this PR (it only changes analyzer passes for constant if/multiIf GROUP BY keys): CREATE TABLE fails with Code 107 (metadata file does not exist) because the test_storage_delta/test_writes_interop.py module ran in the same job and its reused Spark JVM kept an s3a filesystem bound to that module's MinIO, so Spark wrote the Iceberg metadata elsewhere; the fix merged after the tree of this run was pinned #125448 (mine, merged)
Mergeable Check, PR praktika rollups of the row above #125448 (mine, merged)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261013-063008

@fm4v
fm4v added this pull request to the merge queue Oct 14, 2026
Merged via the queue into ClickHouse:master with commit 852cfef Oct 14, 2026
175 of 177 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 14, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @fm4v — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Both #125803 and #125804 are fixed in #125828.

alexey-milovidov pushed a commit to tripleaceme/ClickHouse that referenced this pull request Oct 19, 2026
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]>
@novikd novikd added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Nov 19, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 19, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 19, 2026
Backport #122512 to 26.9: Fix constant-condition `if`/`multiIf` GROUP BY keys with the identifier resolve cache and `group_by_use_nulls`
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 20, 2026
alexey-milovidov pushed a commit that referenced this pull request Nov 22, 2026
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]>
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 comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

NOT_FOUND_COLUMN_IN_BLOCK with enable_identifier_resolve_cache=1: GROUP BY alias of a constant-condition multiIf over a JOIN

7 participants