Skip to content

Add allow_lossy_numeric_supertype setting for numeric Variant common types - #107236

Merged
Avogar merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/variant-numeric-supertype-106707
Jul 22, 2026
Merged

Avogar merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/variant-numeric-supertype-106707

Conversation

@groeneai

@groeneai groeneai commented Jun 11, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Improvement

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

Added a new setting allow_lossy_numeric_supertype (disabled by default). When enabled, if, multiIf, coalesce, ifNull, array and map over numeric arguments that have no lossless common type (for example a Decimal and a Float64, or an Int64 and a Float64) resolve to the numeric supertype Float64 instead of a Variant, so the result can be used with aggregate functions like sum, avg, min and max. The setting name is now mentioned in the relevant aggregate function error messages. Closes #106707.

Description

Since use_variant_as_common_type became the default (#90677), if/multiIf/coalesce/array over mixed numeric branches with no lossless common type produce a Variant, and value-combining aggregates reject it:

SELECT sum(if(1, toDecimal64(1, 2), 0.));
-- Code: 43. Illegal type Variant(Decimal(18, 2), Float64) of argument for aggregate function sum. (ILLEGAL_TYPE_OF_ARGUMENT)

This is not a regression: the same query threw NO_COMMON_TYPE before #90677, only the error text changed.

Per the discussion on #106707, this is implemented as an opt-in improvement rather than a behavior change:

  • New setting allow_lossy_numeric_supertype, default false. With it off, behavior is exactly as before.
  • When on, getLeastSupertypeOrVariant first tries the lossless common type; if there is none and every branch is numeric with at least one floating point branch, it returns Float64 (matching binary arithmetic promotion) instead of building a Variant. Integer-only sets that lack a common type (for example Int64 + UInt64) keep producing a Variant, since there is no obvious lossy numeric supertype.
  • The setting is threaded through if/multiIf/coalesce/ifNull/array/map and the MultiIfToIf / IfChainToMultiIf analyzer passes.
  • sum, avg, min and max now name the setting in their illegal-type error when the rejected argument is an all-numeric Variant, giving users a clear escape hatch.
SET allow_lossy_numeric_supertype = 1;
SELECT toTypeName(if(1, toDecimal64(1, 2), 0.)); -- Float64
SELECT sum(if(1, toDecimal64(1, 2), 0.));        -- 1

Added stateless test 04327_allow_lossy_numeric_supertype covering both directions across if/multiIf/coalesce/array and sum/avg/min/max.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. clickhouse local -q "SET use_variant_as_common_type=1; SELECT sum(if(1, toDecimal64(1, 2), 0.))" fails every time with ILLEGAL_TYPE_OF_ARGUMENT on Variant(Decimal(18, 2), Float64).
b Root cause explained? use_variant_as_common_type (default since #90677) makes if/multiIf/coalesce/array call getLeastSupertypeOrVariant. For numeric branches with no lossless common type (Decimal + Float64, Int64 + Float64) getLeastSupertype returns no type, so a Variant is built; value-combining aggregates (sum/avg/min/max) reject Variant. Not a regression: pre-#90677 the same query threw NO_COMMON_TYPE, only the error text changed.
c Fix matches root cause? Yes. Adds an opt-in setting that makes the resolver produce the numeric supertype Float64 (arithmetic promotion) instead of a Variant for all-numeric branch sets, which is exactly the resolver-side approach requested on the issue.
d Test intent preserved / new tests added? New test 04327_allow_lossy_numeric_supertype added (both directions). No existing test weakened: the setting is default-off, so prior behavior is unchanged (verified against 02944_variant_as_common_type_analyzer, 03215_varian_*, 02513_validate_data_types, 04259_window_partition_by_dynamic_variant_validation).
e Both directions demonstrated? Yes, on a Build-ID-matched server. OFF: if(1, toDecimal64(1, 2), 0.) -> Variant(...), sum rejected with the new hint. ON: same -> Float64, sum = 1, min/max numeric (0.5, 3, not discriminator-ordered).
f Fix is general, not a narrow patch? Threaded through all six resolvers (if/multiIf/coalesce/ifNull/array/map) plus the MultiIfToIf / IfChainToMultiIf analyzer passes, and the error hint added to sum/avg/min/max. The fix is at the supertype-resolution source, not a defensive guard. Integer-only no-common-type sets (e.g. Int64 + UInt64) intentionally keep producing a Variant, since there is no obvious lossy numeric supertype.

Session id: cron:clickhouse-worker-slot-21:20260611-140600

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Avogar @CurtizJ — could you review this? Per your direction on #106707, it adds the default-off allow_lossy_numeric_supertype setting: when enabled, if/multiIf/coalesce/ifNull/array/map over all-numeric branches with no lossless common type resolve to Float64 instead of a Variant (so they can be aggregated), and the setting name is printed in the sum/avg/min/max error message.

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Jun 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [45567ae]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6) FAIL
test_check_table/test.py::test_check_all_tables FAIL cidb, issue ISSUE EXISTS

AI Review

Summary

This PR adds the opt-in allow_lossy_numeric_supertype fallback so if/multiIf/coalesce/ifNull/array/map can resolve mixed numeric branches to Float64 instead of Variant, and extends aggregate error hints around that behavior. The current tree still reintroduces the nullable-Map-key regression and the corresponding misleading aggregate hint, so I would request changes.

Findings

⚠️ Majors

  • [src/Functions/map.cpp:106-114] map still routes nullable numeric keys through the lossy Float64 fallback. For map(materialize(toNullable(toDecimal64(1, 2))), 1, 0., 2) this produces Nullable(Float64) and DataTypeMap throws BAD_ARGUMENTS, even though the pre-setting path produced a valid Map(Variant(Decimal(18, 2), Float64), UInt8). That makes enabling allow_lossy_numeric_supertype break an existing valid map shape instead of improving it.
    Suggested fix: keep the old Variant path for keys when the lossy key type is not a valid Map key (!DataTypeMap::isValidKeyType(lossy_type)), and cover the nullable-key case in the stateless test as a successful Map(Variant(...), UInt8) result.
  • [src/DataTypes/getLeastSupertype.cpp:1030-1046], [src/AggregateFunctions/AggregateFunctionsMinMax.cpp:38-50], [src/AggregateFunctions/AggregateFunctionsArgMinArgMax.cpp:122-135], [src/AggregateFunctions/Combinators/AggregateFunctionCombinatorsArgMinArgMax.cpp:77-90] The setting hint is still unconditional for float-bearing numeric Variants, so min/argMin/*ArgMin over a Map with a nullable numeric key still tell users to enable allow_lossy_numeric_supertype, but the current map resolver turns the enabled case into BAD_ARGUMENTS instead of removing the Variant. That guidance is incorrect for one of the touched SQL surfaces.
    Suggested fix: thread Map-key context into getNumericVariantSupertypeHint (or otherwise suppress/retune the wording for nullable key paths) and add one nullable-key negative-path check for argMin or a combinator alongside the existing min coverage.
Final Verdict
  • Status: ⚠️ Request changes

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jun 11, 2026
Comment thread src/DataTypes/getLeastSupertype.cpp Resolved
Comment thread src/DataTypes/getLeastSupertype.cpp Resolved
@groeneai
groeneai force-pushed the groeneai/variant-numeric-supertype-106707 branch from 368e6ab to 8643161 Compare June 11, 2026 16:01
@groeneai
groeneai force-pushed the groeneai/variant-numeric-supertype-106707 branch from 8643161 to bf4ef9b Compare June 11, 2026 16:46
@groeneai

Copy link
Copy Markdown
Collaborator Author

Addressed all four review comments in bf4ef9b (replied in-thread to each):

  • getLeastSupertype.cpp: tryGetLossyNumericSupertype skips onlyNull() branches while tracking nullability, so a NULL branch no longer forces a Variant (multiIf(c1, NULL, c2, Decimal, Float64) -> Nullable(Float64)).
  • The aggregate error hint now reuses that eligibility check, so it is shown only when enabling the setting would actually replace the Variant (>=1 float branch); integer-only Variants no longer point at the setting.
  • Test: nullable coalesce that reaches the fallback, focused ifNull/map cases, end-to-end value assertions for if/multiIf/coalesce/ifNull/array/map, an integer-only aggregate-error case, and the NULL-branch case. Dropped no-fasttest.

Verified both directions locally on a Build-ID-matched debug binary; the test passes plain and 30/30 with full settings randomization. Regression: 00735_long_conditional, 02944_variant_as_common_type_analyzer, 00435_coalesce, 00433_ifnull, 02513_validate_data_types unchanged (fix is gated behind the default-off setting).

Comment thread src/Functions/map.cpp
{
tmp.emplace_back(getLeastSupertypeOrVariant(keys));
tmp.emplace_back(getLeastSupertypeOrVariant(values));
tmp.emplace_back(getLeastSupertypeOrVariant(keys, allow_lossy_numeric_supertype));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Applying the lossy fallback to keys can turn a previously valid Map(Variant(...), ...) into an exception. For example, with use_variant_as_common_type = 1, map(materialize(toNullable(toDecimal64(1, 2))), 1, 0., 2) used to infer the key type through the old getLeastSupertypeOrVariant path: Nullable(Decimal) + Float64 has no lossless common type, so the Variant builder strips the nullable wrapper and produces Variant(Decimal(18, 2), Float64), which DataTypeMap::assertKeyType accepts. With this line, tryGetLossyNumericSupertype preserves nullability and returns Nullable(Float64), and DataTypeMap::assertKeyType rejects Map keys of that type. Please keep the old Variant path for keys when the lossy key type would be nullable (or restrict the setting to map values), and add a regression for nullable numeric keys.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Good catch, fixed in 57061b4. A Map key cannot be Nullable, and the lossy fallback preserves nullability (returns Nullable(Float64)), so applying it to keys regressed valid map(...) constructions. Now, when the lossy key type would be an invalid Map key (!DataTypeMap::isValidKeyType), the key falls back to the plain Variant path (which drops the Nullable wrapper). Map values are unaffected, and non-nullable numeric keys still resolve to the lossy Float64 supertype.

Verified on a debug build (use_variant_as_common_type=1):

  • allow_lossy_numeric_supertype=1, map(materialize(toNullable(toDecimal64(1, 2))), 1, 0., 2): was BAD_ARGUMENTS (Map cannot have a key of type Nullable(Float64)), now Map(Variant(Decimal(18, 2), Float64), UInt8) and the map builds.
  • allow_lossy_numeric_supertype=1, non-nullable key map(toDecimal64(1, 2), 'x', 0., 'y'): still Map(Float64, String).
  • allow_lossy_numeric_supertype=0: unchanged.

Added regressions to 04327 (nullable numeric key under both setting values, plus the non-nullable lossy key case). Passes 30/30 with full randomization.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This is still present in the current tree. src/Functions/map.cpp:106-114 now goes straight through getLeastSupertypeOrVariant(keys, allow_lossy_numeric_supertype) again, so a nullable numeric key still becomes Nullable(Float64) and DataTypeMap rejects it. The new expectation at tests/queries/0_stateless/04327_allow_lossy_numeric_supertype.sql:39-40 now hard-codes that original failure mode (BAD_ARGUMENTS) instead of preserving the previously valid Map(Variant(...), UInt8) key type.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

This is intentional and was settled in review. On 2026-06-24 (comment 3467725468) @ Avogar directed: "how supertype here can become Nullable? Even if it can, we should just throw if it becomes Nullable." The carve-out that kept the plain Variant key was dropped per that direction, so an opted-in nullable numeric Map key now throws BAD_ARGUMENTS. That is the requested behavior, not a regression.

The setting is default-off, so nothing changes for anyone who does not opt in (verified locally, Build ID f20bfd2):

  • allow_lossy_numeric_supertype=0 (default), use_variant_as_common_type=1: map(materialize(toNullable(toDecimal64(1,2))), 1, 0., 2) -> Map(Variant(Decimal(18, 2), Float64), UInt8), exactly as before.
  • allow_lossy_numeric_supertype=1: throws BAD_ARGUMENTS (Avogar's "just throw" outcome).
  • Non-nullable numeric key, setting on: Map(Float64, String) (lossy applies where it can).

The 04327:39-40 expectation encodes precisely this settled outcome.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jun 11, 2026
A Map key cannot be Nullable, but the opt-in lossy numeric fallback
(allow_lossy_numeric_supertype) preserves nullability and can return
Nullable(Float64). For map(...) keys that made a previously valid
construction throw: with use_variant_as_common_type=1,
map(materialize(toNullable(toDecimal64(1, 2))), 1, 0., 2) used to infer
the key type via the Variant path, which strips the Nullable wrapper and
produces an accepted Variant(Decimal, Float64) key; with the lossy
fallback it became Nullable(Float64), which DataTypeMap::assertKeyType
rejects.

Keep the plain Variant key (dropping the Nullable wrapper) when the lossy
key type would be an invalid Map key. Map values are unaffected, and
non-nullable numeric keys still resolve to the lossy Float64 supertype.

Addresses clickhouse-gh[bot] review on src/Functions/map.cpp in PR ClickHouse#107236.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (commit 57061b4, nullable Map-key fix)

# Question Answer
a Deterministic repro? Yes. On the unfixed binary, SET use_variant_as_common_type=1, allow_lossy_numeric_supertype=1; SELECT map(materialize(toNullable(toDecimal64(1, 2))), 1, 0., 2); throws Code 36 BAD_ARGUMENTS: Map cannot have a key of type Nullable(Float64) every time.
b Root cause explained? A Map key cannot be Nullable (DataTypeMap::isValidKeyType rejects isNullableOrLowCardinalityNullable). The lossy fallback tryGetLossyNumericSupertype preserves nullability and returns Nullable(Float64) for a nullable numeric key. The previous Variant path stripped the Nullable wrapper and produced an accepted Variant(Decimal, Float64) key, so opting in regressed a valid map(...).
c Fix matches root cause? Yes. In FunctionMap::getReturnTypeImpl, when the lossy key type is not a valid Map key, fall back to the plain getLeastSupertypeOrVariant(keys) (Variant, non-nullable). Targets exactly the invalid-nullable-key mechanism; values are untouched.
d Test intent preserved / new tests added? Yes. Added 04327 regressions: nullable numeric key under allow_lossy_numeric_supertype 0 and 1 (both must yield a valid Variant key, and the map must build), plus a non-nullable numeric key that still resolves to the lossy Float64 key. No existing assertions weakened.
e Both directions demonstrated? Yes. Unfixed: throws Code 36. Fixed (Build ID ba9c9dfd..., verified differs from pre-edit 053ffcbf...): type is Map(Variant(Decimal(18, 2), Float64), UInt8) and the map builds ({1:1,0:2}).
f Fix is general, not a narrow patch? Yes. Checked every caller of the lossy getLeastSupertypeOrVariant(types, bool) overload (if/multiIf/coalesce/ifNull/array, map values). The no-Nullable-key restriction is Map-key-specific; all other sinks accept Nullable results, so the fix belongs only at the map-key site. mapFromArrays takes pre-typed arrays and is unaffected.

Session id: cron:clickhouse-worker-slot-4:20260611-174300

@groeneai

Copy link
Copy Markdown
Collaborator Author

Follow-up: the Stateless tests (old analyzer) CI variant failed on 04327 (its own new test). Fixed in 8950405 (test-only). Pre-PR validation gate:

Gate Status
a) Deterministic repro Yes. clickhouse local --enable_analyzer=0 -q "SET use_variant_as_common_type=1; SET allow_lossy_numeric_supertype=0; SELECT sum(if(1, toDecimal64(1, 2), 0.))" returns 1 instead of raising error 43, on every run.
b) Root cause The old (non-analyzer) pipeline constant-folds a literal-constant condition if(1, X, Y) / multiIf(1, X, Y) to the taken branch before combining branch types, so no Variant is built: the branch resolves to plain Decimal/Int64 and sum/avg/max succeed (no 43), and toTypeName prints the folded branch type. The new analyzer does not fold at type resolution, builds the Variant, and raises 43. So only the literal-constant-condition queries diverged on the old analyzer; the feature itself is analyzer-agnostic (with a non-constant condition both analyzers build the same Variant when the setting is off and the same Float64 supertype when it is on).
c) Fix matches root cause Yes. Wrapping the constant conditions in materialize(...) stops the fold, so the branch types are always combined under both analyzers. This targets the fold directly rather than masking it with a no-old-analyzer tag.
d) Test intent preserved Strengthened. A folded constant condition never exercised branch-type-combining under the old analyzer at all; materialize keeps full coverage under both analyzers. The .reference is unchanged.
e) Demonstrated both directions Pre-fix: old-analyzer full-file run diverges on the 9 constant-condition queries. Post-fix: clickhouse-test with randomization passes 10/10 under the old analyzer (enable_analyzer=0) and 10/10 under the new analyzer (enable_analyzer=1); reference unchanged.
f) Fix is general N/A (test-only change). No source code modified by this commit.

Session: cron:clickhouse-worker-slot-0:20260611-225500

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jun 12, 2026
min/max recurse into the argument type with forEachChild and reject any
nested Variant. For Array(Variant(...)) and Map(..., Variant(...)) the
Variant is reached as a child, but the error built the
allow_lossy_numeric_supertype hint from this->result_type (the outer
Array/Map), which is not itself a Variant, so getNumericVariantSupertypeHint
returned empty and no hint was shown. Enabling the setting turns the nested
Variant into a numeric supertype (e.g. Array(Float64)) and the aggregate
works, so the hint should be shown.

Build the hint from the rejected child type instead. The helper still
self-guards (all-numeric with at least one float), so it stays silent for
non-numeric or integer-only nested Variants where the setting cannot help.
sum/avg are unaffected: they reject Array/Map before recursing and the
setting would not make them work, so they correctly emit no hint.

Addresses clickhouse-gh[bot] review on
src/AggregateFunctions/AggregateFunctionsMinMax.cpp in PR ClickHouse#107236.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

Follow-up commit 64128a9 (min/max hint for nested Variant arguments).

# Question Answer
a Deterministic repro? Yes. With use_variant_as_common_type=1, allow_lossy_numeric_supertype=0: SELECT min([toDecimal64(1, 2), 0.]) and SELECT min(map('a', toDecimal64(1, 2), 'b', 0.)) throw ILLEGAL_TYPE_OF_ARGUMENT with NO setting hint, while the scalar min(if(...)) already showed it. Same on both analyzers.
b Root cause explained? min/max recurse into the argument type via forEachChild and reject any nested Variant. For Array(Variant(...))/Map(..., Variant(...)) the Variant is the child; the error built the hint from this->result_type (the outer Array/Map), which is not a Variant, so getNumericVariantSupertypeHint returned empty.
c Fix matches root cause? Yes. The hint is built from the rejected child type (the lambda argument) instead of this->result_type, so the nested Variant is inspected directly. One-line change at the throw site.
d Test intent preserved / new tests added? New regression 04328_lossy_numeric_supertype_nested_hint.sh: asserts the hint is present for nested numeric Variants (Array min/max, Map min), absent for a non-numeric branch and an integer-only set, and that the aggregate works with the setting on. Existing 04327 unchanged (10/10).
e Both directions demonstrated? Yes. Pre-fix binary (Build ID ba9c9dfd): no hint for Array/Map. Post-fix binary (Build ID 6e48acbf): hint present for Array/Map, still absent for non-numeric/integer-only, aggregate succeeds with setting on. New test 20/20 with randomization.
f Fix is general, not a narrow patch? Checked all getNumericVariantSupertypeHint callers: sum (AggregateFunctionSum.cpp) and avg (AggregateFunctionAvg.cpp) reject Array/Map before recursing and enabling the setting would not make them accept an array, so emitting a hint there would be misleading; they correctly stay silent and are left unchanged. Fix is scoped to the min/max per-child site. The helper's own all-numeric+float self-guard prevents misleading hints for the child type.

Session id: cron:clickhouse-worker-slot-0:20260612-001100

@Avogar Avogar self-assigned this Jun 12, 2026
this->result_type->getName(),
getName());
getName(),
getNumericVariantSupertypeHint(type.getPtr()));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The hint can still fire for numeric Variant Map keys even though enabling the setting cannot remove that Variant. For map(materialize(toNullable(toDecimal64(1, 2))), 1, 0., 2), FunctionMap first gets Nullable(Float64) from the lossy path, then falls back to plain getLeastSupertypeOrVariant(keys) because Map keys cannot be Nullable, so the key stays Variant(Decimal(18, 2), Float64) with the setting enabled. min/max then reach this child and append the hint from type, telling the user to enable a setting that will not make the aggregate work. Please suppress the hint for Map keys where the map resolver will keep the Variant, or make the fallback eligibility helper aware of that key-type constraint and add a regression like min(map(materialize(toNullable(toDecimal64(1, 2))), 1, 0., 2)).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in f68a9a5. min/max now track whether a Variant is reached through a Map key and suppress the setting hint there, since enabling the setting cannot remove a Variant Map key (Map keys cannot be Nullable, so FunctionMap keeps the plain Variant key, and the resolved type is identical for nullable and non-nullable numeric keys). The hint is kept for Map values, array/tuple elements and scalars. Replaced the position-blind forEachChild scan with a recursive walk over immediate children. Regression added in 04328 for min/max over a nullable-numeric Map key, the same nested in an Array, and a Map with a numeric Variant in both key and value (the surviving key Variant means no hint).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This is still present in the current tree. src/DataTypes/getLeastSupertype.cpp:1030-1046 no longer carries any Map-key context; it emits the generic setting hint for any float-bearing numeric Variant. src/AggregateFunctions/AggregateFunctionsMinMax.cpp:38-50, src/AggregateFunctions/AggregateFunctionsArgMinArgMax.cpp:122-135, and src/AggregateFunctions/Combinators/AggregateFunctionCombinatorsArgMinArgMax.cpp:77-90 all call that helper directly on the rejected child type, so nullable numeric Map keys still point users at allow_lossy_numeric_supertype even though src/Functions/map.cpp:106-114 now turns the enabled case into BAD_ARGUMENTS instead of removing the Variant.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The Map-key hint scoping was intentionally removed in review. On 2026-06-24 (comment 3467707340) @ Avogar directed: "Let's not care about strange case with map key, it only pollutes the code", and the map-key context tracking in the hint helper was dropped accordingly. Re-adding a Map-key carve-out here would reintroduce exactly that context tracking.

The hint helper only sees the final rejected type, which for a nullable numeric Map key is the non-nullable Map(Variant(Decimal(18, 2), Float64), UInt8) (Map keys cannot be Nullable). That is indistinguishable at this site from a helpable if/multiIf/array Variant, so scoping it out is not possible without the per-Map-key context Avogar asked us to remove. Leaving as-is per that direction.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. SELECT min(map(materialize(toNullable(toDecimal64(1, 2))), 1, 0., 2)) SETTINGS allow_lossy_numeric_supertype=0 shows the hint, and with =1 the query still throws (Code 43), proving enabling the setting does not help.
b Root cause explained? A Map key cannot be Nullable, so for a nullable numeric key FunctionMap discards the Nullable(Float64) lossy type and keeps the plain Variant(Decimal, Float64) key. The setting-off result type is identical for nullable and non-nullable numeric keys (Map(Variant(Decimal, Float64), ...)), so position is the only signal. min/max recursed into that child via forEachChild and appended getNumericVariantSupertypeHint(child), pointing at a setting that cannot remove the key Variant.
c Fix matches root cause? Yes. Replaced the position-blind forEachChild scan with a recursive walk that carries an in_map_key flag and suppresses the hint only when the Variant is reached through a Map key. No band-aid (no widened bounds, no tag).
d Test intent preserved / new tests added? Preserved: existing array/value/scalar hint cases unchanged. Added 04328 regression: min/max over a nullable-numeric Map key, the same nested in an Array, and a Map(Variant, Variant) (key Variant survives, no hint) all assert grep -c = 0.
e Both directions demonstrated? Yes. Pre-fix binary (Build ID 3754d094): all 4 new map-key lines show the hint (grep -c = 1) vs reference 0, so 04328 FAILS. Fixed binary (Build ID 8e4996f9): 04328 matches reference; runner 10/10 new analyzer + 10/10 old analyzer; 04327 unchanged under both analyzers.
f Fix is general, not a narrow patch? The recursion handles Map keys at any depth (e.g. Array(Map(...))), and Map values, Array, Tuple, Nullable, LowCardinality children. Checked the other hint callers: sum and avg reject Array/Map before recursion and enabling the setting would not make sum(Array(Float64)) work, so they correctly stay silent and are unchanged.

Session id: cron:clickhouse-worker-slot-1:20260620-081200

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. With --allow_lossy_numeric_supertype=0, clickhouse local -q "SELECT min(map(toDecimal64(1,2), 1, 0., 2))" showed NO setting hint on the pre-fix binary (Build ID 8e4996f9), even though enabling the setting makes the aggregate work. On demand, every run.
b Root cause explained? A Map key cannot be Nullable. f68a9a5 suppressed the hint for ALL Map-key Variants via in_map_key. But a non-nullable numeric key resolves to Float64 (valid key) with the setting on, so the hint should show there. Verified the resolved type is byte-identical (Map(Variant(Decimal,Float64),UInt8)) for nullable and non-nullable keys with the setting off, so min/max cannot distinguish them from the resolved type.
c Fix matches root cause? Yes. Since the two cases are indistinguishable at the min/max site, route (a) (suppress only nullable) is infeasible. Took route (b): a Map-key-specific hint wording that names the setting without claiming it always works. Correct for both cases simultaneously.
d Test intent preserved / new tests added? 04328 updated: asserts the Map-key wording for non-nullable AND nullable keys (and array-nested), that the non-nullable key aggregates to Map(Float64, UInt8) with the setting on, and that the general if/multiIf/array/Map-value sites keep the original wording. Distinguishes the two hint variants by phrase.
e Both directions demonstrated? Yes (Build ID 8e4996f9 -> 9a2d02dd). Pre-fix: non-nullable Map key shows NO hint. Post-fix: both Map-key cases show the Map-key wording; setting on -> non-nullable key gives Map(Float64, UInt8) (works), nullable key still throws (Variant). 04328 + 04327 match reference under enable_analyzer=1 and =0 against a running server.
f Fix is general, not a narrow patch? Checked all 3 callers of getNumericVariantSupertypeHint. sum/avg reject Array/Map before recursion and the setting would not make sum(Array(Float64)) work, so they correctly stay silent (default flag, unchanged). The Map-key constraint is min/max-specific (only they recurse into nested Variants). The recursion handles Map keys at any nesting depth.

Session id: cron:clickhouse-worker-slot-1:20260620-102500

Comment thread src/Core/Settings.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. Doc-accuracy issue: SELECT description FROM system.settings WHERE name='allow_lossy_numeric_supertype' returned text promising map over mixed numerics resolves to Float64, with no nullable-Map-key exception, while toTypeName(map(materialize(toNullable(toDecimal64(1,2))), 1, 0., 2)) SETTINGS allow_lossy_numeric_supertype=1 stays Map(Variant(Decimal(18,2),Float64), UInt8).
b Root cause explained? The setting description over-promised: a Map key cannot be Nullable, so FunctionMap discards the lossy Nullable(Float64) key and keeps the Variant key (shipped in 57061b4). The description text did not state that exception, so the user-facing contract did not match the implemented behavior.
c Fix matches root cause? Yes. Added one sentence to the setting description documenting the exception (non-nullable keys and all values resolve; a nullable numeric Map key stays a Variant), mirroring the min/max error-hint wording. Aligned the PR Description bullet to match.
d Test intent preserved / new tests added? N/A (documentation-text-only change). No test asserts the description string; setting name/type/default unchanged, so SettingsChangesHistory.cpp needs no entry and 04327/04328 are unaffected.
e Both directions demonstrated? Yes. Verified the documented behavior is the actual behavior on the rebuilt binary (Build ID 9a2d02dd -> e4a88fdc): setting on -> nullable numeric Map key stays Map(Variant(...)); non-nullable key -> Map(Float64, UInt8); nullable value -> Map(UInt8, Nullable(Float64)). The new sentence describes exactly these results.
f Fix is general, not a narrow patch? Yes. The same map->Float64 promise also appeared in the PR Description; updated it identically so the setting description, the min/max in-code hint, and the PR Description all state the nullable-Map-key exception consistently. DECLARE macro re-parses (incremental build clean).

Session id: cron:clickhouse-worker-slot-1:20260620-154500

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. The gap is deterministic: 04327 asserts only the error code (43) for scalar sum/avg over a top-level numeric Variant, so the hint text was unguarded. Against the current binary: sum(if(materialize(1), toDecimal64(1,2), 0.)) and avg(multiIf(materialize(1), toInt64(1), 0.)) print the if/multiIf/coalesce/array hint; sum(if(materialize(toUInt8(1)), toInt64(1), toUInt64(2))) prints no setting mention.
b Root cause explained? getNumericVariantSupertypeHint is appended by scalar sum (AggregateFunctionSum.cpp:68) and avg (AggregateFunctionAvg.cpp:45) with in_map_key=false, emitting the general hint for an all-numeric Variant with a float and staying silent for an integer-only Variant. 04328 was the only test asserting the hint text, but it exercised only the min/max nested-type walk, leaving the scalar sum/avg paths untested.
c Fix matches root cause? This is a test-coverage gap, not a code bug. The fix adds three grep assertions covering exactly the untested scalar sum/avg hint paths the bot identified. No source change.
d Test intent preserved / new tests added? Test strengthened, nothing removed. Three assertions added: general hint present for sum(if(...Decimal..., 0.)) and avg(multiIf(...Int64..., 0.)), absent for the integer-only sum(if(...Int64..., UInt64...)). Mirrors 04327's scalar negative-path queries (which check only the code) but asserts the hint text.
e Both directions demonstrated? Yes. The three new lines were verified to produce exactly the committed reference values against the current binary (Build ID e4a88fdc, matching PR head). A future regression in the sum/avg hint (lost hint, or hint wrongly shown for the integer-only case) would flip these grep outputs and fail the test.
f Fix is general, not a narrow patch? N/A (test-only addition, no code change). The sibling-path coverage is the point: this closes the sum/avg branch of the hint that the existing min/max-only assertions did not cover.

Validation: new analyzer via the clickhouse-test runner with full randomization (04328 OK, 04327 10/10); old analyzer via a full-file clickhouse-local diff (no diff). ASCII only, no source change, SettingsChangesHistory untouched.

Session id: cron:clickhouse-worker-slot-3:20260620-163900

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finished on HEAD 96fed2009af. The two red checks rolled up into Mergeable Check are both CI infrastructure, not caused by this PR:

  • Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DatabaseReplicated, WasmEdge, parallel) — job-level error with "Lost s3 keys" (transient S3 credential expiry on the coverage runner; 8 unrelated PRs hit the same signature in the last 3 days). report
  • Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6) — batch crashed at setup, emitting zero test rows; batches 1/6, 2/6, 3/6, 4/6, 6/6 all passed with 0 failures. job

No PR-caused failures. All other jobs green; Style check and Finish Workflow succeeded.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 1ca16a9

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. This PR's diff (Variant numeric common types) does not touch any failing code path — no failure is PR-caused.

Check / test Reason Owner / fixing PR
Stateless (amd_debug/amd_msan/amd_tsan/arm_binary, sequential) / 02346_text_index_bug108519_qcc_skip_index flaky (randomized statistics) #110260 (ours, merged 2026-07-13 15:05Z) — this build predates the merge
Stateless (amd_tsan, s3, sequential) / Scraping system tables infra (minio_audit_logs dump 600s timeout) a fix task is created (investigating at full effort — fixing-PR link to follow here)
Stress test (arm_debug) / Logical error: Block structure mismatch in ... stream (STID 0993-386d) logical error (JoinStep duplicate column, trunk) #109114 (ours, open)
Stress test (arm_release) / Hung check failed, possible deadlock found deadlock (hung-check family) #108212 (ours, merged) / #105905 (ours, merged)
CH Inc sync — CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260713-190000

Comment thread src/Functions/coalesce.cpp Outdated
bool has_variant = std::any_of(new_args.begin(), new_args.end(), [](const auto & t) { return isVariant(t); });
auto res = (use_variant_as_common_type || has_variant) ? getLeastSupertypeOrVariant(new_args) : getLeastSupertype(new_args);
auto res = (use_variant_as_common_type || has_variant || allow_lossy_numeric_supertype)
? getLeastSupertypeOrVariant(new_args, use_variant_as_common_type || has_variant, allow_lossy_numeric_supertype)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

It looks weird. I would expect it to be smth like:

DataType res;
if (use_variant_as_common_type || has_variant)
    res = getLeastSupertypeOrVariant(new_args, allow_lossy_numeric_supertype);
else
    res = getLeastSupertype(new_args, allow_lossy_numeric_supertype);

Comment thread src/Functions/coalesce.cpp Resolved
@Avogar

Avogar commented Jul 16, 2026

Copy link
Copy Markdown
Member

@groeneai address my comments

@groeneai

Copy link
Copy Markdown
Collaborator Author

@Avogar addressed in 5010452:

1. The resolver shape. Dropped the use_variant parameter. There are now two overloads and each call site picks between them exactly as you suggested:

getLeastSupertype(types, allow_lossy_numeric)          // lossless -> lossy numeric -> throw
getLeastSupertypeOrVariant(types, allow_lossy_numeric) // lossless -> lossy numeric -> Variant

Call sites (if/multiIf/coalesce/ifNull/array/map):

if (use_variant_as_common_type || has_variant)
    res = getLeastSupertypeOrVariant(new_args, allow_lossy_numeric_supertype);
else
    res = getLeastSupertype(new_args, allow_lossy_numeric_supertype);

No behavior change: the lossy numeric fallback was already independent of use_variant, and both overloads run it before their respective final step.

2. The LowCardinality(Nullable(...)) de-nulling concern (bot comment): not valid on this branch. I could not reproduce a leak. coalesce/ifNull use the default useDefaultImplementationForLowCardinalityColumns() (returns true), so the adaptor strips LowCardinality before getReturnTypeImpl. The method sees Nullable(Int64) + Float64, the existing removeNullable cleanup de-nulls to Float64, and the adaptor re-wraps to LowCardinality(Float64). The bot's own repro confirms it:

SELECT toTypeName(coalesce(toLowCardinality(toNullable(toInt64(1))), toLowCardinality(0.)))
SETTINGS use_variant_as_common_type = 0, allow_lossy_numeric_supertype = 1;
-- LowCardinality(Float64)   (not LowCardinality(Nullable(Float64)))

SELECT toTypeName(ifNull(toLowCardinality(toNullable(toInt64(1))), toLowCardinality(0.))) SETTINGS ...;
-- LowCardinality(Float64)

When the last branch is genuinely nullable it correctly stays nullable (LowCardinality(Nullable(Float64))). So there is nothing to fix here and no separate PR is needed.

Both regression tests (04327_allow_lossy_numeric_supertype, 04328_lossy_numeric_supertype_nested_hint) pass on the rebuilt binary.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 5010452

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (amd_asan_ubsan) / UBSan division-by-zero (STID 4141-5b13, __chrono/duration.h:460) chronic trunk (22 PRs / 1 master, 30d; zero-length quota interval) fixing PR #110346 (ours, open, @PedroTadim approved)
Upgrade check (amd_release) / "Error message in clickhouse-server.log" (DiskLocalCheckThread clickhouse_disk_checker_* FILE_DOESNT_EXIST) infra teardown race (2 unrelated PRs / 0 master, 30d) a fix task is created (investigating at full effort; fixing-PR link to follow here)
CH Inc sync - CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260717-020000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Upgrade-check DiskLocalCheckThread disk_checker FILE_DOESNT_EXIST/CANNOT_UNLINK teardown-race leak: #110773

Comment thread src/DataTypes/getLeastSupertype.cpp Outdated
return {};

/// Only the final Variant type is visible here, not whether it was inferred (setting applies)
/// or stored/cast (it does not), so keep the wording conditional. Kept short per review.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Kept short per review.

This is a bad comment. Check throughout the changes for bad/too long/non-informative comments and clean them up.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in 45567ae. Dropped the "Kept short per review" meta-note from the hint comment and tightened the onlyNull()-skip comment in getLeastSupertype.cpp. Swept the rest of the diff for meta/non-informative comments; those were the only ones. No behavior change.

Comment thread src/Core/SettingsChangesHistory.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 3f848b6

CI fully finished (Finish Workflow pass; 0 checks queued/in-progress). Four failures, all non-PR-caused (this PR only affects numeric Variant supertype / getLeastSupertype), each with an owner:

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug) / Logical error '!part.empty()' (STID 2508-2ef2) trunk AST-fuzzer bug (backquoted identifier ending in dot; many unrelated PRs + master) a fix task is on review for this (ASTIdentifier !part.empty() family)
Stress test (amd_tsan) / Type mismatch when building statistics (STID 0250-4148) trunk flaky (7+ unrelated PRs + 2 master in 14d) #109415 (ours, open)
Stress test (amd_tsan) / Cannot start clickhouse-server + Check failed flaky infra (multiple unrelated PRs in 7d) flaky server-restart, not PR-caused
CH Inc sync — CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260717-170000

@Avogar Avogar left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai check latest review comments from bot

New default-off setting allow_lossy_numeric_supertype. When enabled,
if/multiIf/coalesce/ifNull/array/map over numeric arguments with no lossless
common type (e.g. Decimal + Float64, or Int64 + Float64) resolve to the numeric
supertype Float64 (with possible precision loss) instead of failing, so the
result can be used with value-combining aggregates (sum/avg/min/max). This is
independent of use_variant_as_common_type: the numeric supertype is produced
whether or not use_variant_as_common_type is enabled.

When the aggregate rejects a Variant that this setting could turn into a numeric
supertype, the "illegal type" error points at the setting; the hint stays silent
for Variants the setting cannot help (integer-only, non-numeric, or composite
branches that resolve to a top-level Variant of composites).

Closes: ClickHouse#106707

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai
groeneai force-pushed the groeneai/variant-numeric-supertype-106707 branch from 3f848b6 to 45567ae Compare July 21, 2026 19:09
@clickhouse-gh

clickhouse-gh Bot commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.10% 92.00% -0.10%
Branches 78.30% 78.30% +0.00%

Changed lines: Changed C/C++ lines covered: 185/185 (100.00%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 45567ae

CI fully finished on this head (174 checks completed: 154 success, 19 skipped, 1 failure). No PR-caused failure: this PR only changes Variant numeric common-type resolution (getLeastSupertype + Settings + Functions map/coalesce + aggregate hints), which does not touch the failing code path.

Check / test Reason Owner
Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6) / test_check_table::test_check_all_tables trunk flaky (30d: ~20 unrelated PRs + 6 on master) #111289 (open tracking issue)

Session id: cron:clickhouse-maint-slot-8:20260722-011501

@Avogar
Avogar enabled auto-merge July 22, 2026 12:24
@Avogar
Avogar added this pull request to the merge queue Jul 22, 2026
Merged via the queue into ClickHouse:master with commit 2311b21 Jul 22, 2026
177 of 179 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 22, 2026
alexey-milovidov added a commit that referenced this pull request Jul 23, 2026
… declarative signatures

After merging master (which brought #107236, the `allow_lossy_numeric_supertype`
setting), the declarative signatures of `if`, `array` and `map` remained
authoritative on the `ColumnsWithTypeAndName` path, but the `leastSupertype`
type-function always uses the strict mode, so the setting was ignored and these
functions kept returning `Variant` where master returns the lossy numeric
supertype. Apply the same reconciliation `multiIf`, `coalesce` and `ifNull`
already received: when the setting is enabled, bypass the declarative signature
and compute the common type via the legacy implementation.

Fixes `04327_allow_lossy_numeric_supertype` and
`04328_lossy_numeric_supertype_nested_hint` in Fast test:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104948&sha=6facf8919dd6a30d64dacd199d42dfd7cc28fed0&name_0=PR&name_1=Fast%20test

Co-Authored-By: Claude Fable 5 <[email protected]>
@atsarevskiy

Copy link
Copy Markdown
Contributor

@Avogar
Could we make allow_lossy_numeric_supertype work for stored columns as well? We have a use-case for this, see #118700

@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

allow_lossy_numeric_supertype sits in supertype resolution (getLeastSupertype / getLeastSupertypeOrVariant), so it only changes the type ClickHouse infers for if/multiIf/coalesce/ifNull/array/map over numeric arguments. A stored column's type is declared rather than inferred, so there is no resolution step for the flag to intercept: accepting sum(v) on a stored Variant/Dynamic means combining the active subtypes inside the aggregate itself, which is new behaviour in the argument-type path rather than a wider scope for this setting. That is a design call for the aggregate-functions owners, so I will leave #118700 to them.

One thing that works today, in case it helps before that: cast per row instead of per subcolumn. It covers all four aggregates, works on a stored Variant and on Dynamic, keeps the rows of every numeric alternative, and needs no knowledge of the stored type. Measured on master (26.9.1.1) over rows 1::UInt64, 2.5::Float64, -3::Int64, true::Bool, 'n/a'::String:

SELECT sum(x), max(x), avg(x), quantile(0.5)(x), count(x)
FROM (SELECT accurateCastOrNull(v, 'Float64') AS x FROM t);
-- 1.5   2.5   0.375   1   4

accurateCastOrNull rather than v::Float64 because the plain cast raises CANNOT_PARSE_NUMBER on the 'n/a' row. Two semantics worth knowing: Bool counts as 0/1, and a numeric string is parsed rather than skipped (adding '42'::String gives sum = 43.5, count = 5), so count(x) against count() is what tells you how many rows the cast dropped.

zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…umeric-supertype-106707

Add allow_lossy_numeric_supertype setting for numeric Variant common types
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-improvement Pull request with some product improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Cannot aggregate a Variant produced by if/coalesce/multiIf over mixed types

6 participants