Skip to content

Scale Float32 sources of DateTime64 / Time64 in Float64 precision - #101512

Draft
yariks5s wants to merge 68 commits into
masterfrom
yarik/fix-date_time_overflow_behavior-ignored
Draft

yariks5s wants to merge 68 commits into
masterfrom
yarik/fix-date_time_overflow_behavior-ignored

Conversation

@yariks5s

@yariks5s yariks5s commented Apr 1, 2026 •

Copy link
Copy Markdown
Member

The original goal of this PR - making integer and Float32 / Float64 casts to DateTime64 and Time64 honour date_time_overflow_behavior - was implemented on master by #117667. After merging master, this PR keeps only what is still missing there: a Float32 source is now scaled to ticks in Float64 instead of Float32.

The 24-bit mantissa of a Float32 rounds the product with the scale multiplier, so:

  • toDateTime64(toFloat32(1665519700), 3) returned 2022-10-11 20:21:54.304 instead of 20:22:24.000 (the value is exact in Float32);
  • CAST(9223371776::Float32, 'DateTime64(9)') is in range (exactly 9223371776 seconds), but its product rounded to 2^63 ticks. In the ignore / saturate modes it was clamped to the last tick. In the throw mode it was rejected, and accurateCast / accurateCastOrNull rejected it too.

The transforms and the window check of the accurate casts now compute in Float64 for every floating-point source. BFloat16 and Float32 values are exactly representable in Float64. The PR also keeps its extra coverage of the overflow modes in 04050. The coverage tests that pass on current master (05055, 05218) moved to #127309.

Related: #117667
Related: #127309

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Conversions of Float32 values to DateTime64 and Time64 are now computed in Float64 precision. Previously the result could be off by tens of seconds, and an in-range value near the upper end of DateTime64(9) was treated as out of range.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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

@clickhouse-gh

clickhouse-gh Bot commented Apr 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [34ea9f2]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py FAIL

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Apr 1, 2026
@yariks5s
yariks5s marked this pull request as draft April 1, 2026 14:44
@alexey-milovidov

Copy link
Copy Markdown
Member

The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix.

@alexey-milovidov

Copy link
Copy Markdown
Member

The failures of "Flaky check" in "functions_bad_arguments" will be fixed by #101994.

@alexey-milovidov

Copy link
Copy Markdown
Member

This was fixed by #105146. Let's update the branch.

Comment thread src/Functions/FunctionsConversion.h Resolved
The previous fix only routed `DataTypeUInt64` through `ToTime64TransformUnsigned`
and `ToDateTime64TransformUnsigned`, so `DataTypeUInt8`/`UInt16`/`UInt32` fell
back to the generic decimal conversion path and bypassed the
`date_time_overflow_behavior` check. This meant cases like
`CAST(3600000::UInt32, 'Time64') SETTINGS date_time_overflow_behavior='throw'`
silently saturated instead of raising `VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE`.

Extend the dispatch to include all narrower unsigned integer sources and
template the transforms on `FromDataType::FieldType`. Guard the overflow
check with a `constexpr` predicate so widths whose entire range fits inside
the target bounds (UInt8/UInt16 to Time64, UInt8/UInt16/UInt32 to DateTime64)
skip it entirely.

Addresses a review comment on
#101512
Comment thread src/Functions/FunctionsConversion.h Resolved
Extend the explicit ConvertImpl branches for `DateTime64`/`Time64` to
cover `Int128`/`Int256` and `UInt128`/`UInt256` source types, so that
`date_time_overflow_behavior` is honored when casting wide integers
through `CAST`. Previously these sources fell through to the generic
decimal path and silently ignored the setting.

The transforms now compare and clamp in the source type's domain so
values above `INT64_MAX` are not truncated before the bounds check.
The constexpr skip is reformulated in terms of `sizeof(FromType)` so it
correctly identifies wide ints as requiring a bounds check.

Includes `base/wide_integer_to_string.h` to make the `fmt::formatter`
specialization for `wide::integer` visible to the `Exception` message.
Comment thread src/Functions/FunctionsConversion.h Resolved
Comment thread src/Functions/FunctionsConversion.h Resolved
alexey-milovidov and others added 5 commits May 25, 2026 13:09
Without this, casts from `Int128`/`Int256`/`UInt128`/`UInt256` to
`DateTime64`/`Time64` were rejected at the wrapper-construction stage with
`CANNOT_CONVERT_TYPE` (code 70), so the routing into the overflow-aware
`ToDateTime64Transform*` / `ToTime64Transform*` paths added in `bce5fc0`
was never reached. The `serverError VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE`
assertions in `04050_time64_cast_uint64_no_wrap.sql` therefore observed
the wrong error code in Fast test.

Allow the wide unsigned/signed integer source families through the
`DataTypeDateTime64`/`DataTypeTime64` wrapper so `date_time_overflow_behavior`
applies uniformly, matching the dispatch in `ConvertImpl`.
The float conversion paths `ToDateTime64TransformFloat` and
`ToTime64TransformFloat` compared the source value against whole-second
bounds (`MAX_DATETIME64_TIMESTAMP` / `MAX_TIME_TIMESTAMP`). However,
`DateTime64` and `Time64` can represent fractional seconds within the
boundary second, so valid values such as `10413791999.1` (a valid
`DateTime64(1)` = `2299-12-31 23:59:59.1`) and `3599999.1` (a valid
`Time64(1)` = `999:59:59.1`) were incorrectly rejected with
`VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE` under `date_time_overflow_behavior =
'throw'`, and clamped down to the whole second under the other modes.

Extend the bounds by the largest fraction representable at the target
scale (`MAX + (1 - 10^-scale)`) so boundary-second fractions are accepted,
and out-of-range values saturate to the maximum representable value rather
than to the truncated whole second. This addresses the review feedback at
`src/Functions/FunctionsConversion.h:605` and `:742`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Functions/FunctionsConversion.h Resolved
alexey-milovidov and others added 3 commits June 4, 2026 08:52
`ToDateTime64TransformFloat`/`Signed`/`Unsigned` computed overflow bounds
from the calendar maximum second (`MAX_DATETIME64_TIMESTAMP`), but at scale
9 that second does not fit in the `Int64` native storage once multiplied by
the scale (`10413791999 * 1e9 > Int64::max`). As a result a value that
passed the bound check could still raise `DECIMAL_OVERFLOW` inside the
conversion even with `date_time_overflow_behavior = 'saturate'`, where it
should clamp instead.

Derive the bounds from the maximum representable native value, capped at
`Int64::max`, so scale 9 saturates to the largest representable value. The
float path now also produces saturated values directly in the native domain
to avoid `Float64` rounding losing the last representable fraction (e.g.
`CAST(1e20 AS DateTime64(6))` now yields `...59.999999` instead of the
imprecise `...59.999998`).

Also initialize `clamped` in the signed transforms (fixes
`cppcoreguidelines-init-variables` in the `arm_tidy` build) and apply the
same native-domain saturation to `ToTime64TransformFloat` for consistency.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`03011_definitive_guide_to_cast`: `CAST(1e20 AS DateTime64(6))` now saturates
to the exact maximum fraction (`...59.999999`) instead of the float-imprecise
`...59.999998`, and `CAST(1e20 AS DateTime64(9))` now saturates to the maximum
representable value instead of raising `DECIMAL_OVERFLOW` (the comment is
updated accordingly).

`04050_time64_cast_uint64_no_wrap`: add `throw`/`saturate` coverage for
`DateTime64(9)` with `Float64`, `UInt64` and `Int64` sources, proving `throw`
raises `VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE` (not `DECIMAL_OVERFLOW`) and
`saturate` clamps to the maximum representable value.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

