Skip to content

Support Variant type in aggregate functions (sum, avg, min, max, ...) - #109369

Closed
alexey-milovidov wants to merge 141 commits into
masterfrom
variant-aggregate-functions
Closed

alexey-milovidov wants to merge 141 commits into
masterfrom
variant-aggregate-functions

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 3, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Backward Incompatible Change

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Aggregate functions that do not handle the Variant type natively (sum, avg, min, max, argMin, argMax, quantile, stddevPop, ...) can now be applied to Variant arguments. Previously they failed, e.g. Illegal type Variant(Decimal(7, 2), Float64) of argument for aggregate function sum. The aggregate functions that do accept a Variant argument natively (count, any, groupArray, groupConcat, the uniq family, ...) now skip the rows where the Variant holds a NULL value, like they skip the NULL values of a Nullable argument (only the row skipping matches Nullable: the result type and the empty-set result of the function are preserved) -- previously count counted those rows, any could return NULL from a group that has non-NULL values, groupArray stored the NULLs, and the uniq family counted NULL as a distinct value. The -SimpleState combinator and declared SimpleAggregateFunction(..., 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. Set aggregate_functions_skip_variant_nulls = 0 (or SET compatibility = '26.9') to restore the previous behavior for other aggregate functions. Persisted AggregateFunction(f, Variant(...)) states (materialized views, AggregateFunction columns) 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.10 results over such data, set aggregate_functions_skip_variant_nulls = 0 before 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:

f(variant) == f(CAST(variant AS Nullable(supertype(T1, ..., TN))))

Nullable preserves the implicit NULLs of the Variant, which the aggregation skips.

How it works. AggregateFunctionFactory::get() resolves the function normally first; only if that fails for a Variant argument with an "unsupported argument type" error — ILLEGAL_TYPE_OF_ARGUMENT, or NOT_IMPLEMENTED for the creators that use it instead (rankCorr, mannWhitneyUTest, kolmogorovSmirnovTest, largestTriangleThreeBuckets) — does it fall back to a new AggregateFunctionVariantAdapter, which casts the Variant argument column(s) to Nullable(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 accept Variant (count, any, uniq, groupArray, ...) are unaffected.

Supertype. getLeastSupertype is 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 (the sum/avg/variance/... families), a mix of numeric variants with no lossless common supertype falls back to Float64 — but only when the user has opted into the lossy numeric supertype with the allow_lossy_numeric_supertype setting, and under the same promotion rule that setting applies at type inference for if/multiIf/coalesce/ifNull/array/map (all-numeric variants with at least one floating-point member; an integer-only mix such as Variant(Int64, UInt64) is not promoted). With the setting off (the default) the adapter handles only lossless supertypes and the original ILLEGAL_TYPE_OF_ARGUMENT error — which points at the setting when enabling it would help — is reported unchanged. Reconstruction of an already declared state type such as AggregateFunction(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 / ATTACH at startup, merges) and, through from_declared_state_type, every query-time path that names the state type explicitly — a column type, a CAST target, a decoded binary type, and the nested function of -Merge over 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 lossy Float64 cast would silently return wrong results for them (two distinct integers above 2^53 collapse to the same Float64), so they keep reporting the original ILLEGAL_TYPE_OF_ARGUMENT when there is no lossless common supertype. Whether a function is float-promoting is declared by AggregateFunctionProperties::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), so min/max still 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/-Merge and GROUP BY work; state serialization for sumState uses 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/*ArgMax combinators) accept a Variant in the returned "arg" position and reject it only in the comparable key, so the "arg" keeps its original Variant type while just the key is cast to Nullable(supertype).

Examples.

SET allow_lossy_numeric_supertype = 1;

SELECT sum(v), toTypeName(sum(v))
FROM values('v Variant(Decimal(7, 2), Float64)', 1.5, 2.5, NULL, 10);
-- 14   Nullable(Float64)

Scope. Only top-level Variant arguments whose common supertype can be wrapped in Nullable are handled — the adapter uses Nullable to carry the implicit NULLs of the Variant. A Variant whose common supertype is a container type (Array/Tuple/Map) is therefore still rejected, even for an orderable aggregate such as min/max over Variant(Array(UInt8), Array(UInt16)) (supporting it would require tracking the Variant's NULLs separately from the value column). A Variant nested inside Tuple/Array, and the Dynamic type, are likewise still rejected as before. These are all natural follow-ups. The result is Nullable because a Variant value can always be NULL. singleValueOrNull is deliberately excluded from the adapter (AggregateFunctionProperties::is_distinctness_sensitive): its contract keys on how many distinct values there are, and the cast to Nullable(supertype) collapses Variant values that are distinct because their alternative types differ (1::UInt8 vs 1::UInt64, which uniq counts as 2), so it would silently return a non-NULL value where the contract requires NULL — including inside the x = ALL (SELECT ...) rewrite. It keeps reporting ILLEGAL_TYPE_OF_ARGUMENT for a Variant argument, unchanged from before. The -Distinct combinator makes any combined function distinctness-sensitive in the same way (sumDistinct must deduplicate the genuine Variant values, not their casts to the supertype), so the combinator propagates the property through AggregateFunctionFactory::tryGetProperties (IAggregateFunctionCombinator::isDistinctnessSensitive) and every ...Distinct form over a Variant argument keeps its original error too. groupArrayInsertAt and groupArraySorted do not claim native Variant support either: their generic implementations keep the state as Fields, which loses the original alternative type of a Variant value on ingest and reinfers the first compatible one on output (1::UInt8 and 1::UInt64 collapse), and groupArraySorted would order by Field comparison instead of Variant order. Like sum / avg, they go through the adapter over the least common supertype of the variants, and reject a Variant (or Dynamic) argument at resolution when there is no lossless supertype.

Error codes. BAD_ARGUMENTS is deliberately not part of the "unsupported argument type" retry signal, because creators use it for genuine semantic failures — above all invalid parameters, as in kolmogorovSmirnovTest('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 with BAD_ARGUMENTS now reject them with ILLEGAL_TYPE_OF_ARGUMENT, like every other function, which keeps them adaptable to a Variant argument: analysisOfVariance, studentTTest, studentTTestOneSample, welchTTest, meanZTest and boundingRatio report ILLEGAL_TYPE_OF_ARGUMENT instead of BAD_ARGUMENTS when applied to an argument of an unsupported type.

count over a Variant. count accepts a Variant natively, without the adapter, but count(expr) counts the not-NULL values of its argument, and a Variant row can hold a NULL value (isNull is true for it). A Variant is not Nullable, so the Null combinator -- and with it AggregateFunctionCountNotNullUnary -- is never applied to it, and the native path counted every row. count over a single Variant argument now resolves to AggregateFunctionCountNotNullVariant, which counts the rows whose local discriminator is not NULL_DISCRIMINATOR; its state is the same single counter and normalizes to AggregateFunction(count), so the state forms stay byte-compatible with the plain count state.

The NULL-skipping contract of the natively-supported functions. The other functions that accept a Variant natively are held to the same contract by AggregateFunctionVariantNull, a wrapper mirroring the Null combinator: the rows where a Variant argument is NULL are skipped, like the Null combinator skips the NULL values of Nullable arguments (only the row skipping is mirrored; the result-type promotion and the all-NULL-group result of the combinator are deliberately not). Without it, any returned NULL from a group that has non-NULL values, groupArray stored the NULLs its documentation promises to remove, groupConcat concatenated 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 declared AggregateFunction(f, Variant(...)) state types -- so the state layouts always match. Unlike the Null combinator, the wrapper never changes the result type, the state layout or the serialization of the nested function: a function that accepts a Variant natively already accepted it before this change, with exactly the nested result type and state representation, and both are persisted (in AggregateFunction(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 (groupConcat over a Variant keeps returning String, and an empty string for an all-NULL group); for functions whose result is the Variant itself (any, argMin, ...) an all-NULL group still reports NULL, because a Variant represents NULL on its own. Window functions keep handling their argument types themselves, so the RESPECT NULLS forms and estimateCompressionRatio still see the NULL rows, and count keeps its dedicated implementation above and declares AggregateFunctionProperties::skips_variant_nulls.

Compatibility of the NULL-skipping contract. The functions above accepted a Variant argument 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 by compatibility below 26.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 an AggregateFunction(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 with aggregate_functions_skip_variant_nulls = 0 until 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 -Distinct combinator -- keeps the rule by construction: the nested function of -Distinct over a Variant argument 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 stored countDistinctState over a Variant reads 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 outer AggregateFunctionVariantNull over the combined function under the same setting. The aggregation of Variant arguments, the NULL-skipping contract and this compatibility note are documented in the Variant docs (the embedded documentation block in DataTypeVariant.cpp and docs/reference/data-types/variant.mdx).

Exclusions. The CrossTab family (contingency, cramersV, cramersVBiasCorrected, theilsU) keys on the exact identity of each category, so, like singleValueOrNull and -Distinct, it is declared is_distinctness_sensitive and is never adapted: 1::UInt8 and 1::UInt64 of a Variant(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 lossy Float64 fallback (AggregateFunctionProperties::has_sample_label_argument), the same as the -ArgMin / -ArgMax key.

Merges. CoalescingMergeTree merges and TTL ... GROUP BY rollups take aggregate_functions_skip_variant_nulls from the settings profile for background operations, like every other merge setting, and never from the OPTIMIZE query that triggered the merge, so MergeTree and ReplicatedMergeTree behave the same. The TTL ... GROUP BY aggregates over Variant arguments are re-resolved with the merge settings instead of the settings cached at CREATE time.

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.sql tests/queries/0_stateless/04657_variant_aggregate_functions_skip_nulls.sql tests/queries/0_stateless/04692_variant_aggregate_nulls_compatibility_setting.sql and tests/queries/0_stateless/04817_variant_distinct_states_setting_independence.sql.

🤖 Generated with Claude Code


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

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]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4aa86f5]

Summary: ✅


AI Review

Summary

This PR extends Variant support across aggregate-function resolution, state reconstruction, and background/query-time aggregation paths, while preserving compatibility for persisted states and the historical SimpleAggregateFunction / -SimpleState surface. I reviewed the current head together with the full prior discussion, spot-checked the state-type reconstruction paths (AggregateFunction(...), binary type decoding, -Merge, aggregate_function_input_format, FINAL/TTL/coalescing merges), and the latest follow-up fixes look consistent. I do not see any new blocker or major issue on the current revision.

Final Verdict

✅ No new findings on the current PR head.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jul 3, 2026
alexey-milovidov and others added 5 commits July 3, 2026 22:55
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Suggested fix: only apply the Float64 fallback to aggregates whose semantics already promote through floating-point arithmetic

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]>
alexey-milovidov and others added 2 commits July 8, 2026 11:23
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai — noted that #123790 and #123649 cover the two arm_binary failures, so no further action on them here.

Merged the latest master again to resolve the new conflicts (AggregateFunctionIf.h / AggregateFunctionNull.h: kept both the PR's ML-prediction forwarding and master's getStateType forwarding; native-protocol/format.mdx: took master's extended uniq versioning text and re-inserted the PR's paragraph about decoding declared state types). Following master's change that makes pass-through combinators spell the nested state version in their state type, AggregateFunctionVariantAdapter and AggregateFunctionVariantNull now forward getStateType the same way. The PR's 23 stateless tests and 02366_normalize_aggregate_function_types_and_states pass locally on the merged tree.

alexey-milovidov and others added 2 commits October 6, 2026 20:13
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @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 sum_map test (sumMap(key, val) over arrays, which does not touch any Variant code path) reports "slower" on many unrelated PRs and on master in the last few days (e.g. PRs 120371, 123649, 120632, 123686, 121639, 124018, 119147, 100377 per the CIDB checks table), so it looks unstable rather than a regression here.

@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator

This is the same cause as the sum_map reds on the other PRs (analysis on #117136). Here query 2 (sumMap(key, val)) takes 0.136 s on the reference and 0.162 s on the PR binary in every run, including both confirmation reruns. The extra CPU samples are in Field::operator< (249 to 304) and its caller AggregateFunctionMapBase::add (104 to 119), from the std::map<Field, Array> lookup done for every array element. Both functions have the same code in the reference (a2e4282a) and in this PR's binary (in add one register move is scheduled one instruction later), only their addresses differ. Of the 41 PR runs against the same reference, only this one is slower on this query, and the previous build of this PR (458e5f43) ran it at 0.94x. In the last 14 days the test was flagged "slower" on 67 PRs and 6 master runs, on 6 of its 8 queries, on both arches.

The fix in progress is #107554: typed aggregation, so these queries no longer compare Fields (about 3x faster in its own runs). It has had no commits since June and no review, so I will send a smaller separate PR that compares integer keys inline in this map, keeping the ordering and the state format, and link it here.

@groeneai

groeneai commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator

The smaller PR is #124340: it compares integer keys inline in the sumMap/minMap/maxMap map, which removes the Field::operator< call from all 8 sum_map queries (0.43x to 0.53x of master time locally, same results and state bytes).

…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]>
alexey-milovidov pushed a commit to valerypetrov/ClickHouse that referenced this pull request Oct 7, 2026
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 CH Inc sync is red only because of private-side test failures that are unrelated to this PR (no Variant or aggregate-function code is involved):

  • 02345_compact_parts_read_bytes fails in 10 sequential jobs (the S3GetObject count is 22 instead of the expected 2). This is a private-only test, and a fix is already open in the private repository: ClickHouse/clickhouse-private#79792.
  • 03029_shared_merge_tree_slow_merge and 04238_alter_rename_column_merge_race each fail once, and the amd_msan parallel 1/3 job failed its hung check (server liveness check failed).

The public CI for this PR is green and there are no unresolved review threads. Re-running the sync will not help until the 02345 fix lands.

@Blargian
Blargian removed the request for review from a team October 8, 2026 07:33
@jh0x

jh0x commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

The fix in progress is #107554: typed aggregation, so these queries no longer compare Fields (about 3x faster in its own runs). It has had no commits since June and no review, so I will send a smaller separate PR that compares integer keys inline in this map, keeping the ordering and the state format, and link it here.

I'm updating #107554 - it got stuck in more or less done state.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @jh0x thank you, I will follow #107554. This PR does not depend on it, and the smaller #124340 covers the sum_map slowdown on its own.

The latest CH Inc sync run (on 9bcb2c8) is still red only because of private-side failures that have nothing to do with Variant or aggregate functions. Each one already has a tracking issue or an open fix:

The public CI is green, and no review threads are unresolved.

Comment thread src/AggregateFunctions/CrossTab.h Resolved
Comment thread src/Storages/StorageMergeTree.cpp Resolved
alexey-milovidov and others added 4 commits October 11, 2026 11:07
# 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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 CH Inc sync was red because the sync branch conflicted with private master in docs/resources/develop-contribute/native-protocol/format.mdx. I resolved it by taking this PR's version of the AggregateFunction paragraph, which was already reconciled with public master, merged the current PR head 4aa86f5ab28 into the sync branch, and pushed. The sync PR is MERGEABLE again, and private CI is running. All other CI checks on this PR are green, and there are no unresolved review threads.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Public CI is green. CH Inc sync failed on private-only test jobs that have nothing to do with this PR:

  • 04238_alter_rename_column_merge_race timed out after 600 s in Stateless tests (amd_msan, distributed cache, meta in keeper, s3 storage, parallel, 3/3). The timeout hit during the CREATE TABLE / INSERT phase of a SharedMergeTree table with plain String columns, with no Variant or aggregate functions involved. The test passes in every public run of the last 30 days.
  • test_storage_iceberg_with_spark/test_compaction.py::test_compaction_cleanup_tasks_are_released[s3-2] failed in Integration tests (amd_msan, 7/8). It is unrelated, and the sync status reports one of these failures as already known.
  • Stateless tests (amd_ubsan, meta in keeper, s3 storage, parallel, 2/2) was killed (exit code 143) with 0 test failures, which is an infrastructure problem.

I reran the failed jobs of the sync PR.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Superseded by a simpler reimplementation: #125726

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... pr-autogenerated-docs PR that regenerates docs artifacts from source; exempt from the autogenerated-region edit guard pr-backward-incompatible Pull request with backwards incompatible changes submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants