Skip to content

Fix wrong result when a sumIf alias is referenced more than once - #122726

Merged
fm4v merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-sum-if-to-count-if-shared-alias
Nov 16, 2026
Merged

fm4v merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-sum-if-to-count-if-shared-alias

Conversation

@groeneai

@groeneai groeneai commented Sep 28, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #122404
Related: #122512
Related: #108553

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 a wrong result when an alias of sumIf(k, cond) or sum(if(cond, 0, k)) with a constant k other than 1 is referenced more than once, for example SELECT sumIf(2, cond) AS r, r + 0, r + 1 or HAVING r > 3 AND r < 15: every reference after the first returned countIf without the factor k.

Description

On 26.6 to 26.9, SELECT sumIf(2, number > 1) AS r, r + 0, r + 1 FROM numbers(12) returns 20 20 11 instead of 20 20 21, and SELECT sumIf(2, number > 1) AS r FROM numbers(12) HAVING r > 3 AND r < 15 returns 20 instead of no rows. 26.3 is correct. It also reproduces on play.clickhouse.com.

Cause. With enable_identifier_resolve_cache (default since 26.6) every reference to an alias is the same query tree node. SumIfToCountIfPass rewrote that node in place into countIf(cond) and wrapped only the reference it was visiting in k * ..., so the other references kept the bare countIf and lost k.

Change. The pass no longer modifies the visited node: it builds a new countIf (and multiply) node for each reference, as RewriteAggregateFunctionWithIfPass already does. This follows #108553, where cloning in the cache was declined and the pass was made independent of node sharing. Found while fixing #122404 (#122512 fixes IfConstantConditionPass).

Validation. The new test fails on master in every statement and passes 50 randomized runs. No new failures in 184 related tests. remote() returns the right values, also with unfixed shards.


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

Version info

  • Merged into: 26.11.1.2450-master (included in 26.11 and later)
  • Backported to: 26.10.5.42

With `enable_identifier_resolve_cache` (default since 26.6) every reference
to an alias resolves to the same query tree node, so in

    SELECT sumIf(2, number > 1) AS r, r + 0, r + 1 FROM numbers(12)
    SELECT sumIf(2, number > 1) AS r FROM numbers(12) HAVING r > 3 AND r < 15

all references share one `sumIf(2, number > 1)` node. `SumIfToCountIfPass`
rewrote the node it visited in place into `countIf(number > 1)` and wrapped
only that reference in `multiply(2, ...)`. Every later reference then saw
`countIf`, failed the `sum`/`sumIf` entry check and kept the bare `countIf`,
so it lost the factor: `r + 1` returned 11 instead of 21, and the HAVING
compared `countIf` with 15 and returned the row. The same happened for
`sum(if(cond, 0, k))` at default settings and for `sum(if(cond, k, 0))`
with `optimize_rewrite_aggregate_function_with_if = 0`.

The pass now leaves the visited node unchanged and assigns a new `countIf`
node (wrapped in `multiply` when the constant is not 1) to each reference,
like `RewriteAggregateFunctionWithIfPass` does. Every reference is rewritten
on its own visit, and the tree with the cache on is the same as with it off.
Cloning shared nodes in the cache was rejected in ClickHouse#108553, which made the
pass it fixed independent of node sharing instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-self PR origin: self-found defect (impact-bar validated) labels Sep 28, 2026
@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).

# Sev Finding Verdict Evidence / action
1 ⚠️ The test statement with sum(if(cond, 0, k)) does not reach the changed branch, because RewriteAggregateFunctionWithIfPass rewrites it first unless optimize_rewrite_aggregate_function_with_if = 0 DISAGREE That pass leaves if(c, 0, 2) alone: both branches are constants, so it takes the second_const_node branch (RewriteAggregateFunctionWithIfPass.cpp:118), which needs the second constant to be NULL or 0, and never tries the first_const_node branch (:162). The unfixed build returns 4 4 3 for this statement with optimize_rewrite_aggregate_function_with_if = 1; the fix returns 4 4 5.

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

Session id: cron:clickhouse-review-self-slot-58:20260928-172600

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. At default settings SELECT sumIf(2, number > 1) AS r, r + 0, r + 1 FROM numbers(12) returns 20 20 11 on every run (also 26.6.8.7, 26.8.10.6, 26.9.1.1629); enable_identifier_resolve_cache = 0 and 26.3 return 20 20 21.
b Root cause explained? The resolve cache makes every reference to the alias one node; the pass turned that node into countIf in place and wrapped only the visited reference in k * ..., so later references lost k.
c Fix matches root cause? Yes. The pass builds a new countIf/multiply node per reference and never mutates the shared one; no guard, no setting, no cache change.
d Test intent preserved / new tests added? New 05293_sum_if_to_count_if_shared_alias: HAVING, grouped HAVING, projection reuse for sumIf, sum(if(c, 0, k)), sum(if(c, k, 0)), plus an EXPLAIN count proving the rewrite still fires at every reference.
e Both directions demonstrated? Yes. The test fails in every statement on the unfixed build and passes on the fix; 50/50 randomized runs pass.
f Fix is general across code paths? All three rewrite branches use one helper; sum(k) FILTER (WHERE c) reaches the same branch. The sibling aggregate rewrites already build fresh nodes and give identical results with the cache on and off.
g Fix generalizes across inputs (params/datatypes/wrappers)? Nullable, LowCardinality, LowCardinality(Nullable), constant and NULL conditions; k from 0 to UInt64 max; empty input; GROUPING SETS, ROLLUP, window, QUALIFY, CTE, scalar subquery, remote(): results with the cache on now equal the cache off results in 87 probe queries.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change; trees without shared nodes are unchanged; a fixed initiator returns the right result with unfixed shards.
i Invariants and contracts preserved? Rewriting one reference no longer changes what another reference evaluates to; the replacement keeps the UInt64 result type; arguments are copied before the old node can be released; early returns unchanged.

Session id: cron:clickhouse-impl-self-slot-57:20260928-142200

@clickhouse-gh

clickhouse-gh Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [72ed40e]

Summary: ✅


AI Review

Summary

This PR fixes the shared-query-tree alias bug in SumIfToCountIfPass by replacing each visited sumIf / sum(if(...)) reference with a fresh rewritten subtree instead of mutating a possibly shared node in place. I did not find new correctness, compatibility, or coverage gaps in the current diff; the added stateless test covers both projection and HAVING reuse and checks that every reference is rewritten.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit 72ed40e.

Metric Baseline Current Δ
Lines 87.90% 87.90% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 26/28 (92.86%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 28, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 28, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 28, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 72ed40eb6 with master 2bfd00884 (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, 8 s compile time in total, 7 of them have a recent master baseline.

Job report

@fm4v
fm4v added this pull request to the merge queue Nov 16, 2026
Merged via the queue into ClickHouse:master with commit 052f762 Nov 16, 2026
150 checks passed
@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 16, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 16, 2026
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 16, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 16, 2026
Backport #122726 to 26.10: Fix wrong result when a `sumIf` alias is referenced more than once
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-self PR origin: self-found defect (impact-bar validated) 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-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants