Repository navigation
Support Variant type in aggregate functions (sum, avg, min, max, ...) - #109369
alexey-milovidov wants to merge 141 commits into
Conversation
Aggregate functions that do not handle the Variant type natively previously
rejected it, e.g.:
Illegal type Variant(Decimal(7, 2), Float64) of argument for aggregate function sum.
Now such functions can be applied to a Variant argument. AggregateFunctionFactory
resolves the function normally first; if that fails with ILLEGAL_TYPE_OF_ARGUMENT
for a Variant argument, it falls back to AggregateFunctionVariantAdapter, which
aggregates over the least common supertype of the variants wrapped in Nullable:
f(variant) == f(CAST(variant AS Nullable(supertype(T1, ..., TN))))
getLeastSupertype is strict (no lossless conversion for Decimal/Int64 <-> Float64),
so a mix of numeric variants falls back to Float64, matching arithmetic semantics
(Decimal + Float64 -> Float64). Nullable preserves the implicit NULLs of the Variant,
which the aggregation skips.
The adapter is applied as the outermost wrapper (combinator recursion resolves nested
functions without it), so combinators compose in the usual order, e.g.
Adapter(Null(If(sum))). Functions that already accept Variant (count, any, uniq,
groupArray, ...) are unaffected, and nested Variant (inside Tuple/Array) as well as
the Dynamic type are still rejected as before.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Workflow [PR], commit [4aa86f5] Summary: ✅
AI ReviewSummaryThis PR extends Final Verdict✅ No new findings on the current PR head. |
The `cpp` style check flags raw `std::vector` usages in the linted `src/AggregateFunctions` directory (it wants an `-WithMemoryTracking` alternative or an explicit opt-out marker). The three vectors here are tiny, per-argument scratch structures whose allocation is dwarfed by the `castColumn` call they support, so mark them with `STYLE_CHECK_ALLOW_STD_CONTAINERS`, matching the sibling `AggregateFunctionFactory.h`. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109369&sha=f8358abc4c0ea8ff6bb25d7f64824d18205533c1&name_0=PR&name_1=Style%20check PR: #109369 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The `test_numbers_check` style check reported `Gap (4500, 5020) > 100`: the new test was numbered far ahead of the current maximum (`04500`). Renumber `05020_variant_aggregate_functions` to `04504_variant_aggregate_functions` (04501-04503 are taken by other in-flight pull requests) so the numbering stays contiguous. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109369&sha=f8358abc4c0ea8ff6bb25d7f64824d18205533c1&name_0=PR&name_1=Style%20check PR: #109369 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`03271_dynamic_variant_in_min_max` asserted that `min`, `max`, `argMin`, `argMax`, `anyArgMax` and `anyArgMin` over a `Variant` argument throw `ILLEGAL_TYPE_OF_ARGUMENT`. This pull request makes such functions aggregate over the least common supertype of the variants (wrapped in `Nullable`) via `AggregateFunctionVariantAdapter`, so those queries now succeed. Update the `Variant` section to expect the results (the `Dynamic` cases and the `minmax` skip-index case are unchanged and still throw). CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109369&sha=f8358abc4c0ea8ff6bb25d7f64824d18205533c1&name_0=PR&name_1=Fast%20test PR: #109369 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The `arm_tidy` build failed with four `-warnings-as-errors`: - `readability-inconsistent-declaration-parameter-name`: the declaration of `AggregateFunctionFactory::getWithoutVariantAdapter` named the argument `argument_types` while the definition named it `types_without_low_cardinality`. Renamed the declaration (and its comment) to match the definition. - `google-default-arguments` (x3): the `addBatch`, `addBatchSinglePlace` and `addBatchSinglePlaceNotNull` overrides in `AggregateFunctionVariantAdapter` repeated the `if_argument_pos = -1` default argument. Default arguments on virtual/override methods are prohibited; the default is inherited from the `IAggregateFunction` base declaration. Removed the redundant defaults, matching the convention in `AggregateFunctionIf` and other combinators. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109369&sha=cd0c39bfc5d9a735f0bc9dad6029c36a5bacc39f&name_0=PR&name_1=Build%20%28arm_tidy%29 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Aggregate functions applied to a `Variant` argument are resolved through `AggregateFunctionVariantAdapter`. The state type of such an aggregation keeps the original `Variant` argument list: for example, non-final aggregation blocks are typed `AggregateFunction(sum, Variant(...))` by `Aggregator::calculateAggregateStateTypes`, and this type is both constructible and reconstructible via `AggregateFunctionFactory::get`. However, the `-Merge` combinator resolved its nested function via `getWithoutVariantAdapter`, so `sumMerge` over `AggregateFunction(sum, Variant(...))` threw `ILLEGAL_TYPE_OF_ARGUMENT` instead of reconstructing the adapter, leaving the state constructible but not mergeable. Resolve a combinator's nested function through the `Variant` adapter when the combinator reintroduces a `Variant` argument that was absent from the top-level call (controlled by a new `apply_variant_adapter_to_nested` flag threaded through `getWithoutVariantAdapter`/`getImpl`). This keeps the adapter as the outermost wrapper on the forward path (e.g. `sumIf` over a `Variant` stays `Adapter(If(sum))`) while making `-Merge` reconstruct the same `Adapter(f)` state layout the state was produced with. As a consistent side effect, container combinators over a nested `Variant` (e.g. `sumArray` over `Array(Variant(...))`) now resolve as well. Addresses the AI review feedback on #109369 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`AggregateFunctionVariantAdapter` shares the nested function's state bytes as-is, so it is state-transparent exactly like the `-If` and `-Array` combinators. Unlike those, it did not forward `getNormalizedStateType` and `getBaseAggregateFunctionWithSameStateRepresentation`, so once a state passed through the adapter it stopped being interchangeable with the same underlying state produced without it: for example, a declared `AggregateFunction(sum, Variant(...))` column and the byte-compatible `AggregateFunction(sum, Nullable(supertype))` no longer normalized to the same type, so `CAST(... AS AggregateFunction(...))` between them and unions of such states failed even though both hold the same `sum` state. Forward both helpers to `nested_function`, mirroring `AggregateFunctionIf` and `AggregateFunctionArray`. This is the state-representation property tested for `-If`/`-Array` by `02366_normalize_aggregate_function_types_and_states`. Extended `04504_variant_aggregate_functions` with casts between the Variant-form and `Nullable(supertype)`-form states in both directions and a `UNION ALL` that unifies them; before this change the cast threw `CANNOT_CONVERT_TYPE`. Addresses the AI review "Not ready" verdict and the unresolved `clickhouse-gh` thread on `AggregateFunctionVariantAdapter.h`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…gate functions Address the AI-Review "Request changes" finding on `src/AggregateFunctions/AggregateFunctionFactory.cpp`: a top-level `Variant` whose least common supertype is a container type (`Array`/`Tuple`/`Map`) is rejected because the adapter casts to `Nullable(supertype)` to carry the `Variant`'s implicit NULLs, and such types cannot be wrapped in `Nullable`. For example, `min` over `Variant(Array(UInt8), Array(UInt16))` throws `ILLEGAL_TYPE_OF_ARGUMENT` even though `Array` is orderable. This is a deliberate scope limitation of the `Nullable`-based adapter; supporting it would require tracking the `Variant`'s NULLs separately from the value column (a natural follow-up). Expand the code comment to document it and add a boundary test to `04504_variant_aggregate_functions` that locks in the clean `ILLEGAL_TYPE_OF_ARGUMENT` rejection. The PR description's scope note is aligned accordingly. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The Variant fallback adapter rewrote every Variant argument to
`Nullable(supertype)` before retrying resolution. That broke mixed-role
aggregates such as `argMin`/`argMax` and the `*ArgMin`/`*ArgMax`
combinators, which natively accept a `Variant` in the returned "arg"
position and reject it only in the comparable key position: retrying with
both arguments adapted either silently changed the result type from
`Variant(...)` to `Nullable(supertype)`, or threw when the "arg" `Variant`
had no common supertype, e.g.
`argMin(CAST('a' AS Variant(String, UInt64)), CAST(1 AS Variant(UInt8, UInt64)))`.
Now `tryGetVariantAdapter` adapts only the minimal set of `Variant`
positions the function does not accept natively: when more than one
argument is a `Variant`, it keeps as `Variant` every position the function
still resolves with and adapts the rest. The adapter converts an argument
column only when its nested type differs from the original, so a kept
`Variant` argument is forwarded unchanged and the result type is preserved.
Extends `04504_variant_aggregate_functions` with `argMin`/`argMax` coverage.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The `-Merge` support added earlier routed the nested function of any combinator through the adapter-aware `get` whenever the combinator's transformed arguments contained a `Variant`. That was broader than intended: `AggregateFunctionCombinatorArray::transformArguments` turns `sumArray(Array(Variant(...)))` into a nested `sum(Variant(...))`, so the adapter was also applied to a `Variant` coming from ordinary user data, silently making `sumArray`/`minArray`/... over `Array(Variant(...))` resolve. That violates the PR's own contract that only top-level `Variant` arguments are handled while a `Variant` nested inside `Array`/`Tuple` is still rejected. Narrow the recursive adapter routing to genuine state-type reintroduction: only when the combinator consumes an `AggregateFunction(...)` state type (as `-Merge`/`-MergeState` do, whose nested argument types come from a stored `AggregateFunction(f, Variant(...))` state produced earlier by this same adapter). Combinators that merely expose a nested `Variant` from user data no longer get the adapter, so such calls report the original `ILLEGAL_TYPE_OF_ARGUMENT` again. Added boundary tests to `04504_variant_aggregate_functions` for `sumArray`/`minArray` over `Array(Variant(...))`; the `-Merge` state and top-level `Variant` cases are unchanged. Addresses the AI-Review "Request changes" finding on `AggregateFunctionFactory.cpp` and the matching `clickhouse-gh` thread. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
I agree, we should fix this. |
…nctions When a `Variant` argument has no lossless common supertype but all its variants are numeric (e.g. `Int64` + `Float64`, `Decimal` + `Float64`), the adapter fell back to aggregating in `Float64`. That is the natural arithmetic semantics for functions such as `sum` and `avg`, but for exact/order-based aggregates (`min`, `max`, `argMin`, `argMax`, `any`, `quantileExact`, ...) a lossy `Float64` cast silently returns wrong results: two distinct integers above 2^53 collapse to the same `Float64`, so the reported max/winner can be wrong. Apply the `Float64` fallback only to aggregates whose result is a floating-point value computed by arithmetic over the input (the `sum`/`avg`/variance/... families), classified by an allowlist keyed on the combinator-stripped, alias-resolved base function name. Every other function keeps reporting the original `ILLEGAL_TYPE_OF_ARGUMENT` when there is no lossless common supertype (fail-closed: an unknown function is treated as not float-promoting). Aggregation over a `Variant` with a genuine lossless supertype is unchanged, so `min`/`max` still work over e.g. `Variant(Int32, Float64)` (-> `Float64`) or `Variant(UInt8, UInt32)`. Addresses the review finding on the lossy `Float64` fallback. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…gate-functions # Conflicts: # src/AggregateFunctions/AggregateFunctionFactory.cpp
Addresses review of `AggregateFunctionFactory.cpp:504`: the master merge introduced the multiple-nested-functions branch (the `-Tuple` combinator, which wraps one nested function per tuple element), and it resolved each element through the adapter-aware `get`. That re-entered the Variant fallback for nested Variant arguments, so `sumTuple`/`avgTuple` over `Tuple(Variant(...))` started to resolve -- contradicting the PR's documented "top-level Variant only; nested Array/Tuple Variant still rejected" contract (the same scope kept for the `-Array` path). Resolve each nested function through `getWithoutVariantAdapter` instead, mirroring the single-nested path's default. `-Tuple` is the only multiple-nested combinator and it does not consume an aggregate-function state, so the `-Merge` state-reintroduction special case does not arise here. For non-Variant arguments this is equivalent to the previous `get` (a top-level call with no Variant argument resolves via `getWithoutVariantAdapter` with `apply_variant_adapter_to_nested = true`), and the tuple elements are already recursively free of `LowCardinality`, so the behavior is unchanged there. Extend `04504_variant_aggregate_functions` with a `-Tuple` boundary: an ordinary `sumTuple` over a non-Variant tuple still works, while `sumTuple`/`avgTuple` over `Tuple(Variant(...))` throw `ILLEGAL_TYPE_OF_ARGUMENT`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…PE_OF_ARGUMENT The `Variant` adapter fallback in `AggregateFunctionFactory` only retried the resolution after `ILLEGAL_TYPE_OF_ARGUMENT`. But not every aggregate creator reports an unsupported argument type with that code: `analysisOfVariance` and the `*TTest` family throw `BAD_ARGUMENTS`, and `rankCorr` throws `NOT_IMPLEMENTED`. Such functions never reached `tryGetVariantAdapter`, so a `Variant` argument that could have been adapted to `Nullable(supertype)` was rejected outright -- e.g. `analysisOfVariance(CAST(1 AS Variant(UInt8, UInt64)), 0)`, whose adapted signature `analysisOfVariance(Nullable(UInt64), UInt8)` resolves cleanly. Treat `ILLEGAL_TYPE_OF_ARGUMENT`, `BAD_ARGUMENTS`, and `NOT_IMPLEMENTED` as the "unsupported argument type" errors that make a retry through the adapter worthwhile, in both retry sites: the top-level catch in `getImpl` and the `try_resolve` probe inside `tryGetVariantAdapter` (the latter also drives the multi-`Variant` probe). Any other error code still propagates unchanged, and the fallback still only runs when a `Variant` argument is present, so non-`Variant` calls are unaffected; when the `Variant` cannot be adapted the original creator error (with its original code) is reported as before. Extends `04504_variant_aggregate_functions` with `rankCorr` and `analysisOfVariance` over a `Variant(UInt8, UInt64)` argument, plus boundary cases that show the original `NOT_IMPLEMENTED` / `BAD_ARGUMENTS` is preserved when the `Variant` has no common numeric supertype. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The two boundary checks used `CAST(1 AS Variant(String, UInt64))`, but the integer literal `1` has type `UInt8`, which is not a member of `Variant(String, UInt64)`. Casting to a `Variant` requires the source type to be one of the variant's alternatives, so the query threw `CANNOT_CONVERT_TYPE` instead of the intended `NOT_IMPLEMENTED` / `BAD_ARGUMENTS`, failing `Fast test`. Cast a `UInt64` value (a member of the variant) instead, so the queries construct a valid, unadaptable `Variant(String, UInt64)` and exercise the intended path: `rankCorr` throws `NOT_IMPLEMENTED` and `analysisOfVariance` throws `BAD_ARGUMENTS`, both reported unchanged because the variant has no common numeric supertype to adapt. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109369&sha=80e4b360174c20e0a47914f4169d7e06a05f2481&name_0=PR&name_1=Fast%20test Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
🕵 Thanks @groeneai — noted that #123790 and #123649 cover the two Merged the latest |
…dapted `Variant` key When only the comparison key of `argMin` / `argMax` is adapted by `AggregateFunctionVariantAdapter`, the natively kept `Variant` "arg" is still filtered by the `AggregateFunctionVariantNull` wrapper that `getImpl` applies to the nested function. Cover it, since existing tests only used non-`NULL` args. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=109369&sha=057d1a84efd5862b92d7cf35211c466cd4a3aa99&name_0=PR&name_1=Performance%20Comparison%20%28arm_release%2C%20master_head%2C%201%2F6%29 and provide a fix in a separate PR. If the fix is already in progress, link it here. The |
|
This is the same cause as the The fix in progress is #107554: typed aggregation, so these queries no longer compare |
|
The smaller PR is #124340: it compares integer keys inline in the |
…uilding states from raw values With `aggregate_function_input_format = 'value'` / `'array'`, the states of an `AggregateFunction(f, Variant(...))` column were built with the function stored in the declared type, which is resolved without query settings, so the NULL rows of the `Variant` were always skipped, even under `aggregate_functions_skip_variant_nulls = 0`. `AggregateFunctionStatesFromValuesInputFormat` now resolves such functions again with the query settings (still as a declared state type, so the admissibility checks like `allow_lossy_numeric_supertype` are unaffected). The state layout is the same in both modes. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The per-comparison type check of the previous commit cost every other key type a few instructions per tree step (String keys: +4.4% instructions). Choose the comparator once, from the key type, when the function is created: native integer, Enum, Date, Date32 and DateTime keys use FieldLess, every other key type keeps std::less<Field>, so it runs the same code as before. Measured against master (release, x86, max_threads=1, median of 15, 4 interleaved rounds): sum_map.xml queries 0..7 at 0.43x..0.53x (gmean 0.47), Int64 keys 0.47x, Date keys 0.52x, sumMapFiltered 0.70x. String and Float64 keys: 0.99x and 1.03x wall, the same instruction count (1.000x). .text grows by 335,872 bytes (+0.07%). CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=109369&sha=057d1a84efd5862b92d7cf35211c466cd4a3aa99&name_0=PR&name_1=Performance%20Comparison%20%28arm_release%2C%20master_head%2C%201%2F6%29 PR: ClickHouse#109369 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵
The public CI for this PR is green and there are no unresolved review threads. Re-running the sync will not help until the |
I'm updating #107554 - it got stuck in more or less done state. |
|
🕵 @jh0x thank you, I will follow #107554. This PR does not depend on it, and the smaller #124340 covers the The latest
The public CI is green, and no review threads are unresolved. |
# Conflicts: # docs/resources/develop-contribute/native-protocol/format.mdx
…mily `contingency`, `cramersV`, `cramersVBiasCorrected` and `theilsU` key on the exact identity of each category, and `Variant` values with different alternative types are distinct categories (`1::UInt8` and `1::UInt64` of a `Variant(UInt8, UInt64)`). Aggregating over the common supertype collapsed them into one bucket and silently changed the statistic. Register the family as `is_distinctness_sensitive`, like `singleValueOrNull`, so a `Variant` argument is rejected with `ILLEGAL_TYPE_OF_ARGUMENT` instead of being routed through `AggregateFunctionVariantAdapter`. Test `04615_variant_crosstab_window_merge` covered the adapted state merging of this family, which no longer exists, so it is removed. #109369 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ough `Float64` `studentTTest`, `welchTTest`, `meanZTest`, `mannWhitneyUTest` and `kolmogorovSmirnovTest` read their second argument, the sample label, with `getUInt`. Being float-promoting, they let the `Variant` adapter apply the lossy `Float64` fallback to the label as well, so a label such as `Variant(Int64, Float64)` was cast to `Float64` and truncated into sample 0 or 1. Add `AggregateFunctionProperties::has_sample_label_argument` and exclude that position from the fallback, as for the `-ArgMin` / `-ArgMax` key. The sample data keeps the fallback, and a label with a lossless common supertype is still adapted. #109369 Co-Authored-By: Claude Opus 5.5 <[email protected]>
… query Revert "Preserve query settings for `OPTIMIZE` merges" (5de3fa1) and the matching test update of `03164_s3_settings_for_queries_and_merges`. Passing the whole query context to the merge task made a plain `MergeTree` merge honor `OPTIMIZE ... SETTINGS`, while `ReplicatedMergeTree` executes the merge from the replication log with the background context, so the two engines diverged on the same statement. It also leaked unrelated settings into persisted data: `OPTIMIZE ... FINAL SETTINGS max_rows_to_group_by = 1, group_by_overflow_mode = 'any'` could write truncated `TTL ... GROUP BY` rollups. Merges now consistently take `aggregate_functions_skip_variant_nulls` from the settings profile for background operations, like every other setting of a merge. `TTLAggregationAlgorithm` still re-resolves the `Variant` aggregates with the merge context (so the value is not frozen at `CREATE` time), but builds `Aggregator::Params` from the table's context again, as before this PR. #109369 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 |
|
🕵 Public CI is green.
I reran the failed jobs of the sync PR. |
|
Superseded by a simpler reimplementation: #125726 |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Aggregate functions that do not handle the
Varianttype natively (sum,avg,min,max,argMin,argMax,quantile,stddevPop, ...) can now be applied toVariantarguments. Previously they failed, e.g.Illegal type Variant(Decimal(7, 2), Float64) of argument for aggregate function sum. The aggregate functions that do accept aVariantargument natively (count,any,groupArray,groupConcat, theuniqfamily, ...) now skip the rows where theVariantholds a NULL value, like they skip the NULL values of aNullableargument (only the row skipping matchesNullable: the result type and the empty-set result of the function are preserved) -- previouslycountcounted those rows,anycould return NULL from a group that has non-NULL values,groupArraystored the NULLs, and theuniqfamily counted NULL as a distinct value. The-SimpleStatecombinator and declaredSimpleAggregateFunction(..., Variant(...))columns retain the previous behavior regardless of this setting, so their raw values can be safely re-aggregated during table loading and background merges. Setaggregate_functions_skip_variant_nulls = 0(orSET compatibility = '26.9') to restore the previous behavior for other aggregate functions. PersistedAggregateFunction(f, Variant(...))states (materialized views,AggregateFunctioncolumns) keep the same type name, layout and serialization in both modes, so states written before and after the upgrade merge freely but mean different things -- the old ones aggregated the NULL rows, the new ones skip them -- and a merged result over the mix follows neither rule consistently. To keep the pre-26.10results over such data, setaggregate_functions_skip_variant_nulls = 0before inserting new data; the NULL rows already aggregated into the historical states cannot be removed by re-merging, only by re-inserting the data from the source.Description
Such functions now aggregate over the least common supertype of the variants, wrapped in
Nullable:Nullablepreserves the implicit NULLs of theVariant, which the aggregation skips.How it works.
AggregateFunctionFactory::get()resolves the function normally first; only if that fails for aVariantargument with an "unsupported argument type" error —ILLEGAL_TYPE_OF_ARGUMENT, orNOT_IMPLEMENTEDfor the creators that use it instead (rankCorr,mannWhitneyUTest,kolmogorovSmirnovTest,largestTriangleThreeBuckets) — does it fall back to a newAggregateFunctionVariantAdapter, which casts theVariantargument column(s) toNullable(supertype)on the fly and forwards everything else to the nested function (whose state layout it shares). If the supertype route is not possible either, the original error is reported unchanged. Functions that already acceptVariant(count,any,uniq,groupArray, ...) are unaffected.Supertype.
getLeastSupertypeis strict and has no common type for e.g.Decimal/Int64↔Float64(no lossless conversion). For an aggregate whose result is a floating-point value computed by arithmetic over its input (thesum/avg/variance/... families), a mix of numeric variants with no lossless common supertype falls back toFloat64— but only when the user has opted into the lossy numeric supertype with theallow_lossy_numeric_supertypesetting, and under the same promotion rule that setting applies at type inference forif/multiIf/coalesce/ifNull/array/map(all-numeric variants with at least one floating-point member; an integer-only mix such asVariant(Int64, UInt64)is not promoted). With the setting off (the default) the adapter handles only lossless supertypes and the originalILLEGAL_TYPE_OF_ARGUMENTerror — which points at the setting when enabling it would help — is reported unchanged. Reconstruction of an already declared state type such asAggregateFunction(sum, Variant(Int64, Float64))always allows the promotion, so a state validated when it was declared never becomes unreadable because of the setting's current value: this covers the background paths that have no query context (table load /ATTACHat startup, merges) and, throughfrom_declared_state_type, every query-time path that names the state type explicitly — a column type, aCASTtarget, a decoded binary type, and the nested function of-Mergeover such a state. The fallback is deliberately not applied to exact/order-based aggregates (min,max,argMin,argMax,any,quantileExact, ...) even under the setting: a lossyFloat64cast would silently return wrong results for them (two distinct integers above 2^53 collapse to the sameFloat64), so they keep reporting the originalILLEGAL_TYPE_OF_ARGUMENTwhen there is no lossless common supertype. Whether a function is float-promoting is declared byAggregateFunctionProperties::is_float_promoting(set at registration, consulted through the factory), fail-closed: a function that does not set it is treated as not float-promoting. Clean supertypes are preserved regardless of the function and the setting (Variant(UInt8, UInt32) -> UInt32,Variant(Int32, Float64) -> Float64,Variant(Date, DateTime) -> DateTime), somin/maxstill work over such variants.Combinators. The adapter is applied as the outermost wrapper (the combinator recursion resolves nested functions without it), so combinators compose in the usual order, e.g.
Adapter(Null(If(sum))).-If,-State/-MergeandGROUP BYwork; state serialization forsumStateuses the supertype (AggregateFunction(sum, Nullable(Float64))), so distributed / two-phase aggregation is unchanged. Only the argument positions the function actually rejects are adapted:argMin/argMax(and the*ArgMin/*ArgMaxcombinators) accept aVariantin the returned "arg" position and reject it only in the comparable key, so the "arg" keeps its originalVarianttype while just the key is cast toNullable(supertype).Examples.
Scope. Only top-level
Variantarguments whose common supertype can be wrapped inNullableare handled — the adapter usesNullableto carry the implicit NULLs of theVariant. AVariantwhose common supertype is a container type (Array/Tuple/Map) is therefore still rejected, even for an orderable aggregate such asmin/maxoverVariant(Array(UInt8), Array(UInt16))(supporting it would require tracking theVariant's NULLs separately from the value column). AVariantnested insideTuple/Array, and theDynamictype, are likewise still rejected as before. These are all natural follow-ups. The result isNullablebecause aVariantvalue can always be NULL.singleValueOrNullis deliberately excluded from the adapter (AggregateFunctionProperties::is_distinctness_sensitive): its contract keys on how many distinct values there are, and the cast toNullable(supertype)collapsesVariantvalues that are distinct because their alternative types differ (1::UInt8vs1::UInt64, whichuniqcounts as 2), so it would silently return a non-NULL value where the contract requires NULL — including inside thex = ALL (SELECT ...)rewrite. It keeps reportingILLEGAL_TYPE_OF_ARGUMENTfor aVariantargument, unchanged from before. The-Distinctcombinator makes any combined function distinctness-sensitive in the same way (sumDistinctmust deduplicate the genuineVariantvalues, not their casts to the supertype), so the combinator propagates the property throughAggregateFunctionFactory::tryGetProperties(IAggregateFunctionCombinator::isDistinctnessSensitive) and every...Distinctform over aVariantargument keeps its original error too.groupArrayInsertAtandgroupArraySorteddo not claim nativeVariantsupport either: their generic implementations keep the state asFields, which loses the original alternative type of aVariantvalue on ingest and reinfers the first compatible one on output (1::UInt8and1::UInt64collapse), andgroupArraySortedwould order byFieldcomparison instead ofVariantorder. Likesum/avg, they go through the adapter over the least common supertype of the variants, and reject aVariant(orDynamic) argument at resolution when there is no lossless supertype.Error codes.
BAD_ARGUMENTSis deliberately not part of the "unsupported argument type" retry signal, because creators use it for genuine semantic failures — above all invalid parameters, as inkolmogorovSmirnovTest('bogus')— and retrying on it would report the unrelated type error of the original, unadapted call instead of the parameter error. The few creators that rejected argument types withBAD_ARGUMENTSnow reject them withILLEGAL_TYPE_OF_ARGUMENT, like every other function, which keeps them adaptable to aVariantargument:analysisOfVariance,studentTTest,studentTTestOneSample,welchTTest,meanZTestandboundingRatioreportILLEGAL_TYPE_OF_ARGUMENTinstead ofBAD_ARGUMENTSwhen applied to an argument of an unsupported type.countover aVariant.countaccepts aVariantnatively, without the adapter, butcount(expr)counts the not-NULL values of its argument, and aVariantrow can hold a NULL value (isNullis true for it). AVariantis notNullable, so theNullcombinator -- and with itAggregateFunctionCountNotNullUnary-- is never applied to it, and the native path counted every row.countover a singleVariantargument now resolves toAggregateFunctionCountNotNullVariant, which counts the rows whose local discriminator is notNULL_DISCRIMINATOR; its state is the same single counter and normalizes toAggregateFunction(count), so the state forms stay byte-compatible with the plaincountstate.The NULL-skipping contract of the natively-supported functions. The other functions that accept a
Variantnatively are held to the same contract byAggregateFunctionVariantNull, a wrapper mirroring theNullcombinator: the rows where aVariantargument is NULL are skipped, like theNullcombinator skips the NULL values ofNullablearguments (only the row skipping is mirrored; the result-type promotion and the all-NULL-group result of the combinator are deliberately not). Without it,anyreturned NULL from a group that has non-NULL values,groupArraystored the NULLs its documentation promises to remove,groupConcatconcatenated them as data, and the uniq family counted NULL as a distinct value. The wrapper is applied at the factory's leaf resolution point (getImpl), which every path funnels through -- the top-level native resolution as well as nested functions reconstructed from declaredAggregateFunction(f, Variant(...))state types -- so the state layouts always match. Unlike theNullcombinator, the wrapper never changes the result type, the state layout or the serialization of the nested function: a function that accepts aVariantnatively already accepted it before this change, with exactly the nested result type and state representation, and both are persisted (inAggregateFunction(f, Variant(...))columns and in the schemas of the materialized views reading them), so changing either would break an upgrade. An all-NULL group produces the empty nested state and returns the nested function's empty-set result (groupConcatover aVariantkeeps returningString, and an empty string for an all-NULL group); for functions whose result is theVariantitself (any,argMin, ...) an all-NULL group still reports NULL, because aVariantrepresents NULL on its own. Window functions keep handling their argument types themselves, so theRESPECT NULLSforms andestimateCompressionRatiostill see the NULL rows, andcountkeeps its dedicated implementation above and declaresAggregateFunctionProperties::skips_variant_nulls.Compatibility of the NULL-skipping contract. The functions above accepted a
Variantargument before this change, so skipping its NULL rows is a change of their behavior and is gated by a compatibility setting:aggregate_functions_skip_variant_nulls = 0(implied bycompatibilitybelow26.10) restores the previous behavior, where those rows were aggregated as ordinary values. The setting only controls which rows are added to a state -- the result type, the state layout and the serialization are identical in both modes, so anAggregateFunction(f, Variant(...))state written by either mode stays readable and mergeable by the other. For the same reason the setting cannot change the meaning of a state that has already been written: a state written by an older version keeps the values that went into it, including the ones that came from the NULL rows, and no state-type version can retroactively tell the two apart because their bytes are identical. The consequence for existing data is spelled out in the changelog entry and in the documentation: states written before and after the upgrade merge freely but follow different accumulation rules, so a deployment that must keep the old results over persisted states has to keep writing withaggregate_functions_skip_variant_nulls = 0until the historical data is re-inserted. It is deliberately not consulted when there is no query context (a background operation, or a table loaded at startup). The one state that replays raw values into a nested function -- the distinct-key history of the-Distinctcombinator -- keeps the rule by construction: the nested function of-Distinctover aVariantargument is resolved with the NULL skipping disabled, so the replay always aggregates the NULL keys a history contains (exactly like the versions that wrote states before the contract existed, so a storedcountDistinctStateover aVariantreads back to the same result under either value of the setting), and the NULL rows of newly aggregated data are skipped in front of the history instead, by an outerAggregateFunctionVariantNullover the combined function under the same setting. The aggregation ofVariantarguments, the NULL-skipping contract and this compatibility note are documented in theVariantdocs (the embedded documentation block inDataTypeVariant.cppanddocs/reference/data-types/variant.mdx).Exclusions. The
CrossTabfamily (contingency,cramersV,cramersVBiasCorrected,theilsU) keys on the exact identity of each category, so, likesingleValueOrNulland-Distinct, it is declaredis_distinctness_sensitiveand is never adapted:1::UInt8and1::UInt64of aVariant(UInt8, UInt64)are different categories that a cast to the supertype would merge. The sample label (second argument) of the two-sample tests (studentTTest,welchTTest,meanZTest,mannWhitneyUTest,kolmogorovSmirnovTest) is never adapted through the lossyFloat64fallback (AggregateFunctionProperties::has_sample_label_argument), the same as the-ArgMin/-ArgMaxkey.Merges.
CoalescingMergeTreemerges andTTL ... GROUP BYrollups takeaggregate_functions_skip_variant_nullsfrom the settings profile for background operations, like every other merge setting, and never from theOPTIMIZEquery that triggered the merge, soMergeTreeandReplicatedMergeTreebehave the same. TheTTL ... GROUP BYaggregates overVariantarguments are re-resolved with the merge settings instead of the settings cached atCREATEtime.Added
tests/queries/0_stateless/04504_variant_aggregate_functions.sql,tests/queries/0_stateless/04644_variant_aggregate_state_setting_independence.sql,tests/queries/0_stateless/04652_variant_count_skips_nulls.sqltests/queries/0_stateless/04657_variant_aggregate_functions_skip_nulls.sqltests/queries/0_stateless/04692_variant_aggregate_nulls_compatibility_setting.sqlandtests/queries/0_stateless/04817_variant_distinct_states_setting_independence.sql.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/109369]