Repository navigation
Fix values() table function rejecting lossy floats for narrow float columns - #108055
Conversation
…olumns
The `values` table function rejected decimal literals that are not exactly
representable in a narrower floating-point column, e.g.
SELECT * FROM values('x Float32', 0.1)
-- Code 69: Cannot convert value '0.1' from Float64: it cannot be represented as Float32
This was inconsistent with `INSERT ... VALUES (0.1)` into the same column,
which works.
Root cause: `convertNumericType`/`convertNumericTypeImpl` in
`convertFieldToType.cpp` ignored the `strict` parameter and always asked
`accurate::convertNumeric` for an exact-equality check after the conversion.
Almost no decimal literal is exactly representable in `Float32`, so non-strict
callers (the `VALUES` section, the `values` table function, `INSERT`) rejected
them.
Thread `strict` through these helpers and skip the exact-equality check when
converting to a floating-point type in non-strict mode, returning the nearest
representable value like `CAST` does. The range check inside
`accurate::convertNumeric` is unchanged, so out-of-range values are still
rejected (`1e300` to `Float32` still errors, no silent overflow to `inf`), and
conversions to integer or `Decimal` types stay exact.
The `IN` operator passes `strict = true`, so its exact-value semantics are
preserved and stay consistent with the `=` operator:
`toFloat32(0.1) IN (0.1)` is `0`, exactly like `toFloat32(0.1) = 0.1`.
Closes: #43144
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Workflow [PR], commit [4047906] Summary: ✅
AI ReviewSummaryThis PR changes Final Verdict
|
When converting a `Field` to a `Variant`, `convertFieldToType` falls back to trying each alternative in turn and returns the first that converts. The alternatives are listed in sorted order, so e.g. `Array(Float64)` is tried before `Array(Int64)`. After this branch enabled non-strict (lossy) conversion to floating-point types, an exactly-representable integer such as `9223372036854775807` could be stored lossily in an earlier `Array(Float64)` alternative instead of the exact `Array(Int64)` one, changing the result of, e.g., `arrayRemove([[9223372036854775807, -9223372036854775808], [0.9999, 7]], ...)`. Make the fallback prefer a lossless alternative: try a strict (exact) conversion across all alternatives first, and fall back to a lossy conversion only when no alternative can represent the value exactly. This restores the previous selection while still accepting lossy values when no exact alternative exists (e.g. a `Variant(Float32)` column). This fixes the `04256_arrayRemove_variant_no_throw_on_mismatch` test that started failing on this branch, and is covered by new `values()` cases in `04403_values_float32_conversion_and_in`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`SELECT * FROM VALUES('x Float64', toUInt64(-1))` previously failed with
`ARGUMENT_OUT_OF_BOUND` because `18446744073709551615` is not exactly
representable as `Float64`. With non-strict conversion to floating-point types
now returning the nearest representable value (like `CAST`), the value is
within the `Float64` range and is accepted, returning `18446744073709552000`.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The Variant branch of `convertFieldToTypeImpl` tried each alternative twice - once strict, then non-strict - regardless of the outer `strict` flag. This preferred a lossless alternative (the original intent), but it also ran the lossy pass for strict callers. The `IN` operator builds set elements with `strict = true` so that values not exactly representable in the target type are excluded, consistent with the `=` operator. With the unconditional second pass, a `Variant(Float64)` set could accept e.g. `toUInt64(-1)` by rounding it to `Float64` on the non-strict pass, so the set contained a value the underlying `Float64` comparison would never equal. Run the lossy fallback pass only when `strict` is false. Strict conversion now only accepts an exact alternative, restoring the pre-change behaviour for `IN` (an unrepresentable value is rejected) while non-strict callers keep preferring a lossless alternative and falling back to a lossy one. A regression test is added in `04403_values_float32_conversion_and_in`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Two changes to `04403_values_float32_conversion_and_in`: - The two `Array(Variant(...))` cases failed under the old query analysis, which eagerly computes a common type for the array literal (mixing a large `Int64` with `Float64`) and rejects it with `NO_COMMON_TYPE` before the value reaches the `Variant` column type. Pin these cases to the analyzer with `SETTINGS allow_experimental_analyzer = 1`; the behaviour they check is in the `Variant` alternative selection, which the analyzer reaches and the old path cannot express. - Add a regression for the strict-`IN` `Variant` fix: a `Variant(Float64)` `IN` set must not round `toUInt64(-1)` to `Float64`, so the unrepresentable value is rejected instead of silently matching. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…conversion Master commit 3701b73 (PR #106202) combined the `Time` branches in `convertFieldToTypeImpl` so both `UInt64` and `Int64` partition values are routed through `convertNumericType<Int32>(src, type)`. This PR changed `convertNumericType` to take a `strict` argument with no default value, so after merging `master` that call site no longer compiled (2 arguments passed to a 3-argument function). Pass `strict` through. `Int32` is an integer type, so the conversion stays exact regardless of the flag (`exact = strict || !is_floating_point<Int32>` is always `true`), making this change behavior-neutral for the `Time` partition path while restoring a clean build.
… paths The original fix overloaded the existing `strict` flag of `convertFieldToType` so that every non-strict caller rounded an inexact value to the nearest floating-point value. That leaked into optimizer/pruning callers that pass `strict = false` but treat the converted constant as an exact comparison bound - in particular `KeyCondition`. For a `Float64` primary key and a predicate like `x > toUInt64(-1)`, the literal would be rounded to `static_cast<Float64>(max)` and the stricter range `x > rounded` could prune the mark holding a row that actually matches under the accurate comparison used at execution time. Introduce a dedicated `convert_inexact_floats` flag instead. Conversion to a floating-point type now stays exact by default (an inexact value returns Null), so `KeyCondition`, the sharding-key rewrite, the statistics estimator, the secondary-index conditions and the strict `IN` operator never build a wrong bound from a rounded constant. Only the value-materialization paths opt in: `convertFieldToTypeOrThrow` (the `values`/`VALUES` table function, `WITH FILL`, window frame offsets, ...) and the `INSERT` VALUES expression fallback in `ValuesBlockInputFormat`, which now matches the streaming literal path and `CAST`. Add a regression test that a `Float64` primary key compared against `toUInt64(-1)` is not pruned, and a test that the `INSERT` VALUES expression path rounds an inexact float to the nearest value. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…master `master` already has several `04403_*` tests, so move the `values_float32_conversion_and_in` test to a free number. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…kHouse/ClickHouse into fix-values-float32-conversion-43144
…er the pre-existing ColumnVariant order The AI review's remaining blocker (PR #108055 discussion, `Variant(Float32, Float64)` with a `Float64` value such as `toFloat64(16777217)`) is a pre-existing `ColumnVariant::tryInsert` ordering issue, not introduced by this PR. `convertFieldToType` returns a bare `Field`; the alternative discriminator is chosen downstream at column-insert time by `ColumnVariant::tryInsert`, which scans variants in sorted order (`Float32` before `Float64`) and accepts the `Float64` field lossily into the earlier `Float32` alternative. The exact-first conversion loop only governs fields that fall through to it, so the converter cannot influence this selection. Reworking `ColumnVariant::tryInsert` has a far broader blast radius and is left as a separate design decision. Following the review's accepted alternative, narrow the contract instead of making the broad change: - Explicitly scope the exact-alternative preference to the fall-through conversion loop in `convertFieldToType`, documenting that directly-insertable fields keep `ColumnVariant`'s pre-existing alternative order. - Reword the test's section header to "the fall-through Variant conversion path" so it no longer promises universal lossless alternative preference. - Add a `variantType` regression for `values('x Variant(Float32, Float64)', toFloat64(16777217))` that documents the pre-existing lossy selection (stored as `Float32` = 16777216). The type is suspicious (ambiguous float alternatives), so the test sets `allow_suspicious_variant_types`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…master Master added 04417_numeric_indexed_vector_pointwise_multiply_all_ones, which collides with this PR's 04417_keycondition_float_pk_no_lossy_prune. Move the latter to the next free prefix 04490 to keep stateless test numbers unique. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
All non-flaky checks are green and the PR is ready to merge:
The only red is the aggregate I pulled SELECT formatQuery($$SELECT [[[[[[[[[[ ... (a deeply nested array literal) ... $$)from Merge-base with |
|
Status after the latest run (
|
|
The stress jobs were re-executed on the latest run (
This PR's Everything else is green: |
|
Re-merged Since the previous "no re-merge needed" note ( The merge is clean:
On the test-number prefixes ( The only remaining reds were the two TSan |
…ALUES path Address review feedback on #108055: the existing `04489` regression only exercised the single-expression fallback (with `input_format_values_deduce_templates_of_expressions = 0`) and never the default template-deduction path (setting = 1). Add cases that leave template deduction enabled and insert inexact float literals inside `Array`/`Tuple` expressions and into a scalar `Float32` column, asserting the values are rounded to the nearest representable value (matching `CAST`), not rejected with `ARGUMENT_OUT_OF_BOUND` or turned into `NULL`. This path is handled by `ConstantExpressionTemplate::parseLiteralAndAssertType`: the captured array/tuple literal keeps its own deduced `Array(Float64)` type, so the per-row `convertFieldToType` there is a lossless `Float64` -> `Float64` conversion, and the narrowing to the `Float32` column happens afterwards via `CAST` in `evaluateAll`. It therefore never needed the `convert_inexact_floats` opt-in, and the behavior is identical on `master` and on this branch. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Status after the AI Review " CI reds — both pre-existing, unrelated flakes (not
Fresh CI is running on |
…oat32-conversion-43144 # Conflicts: # src/Interpreters/convertFieldToType.cpp # src/Interpreters/convertFieldToType.h
`convertFieldToTypeOrThrow` applied lossy float conversion (`convert_inexact_floats = true`) unconditionally, so it leaked into callers that resolve an exact target rather than materialize a value. In particular `MergeTreeData::getPartitionIDFromQuery` uses it to resolve `ALTER ... PARTITION` targets: with `allow_floating_point_partition_key`, `DROP PARTITION 0.1` on a `Float32` partition key rounded the literal to `toFloat32(0.1)` and could drop a partition instead of rejecting the unrepresentable value - turning a destructive statement from fail-closed into lossy matching. Add a `convert_inexact_floats` parameter to `convertFieldToTypeOrThrow` (default `false`, i.e. exact) and pass `true` only at the true value-materialization callers (the `values`/`VALUES` table function, `WITH FILL`, window frame offsets). Partition resolution, `ConstantNode` and executable-UDF parameter conversion keep the exact default, which matches the pre-existing behavior for those paths and the design already documented in the header. Add `04509_partition_float32_no_lossy_drop` covering the partition path. Addresses the review on #108055 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Making `convertFieldToTypeOrThrow` exact by default (previous commit) means the `ConvertFieldToTypeStrictness.Float64ToFloat32` unit test's bare call for the inexact value `0.1 -> Float32` now throws `ARGUMENT_OUT_OF_BOUND` instead of rounding, so the test asserted the pre-change behavior and would fail. Pass `convert_inexact_floats=true` at the materialization call to exercise the `values`/`INSERT` rounding semantics the test intends to cover, and add an `EXPECT_THROW` documenting the exact-by-default contract that protects `ALTER ... PARTITION` resolution in `getPartitionIDFromQuery`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…tition literals
Fresh CI on the merge head raised an AI review requesting changes with two
findings on `convertFieldToType.cpp`.
- `convertFieldToType.cpp:80`: claimed `convert_inexact_floats` never activates
for `BFloat16` because `std::is_floating_point<BFloat16>` is `false`. The code
uses the ClickHouse `is_floating_point` concept (`base/base/extended_types.h`,
`std::is_floating_point_v<T> || std::is_same_v<T, BFloat16>`), so `BFloat16` is
a floating-point type there and already takes the lossy path when
`convert_inexact_floats` is set. The existing test only used `0.5` (exactly
representable), which does not exercise it. Added a regression asserting
`values('x BFloat16', 0.1)` equals `CAST(0.1, 'BFloat16')` and a clarifying
comment. No code change (the behavior is already correct).
- `convertFieldToType.cpp:958`: noted a quoted string partition literal
(`DROP PARTITION '0.1'`) bypasses the fail-closed guarantee. The string branch
parses it into the target type via `deserializeWholeText` (rounding) before the
exactness check, then recurses. This is pre-existing behavior (verified on
master), shared with string-to-float value comparisons like `WHERE f = '0.1'`,
and unchanged by this PR; threading the flags through the string recursion is a
no-op because the rounding happens during parsing. Narrowed the documented
contract (the guarantee is for numeric literals) and added a regression
documenting the quoted-string behavior.
Comments and tests only; no behavior change.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…o fix-values-float32-conversion-43144
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 160/167 (95.81%) · Uncovered code |
…er the pre-existing ColumnVariant order The AI review's remaining blocker (PR ClickHouse#108055 discussion, `Variant(Float32, Float64)` with a `Float64` value such as `toFloat64(16777217)`) is a pre-existing `ColumnVariant::tryInsert` ordering issue, not introduced by this PR. `convertFieldToType` returns a bare `Field`; the alternative discriminator is chosen downstream at column-insert time by `ColumnVariant::tryInsert`, which scans variants in sorted order (`Float32` before `Float64`) and accepts the `Float64` field lossily into the earlier `Float32` alternative. The exact-first conversion loop only governs fields that fall through to it, so the converter cannot influence this selection. Reworking `ColumnVariant::tryInsert` has a far broader blast radius and is left as a separate design decision. Following the review's accepted alternative, narrow the contract instead of making the broad change: - Explicitly scope the exact-alternative preference to the fall-through conversion loop in `convertFieldToType`, documenting that directly-insertable fields keep `ColumnVariant`'s pre-existing alternative order. - Reword the test's section header to "the fall-through Variant conversion path" so it no longer promises universal lossless alternative preference. - Add a `variantType` regression for `values('x Variant(Float32, Float64)', toFloat64(16777217))` that documents the pre-existing lossy selection (stored as `Float32` = 16777216). The type is suspicious (ambiguous float alternatives), so the test sets `allow_suspicious_variant_types`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ALUES path Address review feedback on ClickHouse#108055: the existing `04489` regression only exercised the single-expression fallback (with `input_format_values_deduce_templates_of_expressions = 0`) and never the default template-deduction path (setting = 1). Add cases that leave template deduction enabled and insert inexact float literals inside `Array`/`Tuple` expressions and into a scalar `Float32` column, asserting the values are rounded to the nearest representable value (matching `CAST`), not rejected with `ARGUMENT_OUT_OF_BOUND` or turned into `NULL`. This path is handled by `ConstantExpressionTemplate::parseLiteralAndAssertType`: the captured array/tuple literal keeps its own deduced `Array(Float64)` type, so the per-row `convertFieldToType` there is a lossless `Float64` -> `Float64` conversion, and the narrowing to the `Float32` column happens afterwards via `CAST` in `evaluateAll`. It therefore never needed the `convert_inexact_floats` opt-in, and the behavior is identical on `master` and on this branch. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`convertFieldToTypeOrThrow` applied lossy float conversion (`convert_inexact_floats = true`) unconditionally, so it leaked into callers that resolve an exact target rather than materialize a value. In particular `MergeTreeData::getPartitionIDFromQuery` uses it to resolve `ALTER ... PARTITION` targets: with `allow_floating_point_partition_key`, `DROP PARTITION 0.1` on a `Float32` partition key rounded the literal to `toFloat32(0.1)` and could drop a partition instead of rejecting the unrepresentable value - turning a destructive statement from fail-closed into lossy matching. Add a `convert_inexact_floats` parameter to `convertFieldToTypeOrThrow` (default `false`, i.e. exact) and pass `true` only at the true value-materialization callers (the `values`/`VALUES` table function, `WITH FILL`, window frame offsets). Partition resolution, `ConstantNode` and executable-UDF parameter conversion keep the exact default, which matches the pre-existing behavior for those paths and the design already documented in the header. Add `04509_partition_float32_no_lossy_drop` covering the partition path. Addresses the review on ClickHouse#108055 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…32-conversion-43144 Fix values() table function rejecting lossy floats for narrow float columns
Closes: #43144
The
valuestable function rejected decimal literals that are not exactly representable in a narrower floating-point column:This was inconsistent with
INSERT ... VALUES (0.1)into the sameFloat32column, which works.The cause was in
convertFieldToType: the numeric narrowing helpers ignored thestrictparameter and always required the converted value to be exactly equal to the input. Almost no decimal literal is exactly representable inFloat32, so the non-strict callers (theVALUESsection, thevaluestable function,INSERT) rejected them. The fix threadsstrictthrough these helpers and, in non-strict mode, returns the nearest representable value when converting to a floating-point type — the same behaviour asCAST. The range check is unchanged, so out-of-range values are still rejected (1e300toFloat32still errors, with no silent overflow toinf), and conversions to integer orDecimaltypes remain exact.The
INoperator passesstrict = true, so its exact-value semantics are preserved and remain consistent with the=operator:toFloat32(0.1) IN (0.1)is0, exactly liketoFloat32(0.1) = 0.1.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed the
valuestable function failing withARGUMENT_OUT_OF_BOUNDwhen a decimal literal that is not exactly representable in a narrow floating-point column (such as0.1for aFloat32column) is used, e.g.SELECT * FROM values('x Float32', 0.1). Such values are now accepted and converted to the nearest representable value, consistent withCASTandINSERT ... VALUES.Version info
26.7.1.878(included in26.7and later)