Skip to content

Fix wrong results and NOT_FOUND_COLUMN_IN_BLOCK for a GROUP BY key inside an if chain or an ORDER BY tuple - #125828

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-group-by-key-in-if-chain-and-order-by-tuple
Oct 19, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-group-by-key-in-if-chain-and-order-by-tuple

Conversation

@groeneai

@groeneai groeneai commented Oct 14, 2026 •

Copy link
Copy Markdown
Collaborator

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

Fix NOT_FOUND_COLUMN_IN_BLOCK and wrong results when a GROUP BY key is used inside an if chain with optimize_if_chain_to_multiif = 1, or is a tuple used in ORDER BY (for example if(1, tuple(a), tuple(0)) AS k ... GROUP BY k ORDER BY k). With group_by_use_nulls = 1, such an if key returned its value instead of NULL in ROLLUP, CUBE and GROUPING SETS subtotal rows. Closes #125803. Closes #125804.

Description

Closes #125803, closes #125804. Related: #122512.

On 26.9.7.6, SELECT if(1, tuple(a), tuple(0)) AS k, count() FROM (SELECT number % 3 AS a FROM numbers(10)) GROUP BY k ORDER BY k throws NOT_FOUND_COLUMN_IN_BLOCK, and with optimize_if_chain_to_multiif = 1 and group_by_use_nulls = 1 an if key nested in another if returns its value instead of NULL in ROLLUP subtotal rows. Since #122512 the constant-condition forms of both issues fail on master too.

After GROUP BY the planner reads a key from the aggregation result by its action name. IfChainToMultiIfPass spliced a nested if that is a key (or its group_by_use_nulls copy) into a multiIf, and OrderByTupleEliminationPass split a tuple key into its elements, so the key was recomputed from arguments that are gone after aggregation, or are not NULL on subtotal rows.

Both passes now keep such a node whole via one helper: the node is a copy marked by convertToNullable (new FunctionNode::isConvertedToNullable, which also covers an Array copy whose type cannot become Nullable), or equals a key by compareGroupByKeys. IfChainToMultiIfPass classifies the query's if nodes before rewriting it, since it changes nodes inside keys and a key can be shared with its references; this costs nothing unless the setting is on and the query has an if key.

LogicalExpressionOptimizerPass (or chains to IN) has the same pattern for keys like x = 1; it is not changed here.

The new test fails on master and passes with the fix, 50/50 with randomized settings; related group_by_use_nulls, ROLLUP, CUBE, GROUPING SETS and multiIf tests pass.

🤖 Generated with Claude Code


Workflow [PR]
Sync PR [sync-upstream/pr/125828]

Version info

  • Merged into: 26.11.1.197-master (included in 26.11 and later)
  • Backported to: 26.10.8.39, 26.9.34.19, 26.3.70.3

groeneai and others added 2 commits October 14, 2026 15:37
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]>
Condense the collectGroupByKeyIfNodes and isGroupByKeyAfterAggregation comments to their invariants.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@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; 1 finding) plus my own cold review (3 nits).

# Sev Finding Verdict Evidence / action
1 💡 Relationship URLs sit inside the template's HTML comment DISAGREE The upstream template itself keeps those lines in its comment; visible Closes #125803, Closes #125804 and Related: #122512 are in the description and changelog entry
2 💡 One ROLLUP test statement has two rows with the same ORDER BY key AGREE, not blocking The rolled-up chunk is always emitted after the aggregated one, so the order is stable; 50/50 runs with randomized settings passed
3 💡 The Nullable-copy check in the chain loop is also covered by the per-query node set AGREE, not blocking Cheap early check, no behavior difference
4 💡 The key check also skips the rewrite in pre-aggregation clauses AGREE, not blocking Only a missed multiIf rewrite there; keys and their copies stay consistent

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

Session id: cron:clickhouse-review-slot-8:20261014-154400

@clickhouse-gh

clickhouse-gh Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [da75a09]

Summary: ✅


AI Review

Summary

Preserves GROUP BY keys and their nullable copies when rewriting if chains and eliminating ORDER BY tuples, preventing missing-column exceptions and incorrect subtotal results. No actionable findings. The regression test matches its reference on the PR binary; 120 additional query comparisons found no semantic discrepancies.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 14, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @nihalzp @novikd, could you review this and add can be tested? IfChainToMultiIfPass spliced a nested if that is a GROUP BY key (or its group_by_use_nulls copy) into a multiIf, and OrderByTupleEliminationPass split a tuple key, so the key was recomputed from arguments that are gone after aggregation; both passes now keep a key whole, using a helper in OptimizeKeyExpressionsUtils.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Not bad, LGTM.

@alexey-milovidov alexey-milovidov self-assigned this Oct 19, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 19, 2026
Merged via the queue into ClickHouse:master with commit 2134b44 Oct 19, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 19, 2026
@novikd novikd added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Nov 20, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 20, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 20, 2026
Backport #125828 to 26.10: Fix wrong results and `NOT_FOUND_COLUMN_IN_BLOCK` for a `GROUP BY` key inside an `if` chain or an `ORDER BY` tuple
clickhouse-gh Bot added a commit that referenced this pull request Nov 20, 2026
Backport #125828 to 26.9: Fix wrong results and `NOT_FOUND_COLUMN_IN_BLOCK` for a `GROUP BY` key inside an `if` chain or an `ORDER BY` tuple
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]>
robot-ch-test-poll2 added a commit that referenced this pull request Nov 22, 2026
Cherry pick #125828 to 26.3: Fix wrong results and `NOT_FOUND_COLUMN_IN_BLOCK` for a `GROUP BY` key inside an `if` chain or an `ORDER BY` tuple
robot-clickhouse added a commit that referenced this pull request Nov 22, 2026
…BLOCK` for a `GROUP BY` key inside an `if` chain or an `ORDER BY` tuple
alexey-milovidov added a commit that referenced this pull request Nov 22, 2026
Backport #125828 to 26.3: Fix wrong results and `NOT_FOUND_COLUMN_IN_BLOCK` for a `GROUP BY` key inside an `if` chain or an `ORDER BY` tuple
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). 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.

group_by_use_nulls tuple GROUP BY key broken by OrderByTupleEliminationPass IfChainToMultiIfPass inlines a group_by_use_nulls key copy, losing NULLs

5 participants