Skip to content

Fix toDateTime32 embedded docs example that documented toDateTime64 - #110459

Merged
alexey-milovidov merged 26 commits into
masterfrom
fix-todatetime32-doc-example
Aug 2, 2026
Merged

alexey-milovidov merged 26 commits into
masterfrom
fix-todatetime32-doc-example

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

Related: #109965

The embedded FunctionDocumentation block for toDateTime32 in src/Functions/FunctionsConversion_reg.cpp was copy-pasted from toDateTime64: all three examples called toDateTime64 and showed DateTime64(3) results, and the description claimed an extended range of 1900-01-01 to 2299-12-31, which is a property of DateTime64, not DateTime. As a result, the generated toDateTime32 docs page was technically incorrect.

This was noticed during the review of #109965, which was scoped to box-formatting fixes only; the author suggested handling this correctness issue in a separate PR.

The new examples call toDateTime32 and their outputs were verified against a real server. The description now correctly states that DateTime32 is an alias of DateTime with the supported range 1970-01-01 00:00:00 to 2106-02-07 06:28:15. Out-of-range handling is documented precisely: string inputs and the saturating numeric types ((U)Int8 through (U)Int64, BFloat16, Float32, Float64) are always clamped to the range boundaries; the Time type and wide integer types such as (U)Int128/(U)Int256 wrap around instead of saturating (and, unlike other date and time types, Time does not follow date_time_overflow_behavior), while Decimal and Time64 inputs throw an exception; conversions from other date and time types such as Date32 or DateTime64 follow the date_time_overflow_behavior setting (the default ignore mode may produce wrapped-around values). The Arguments type list is aligned with the corrected description. All statements were verified against a real server.

During review it turned out that the saturation of BFloat16 inputs was not actually guaranteed by the implementation: unlike Float32 and Float64, BFloat16 was missing from the saturating conversion branch for the DateTime and Time targets in src/Functions/FunctionsConversion.h (while being present in the corresponding branches for the Date and Date32 targets), so out-of-range values fell through to a raw float-to-integer cast whose result is architecture-dependent: it happens to saturate on AArch64, where the hardware conversion instruction clamps, but wraps around on x86-64. This PR adds BFloat16 to the saturating branch, making the documented saturation an actual contract on all architectures, and adds a test.

A follow-up review round found that the saturating branch itself was still unsound for floating-point sources: it converted the value with time_t(from) before clamping with std::min/std::max, so finite values above the range of time_t still hit an undefined float-to-integer cast, and non-finite values (NaN, inf) produced architecture-dependent garbage instead of an error (for BFloat16 they previously threw via the isFinite check in the generic conversion path). The shared helpers ToDateTimeTransform64Signed and ToTimeTransform64Signed are now hardened for all floating-point sources (BFloat16, Float32, Float64): non-finite inputs throw CANNOT_CONVERT_TYPE, matching integer targets, and finite values are clamped to the target range in the Float64 domain (which represents every BFloat16/Float32 value and the range boundaries exactly) before the conversion to time_t. The Accurate/OrNull conversion strategies already bounds-check before calling the transform and are unchanged. The test covers nan/inf/-inf and very large finite inputs for the DateTime and Time targets.

A further review round pointed out that the sibling toDate float path (ToDateTransformFromSecondsOrDays) had the same defect: no non-finite check and a time_t cast before clamping. It is now hardened with the same contract: non-finite inputs throw CANNOT_CONVERT_TYPE, and huge finite values are clamped in the Float64 domain before the cast, saturating to the upper Date boundary (2106-02-07). toDate32 already clamped in the float domain and handled NaN, so it is unchanged. The test covers the toDate cases as well.

Another review round found the same cast-before-clamp defect on the unsigned side: the UInt64 helpers (ToDateTimeTransform64, ToTimeTransform64, and the UInt64 path of ToDateTransformFromSecondsOrDays) converted the value with time_t(from) before clamping, so UInt64 values above Int64::max() wrapped to a negative time_t and escaped the clamp entirely: toDateTime32(toUInt64(9223372036854775808), 'UTC') returned 1970-01-01 00:00:00 instead of saturating. These helpers now compare in the unsigned domain before any conversion to time_t, following the pattern already used by ToDateTime64TransformUnsigned, making the documented (U)Int64 saturation an actual contract. Wide integer types ((U)Int128/(U)Int256) keep their documented wrap-around behavior for the DateTime target, where they are converted by the generic numeric conversion path rather than by these transforms. The test covers UInt64 values just above Int64::max() and at UInt64::max() for the DateTime, Time, and Date targets.

A further review round found two more defects of the same class around the Time target. First, the accurate cast of a number to Time validated the value against the unsigned DateTime window [0, 0xFFFFFFFF] in Transformer, which is wrong in both directions for Time: accurateCast(-1, 'Time') was rejected even though Time is a signed type that preserves negative numeric inputs, while accurateCast(4000000, 'Time') passed the check and was then silently saturated to 999:59:59. Time now has its own accurate bounds (-999:59:59 to 999:59:59), and the exception names the target type instead of its underlying Int32. Second, that check only runs for the source types dispatched through DateTimeTransformImpl, and UInt8/UInt16/UInt32 (the type of the literal 4000000) as well as the wide integer types had no numeric-to-Time branch at all: they were converted by a plain static_cast, so an out-of-range value was stored unclamped and clamped only when printed, unlike the same value with an Int64 or Float64 source. All numeric sources now go through the saturating ToTimeTransform64/ToTimeTransform64Signed helpers, which compare against the boundaries in the domain of the source type, so a wide integer is no longer truncated by a cast to time_t first. The embedded documentation of toTime states the saturation and non-finite contract, and 04092_date_plus_time (which asserted the previous, source-type-dependent behavior of toTime(9999999)) now asserts the uniform saturation.

The toDate32 transform got the same treatment: its throw branches formatted the offending value as static_cast<Int64>(from), which is undefined behavior for a NaN or for a float outside of the range of Int64 (a latent fix - numeric-to-Date32 is instantiated with default_date_time_overflow_behavior, so this branch is not reachable for numeric sources), and its saturating path had the same UInt64 wrap-around hole as toDate: toDate32(toUInt64(9223372036854775808)) returned 0000-01-01 instead of saturating to 2299-12-31.

A final review round pointed out that the same cast-before-clamp hole remained for the wide integer sources of toDate and toDate32: unlike the DateTime target, ConvertImpl does route Int128, UInt128, Int256 and UInt256 through ToDateTransformFromSecondsOrDays and ToDate32TransformFromSecondsOrDays, and only UInt64 was compared against the boundary before the conversion to time_t, so a wide integer above Int64::max() wrapped to a negative time_t and produced a pre-epoch day instead of saturating. The comparison is now generalized to every integer source whose maximum exceeds the target boundary, and the test covers (U)Int128 and (U)Int256 for both toDate and toDate32.

A further review round found the last hole of this family on the accurate-cast side: FunctionCast::createWrapper passes the DateTimeAccurate*ConvertStrategyAdditions for every numeric to date-or-time conversion, but the precheck in Transformer::vector only ran for Date, DateTime and Time, so Date32 fell through to the plain saturating transform: accurateCastOrNull(toUInt64(18446744073709551615), 'Date32') returned 2299-12-31 instead of NULL, and accurateCast silently clamped instead of throwing. Date32 now has its own accurate bounds - a numeric source is read either as an extended day number or as a unix timestamp, so its representable window is [-DateLUTImpl::getDayNumOffsetEpoch(), MAX_DATE32_TIMESTAMP] - checked in the domain of the source type, which also rejects the non-finite floats. The ordinary toDate32 keeps saturating. The OrDefault flavours are built on the accurate cast, so toDate32OrDefault and accurateCastOrDefault(..., 'Date32') of an out-of-range value now yield the default of Date32, which is 1900-01-01, instead of the saturated 2299-12-31; the expected output of 03212_variant_dynamic_cast_or_default is updated accordingly.

A further review round found that the accurate-cast prechecks for floating-point sources only validated the range, not the exact representability, so a non-integral float passed the check and was then silently truncated by the transform: accurateCastOrNull(toFloat64(-1.5), 'Time') returned -00:00:01 and accurateCastOrNull(toFloat64(1704067200.5), 'Date32') returned 2024-01-01 instead of NULL, violating the accurateCast contract (a non-integral 1.5 is rejected by accurateCast(1.5, 'Int32')). The pre-existing Date/DateTime accurate branch had the same hole, e.g. accurateCast(toFloat64(1.5), 'DateTime') truncated to 1970-01-01 00:00:01. A floating-point source must now also be integral (value == trunc(value)) to pass the accurate cast to Date, Date32, DateTime or Time; the ordinary (saturating/truncating) conversions are unchanged.

Changelog category (leave one):

  • Backward Incompatible Change

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

Conversion of out-of-range floating-point values (BFloat16, Float32, Float64) and of UInt64 values above Int64::max() to DateTime and Time now reliably saturates to the range boundaries on all architectures (previously the result of an out-of-range conversion was architecture-dependent and could wrap around on x86-64), and non-finite values (NaN, inf) now throw an exception instead of producing an arbitrary result. The same fix is applied to the float-to-Date conversion path of toDate and to the conversions of UInt64 and of wide integers ((U)Int128, (U)Int256) to Date and Date32, which could return a pre-epoch day instead of saturating. Conversion of a number to Time now saturates to the range of the type for every numeric source type (previously values from narrow unsigned or wide integer sources were stored unclamped and clamped only when printed), and the accurate cast to Time no longer rejects the negative values that Time supports, nor silently saturates the values that do not fit into it. The accurate cast of a number to Date32 (accurateCast, accurateCastOrNull) no longer silently saturates an out-of-range or non-finite value, but throws or returns NULL as it already did for Date and DateTime, and the OrDefault flavours return the default value of Date32 for such an input. The accurate cast of a non-integral floating-point number to Date, Date32, DateTime or Time is now rejected instead of being silently truncated. Also fixed the toDateTime32 function documentation, which mistakenly showed toDateTime64 examples and described the DateTime64 value range.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.8.1.637 (included in 26.8 and later)

The embedded `FunctionDocumentation` block for `toDateTime32` in
`FunctionsConversion_reg.cpp` was copy-pasted from `toDateTime64`: all
three examples called `toDateTime64` and showed `DateTime64(3)` results,
and the description claimed an extended range of `1900-01-01` to
`2299-12-31`, which is a property of `DateTime64`, not `DateTime`.

Replace the examples with actual `toDateTime32` calls (outputs verified
against a real server) and correct the description: `DateTime32` is an
alias of `DateTime` with the range `1970-01-01 00:00:00` to
`2106-02-07 06:28:15`, saturating outside of it.

Follow-up to the review discussion in
#109965

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

clickhouse-gh Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e64e5f8]

Summary: ✅


AI Review

Summary

This PR started as a toDateTime32 embedded-doc fix, but the current diff also hardens numeric conversions to Date, Date32, DateTime, and Time and aligns the docs/tests with the actual contract. I re-checked the current code against the full PR diff, all prior inline threads, and the current Praktika status; the previously raised issues appear fixed in the current revision, and I did not find new correctness, safety, or coverage gaps that warrant another inline comment.

Final Verdict

✅ Approved. No new findings.

@clickhouse-gh clickhouse-gh Bot added the pr-documentation Documentation PRs for the specific code PR label Jul 14, 2026
@yariks5s yariks5s self-assigned this Jul 14, 2026
…e32` docs

String and numeric inputs are always saturated to the `DateTime` range, but
conversions from other date and time types such as `Date32` or `DateTime64`
follow the `date_time_overflow_behavior` setting, whose default `ignore`
mode may produce wrapped-around values (verified against a local server).
…at actually saturate

Verified against a local build that `Decimal` is not actually supported by
`toDateTime32` (throws `ILLEGAL_COLUMN`) and that wide integer types such as
`(U)Int128`/`(U)Int256` wrap around instead of saturating, since they fall
through to the plain `static_cast` path in `convertNumericGeneral` rather
than the saturating `ToDateTimeTransform*` helpers used by `(U)Int8/16/32/64`
and `Float32`/`Float64`.
…rected description

The generated `Arguments` section only advertised `UInt*` while the corrected
description states that `Date32` and signed integers are supported. List the
verified input families: `(U)Int*`, `Float*`, `Date`, `Date32`, `DateTime`,
`DateTime64`, `String`, `FixedString`.

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

clickhouse-gh Bot commented Jul 16, 2026

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [77d1ad4]

@alexey-milovidov

Copy link
Copy Markdown
Member Author

The three red checks on 12b278dd are unrelated to this docs-only change (it touches only the toDateTime32 FunctionDocumentation block):

The previous CH Inc sync red cleared on the latest sync run (now green). The one remaining AI-review Major (the arguments_toDateTime32 type list contradicting the corrected description) is addressed in 77d1ad4.

The description's support sentence omitted `DateTime64`, while the next
sentence documents `DateTime64` overflow behavior and the `Arguments`
section (`arguments_toDateTime32`) advertises `DateTime64` as an accepted
input. Add `DateTime64` to the sentence so the description and the
`Arguments` section agree.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…Time32`

The AI review correctly flagged that the accepted-type list in the
`toDateTime32` embedded documentation still omitted `BFloat16`, even
though `callOnIndexAndDataType` dispatches `TypeIndex::BFloat16` for the
function (`src/Core/callOnTypeIndex.h`), so it is accepted rather than
rejected. Verified locally that `toDateTime32` accepts `BFloat16` input
and saturates on overflow just like `Float32`/`Float64` (e.g.
`toDateTime32(CAST(1e10 AS BFloat16), 'UTC')` returns the range boundary
`2106-02-07 06:28:15`, and a negative `BFloat16` clamps to
`1970-01-01 00:00:00`), unlike wide integer types which wrap.

Added `BFloat16` to both the numeric-types enumeration in the
description (grouped with the saturating floating-point types) and to the
`arguments_toDateTime32` type list, following the neighboring convention
of listing `BFloat16` separately from `Float*`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The AI review pointed out that the accepted-type lists for `toDateTime32`
still omitted `Time`, even though `FunctionToDateTime32` is the same
`FunctionConvert<DataTypeDateTime>` alias as `toDateTime` and thus accepts
`Time` input (covered by `03365_time_time64_conversions`).

Verified against a local build:
- `toDateTime32(toTime('12:34:56'), 'UTC')` returns a `DateTime` value.
- `Time` overflow wraps around (like wide integers) and does not follow
  `date_time_overflow_behavior`, e.g. `toDateTime32(toTime('-999:00:00'), 'UTC')`
  yields `2105-12-27 15:28:16` in all overflow modes.
- `Time64` is not accepted: `toDateTime32(toTime64('12:34:56.789', 3), 'UTC')`
  throws `CANNOT_CONVERT_TYPE`, matching `toDateTime`.

Added `Time` to the description and to `arguments_toDateTime32`, listed it
with the wrapping types, and noted that `Time64` (like `Decimal`) throws.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ate by contract

The documentation added in this PR claims that out-of-range `BFloat16`
values are saturated when converted to `DateTime`, but unlike `Float32`
and `Float64`, `BFloat16` was missing from the saturating
`ToDateTimeTransform64Signed` branch in `FunctionsConversion.h` (while
being present in the corresponding branches for the `Date` and `Date32`
targets), so the conversion fell through to `convertNumericGeneral`,
whose default branch is a raw float-to-integer `static_cast` with an
architecture-dependent out-of-range result: it saturates on AArch64,
where the hardware conversion instructions clamp, but wraps around on
x86-64.

Add `BFloat16` to the saturating branch (covering both the `DateTime`
and `Time` targets) so the documented saturation is an actual contract
on all architectures, and add a test.

#110459 (comment)

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default and removed pr-documentation Documentation PRs for the specific code PR labels Jul 17, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

The three red checks on 9147d68a are unrelated to this change, which touches only the toDateTime32 docs block, the BFloat16→DateTime/Time saturating branch in FunctionsConversion.h, and a new stateless test:

Mergeable Check and PR are aggregates of the above; CH Inc sync is still running.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

CI status on 8d8d608d (fresh run after today's master merge): 158 checks pass; the 2 real failures are unrelated to this PR (docs + BFloat16 → DateTime conversion path):

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110459&sha=8d8d608d4e553ce32a5c2a560d58f25d7627d45e&name_0=PR&name_1=Stress%20test%20%28amd_debug%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

@alexey-milovidov this is the set skip-index snapshot bug we already track (STID 6726). Fix in progress: #106988.

Confirmed the same instance from the amd_debug report at 8d8d608d:

  • STID 6726-6874, null map size = 1, nested column size = 0
  • Stack: SerializationNullable::deserializeBinaryBulkWithMultipleStreams (SerializationNullable.cpp:174) <- MergeTreeIndexBulkGranulesSet::deserializeBinary (MergeTreeIndexSet.cpp:196) <- MergeTreeIndexReader::read <- MergeTreeDataSelectExecutor::filterMarksUsingIndex (MergeTreeDataSelectExecutor.cpp:2672)

Root cause: a set skip-index granule is written for the old column type; after ALTER MODIFY COLUMN ... Nullable(...) the read snapshot does not see the pending alter mutation (with apply_mutations_on_fly=0 and apply_patch_parts=0), so the granule is deserialized as Nullable while the bytes are the old type, giving the null map / nested size mismatch. It recurs across unrelated PRs and on master because any query hitting a set index over a just-altered column can trip it, so #106988 is the single fix for all of them.

#106988 fixes it in MergeTreeData::createStorageSnapshot by setting need_alter_mutations when the table has pending alter mutations (previously gated only on apply_mutations_on_fly || apply_patch_parts). Includes a deterministic repro + regression test 04151_skip_index_after_alter_modify_column_nullable. It is open and awaiting review.

No standalone issue exists; #106988 is the tracking artifact. I can open a dedicated issue if you prefer.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

The only real red on 174ece3ddfc was Upgrade check (amd_release) — Error message in clickhouse-server.log:

Code: 27. DB::Exception: Cannot parse input: expected '\n' before: 'version: 1
storing_version: 0
creation_tid: (2, 33, ...)

It is unrelated to this PR. The failing query is ATTACH TABLE t_plt_rb_contains (comment 04241_part_loading_tree_rollback_contains.sh) and the symbolized frames are DiskObjectStorageMetadata::deserialize → MetadataStorageFromCacheObjectStorage::getStorageObjects, i.e. the known issue #111053: upgrade_runner.sh sets an object-storage default MergeTree policy but does not forward --s3-storage to clickhouse-test, so the no-object-storage tag of the 04*_part_loading_tree_rollback_* tests never fires and their fabricated raw txn_version.txt is not in DiskObjectStorageMetadata format.

The fix for exactly that, #111772, merged into master on 2026-07-27T09:13Z — after this branch's previous merge-base — so I merged master (bca429f1630) to pull it in. The merge was clean, the PR diff is unchanged, ninja clickhouse rebuilt clean, and 04545_bfloat16_to_datetime_saturation, 04641_numeric_to_time_saturation_accurate_cast and 04092_date_plus_time all match their references against the fresh binary.

Comment thread src/Functions/DateTimeTransforms.h Resolved
`FunctionCast::createWrapper` passes `DateTimeAccurateConvertStrategyAdditions` /
`DateTimeAccurateOrNullConvertStrategyAdditions` for every numeric to
date-or-time conversion, but the precheck in `Transformer::vector` only ran for
`Date`, `DateTime`, and `Time`, so `Date32` fell through to the plain saturating
`ToDate32TransformFromSecondsOrDays`. As a result
`accurateCastOrNull(toUInt64(18446744073709551615), 'Date32')` returned
`2299-12-31` instead of `NULL`, and `accurateCast` silently clamped instead of
throwing.

A numeric source is read either as an extended day number or as a unix
timestamp, so the representable window of `Date32` is
`[-DateLUTImpl::getDayNumOffsetEpoch(), MAX_DATE32_TIMESTAMP]`; the precheck now
compares against it in the source domain, and rejects non-finite floats because
every comparison with a NaN is false.

Addresses the review finding on `src/Functions/DateTimeTransforms.h`.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

The only red on bca429f1630 was Stateless tests (amd_asan_ubsan, distributed plan, parallel): 00084_external_aggregation failed with MEMORY_LIMIT_EXCEEDED (would use 315.47 MiB … maximum: 286.10 MiB in AggregatingTransform). It is unrelated to this PR (which touches the numeric-to-date/time conversion transforms and their docs) — the harness itself labelled it flaky and its four reruns with the same randomized settings all passed. It is the known memory-headroom flake of that test, fixed by #112054, which merged into master on 2026-07-28. master is merged into this branch (543cf09f1a0), so the fix is now in and the red should clear on this run.

The head also addresses the AI review blocker about the numeric accurate cast to Date32 (commit 411d52891b4, new test 04652_accurate_cast_numeric_to_date32).

…e32`

`toDate32OrDefault` is built on the accurate cast, so after this pull request
made `accurateCastOrNull` to `Date32` reject the values the type cannot
represent, the numeric values above `MAX_DATE32_TIMESTAMP` in the `Dynamic`
column no longer saturate to `2299-12-31` - they now yield the default of
`Date32`, which is `1900-01-01` and was already in the expected output.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110459&sha=latest&name_0=PR&name_1=Fast%20test
Comment thread src/Functions/DateTimeTransforms.h Resolved
… a number

The description of `toDate32OrDefault` claimed that an out-of-range value
returns the lower border value of `Date32`. Since the accurate cast of a number
to `Date32` now rejects the values the type cannot represent, and
`FunctionCastOrDefaultTyped` is built on `castColumnAccurateOrNull`, such a
value yields the default instead: the second argument when it is specified, and
`1900-01-01` otherwise. Added an example with an explicit default.
Comment thread src/Functions/DateTimeTransforms.h Resolved
alexey-milovidov and others added 2 commits July 31, 2026 13:23
…c-example

# Conflicts:
#	src/Functions/FunctionsConversion_reg.cpp
…st to date and time types

The accurate-cast precheck in `Transformer::vector` only validated the range of a
floating-point source, so a non-integral value passed the check and was then silently
truncated by the transform: `accurateCastOrNull(toFloat64(-1.5), 'Time')` returned
`-00:00:01` and `accurateCastOrNull(toFloat64(1704067200.5), 'Date32')` returned
`2024-01-01` instead of `NULL`, violating the `accurateCast` contract (a non-integral
`1.5` is rejected by `accurateCast(1.5, 'Int32')`). The pre-existing `Date`/`DateTime`
branch had the same hole, e.g. `accurateCast(toFloat64(1.5), 'DateTime')` truncated to
`1970-01-01 00:00:01`. Now every floating-point source must also be integral
(`value == trunc(value)`) to take the accurate path; ordinary conversions are unaffected.

Co-Authored-By: Claude Fable 5 <[email protected]>
alexey-milovidov and others added 2 commits August 1, 2026 16:21
The `toTime` docs advertised only `(U)Int*` and `Float*` as numeric
inputs, while the implementation (and the test
`04545_bfloat16_to_datetime_saturation`) treats `BFloat16` as a
supported numeric source going through the same `Time` saturation path.

Co-Authored-By: Claude Fable 5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 1, 2026
…s distances

Two regressions from making the runtime overflow mode reach the numeric temporal
transforms, plus coverage for three dispatch alternatives that no test pinned.

accurateCastOrNull must yield NULL or a value, never raise. The accurate_or_null
dispatch selected the Throw ConvertImpl specialization, which had been harmless
only because no Throw transform existed for Date/Date32/DateTime/Time; once they
did, the transform raised from inside the vectorised loop, where the OrNull
strategy has no way to turn the error into a null-map entry. That arm now
instantiates the Ignore specialization: rejecting an out-of-range value stays the
job of the accurate precheck in Transformer::vector, whose per-target windows
PR ClickHouse#110459 corrects. accurateCast keeps throwing.

A window frame RANGE offset is a distance in the ORDER BY column's underlying
units, not a point in time. WindowTransform coerces it with
convert_inexact_floats = true, which clears the exact flag, so the offset stopped
taking convertNumericType<StorageType> and started taking the temporal coerce
helpers: a Date offset of 65536 was read as a unix timestamp and produced a
roughly zero-day frame instead of being rejected, and a Time offset above
MAX_TIME_TIMESTAMP was clamped, silently shrinking the frame. Both are wrong
results. A new temporal_numeric_is_offset parameter routes such a source to the
storage-type arm in every overflow mode, so an offset the storage type cannot
hold is rejected exactly as it was before the coerce helpers existed.

Also: UInt256, Int128 and BFloat16 each have their own alternative in the
DateTime/Time dispatch, and deleting any of them left the suite green; one row
per alternative per target now covers them. Three comments named
MAX_DATETIME64_TIMESTAMP where the value is MAX_DATE32_TIMESTAMP. The
out-of-range lambda in coerceNumericToDateField had an unreachable non-throwing
arm and a comment describing a caller that does not exist; it now throws
unconditionally, matching both sibling helpers.

The values() table function builds its coercion with a default FormatSettings,
so the session setting never reaches it and it keeps clamping while CAST of the
same literal raises. The test pins that pair; aligning them would make values()
raise and is left to a follow-up.
@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

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

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 2, 2026
Merged via the queue into master with commit 3d794b1 Aug 2, 2026
180 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-todatetime32-doc-example branch August 2, 2026 15:25
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 2, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 3, 2026
PR ClickHouse#110459 hardened the same numeric to Date/Date32/DateTime/Time conversion
paths against undefined float-to-integer and wide-integer casts, so the merge
conflicted in `FunctionsConversion.h` and in `04092_date_plus_time`.

Resolution takes the merged implementation as the base and re-applies only what
this PR adds on top of it, so none of ClickHouse#110459's hardening is reverted:

- Thread the runtime `date_time_overflow_behavior` into the numeric to
  Date/Date32/DateTime/Time transforms. Master still instantiates them with the
  compile-time default, so the setting has no effect there. This is the change
  this PR exists for; ClickHouse#110459 left it untouched.
- Add `formatOutOfBoundsValue` for the exception messages. Threading the setting
  instantiates the `Throw` branches for source types that were previously never
  reached there, and the inline formatting rejects those at compile time: wide
  integers have no `fmt` formatter, and `UInt8`'s field type is `char8_t`, which
  `fmt` refuses as a character type. Floats are widened to double rather than
  narrowed to `Int64`, which is undefined for a huge, infinite or NaN value.
- Add `isAboveBound`/`isBelowBound`, which compare through
  `accurate::greaterOp`/`lessOp` so a source wider or differently signed than
  `time_t` is compared at full precision.
- Route `Int128`/`UInt128`/`Int256`/`UInt256` to the overflow-aware DateTime
  transforms. Master lists only `(U)Int64`, so wide integers fall through to
  `convertNumericGeneral` and ignore the setting.
- Clamp in the source domain in `ToDateTimeTransform64Signed`. The merged code
  narrows to `time_t` before `std::min`, so a wide integer truncates instead of
  saturating: `CAST(99999999999999999999999999::Int256, 'DateTime')` returned
  2091-03-20 05:00:47 rather than the DateTime maximum. The `Date`, `Date32` and
  `Time` siblings already guarded this.

Test updates:

- `04092_date_plus_time`: keep both sides. ClickHouse#110459's assertions that a numeric
  input to `Time` is stored saturated hold under `saturate`, so they moved into
  that section; the throw-mode rows this PR adds follow.
- `04401_...`: a non-finite float is now rejected as unconvertible in every mode
  (`CANNOT_CONVERT_TYPE`) rather than being clamped, and `accurateCast` rejects
  out-of-range values in the precheck, so those rows assert the merged contract.
  `Date32` has no non-finite guard, so its rows pin its actual behavior instead;
  aligning it with the sibling targets is a follow-up.
- `04401_..._message`: match the unconvertible message too. Matching only the
  out-of-bounds form left those rows empty, which would pass whatever the server
  printed.
- `04545_bfloat16_to_datetime_saturation`: the throw-mode rows asserted
  saturation regardless of the setting, which is what this PR changes; they now
  assert the rejection. The saturation rows for the other modes are unchanged.

Co-Authored-By: Claude Fable 5 <[email protected]>
@fm4v fm4v added pr-backward-incompatible Pull request with backwards incompatible changes and removed pr-bugfix Pull request with bugfix, not backported by default labels Oct 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backward-incompatible Pull request with backwards incompatible changes 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.

5 participants