Skip to content

Fix wrong results with group_by_use_nulls for a key that uses another key in several places - #131726

Merged
PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:group-by-use-nulls-shared-sub-key
Nov 19, 2026
Merged

PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:group-by-use-nulls-shared-sub-key

Conversation

@groeneai

@groeneai groeneai commented Nov 15, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #125846

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 wrong results with group_by_use_nulls = 1 and ROLLUP, CUBE or GROUPING SETS when a GROUP BY key uses another key in several places, for example if(x = 1 OR x = 2, 'a', 'b') grouped together with x. The key was computed again from the NULL of the inner key, with a non-Nullable type, instead of being read as the key.

Description

On 26.8, SELECT x, if((x = 1) OR (x = 2) OR (x = 3), 'a', 'b') AS e, count() FROM (SELECT number % 4 AS x FROM numbers(8)) GROUP BY ROLLUP(e, x) SETTINGS group_by_use_nulls = 1 returns b for e in every row where x is NULL: the a subtotal row and the grand-total row show b instead of a and NULL, and toTypeName(e) is String. 26.3 is correct; 26.6, 26.8 and 26.10 are not. enable_identifier_resolve_cache = 0 gives the right result.

Root cause: the identifier resolve cache makes every reference to x inside the key one node. registerNullableGroupByKeys builds the key's shape with Nullable sub-keys from key->clone(), which keeps that sharing, and convertNestedGroupByKeysToNullable converts the shared x in place on its first visit. The other parents of that node (x = 2, x = 3) are then not re-resolved and keep a non-Nullable type, so the shape matches no expression and the projection is not replaced by the key. With the OR chain kept (optimize_min_equality_disjunction_chain_length = 1000), reading such a column hits a LOGICAL_ERROR in debug builds.

Change: convertNestedGroupByKeysToNullable copies a node held by several parents before changing it (use_count() > 1, as in LogicalExpressionOptimizerPass), so each reference is converted as in the tree built without the cache.

Test: ROLLUP, CUBE, GROUPING SETS, an inline key, HAVING, an alias above the key, a key inside a key, and the outer read; the reference equals the output with the cache off. It fails on master and passes with the fix (50 randomized runs). The other 135 group_by_use_nulls / identifier cache / ROLLUP / CUBE / GROUPING SETS tests give the same results as on master.

Found while reviewing #125846 (comment).


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

Version info

  • Merged into: 26.11.1.2855-master (included in 26.11 and later)

With `enable_identifier_resolve_cache` (the default), every reference to
an identifier inside a GROUP BY key resolves to the same node, so a key
such as `if((x = 1) OR (x = 2), 'a', 'b')` grouped together with `x` holds
one `x` node under several parents. `registerNullableGroupByKeys` builds
the key's "sub-keys already Nullable" shape from `key->clone()`, which
keeps that sharing, and `convertNestedGroupByKeysToNullable` converted the
shared `x` in place on its first visit. Later parents of the same node
then saw an already converted `x`, did not match it as a key, and were not
re-resolved, so the shape kept stale non-Nullable types and matched no
resolved expression. The projection, HAVING and ORDER BY then computed the
key again from the NULL of `x`, typed as the non-Nullable key: wrong rows
for ROLLUP / CUBE / GROUPING SETS, and with the OR chain kept a header
type mismatch that aborts a debug build in `count`.

Copy a node that several parents hold before changing it in place
(copy-on-write, the same idiom as LogicalExpressionOptimizerPass). Inside
the key clone a node's use count is the number of parent slots holding
it, so a node is now changed only while one parent owns it, and every
reference is converted exactly as in the tree that is built with the
cache off. A copy only "when seen again" is not enough: the first visit
has already changed the shared node by then.