Picked up the branch: merged latest master (picks up the fixes you flagged — #101239, #101994, #105146) and addressed the two red CI jobs plus the open DateTime64(9) review blocker.

Build (arm_tidy) — variable 'clamped' is not initialized (cppcoreguidelines-init-variables). Initialized clamped in the signed DateTime64/Time64 transforms.

Fast test / 03011_definitive_guide_to_cast and the scale-9 blocker turned out to be the same root cause and are fixed together in f6a9c2d:

  • The overflow bounds were computed from the calendar maximum second (MAX_DATETIME64_TIMESTAMP), but at scale 9 that second does not fit in the Int64 native storage (10413791999 * 1e9 > Int64::max). So a value could pass the bound check and then raise DECIMAL_OVERFLOW inside the conversion even under date_time_overflow_behavior = 'saturate', where it must clamp.
  • The bounds are now derived from the maximum representable native value, capped at Int64::max, in the float and the signed/unsigned integer transforms (the integer paths had the same scale-9 failure mode). saturate clamps to the maximum representable value and throw raises VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE.
  • The float path now produces saturated values directly in the native domain, so CAST(1e20 AS DateTime64(6)) yields the exact 2299-12-31 23:59:59.999999 instead of the float-imprecise ...999998 that was breaking 03011.

I updated the 03011 comment/reference for the DateTime64(9) case (it now saturates instead of throwing DECIMAL_OVERFLOW — matching your note that this behavior was fine to change) and added throw/saturate regression coverage for DateTime64(9) (Float64/UInt64/Int64 sources) to 04050_time64_cast_uint64_no_wrap.

Built on ARM and verified locally: 03011 and 04050 match their references, and a sweep of 13 related date/time cast tests passes. The Decimal*/BFloat16 thread remains as you dismissed it (scale-aware handling belongs in DataTypesDecimal.cpp, out of scope here).

I did not approve, since this is not my own PR.

Comment thread src/Functions/FunctionsConversion.h Resolved
alexey-milovidov and others added 2 commits September 23, 2026 12:07
…_overflow_behavior-ignored

# Conflicts:
#	src/Core/FormatFactorySettings.h
#	src/Functions/FunctionsConversion.cpp
#	src/Functions/FunctionsConversion_reg.cpp
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master (the PR was CONFLICTING, 4152 commits behind) and fixed the only CI red. Pushed f0cc980bfa17.

  • Conflicts (3 files, both sides kept): the date_time_overflow_behavior setting doc now also mentions master's text-parsing clause; in FunctionCast the PR's numeric→DateTime64/Time64 accurate-cast branch and master's new Time64→Time64/DateTime64 branch are both kept (the type sets don't overlap); the toTime docs mention both master's Time64 source and the PR's setting-dependent overflow behavior.
  • Build (arm_tidy): cppcoreguidelines-init-variables in convertNumericToDateTime64OrTime64OrNull. The bounds are now const and initialized with a ternary, and representable starts as false.
  • Local build OK and clang-tidy clean on FunctionsConversion.cpp. The PR's tests and the related master tests pass (31 in total, including 01734, 04050, 04402, 04403, 05042, 05055, 05156, 05218, 01601, 05232, and master's Time64 accurate-cast and date_time_overflow_behavior tests).

This is still @yariks5s' draft, so I'm leaving the review and merge to a human.

Comment thread src/Core/FormatFactorySettings.h Resolved
alexey-milovidov and others added 2 commits October 9, 2026 13:52
…havior`

Integer and floating-point conversions into `Date`, `Date32` and `DateTime`
still always clamp and do not consult the setting, so do not claim that the
setting applies to them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Core/FormatFactorySettings.h Resolved
alexey-milovidov and others added 2 commits October 17, 2026 18:19
`master` merged #117667, which honours
`date_time_overflow_behavior` for every numeric conversion to the date and time types,
including the integer and floating-point casts to `DateTime64` / `Time64` this PR fixes,
and also restores the `accurateCast*` contract. All conflicts in `FunctionsConversion.h`,
`FunctionsConversion.cpp`, `FunctionsConversion_reg.cpp`, `FormatFactorySettings.h` and the
conflicting tests are therefore resolved to `master`'s version. The PR's tests that still
pass on `master` (`04050`, `05055`, `05218`) are kept; the comments the PR changed in
`01734` and `03011` are reverted to `master`'s, because they describe a whole-second clamp
that `master` no longer does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`master` already honours `date_time_overflow_behavior` for these conversions, but it still
computed the tick count of a `Float32` source in `Float32`. Its 24-bit mantissa rounds the
product with the scale multiplier: `toDateTime64(toFloat32(1665519700), 3)` came out 30
seconds early, and `CAST(9223371776::Float32, 'DateTime64(9)')` - in range, since it is
exactly `9223371776` seconds - rounded to 2^63 ticks and was clamped to the last tick, or
rejected in the `throw` mode and by `accurateCast` / `accurateCastOrNull`.

The transforms and the window check of the accurate casts now compute in `Float64` for
every floating-point source; `BFloat16` and `Float32` values are exact there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov alexey-milovidov changed the title Fix date_time_overflow_behavior being ignored for integer and float casts to DateTime64/Time64 Scale Float32 sources of DateTime64 / Time64 in Float64 precision Oct 17, 2026
alexey-milovidov and others added 2 commits October 20, 2026 04:17
…ime64` in `05218`

`accurateCast` rejects an out-of-range number with `CANNOT_CONVERT_TYPE`, the same
code it uses for every other target type, so the test expecting
`VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE` failed in the Fast test:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=101512&sha=latest&name_0=PR&name_1=Fast%20test
#101512

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master and fixed the only CI red (Fast test, 05218_accurate_cast_numeric_to_datetime64_time64). Pushed c6ca00f65e4.

accurateCast to DateTime64 / Time64 rejects an out-of-range number with CANNOT_CONVERT_TYPE, the same code it uses for every other target type (see 01601_accurate_cast). The test expected VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, so I updated those 12 expectations. Locally, 05218, 05406, 05055, 04050 and 02462 all pass with randomized settings. The Bugfix validation failure in Finish Workflow was only a knock-on effect of the Fast test failure.

Both tests describe behaviour that `master` already has, so they pass on
`master` and make `Bugfix validation (functional tests)` fail: that check
requires every test added by a bug-fix PR to fail on `master`. They are
proposed in a separate test-only PR instead. The regression test of this
PR, `05406_float32_to_datetime64_precision`, still reproduces the bug.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=101512&sha=latest&name_0=PR&name_1=Bugfix%20validation%20(functional%20tests%2C%20amd64)
#101512

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Fixed the only CI red, Bugfix validation (functional tests) on both arches (pushed 309f1fb8645). That check requires every test added by a bug-fix PR to fail on master, but 05055_datetime64_numeric_min_native_boundary and 05218_accurate_cast_numeric_to_datetime64_time64 only cover behaviour master already has, so they passed there. I moved them to a separate test-only PR, #127309. The regression test of this PR, 05406_float32_to_datetime64_precision, still reproduces the bug on master. The PR description is updated to match.

shankar-iyer pushed a commit to shankar-iyer/ClickHouse that referenced this pull request Oct 22, 2026
…boundaries

The tests were written in ClickHouse#101512
and moved out of it because they describe behaviour that `master` already has:
- `05055_datetime64_numeric_min_native_boundary`: the lower `Int64` tick boundary
  of `DateTime64(9)` under every `date_time_overflow_behavior` mode;
- `05218_accurate_cast_numeric_to_datetime64_time64`: `accurateCast`,
  `accurateCastOrNull` and `accurateCastOrDefault` to `DateTime64` / `Time64`
  decide on representability alone, regardless of the setting.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master (the branch was 7 days behind; CI on 309f1fb8645 had no failures) and pushed d284f2d26324. The merge had no conflicts and leaves the PR diff unchanged. clickhouse builds, and 02462_number_to_datetype, 04050_time64_cast_uint64_no_wrap and 05406_float32_to_datetime64_precision pass locally. There are no unresolved review threads. The only pending check is CH Inc sync (awaiting).

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=101512&sha=d284f2d26324b321cb4f6b543861eac495fef590&name_0=PR&name_1=Build%20profile%20diff (LogClusterNotReady: the endpoint never became ready in build_profile_diff_job.py, unrelated to this PR) and provide a fix in a separate PR. If the fix is already in progress, link it here. Possibly related: #120462, #126200

@groeneai

Copy link
Copy Markdown
Collaborator

The Build profile diff red on d284f2d is not caused by this PR. Its job log shows all 8 SELECT 1 readiness probes failing (No connection to LogCluster, 2026-10-27 09:26-09:28 UTC) until has_pr_data raises LogClusterNotReady. The read-only CI logs service is at its total memory limit and rejects every query, the probe included: HTTP 500, Code: 241 ... current RSS: 212.89 GiB, maximum: 212.40 GiB (re-checked at 2026-10-28 04:49 UTC). No Build profile diff run in CIDB has been green since 2026-10-26 22:42 UTC.

The fix in progress is my open PR #126200: a readiness probe that the server rejects for its own load (exception code 202 or 241) ends the job green with CI logs cluster unavailable, nothing compared, while every other not-ready cause stays red. The memory exhaustion of the read-only service itself is on the cluster side.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master (the branch was 9 days behind, no conflicts) and pushed c05784963b2d. The PR diff is unchanged. clickhouse builds, and 05406_float32_to_datetime64_precision, 02462_number_to_datetype, 04050_time64_cast_uint64_no_wrap, 01734_datetime64_from_float and 03011_definitive_guide_to_cast pass locally.

@groeneai, thanks for the analysis. The only red on d284f2d2 was Build profile diff (LogClusterNotReady), a CI infrastructure failure that this PR does not cause. Its fix is tracked in #126200, which is still open. There are no unresolved review threads.

@CLAassistant

CLAassistant commented Nov 5, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master (the branch was 8 days behind, no conflicts) and pushed edf768ecd32e. The PR diff is unchanged. The only red on c05784963b2d was six jobs reported as DROPPED/cancelled (Stateless tests (arm_asan_ubsan, azure, parallel), Integration tests (arm_binary, 2/4..4/4), Performance Comparison (arm_release, master_head, 1/6, 4/6)), with no test failures; the new commit re-runs them. clickhouse builds locally, and 05406_float32_to_datetime64_precision, 04050_time64_cast_uint64_no_wrap, 02462_number_to_datetype, 01734_datetime64_from_float and 03011_definitive_guide_to_cast pass. There are no unresolved review threads.

# Conflicts:
#	src/Functions/FunctionsConversion.h
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master and resolved the conflict in src/Functions/FunctionsConversion.h: master added [[nodiscard]] to the BFloat16 overloads of execute in ToDateTime64TransformFloat / ToTime64TransformFloat. I kept the PR's comment and its Float32 overloads, and marked the Float32 overloads [[nodiscard]] too so they match. Pushed 34ea9f2ca07d. Apart from that attribute, the PR diff is unchanged. clickhouse builds, and 02462_number_to_datetype, 04050_time64_cast_uint64_no_wrap and 05406_float32_to_datetime64_precision pass locally.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 The only red on 34ea9f2ca07d is the merge gate in Finish Workflow: draft PR ran only the fast test, merge not allowed until the full CI runs. The fast test and the other checks that ran are green, there are no unresolved review threads, and the branch has no conflicts with master, so there is nothing to fix in the code.

@yariks5s, the PR has been a draft since 2026-04-01. If you consider it finished, please mark it ready for review - that starts the full CI (alternatively, the ci-force-all label does the same while keeping it a draft).

This branch has not been deployed

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

Labels

comp-datetime Date/DateTime/TimeZone datatypes and date-time semantics. pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants