Skip to content

Do not rewrite NULL-preserving aggregates with optimize_rewrite_aggregate_function_with_if - #107430

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-rewrite-aggregate-function-with-if-respect-nulls
Jun 14, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-rewrite-aggregate-function-with-if-respect-nulls

Conversation

@groeneai

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 incorrect results from the optimize_rewrite_aggregate_function_with_if optimization for aggregate functions that preserve NULL payload values (the *_respect_nulls family: anyRespectNulls, first_value_respect_nulls, anyLast_respect_nulls, last_value_respect_nulls). The optimization no longer rewrites f(if(cond, x, NULL)) into the -If form for such functions.

Description

RewriteAggregateFunctionWithIfPass rewrites f(if(cond, NULL, x)) into fIf(x, !cond) and f(if(cond, x, NULL)) into fIf(x, cond). This drops the rows whose payload is NULL, which is only correct for aggregate functions that skip NULL rows.

The *_respect_nulls family keeps NULL payload values, so a NULL row can legitimately be the first/last value of the result. Filtering it out with the -If form silently changed the result, for example on 26.6.1.1:

SELECT anyRespectNulls(if(number % 2 = 0, NULL, number)) FROM numbers(4);
-- returned 1 (wrong); correct answer is NULL (the first value is NULL)

These functions provide their own null adapter: getOwnNullAdapter returns the function itself, which is the general signal (honored by the Null combinator) that the NULL payload must be kept. The pass now skips the rewrite whenever getOwnNullAdapter returns the function itself, so the fix covers the whole family and any future NULL-preserving aggregate. NULL-skipping functions (count, sum, avg, plain any, ...) are unaffected and still optimized.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. SELECT anyRespectNulls(if(number % 2 = 0, NULL, number)) FROM numbers(4) returns 1 on master (wrong) and NULL with the fix. Reproduces every time with optimize_rewrite_aggregate_function_with_if = 1 (the default).
b Root cause explained? The pass rewrites f(if(cond, x, NULL)) -> fIf(x, cond), dropping the rows whose payload is NULL. This is only valid for NULL-skipping aggregates. The *_respect_nulls family keeps NULL payload (its getOwnNullAdapter returns the function itself, so the Null combinator does not wrap it), so the NULL row can be the first/last value. Dropping it via -If silently changed the result.
c Fix matches root cause? Yes. The pass now inspects the resolved aggregate function and skips the rewrite when getOwnNullAdapter(...) returns the function itself, which is the exact, general signal that the function preserves NULL payload.
d Test intent preserved / new tests added? New test 04337_rewrite_aggregate_function_with_if_respect_nulls added. It checks the result values for the whole *_respect_nulls family AND, via EXPLAIN QUERY TREE, that the rewrite is skipped for them while still firing for any/count/sum/avg (no regression).
e Both directions demonstrated? Yes. Built clean master (Build ID 58270996...): repro queries returned 1,1,1,2 (wrong). Built with fix (Build ID 1df0a266..., verified to differ): all return NULL (correct, matches the optimize_rewrite_aggregate_function_with_if = 0 oracle). New test passes 30/30 under randomization; existing 02518, 03132, 03210, 02922_respect_nulls_* all pass.
f Fix is general, not a narrow patch? Yes. Rather than special-casing the four *_respect_nulls names, the fix keys on the general getOwnNullAdapter-returns-self contract, so it automatically covers the whole family and any future NULL-preserving aggregate (e.g. groupFormat from #93201). Functions that override getOwnNullAdapter to return a different NULL-skipping adapter (count, sumCount, ...) are correctly unaffected.

Session id: cron:clickhouse-worker-slot-2:20260613-233400

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @novikd — could you review this? It stops optimize_rewrite_aggregate_function_with_if from rewriting NULL-preserving aggregates (the *_respect_nulls family) into the -If form, which was dropping NULL-payload rows and producing wrong results (#107421). The guard keys on getOwnNullAdapter returning the function itself, so it is general rather than name-based.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jun 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fd2eda7]

Summary: ✅


AI Review

Summary

This PR fixes optimize_rewrite_aggregate_function_with_if so it no longer rewrites aggregates when the if result carries NULL payload rows that the aggregate must still see. The current code addresses the prior issues around zero-argument count, wrapped *_respect_nulls aggregates, and discriminator-NULL Variant/Dynamic values; I do not see a remaining code blocker.

PR Metadata
  • 💡 The Bug Fix category is correct and a changelog entry is required, but the current entry only describes the *_respect_nulls part of the final fix. It should also mention the Variant/Dynamic case now covered for count/any and other aggregates. Suggested replacement:
Fix incorrect results from the `optimize_rewrite_aggregate_function_with_if` optimization when the `if` result contains `NULL` payload rows that must not be filtered out, including `*_respect_nulls` aggregate functions and `Variant`/`Dynamic` values whose `NULL` is stored as a discriminator. The optimization now skips the `-If` rewrite for those cases.
Missing context / blind spots
  • ⚠️ I could not run 04337_rewrite_aggregate_function_with_if_respect_nulls locally because this checkout has no clickhouse build binary, and the current S3 CI report for head fd2eda719fe3db1cbec94af2409829dcfe8b0a9c had no completed test rows yet. A completed CI run or local stateless run would close this gap.
Final Verdict

Status: ✅ Approve

No blocking review findings. Please update the changelog wording to match the final Variant/Dynamic scope, and rely on the still-running CI for execution coverage.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 14, 2026
if (auto aggregate_function = function_node->getAggregateFunction())
{
AggregateFunctionProperties properties;
if (aggregate_function->getOwnNullAdapter(

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.

And what if it has a custom Null Adapter, which is non-default?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The guard treats "custom non-default adapter" and "no adapter" identically: in both cases the rewrite still fires, and that is correct.

The check is pointer identity getOwnNullAdapter(...) == self, so there are exactly three cases an aggregate can fall into, and only the first is NULL-preserving:

  1. Returns the function itself. Only AnyRespectNulls does this (getOwnNullAdapter returns original_function). That is precisely the Null combinator's "do not wrap me, I keep the NULL rows" contract (AggregateFunctionNull.cpp: if (auto adapter = nested_function->getOwnNullAdapter(...)) return adapter;). So returning self is, by construction, the signal that NULL payload is preserved -> we skip the rewrite.

  2. Returns a different, custom (non-default) adapter. This is your question. Every such adapter in the tree is a NULL-skipping AggregateFunctionNull* variant; they differ from the default only in the serialization flag byte (binary-compat), not in null semantics:

    • count -> AggregateFunctionCountNotNullUnary
    • sumCount -> AggregateFunctionNullUnary<false,false> (legacy flag, comment explains it is for state compatibility)
    • intervalLengthSum -> AggregateFunctionNullVariadic<false,false>
    • Distinct / OrFill -> AggregateFunctionNullUnary<false,false> for the sumCount case
    • the If combinator -> AggregateFunctionIfNull* (and *If is excluded earlier by the ends_with("if") guard anyway)
      None of these keep NULL rows, so != self -> rewrite still fires -> correct.
  3. Returns nullptr (the default in IAggregateFunction). The Null combinator then wraps the function with a NULL-skipping AggregateFunctionNull*. != self -> rewrite fires -> correct (sum, avg, min, max, plain any, ...).

So "preserves NULL payload" <=> "getOwnNullAdapter returns the function itself" holds for the whole tree, not just the *_respect_nulls family: a custom non-default adapter is still a NULL-skipping adapter, and the only way to opt out of NULL-skipping is to return self. A hypothetical future aggregate that wants NULL rows kept would have to return itself (that is the only contract the Null combinator honors for "keep my NULLs"), and it would be covered automatically; if it instead returned some other custom adapter, that adapter would itself be doing the NULL-skipping, so firing the rewrite would remain correct.

@groeneai
groeneai force-pushed the fix-rewrite-aggregate-function-with-if-respect-nulls branch from eccc330 to 2890b74 Compare June 14, 2026 01:23
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (update for 2890b74)

# Question Answer
a Deterministic repro? Yes. Crash: SELECT count() FROM numbers(4) SETTINGS optimize_rewrite_aggregate_function_with_if=1 (and count(1)/sum(1)) hit AggregateFunctionCount::getOwnNullAdapter indexing argument_types[0] on empty DataTypes. Wrong results: SELECT anyRespectNulls(if(number%2=0, NULL, number)) FROM numbers(4) returns 1 instead of \N. Both fully deterministic.
b Root cause explained? Two issues. (1) The pass rewrites f(if(cond,x,NULL)) -> fIf(x,cond), dropping NULL-payload rows; valid only for NULL-skipping aggregates. The *_respect_nulls family keeps NULL rows (its getOwnNullAdapter returns the function itself, the Null-combinator "keep my NULLs" contract), so the rewrite silently changed results. (2) The first version of the guard called getOwnNullAdapter before the single-if-argument shape was proven; NormalizeCountVariantsPass rewrites count(1)/sum(1) to zero-argument count, whose adapter indexes argument_types[0] -> OOB on empty DataTypes.
c Fix matches root cause? Yes. (1) Skip the rewrite iff getOwnNullAdapter(...) == self (the precise, general NULL-preserving signal). (2) Move that guard after the function_arguments_nodes.size() == 1 / if_node checks so the adapter is only consulted once the aggregate has exactly one argument.
d Test intent preserved / new tests added? New test 04337_rewrite_aggregate_function_with_if_respect_nulls: result values for the whole *_respect_nulls family (must be \N), EXPLAIN QUERY TREE confirming the rewrite is skipped for them and still fires for any/count/sum/avg, unchanged results for the still-optimized functions, plus zero-argument count()/count(1)/sum(1) regression for the crash.
e Both directions demonstrated? Yes. Without fix (build 58270996): wrong results (1,1,1,2) and the zero-arg-count crash. With fix (build 746954c4): all *_respect_nulls return \N, zero-arg count returns 4 (no crash), countIf/sumIf/avgIf rewrites still fire, count/sum/avg results unchanged. 50/50 under randomization; 12 related rewrite/respect_nulls tests pass.
f Fix is general, not a narrow patch? Yes. The guard keys on the Null-combinator contract (getOwnNullAdapter returns self), not on specific function names, so it covers the entire *_respect_nulls family and any future NULL-preserving aggregate (e.g. groupFormat from #93201) automatically. Verified across every getOwnNullAdapter implementation in the tree: AnyRespectNulls is the only one that returns self; all others return nullptr or a different NULL-skipping AggregateFunctionNull* adapter, so the rewrite correctly still fires for them.

Session id: cron:clickhouse-worker-slot-3:20260614-011100

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI update on 2890b74328b9 (our-pr-ci-monitor): a PR-caused failure appeared, moving back to fix it before review.

  • Fast test / 01710_minmax_count_projection -> FAIL, Code 49 LOGICAL_ERROR. PR-caused: 0 master failures in 7d, only this PR's head hits it; the test exercises the aggregate-with-projection rewrite path that RewriteAggregateFunctionWithIfPass operates on. The zero-arg-count crash-fix reorder on this commit appears to have changed rewrite behavior on a projection query. Investigating + fixing now.
  • Bugfix validation (functional tests) markers (OOM in dmesg, S3_ERROR No such key, Lost forever for SharedMergeTree, Lost s3 keys, Exception in test runner) -> NOT PR-caused: identical marker set fires on 5+ unrelated open PRs in the same window (shared bugfix-validation harness/infra noise), tracked separately.

Will re-validate 01710_minmax_count_projection locally (both directions) and re-push.

@groeneai
groeneai force-pushed the fix-rewrite-aggregate-function-with-if-respect-nulls branch from 2890b74 to 1e148ae Compare June 14, 2026 02:38
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

(Updated for 1e148ae, which extends the NULL-preserving guard to combinator wrappers and fixes the count(if(...)) adapter-probe crash.)

# Question Answer
a Deterministic repro? Yes. Wrong results: SELECT first_value_respect_nullsOrNull(if(number % 2 = 0, NULL, number)) FROM numbers(4) returned 1, must be \N. Crash: count(if(d = 4, d, 1)) with force_optimize_projection = 1 (and 01710_minmax_count_projection) aborted with a Code 49 LOGICAL_ERROR. Both reproduce on demand.
b Root cause explained? The pass rewrites f(if(cond, x, NULL)) -> fIf(x, cond), dropping NULL-payload rows, valid only for NULL-skipping aggregates. (1) Wrapper bug: the previous guard checked only the outer aggregate; a combinator (AggregateFunctionOrFill for -OrNull/-OrDefault) returns nullptr from its own getOwnNullAdapter, so the wrapped *_respect_nulls leaf went undetected and was rewritten. (2) Crash: count(if(...)) over a non-Nullable if result resolves to AggregateFunctionCount; probing its getOwnNullAdapter with the resolved non-Nullable type builds AggregateFunctionCountNotNullUnary, whose constructor rejects a non-Nullable argument and throws.
c Fix matches root cause? Yes. A recursive helper aggregateFunctionPreservesNullPayload (1) looks through getNestedFunction() so wrapped respect_nulls leaves are detected, (2) probes getOwnNullAdapter with a Nullable argument exactly as the Null combinator does (so count's adapter precondition holds), and (3) bails out for non-unary aggregates. The signal remains getOwnNullAdapter returning the function itself, the contract for NULL-preserving aggregates.
d Test intent preserved / new tests added? New regression test 04337_rewrite_aggregate_function_with_if_respect_nulls extended to cover: the -OrNull/-OrDefault wrapper cases (must return \N and not be rewritten), and count(if(d = 4, d, 1)) under force_optimize_projection (must not crash). Existing coverage that NULL-skipping aggregates still rewrite is retained. No test weakened.
e Both directions demonstrated? Yes. On HEAD before the fix: wrappers returned 1, count(if(...)) aborted. After 1e148ae (Build ID verified changed): wrappers and the whole *_respect_nulls family return \N, count(if(...)) returns 1000, and count/sum/avg/plain any still rewrite to the -If form (anyIf/countIf/sumIf/avgIf, results 2 5 2.5 unchanged). 04337 passes 50/50 under randomization; 01710_minmax_count_projection passes.
f Fix is general, not a narrow patch? Yes. The recursion + Nullable-probe covers the whole *_respect_nulls family directly and under any combinator (-OrNull/-OrDefault/-Distinct/-State/...) and any future NULL-preserving aggregate. It is not a guard against one call site: it tests the general NULL-handling contract (getOwnNullAdapter identity) at the wrapped leaf and probes the adapter the same way the Null combinator does, so it neither crashes for nullary/non-Nullable count nor misses a wrapped leaf.

Session id: cron:clickhouse-worker-slot-2:20260614-020200

@groeneai

Copy link
Copy Markdown
Collaborator Author

The 01710_minmax_count_projection Code 49 LOGICAL_ERROR on the previous head (count(if(d = 4, d, 1)) under force_optimize_projection) is fixed in 1e148ae: the null-preserving check now probes getOwnNullAdapter with a Nullable argument and bails out for non-unary aggregates, so AggregateFunctionCount's adapter is no longer constructed with a non-Nullable type. 01710_minmax_count_projection passes locally; the two sibling tests that need a multi-shard cluster (_distributed_query, and 01646_rewrite_sum_if_bug) are not runnable on the local single-node setup and are unrelated to this change.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI on HEAD `1e148aec3a3` has one PR-caused failure to fix: the new test `04337_rewrite_aggregate_function_with_if_respect_nulls` on `Stateless tests (amd_asan_ubsan, distributed plan, parallel, 1/2)`.

CI diagnosis: reproducible 32/32 with randomized `--optimize_use_implicit_projections False --optimize_trivial_count_query False`, passes 50/50 without randomization. The query `SELECT count(if(d = 4, d, 1)) FROM t_04337 SETTINGS force_optimize_projection = 1;` throws `PROJECTION_NOT_USED` (Code 584): `force_optimize_projection=1` requires a projection, but the implicit count projection is randomized off. This is a test-environment gap, not a product issue. Fixing the test by pinning `optimize_use_implicit_projections=1` on that query.

Session: cron:our-pr-ci-monitor:20260614-040000

…gate_function_with_if

RewriteAggregateFunctionWithIfPass rewrites f(if(cond, NULL, x)) -> fIf(x, !cond)
and f(if(cond, x, NULL)) -> fIf(x, cond), which drops the rows whose payload is
NULL. That is only correct for aggregate functions that skip NULL rows.

The *_respect_nulls family (anyRespectNulls, first_value_respect_nulls,
anyLast_respect_nulls, last_value_respect_nulls) keeps NULL payload values, so a
NULL row can be the first/last value of the result. Dropping it via the -If form
silently changed the result, e.g.
  SELECT anyRespectNulls(if(number % 2 = 0, NULL, number)) FROM numbers(4)
returned 1 instead of NULL.

The general signal is that getOwnNullAdapter returns the function itself: that is
the contract honored by the Null combinator meaning "do not wrap me, I keep NULL
rows". NULL-skipping functions (count, sum, avg, plain any, ...) return a wrapping
adapter or nullptr and are still optimized.

The check is done by a helper aggregateFunctionPreservesNullPayload that:
  - recurses through getNestedFunction() so a combinator wrapping a respect_nulls
    function is also detected. The NULL-preserving signal lives on the wrapped
    leaf, not on the combinator (whose own getOwnNullAdapter returns nullptr), so
    without this first_value_respect_nullsOrNull(if(...)) was still rewritten and
    returned 1 instead of NULL;
  - bails out for non-unary aggregates (a nullary count() cannot be respect_nulls);
  - probes getOwnNullAdapter with a Nullable argument, exactly as the Null
    combinator consults it. count builds AggregateFunctionCountNotNullUnary, whose
    constructor rejects a non-Nullable argument, so probing the resolved argument
    type of count(if(d = 4, d, 1)) (a non-Nullable Int64) raised a LOGICAL_ERROR.
    This reproduced on 01710_minmax_count_projection under force_optimize_projection.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

The count(if(...)) projection regression test pins the projection settings that
force_optimize_projection = 1 depends on (optimize_use_projections,
optimize_use_implicit_projections, optimize_trivial_count_query). The runner
randomizes those off, which made the test throw PROJECTION_NOT_USED instead of
exercising the pass. Query-level SETTINGS override the randomized session values.
@groeneai
groeneai force-pushed the fix-rewrite-aggregate-function-with-if-respect-nulls branch from 1e148ae to 7281855 Compare June 14, 2026 04:32
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (head 7281855)

Test-only follow-up: the source pass fix is unchanged; this push only hardens the new test query against settings randomization.

# Question Answer
a Deterministic repro? Yes. With the runner's session settings forced to the failing combo, SELECT count(if(d = 4, d, 1)) FROM t_04337 SETTINGS force_optimize_projection = 1 throws Code 584 PROJECTION_NOT_USED every time: clickhouse-client --optimize_use_implicit_projections 0 --optimize_trivial_count_query 0 -q "...force_optimize_projection = 1".
b Root cause explained? The test query sets force_optimize_projection = 1, which requires some projection to be applied. The only projection available for this count is the implicit count projection. The runner randomizes optimize_use_implicit_projections, optimize_use_projections and optimize_trivial_count_query off (5% each, lines 1488-1491 of tests/clickhouse-test); when implicit projections are off and the trivial-count shortcut is off, no projection can satisfy force_optimize_projection and the optimizer throws PROJECTION_NOT_USED. force_optimize_projection itself is not randomized.
c Fix matches root cause? Yes. Pin the exact three settings the runner randomizes that this query depends on (optimize_use_projections = 1, optimize_use_implicit_projections = 1, optimize_trivial_count_query = 1) at query level, so force_optimize_projection always has an applicable projection. Query-level SETTINGS take priority over the injected session values. Only the settings that cause the failure are pinned; no broad no-random-* tag.
d Test intent preserved / new tests added? Yes. The query still exercises the exact path it was added for: count(if(d = 4, d, 1)) where the if result is non-Nullable Int64, which is what made the null-preserving probe call AggregateFunctionCount::getOwnNullAdapter and previously crash. EXPLAIN QUERY TREE confirms count is still not rewritten to countIf. The force_optimize_projection/MergeTree scenario from 01710 is kept intact; only the dependent projection settings are pinned.
e Both directions demonstrated? Yes, on a Build-ID-verified binary (CD8DFCCC). Without the pins, under the forced culprit settings, the query throws PROJECTION_NOT_USED. With the pins (and the same forced session settings) it returns 1000. Full test: single run OK, 50/50 with full randomization, and the related rewrite/count/projection tests (04337, 01710_minmax_count_projection, 03210, 03132, 02518, 01706) all pass.
f Fix is general, not a narrow patch? N/A for code generality (no source change in this push). The pin covers all three projection settings the runner randomizes for this query, including the optimize_use_implicit_projections -> optimize_use_projections conditional dependency, so the test is randomization-proof.

Session id: cron:clickhouse-worker-slot-1:20260614-041000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixed in 728185561cf: the 04337 failure was the new test's count(if(d=4,d,1)) SETTINGS force_optimize_projection = 1 query throwing PROJECTION_NOT_USED when the runner randomized optimize_use_implicit_projections/optimize_trivial_count_query off. Pinned the three projection settings the query depends on at query level (test-only; the pass is unchanged). 50/50 with full randomization; both directions verified under the forced culprit settings.

The guard in RewriteAggregateFunctionWithIfPass decided whether an
aggregate argument can carry a NULL payload via makeNullableSafe(...)
->isNullable(). Variant and Dynamic hold NULL through a discriminator
without being wrapped in Nullable, so makeNullableSafe leaves them
unchanged and the isNullable() check was false. The guard then treated
them as NULL-free and let anyRespectNulls(if(cond, NULL, x::Variant(...)))
rewrite to the -If form, dropping the NULL payload row (returned 1
instead of NULL).

Gate on canContainNull() instead, which covers Nullable,
LowCardinality(Nullable), Dynamic and Variant. The adapter probe still
needs a Nullable argument (AggregateFunctionCountNotNullUnary rejects a
non-Nullable one), and Variant/Dynamic cannot be wrapped in Nullable, so
fall back to a plain Nullable stand-in; the respect_nulls adapters ignore
the argument and count only checks isNullable(), so the substitution does
not change which adapter is returned.

Adds Variant and Dynamic regression coverage to
04337_rewrite_aggregate_function_with_if_respect_nulls.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The previous gate only skipped the rewrite for NULL-preserving aggregates
(the *_respect_nulls family). NULL-skipping aggregates such as count and any
were still rewritten when the if result is a non-Nullable Variant or Dynamic.

For those types the if NULL branch is absorbed as a discriminator NULL, i.e.
a real payload row, not a Nullable NULL the aggregate discards. count and any
process that row, so the -If form (which skips it via the condition) changes
the result: count(if(number = 0, NULL, number::Variant(String, UInt64)))
returns 4 with the optimization off and 3 with it on, and any returns NULL
off and 1 on. The same holds for Dynamic.

Skip the rewrite whenever the if result can contain NULL but is not Nullable
(Variant/Dynamic), regardless of the aggregate. Plain Nullable and
LowCardinality(Nullable) if results are unaffected and keep being rewritten.

Adds count/any Variant and Dynamic regression coverage, plus an EXPLAIN check
that the rewrite to countIf is not applied for a Variant argument.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (head fd2eda719fe)

Follow-up to the clickhouse-gh[bot] review on 468b61fdc53 (the canContainNull gate only protected NULL-preserving aggregates; NULL-skipping count/any over a non-Nullable Variant/Dynamic were still rewritten and changed results).

# Question Answer
a Deterministic repro? Yes. clickhouse local --query "SET enable_analyzer=1; SELECT count(if(number = 0, NULL, number::Variant(String, UInt64))) FROM numbers(4) SETTINGS optimize_rewrite_aggregate_function_with_if=1" returns 3; with the setting =0 it returns 4. Same for Dynamic, and any(...) returns 1 vs \N.
b Root cause explained? For a non-Nullable Variant/Dynamic if result, the if NULL branch is absorbed as a discriminator-NULL payload row, not a Nullable NULL the aggregate discards. count/any still process that row. The Nullable adapter probe (AggregateFunctionFactory applies the Null combinator only when type->isNullable()) reports the aggregate as NULL-skipping, so the rewrite to countIf(x, not(cond)) / anyIf(...) fires and the -If condition drops the row, changing the result.
c Fix matches root cause? Yes. Skip the rewrite whenever the if result canContainNull() but is not Nullable/LowCardinality(Nullable) (i.e. Variant/Dynamic), for ALL aggregates, before the rewrite branches. This targets the discriminator-NULL mechanism directly rather than the previous aggregate-specific guard.
d Test intent preserved / new tests added? Yes. Added count/any Variant and Dynamic rows plus an EXPLAIN QUERY TREE assertion that countIf is NOT produced for a Variant argument, to 04337_rewrite_aggregate_function_with_if_respect_nulls. Existing rows (including the still-rewritten NULL-skipping Nullable cases) are unchanged.
e Both directions demonstrated? Yes. Without the fix: count Variant/Dynamic 4 -> 3, any \N -> 1. With the fix: 4 -> 4, \N -> \N, and EXPLAIN shows no countIf for the Variant argument. Plain Nullable and LowCardinality(Nullable) if results are unaffected (countIf still produced, results unchanged). Test passes 50/50 with full --random-settings.
f Fix is general, not a narrow patch? Yes. The gate is on the if result type via canContainNull/isNullableOrLowCardinalityNullable, not on a specific function name, so every NULL-skipping aggregate (count, any, sum, avg, ...) and every NULL-payload-by-discriminator type (Variant, Dynamic) is covered by the single check. It composes with the existing *_respect_nulls guard rather than replacing it.

Session id: cron:clickhouse-worker-slot-0:20260614-052400

@clickhouse-gh

clickhouse-gh Bot commented Jun 14, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.80% 84.80% +0.00%
Functions 92.40% 92.40% +0.00%
Branches 77.30% 77.30% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 20/23 (86.96%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@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.

The implementation is more complex than I expected, but it is ok.

@alexey-milovidov alexey-milovidov self-assigned this Jun 14, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jun 14, 2026
Merged via the queue into ClickHouse:master with commit 19db6d3 Jun 14, 2026
166 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 14, 2026
alexey-milovidov pushed a commit that referenced this pull request Nov 15, 2026
Resolve the conflict by porting only the hunks of #118697. The
conflicting region holds aggregateFunctionPreservesNullPayload from
#107430, which is not on 26.3, so it is left as on 26.3 and only
branchCanBeSkippedByShortCircuit is added there.

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