Regression since 26.6 (ClickHouse#88043 cache, ClickHouse#107050 exact key shapes); 26.3 is
correct. Found while reviewing ClickHouse#125846.

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 (2 nits, no change).

# Sev Finding Verdict Evidence / action
1 ⚠️ The test also passes with enable_identifier_resolve_cache = 0, so it does not prove the copy path runs DISAGREE With the cache off there is no shared node and the code without the copy is already correct, so nothing can regress there; the reference is that cache-off output on purpose. With the cache on, removing the copy fails queries 1-7 and aborts query 8 in a debug build; a "copy only when seen again" variant fails all 8. toTypeName(e) checks that the projection is the key's Nullable copy.

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

Session id: cron:clickhouse-review-slot-9:20261115-031000

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse local --queries-file 05768_group_by_use_nulls_key_shares_another_key.sql on master b7a54003d: queries 1-7 give wrong rows or String instead of Nullable(String), query 8 aborts a debug build (bad assert_cast in count), every run.
b Root cause explained? The identifier resolve cache makes every reference to x inside key e one node. registerNullableGroupByKeys builds the Nullable-sub-key shape from key->clone(), which keeps the sharing; convertNestedGroupByKeysToNullable converts the shared x in place on its first visit, so the other parents (x = 2, x = 3) are not re-resolved and keep non-Nullable types. The shape matches no expression, so the projection recomputes e from the NULL of x.
c Fix matches root cause? Yes. The in-place conversion now copies a node held by several parents first (use_count() > 1, the idiom of LogicalExpressionOptimizerPass), so each reference converts as without the cache. No guard and no cache change.
d Test intent preserved / new tests added? New test 05768_group_by_use_nulls_key_shares_another_key (8 queries); its reference equals the output with the cache off and matches a materialized-column oracle. No existing test changed.
e Both directions demonstrated? Yes. Base: 7 queries differ, query 8 aborts (runner: server died). Fix: output identical to the reference, 50/50 randomized runs OK. A "copy only when seen again" variant still fails every query, so the copy has to test sharing on the first visit.
f Fix is general across code paths? convertNestedGroupByKeysToNullable is the only recursive in-place conversion over a cloned key. All key kinds (ROLLUP, CUBE, GROUPING SETS, inline, alias, positional) and all use sites (projection, HAVING, ORDER BY) go through the same registration and lookup.
g Fix generalizes across inputs (params/datatypes/wrappers)? Measured if over OR/AND, multiIf, `
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change. The result type changes from String to Nullable(String) only where it was wrong, matching the cache-off result and 26.3.
i Invariants and contracts preserved? A node of the key clone is changed only while one parent holds it, and the clone is local to the call. The registered shape now equals the tree that use-site resolution builds. No locks, no early returns changed. The 135 related stateless tests give the same results as on master.

Session id: cron:clickhouse-impl-slot-4:20261115-021100

@clickhouse-gh

clickhouse-gh Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9b6ba1f]

Summary: ✅


AI Review

Summary

The PR fixes incorrect values and result types with group_by_use_nulls = 1 when a grouping expression references another key several times. Copying shared nodes before conversion prevents sibling expressions from retaining stale types. No actionable findings. The regression covers ROLLUP, CUBE, GROUPING SETS, aliases, HAVING, and outer reads, and passes in Fast test at the reviewed head. Validation relies on code tracing and existing CI results; no local build or test run was performed.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default can be tested Allows running workflows for external contributors comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). labels Nov 15, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - c1b64e4

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
Upgrade check (amd_release) / Logical error: Context has expired (STID: 1805-3f9b) not from this PR (it changes only the analyzer): the stress phase runs the previous release v26.10.4.207-stable before this PR's build is installed, and that server aborted in FunctionKQLMultiply::executeImpl (FunctionKQLMultiply.cpp:83, a weak context read at execution). The frame addresses are identical on 5 other PRs since 2026-11-14 17:07Z, so it is the same downloaded binary #131363 (external, merged; not in a 26.10 release yet)
Upgrade check (amd_release) / Cannot submit the mutation that has to survive the upgrade same server abort, Connection refused #131363 (external, merged; not in a 26.10 release yet)
Upgrade check (amd_release) / Cannot list the mutations left unfinished by the stress phase same server abort, Connection refused #131363 (external, merged; not in a 26.10 release yet)
Upgrade check (amd_release) / Cannot count the mutations left unfinished by the stress phase same server abort, Connection refused #131363 (external, merged; not in a 26.10 release yet)
Upgrade check (amd_release) / Cannot list the row policies left by the stress phase same server abort, Connection refused #131363 (external, merged; not in a 26.10 release yet)
Upgrade check (amd_release) / Cannot run the mutation entries left behind by the killed mutations same server abort, Connection refused #131363 (external, merged; not in a 26.10 release yet)
Build profile diff infra, not from this PR (no ci/ file in the diff): every readiness probe to the CI logs cluster hit Read timed out. (read timeout=3), so has_pr_data raised LogClusterNotReady: the endpoint never became ready. The same error hit 10 other PRs between 04:43Z and 05:52Z #129675 (mine, open)

Session id: cron:our-pr-ci-monitor:20261115-063013

@clickhouse-gh

clickhouse-gh Bot commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 9b6ba1f32 with master 82024f195 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

7 translation units recompiled, 25 s compile time in total, 7 of them have a recent master baseline.

Job report

@PedroTadim
PedroTadim added this pull request to the merge queue Nov 19, 2026
Merged via the queue into ClickHouse:master with commit d981aec Nov 19, 2026
193 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 19, 2026
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-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants