Repository navigation
Conversation
When casting floating-point values to Decimal types, the conversion truncated toward zero instead of rounding to the nearest integer. For example, CAST(0.5, 'Decimal(9,0)') returned 0 instead of 1. Add std::round() before the integer cast in convertToDecimalImpl to match the behavior of PostgreSQL and MySQL. Signed-off-by: Yash Sancheti <[email protected]>
Float-to-Decimal conversion now rounds instead of truncating, which affects the microsecond precision of interval calculations.
Update expected output to match the actual truncation behavior of float-to-decimal cast.
The initial fix only applied std::round to the scalar path (convertToDecimalImpl) but not the batch/vectorized path (convertToDecimalBatch). CAST on columns uses the batch path, so the rounding was not taking effect for column-level operations. Add std::round to both the nullable and non-nullable branches of the floating-point batch conversion loop. Restore the test reference to expect correct rounding behavior: 0.5 → 1, 2.7 → 3, etc.
Add test cases for: - Scale > 0 (Decimal(9,2)) with IEEE-754 exact half values (1.125, 2.375, 0.875) - Float32 input (previously only Float64 was tested) - Better section headers for clarity
Addresses the bot comment that values like `2147483647.4` were rejected as overflow even though `std::round` produces the representable `2147483647`. The scalar path compared the unrounded product against `<= min / >= max` and only then rounded the result. The batch path had the same bug. Switch both paths to round first and then check strict bounds (`< min || > max`) against the rounded value, so representable-edge values are accepted while truly out-of-range values still throw `DECIMAL_OVERFLOW`. Extend the regression test to cover: - Representable-edge rounding (`2147483647.4`, `-2147483647.4`). - True overflow (`2147483648.0`, `-2147483649.0`) still throws. - Column (batch) path matches the scalar path via `arrayJoin`.
The PR changes `float -> Decimal` cast to round to nearest instead of truncating toward zero, so a handful of pre-existing reference files still encoded the old truncation-based expected values. Update them to the rounded values reported by CI: - `00700_decimal_casts`: `9.99999998` -> `9.99999999` on the `CAST(... , 9)` row. - `00700_decimal_math`: three pairs updated (`5.4066 -> 5.4067`, `1.6275 -> 1.6276`, `3.4875 -> 3.4876`) with their corresponding result columns, in each of the three re-runs of the same query block. - `01035_avg`: `-0.000500002` -> `-0.0005`, `0.49999949943727` -> `0.4999995`, `-0.50000449943727` -> `-0.5000045`. - `01603_decimal_mult_float`: `7.7759 -> 8.1939`, `56.62269 -> 59.66649`, and four `1.641386 -> 1.643852` lines. - `03165_round_scale_as_column`: scale cases 2, 3, 5, 6, 7, 9, 10 updated to rounded values. - `03212_variant_dynamic_cast_or_default`: insert the new `9223372036854775.808` line between `4294967295` and `9223372036854775806` where the `Float -> Decimal64` case now appears. Two more reference files (`01518_nullable_aggregate_states2` and `00700_decimal_casts_2`) still need updates; they require the full new stdout which wasn't available in the CI log tail. Left for a follow-up once this run of CI produces complete diffs.
…ding Audit pointed out that the rounding regression test only exercised the positive `2147483647.4 -> 2147483647` edge and had no Float32 coverage beyond `0.5`. Two additions: 1. Negative edge at INT32_MIN. `-2147483647.9` rounds to `-2147483648`, which `Decimal(9,0)` stores exactly — this must be accepted. A value past the limit (`-2147483648.5`) must still throw `DECIMAL_OVERFLOW`. 2. Float32 non-half values (`2.75`, `2.25`, and their negatives) to confirm the scalar/batch paths both round instead of truncating at magnitudes where Float32 representation is exact.
The previous check compared `out` against `static_cast<Float>(min/max)`, but for widths where the integer max isn't exactly representable as the source float (most notably `Float64(Int64::max) == 2^63`) the upper bound rounds up to the value one past max. `out > max_as_float` then fails to flag products that, once cast to `ToNativeType`, are undefined behavior (e.g. `toDecimal64(9223372036854775807.0, 0)` previously slipped through to a UB `static_cast<Int64>(2^63)`). Use `2^(width - 1)` as a strict overflow boundary: it is always exactly representable in any IEEE float with sufficient exponent range, and combined with the existing `isFinite(out)` guard it also covers the `Float32 × scale-76` case where the boundary itself overflows to `+inf`. The bound now treats the native min as in-range, matching the natural round-to-nearest semantics where values that round to a representable integer must be accepted on both ends. This was flagged by `clickhouse-gh` review on float→Decimal256 high-scale and Float64→Int64 edge cases. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The scalar/batch paths in `DataTypesDecimal.cpp` already call `std::round` on the multiplied float before casting to the decimal native integer, but the JIT-compiled cast (`compileConvert` and `FunctionCast::compile`) went straight from `CreateFMul` to `nativeCast`, whose `CreateFPToSI` truncates toward zero. As a result, queries through the JIT cache (`compile_expressions=1` with low `min_count_to_compile_expression`) silently fell back to truncation behaviour, breaking the column-path contract verified by `04034_decimal_cast_float_rounding`. Wrap the product with the `llvm.round` intrinsic, which produces the same "round half away from zero" semantics as `std::round`, before delegating to `nativeCast`. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Cover the case where the multiplier itself overflows the source float type (`Float32 × scale-76 multiplier` saturates to `+inf`), so a finite Float32 input must still surface `DECIMAL_OVERFLOW` instead of silently casting `inf` to a wide integer. Exercises both the scalar and the batch (column) paths. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Three pre-existing references encoded the asymmetric overflow behaviour where the negative bound was reached at exactly `ToNativeType::min`. With the tightened `2^(width-1)` strict bound, the native min is in range on both ends, so values that previously overflowed to the default (or to a UB-cast wrapped result) now produce the rounded native value: - `00700_decimal_casts_2.sql`: update the three negative-edge cases (`toDecimal32(-2147483648.0, 0)` etc.) to step strictly past the native min so they still trigger `DECIMAL_OVERFLOW`. - `03212_variant_dynamic_cast_or_default.reference`: replace the asymmetric `-18446744073709551.616` rows with their symmetric `-9223372036854775.808` counterpart of the positive case already in the reference. - `01518_nullable_aggregate_states2.reference`: regenerate, the trailing-digit shifts come from `Float → Decimal` rows now rounding rather than truncating. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`9223372036854775.808` exceeds the `Decimal64(3)` upper bound of `Int64::max / 10^3 = 9223372036854775.807` (the tightened `2^(width-1)` strict bound rejects exactly `2^63`). The `toDecimal64OrDefault` cast therefore never produces it for any test input; the row was added by `2ff88833e61` on the (incorrect) assumption that the rounded `Float64` source would land on it. The corresponding negative `-9223372036854775.808` stays in the reference because `-2^63 = Int64::min` is inside the strict bound, so the cast still produces it. Fixes the Fast test failure on https://s3.amazonaws.com/clickhouse-test-reports/PRs/98994/03f0b39a21af7d44bb6d1d59066bfa6b2141aa81/fast_test/ PR: ClickHouse#98994 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Two follow-ups for the bot review of the Float→Decimal rounding fix: 1. `0 * +inf = NaN` was misreported as `DECIMAL_OVERFLOW`. For `CAST(toFloat32(0), 'Decimal256(76)')`, the multiplier `static_cast<Float32>(10^76)` rounds to `+inf`, so `value * multiplier` is `NaN` and the `!isFinite(out)` guard triggered overflow even though zero is representable for every scale. Short-circuit the zero case in both `convertToDecimalImpl` and `convertToDecimalBatch`, and add a regression case to `04034_decimal_cast_float_rounding`. 2. The JIT path emitted by `convertCompileImpl` calls `nativeCast` on the rounded `Float`, which lowers to `FPToSI`/`FPToUI`. LLVM treats those as poison values when the operand is out of integer range, so JIT-compiled `CAST(toFloat64(2147483648.0), 'Decimal(9, 0)')` did not raise the `DECIMAL_OVERFLOW` exception the scalar and batch paths throw. Disable JIT for `Float`→`Decimal` casts in `convertIsCompilableImpl` until the JIT mirrors the explicit bounds check; the interpreted path stays correct. PR: ClickHouse#98994 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Fork-push tokens do not carry the `workflow` OAuth scope, so the post-master-merge updates under `.github/workflows/` cannot be pushed to the PR's fork. Restore each touched workflow file to its pre-merge content so the rest of the merge can land. PR: ClickHouse#98994 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Workflow files in this branch were stale or had been deleted as a workaround for GitHub's workflow-scope check. Restoring them to match `master` so the PR diff no longer contains those unrelated changes.
The Float32 inputs `-1.17549435e-38` and `-1.4e-45` in `03212_variant_dynamic_cast_or_default.sql` produce a non-zero product (`-1.17e-35`) when multiplied by the `Decimal128/256(3)` scale multiplier. With the new code in `convertToDecimalImpl`/`convertToDecimalBatch`, `std::round(-1.17e-35) = -0.0`, and `static_cast<Int128>(-0.0)` correctly yields `0` (no sign extension since `-0.0 < 0` is false in IEEE-754). The previous edit in `03f0b39a21a` replaced the asymmetric `-18446744073709551.616` (the wide-integer UB artifact from the OLD code's `static_cast<Int128>(-1.17e-35)` where `to_Integral` rounded to int64=0 then sign-extended high bits to -1 yielding `-2^64`) with `-9223372036854775.808`, on the assumption the rounded value would land at `-Int64::min/1000`. That was wrong — the value is exactly `0`, which is already present in the output, so the spurious rows must be deleted entirely. Fixes the Fast test failure on https://s3.amazonaws.com/clickhouse-test-reports/PRs/98994/8b91cc68686cbfd85a307dc83a2b463edacd1c66/fast_test/ PR: ClickHouse#98994 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…sCompilable` The `convertIsCompilableImpl` guard added in `d164acad37a` correctly fell back to the interpreted path for `Float` → `Decimal` casts, since the JIT lowers `nativeCast` to `FPToSI`/`FPToUI` which is poison/undefined for out-of-range floats while the scalar/batch paths in `DataTypesDecimal.cpp` throw `DECIMAL_OVERFLOW`. `FunctionCast::isCompilable` was missed: it still returned `true` for every `Number` → `Decimal` cast (including `Float` → `Decimal`), so `CAST(float_val, 'Decimal(...)')` could still be JIT-compiled via `FunctionCast::compile`, which then emits `llvm.round` followed by `nativeCast` (`FPToSI`) without bounds check. That divergence (interpreted path throws, JIT path silently produces garbage) is exactly what the original guard intended to prevent. Mirror the same `std::is_floating_point_v<LeftFieldType>` early return in `FunctionCast::isCompilable` so both compilability checks stay consistent. Per review threads: - ClickHouse#98994 (comment) - ClickHouse#98994 (comment) PR: ClickHouse#98994 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
… cast The `select sum(cityHash64(*)) from file(datetime64_02735.parquet)` line in `02735_parquet_encoder.sql` hashes a dataset built from `toDateTime64(<float>, scale)` columns. `DateTime64` is internally a `Decimal64`, so the Float-to-Decimal cast now rounds to nearest instead of truncating toward zero — for example, `toDateTime64(1/1e9, 9)` no longer collapses to 0 due to IEEE-754 representation error. Update the expected hash from `12670676506515577395` to `5690686702555668970`, the value produced deterministically across three CI configurations: - Stateless tests (amd_debug, sequential) - Stateless tests (amd_debug, distributed plan, s3 storage, sequential) - Stateless tests (arm_binary, sequential) CI report: ClickHouse#98994 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The test inserts 100k rows, builds a 16-column nullable `AggregatingMergeTree`, and runs `OPTIMIZE FINAL`. Normal runs finish in 30-60s, but in the `flaky check` with adverse settings (e.g. `--group_by_two_level_threshold 1`, `--max_insert_threads 1`) it consistently runs past the 180s `TEST_MAX_RUN_TIME_IN_SECONDS` flaky threshold (250-300s). On this PR alone the flaky check failed it 5 times in 2 days, and master has had similar timeouts on other PRs that touched the reference. The `long` tag bypasses the flaky-mode timeout, which is exactly what the tag is for. Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=98994&sha=921d78fb6aea7c4b73dabd3124b74a85979e2114&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20flaky%20check%29
These changes to CI workflow / infrastructure files were unrelated to the purpose of this pull request and were introduced accidentally (stale base branch). Restoring them to match `master`.
The float-to-`Decimal` cast now rounds to nearest (half away from zero) instead of truncating toward zero, but the registered `FunctionDocumentation` for `toDecimal32`, `toDecimal64`, `toDecimal128`, and `toDecimal256` still described the old truncating behavior and gave stale examples such as `toDecimal64(1.15, 2) = 1.14`. Update the `:::note` and `:::warning` blocks to state that `Float32`/`Float64` inputs are rounded to the nearest value, while keeping the string-input truncation caveat. The float-imprecision warning now uses `toDecimal64(1.005, 2) = 1.00`, which is still surprising under round-to-nearest because the closest `Float64` to `1.005` is `1.0049999999999999`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…unding # Conflicts: # src/Functions/FunctionsConversion.cpp
Float-to-Decimal casts changed from truncating toward zero to rounding to nearest (ties away from zero). This silently changes the result of `CAST` and `toDecimal*` for `Float32`/`Float64` inputs after an upgrade, so operators need a way to preserve the previous documented behavior during rollout. Add the `cast_float_to_decimal_uses_rounding` setting (default `true`) and a `SettingsChangesHistory` entry for `26.6` with the previous value `false`, so setting `compatibility` to a version below `26.6` restores truncation. The flag is threaded through `convertToDecimalImpl`, `convertToDecimalBatch`, `convertToDecimal` and `tryConvertToDecimal` (defaulting to `true`, so the `Field`, JSON and Protobuf conversion paths keep the rounding behavior), and is read from the query context in `FunctionConvertSettings` for the `CAST` path. It only affects `Float` -> `Decimal`; integer and decimal source paths ignore it. Since the JIT `Float` -> `Decimal` path is disabled, the interpreted path governs the result regardless of `compile_expressions`. Extend `04034_decimal_cast_float_rounding` to verify that disabling the setting restores truncation in both the scalar and the vectorized batch paths. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`convertToDecimalBatch` dispatches on `isFinite(multiplier)`; the non-finite branch (`Float32` -> `Decimal256` high scale, where the multiplier overflows to `+inf`) was only exercised with rounding enabled. Add the same overflow and zero cases under `cast_float_to_decimal_uses_rounding = 0` so the truncating instantiation of that branch is covered too. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
PR fixes: PR introduces a new inconsistency: Probably it needs to fix string-to-decimal and JSONExtract after this PR. |
…Field paths `convertToDecimal` defaults to rounding, so float -> `Decimal` conversions that do not go through `FunctionConvert` ignored `cast_float_to_decimal_uses_rounding` and always rounded, leaving the compatibility setting unable to restore truncation for them. Carry the setting into the remaining user-facing float -> `Decimal` callers: - Add `cast_float_to_decimal_uses_rounding` to `FormatSettings` (populated from the query setting in `getFormatSettings`), and use it in `JSONExtractTree` (the `Decimal`/`DateTime64`/`Time64` nodes) and `convertFieldToType` (which already carry `FormatSettings`). - Carry the flag on `ProtobufReader` (set by the Protobuf input formats) and consult it in `ProtobufSerializerDecimal::numberToDecimal`. - For the `JSON` data type, `JSONExtract` converts the extracted subcolumn with `castColumnAccurateOrNull`, whose internal cast had a null context and thus always rounded. Add an optional `context` argument to `castColumn*` and thread the query context from `FunctionsJSON` so that cast honors the setting. Extend `04357_decimal_cast_float_rounding_issues` with the `JSON`-type path and the `JSONExtractTree` high-precision float fallback. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Closing, it's too massive and expensive (LLM tokens cost). |
The vectorized fast path dropped the per-element `isFinite(out)` guard, relying on `out >= max_plus_one || out < -max_plus_one` to reject infinite products. That is only valid when the bound `max_plus_one = 2^(width-1)` is finite. For `Float32` -> `Decimal256` the bound is `2^255`, which overflows to `+inf` in `Float32`, while a scale such as 38 still has a finite multiplier. A batch value like `materialize(toFloat32(-10))` then produces `out = -inf`: `-inf >= +inf` and `-inf < -inf` are both false, so the code reached `static_cast<ToNativeType>` (undefined) instead of throwing. Positive `+inf` was caught by `>= +inf`, making it sign-asymmetric. Take the tight fast path only when both the multiplier and the bound are finite; otherwise use the guarded path, which keeps the explicit `isFinite(out)` check (and the zero short-circuit for the non-finite-multiplier case). This keeps the fast path for every case with a finite bound (`Decimal32/64/128` for all float sources, `Float64` -> `Decimal256`); only `Float32` -> `Decimal256` takes the guarded path. Add batch (and scalar) regressions for negative and positive `Float32` products that overflow to infinity while the multiplier is still finite. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…banker-rounding Resolved conflicts: - src/Functions/FunctionsConversion.h (ToTime64TransformFloat): master fixed the Time64 clamp to use MAX_TIME_TIMESTAMP instead of the DateTime64 bounds; kept that fix and the `round` flag threaded on the convertToDecimal call. - tests/queries/0_stateless/00700_decimal_math.reference: kept the rounded cbrt result (this branch rounds float->Decimal) and master's round-to-15 erf/erfc values (libm-portability), both verified against the built binary.
…e-integer narrowing Casting a `Float32` whose scaled value lands above the `Int64` range but within the target's native range produced garbage: `static_cast<ToNativeType>(out)` on a `Float32` picks `wide::integer`'s templated builtin-float constructor, which narrows through `int64_t` in `wide_integer_from_builtin`. This is a pre-existing bug (present in stock, since master does the same `static_cast<ToNativeType>(out)`), surfaced while reworking this conversion. ``` select CAST(toFloat32(1), 'Decimal128(20)'), CAST(toFloat32(1), 'Decimal256(30)'); was ┌─CAST(toFloat⋯al128(20)')─┬─CAST(toFloat32(1), 'Decimal256(30)')─┐ │ 0.09223372036854775807 │ 0.000000000009223372036854775807 │ └──────────────────────────┴──────────────────────────────────────┘ now ┌─CAST(toFloat⋯al128(20)')─┬─CAST(toFloat32(1), 'Decimal256(30)')─┐ │ 1.00000002004087734275 │ 1.000000015047466219891198222336 │ └──────────────────────────┴──────────────────────────────────────┘ ``` Widen the float result to `Float64` before the integer cast in both the scalar (`convertToDecimalImpl`) and batch (`convertToDecimalBatch`) paths. `Float64` -> wide integer is safe; the widen is a no-op for `Float64` sources and exact for `Float32`, so only the buggy `Float32` -> `Decimal128`/`Decimal256` path changes. Add a regression to `04034_decimal_cast_float_rounding` (scalar and batch). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
now fixed |
The `toDecimal32/64/128/256` descriptions said `Float32`/`Float64` inputs are always rounded (ties to even), but the conversion honors `cast_float_to_decimal_uses_rounding = 0`, which truncates toward zero (e.g. `toDecimal64(1.5, 0)` returns `1` instead of `2`). Qualify all four descriptions with the setting. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ses_rounding scope `castColumn` gained an optional `context`, which makes the built cast depend on that context's settings (e.g. `cast_float_to_decimal_uses_rounding`). The `InternalCastFunctionCache` is keyed only by (cast_type, from, to), so caching a context-dependent cast could let one built under a given setting be reused under another. Only cache context-free casts (bypass the cache when a `context` is passed). This is currently latent — the sole context-passing caller uses no cache — but makes it robust. Also document that the setting governs explicit float-to-`Decimal` conversions (`CAST`/`toDecimal*`, `accurateCast*`, `toDateTime64`/`toTime64`, `JSONExtract`, Protobuf/`Values` input), while implicit coercions built through the generic cast helper (for example, a `Float` probe matched against a `Decimal` set in `IN`) always round regardless of the setting. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ntextPtr copy The style check forbids holding a copy of `ContextPtr` in functions. The JSON overload resolver / function base / executable now inherit `WithContext` (which holds a `weak_ptr`) and obtain the context via `getContext()` where needed (build/prepare, and at execution to pass into the JSON-type `castColumn`), instead of storing a strong `ContextPtr` member. Behavior is unchanged. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
replying to @Ergus question:
depends on what you mean by complexity. |
|
@den-crane first of all thank you for helping with this issue |
@yakov-olkhovskiy I'm not going to continue, you can takeover. |
|
A part of the complexity is a performance. |
…nker-rounding Resolve the conflict with the move of the settings changes history into the setting declarations (ee6b44f): the history records this PR added to `SettingsChangesHistory.cpp` now live as trailing arguments of the `DECLARE` of each setting. - retargeted PR record [email protected] to 26.10 (settings-history check rule) Also resolved conflicts in: - `src/DataTypes/DataTypesDecimal.cpp` - `src/Formats/FormatFactory.cpp` - `src/Formats/JSONExtractTree.cpp` - `src/Functions/FunctionsConversion.cpp` - `src/Functions/FunctionsConversion.h` - `src/Functions/FunctionsConversion_reg.cpp` - `src/Functions/FunctionsJSON.cpp` Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Round float-to-
Decimalcasts to the nearest representable value (ties to even, i.e. banker's rounding) instead of truncating toward zero.Previously the cast dropped the fractional part with a plain
static_castto the integer native type, so a value whose nearest binary float is slightly below the decimal grid point lost its last digit:This is a backward incompatible change: float-to-
Decimalcast results change by default. The behavior is gated by thecast_float_to_decimal_uses_roundingsetting (default enabled); set it to0(e.g. viacompatibility) to restore the previous truncating behavior. Rounding is applied consistently in the scalar, batch, and JIT cast paths, and reaches the float →DateTime64/Time64conversions. The overflow check now tests the rounded value against the exactly-representable2^(width-1)bound, andFloat→DecimalJIT compilation is disabled (theFPToSIlowering is undefined for out-of-range inputs) until the JIT emits explicit range checks.This builds on the earlier round-half-away-from-zero attempt, but uses round half to even so the cast agrees with the default tie-breaking of the
roundfunction.Closes: #45247
Closes: #103104
Related: #98994
Related: #57935
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Float-to-Decimal casts now round to the nearest representable value (ties to even) instead of truncating toward zero, so e.g.
toDecimal64(16.4, 6)returns16.4instead of16.399999. This changes results by default; the previous truncating behavior can be restored withcast_float_to_decimal_uses_rounding = 0.Documentation entry for user-facing changes
toDecimal*function docs and thecast_float_to_decimal_uses_roundingsetting description are updated in this PR.Workflow [PR]
Sync PR [sync-upstream/pr/107923]