Repository navigation
Do not rewrite NULL-preserving aggregates with optimize_rewrite_aggregate_function_with_if - #107430
Conversation
Pre-PR validation gate
Session id: cron:clickhouse-worker-slot-2:20260613-233400 |
|
cc @KochetovNicolai @novikd — could you review this? It stops |
|
Workflow [PR], commit [fd2eda7] Summary: ✅
AI ReviewSummaryThis PR fixes PR Metadata
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
Final VerdictStatus: ✅ Approve No blocking review findings. Please update the changelog wording to match the final |
| if (auto aggregate_function = function_node->getAggregateFunction()) | ||
| { | ||
| AggregateFunctionProperties properties; | ||
| if (aggregate_function->getOwnNullAdapter( |
There was a problem hiding this comment.
And what if it has a custom Null Adapter, which is non-default?
There was a problem hiding this comment.
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:
-
Returns the function itself. Only
AnyRespectNullsdoes this (getOwnNullAdapterreturnsoriginal_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. -
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->AggregateFunctionCountNotNullUnarysumCount->AggregateFunctionNullUnary<false,false>(legacy flag, comment explains it is for state compatibility)intervalLengthSum->AggregateFunctionNullVariadic<false,false>Distinct/OrFill->AggregateFunctionNullUnary<false,false>for thesumCountcase- the
Ifcombinator ->AggregateFunctionIfNull*(and*Ifis excluded earlier by theends_with("if")guard anyway)
None of these keep NULL rows, so!= self-> rewrite still fires -> correct.
-
Returns
nullptr(the default inIAggregateFunction). The Null combinator then wraps the function with a NULL-skippingAggregateFunctionNull*.!= 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.
eccc330 to
2890b74
Compare
Pre-PR validation gate (update for 2890b74)
Session id: cron:clickhouse-worker-slot-3:20260614-011100 |
|
CI update on
Will re-validate |
2890b74 to
1e148ae
Compare
Pre-PR validation gate(Updated for 1e148ae, which extends the NULL-preserving guard to combinator wrappers and fixes the
Session id: cron:clickhouse-worker-slot-2:20260614-020200 |
|
The |
|
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.
1e148ae to
7281855
Compare
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.
Session id: cron:clickhouse-worker-slot-1:20260614-041000 |
|
Fixed in |
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]>
Pre-PR validation gate (head
|
| # | 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
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 20/23 (86.96%) | Lost baseline coverage: none · Uncovered code |
alexey-milovidov
left a comment
There was a problem hiding this comment.
The implementation is more complex than I expected, but it is ok.
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]>
Changelog category (leave one):
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_ifoptimization for aggregate functions that preserveNULLpayload values (the*_respect_nullsfamily:anyRespectNulls,first_value_respect_nulls,anyLast_respect_nulls,last_value_respect_nulls). The optimization no longer rewritesf(if(cond, x, NULL))into the-Ifform for such functions.Description
RewriteAggregateFunctionWithIfPassrewritesf(if(cond, NULL, x))intofIf(x, !cond)andf(if(cond, x, NULL))intofIf(x, cond). This drops the rows whose payload isNULL, which is only correct for aggregate functions that skipNULLrows.The
*_respect_nullsfamily keepsNULLpayload values, so aNULLrow can legitimately be the first/last value of the result. Filtering it out with the-Ifform silently changed the result, for example on26.6.1.1:These functions provide their own null adapter:
getOwnNullAdapterreturns the function itself, which is the general signal (honored by theNullcombinator) that theNULLpayload must be kept. The pass now skips the rewrite whenevergetOwnNullAdapterreturns the function itself, so the fix covers the whole family and any futureNULL-preserving aggregate.NULL-skipping functions (count,sum,avg, plainany, ...) are unaffected and still optimized.