Repository navigation
Fix toDateTime32 embedded docs example that documented toDateTime64 - #110459
Conversation
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]>
|
Workflow [PR], commit [e64e5f8] Summary: ✅
AI ReviewSummaryThis PR started as a Final Verdict✅ Approved. No new findings. |
…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]>
|
The three red checks on
The previous |
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]>
|
The three red checks on
|
|
CI status on
@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. |
|
@alexey-milovidov this is the Confirmed the same instance from the amd_debug report at
Root cause: a #106988 fixes it in No standalone issue exists; #106988 is the tracking artifact. I can open a dedicated issue if you prefer. |
|
The only real red on It is unrelated to this PR. The failing query is The fix for exactly that, #111772, merged into |
`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`.
|
The only red on The head also addresses the AI review blocker about the numeric accurate cast to |
…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
… 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.
…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]>
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]>
…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.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 146/146 (100.00%) · Uncovered code |
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]>
Related: #109965
The embedded
FunctionDocumentationblock fortoDateTime32insrc/Functions/FunctionsConversion_reg.cppwas copy-pasted fromtoDateTime64: all three examples calledtoDateTime64and showedDateTime64(3)results, and the description claimed an extended range of1900-01-01to2299-12-31, which is a property ofDateTime64, notDateTime. As a result, the generatedtoDateTime32docs 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
toDateTime32and their outputs were verified against a real server. The description now correctly states thatDateTime32is an alias ofDateTimewith the supported range1970-01-01 00:00:00to2106-02-07 06:28:15. Out-of-range handling is documented precisely: string inputs and the saturating numeric types ((U)Int8through(U)Int64,BFloat16,Float32,Float64) are always clamped to the range boundaries; theTimetype and wide integer types such as(U)Int128/(U)Int256wrap around instead of saturating (and, unlike other date and time types,Timedoes not followdate_time_overflow_behavior), whileDecimalandTime64inputs throw an exception; conversions from other date and time types such asDate32orDateTime64follow thedate_time_overflow_behaviorsetting (the defaultignoremode may produce wrapped-around values). TheArgumentstype list is aligned with the corrected description. All statements were verified against a real server.During review it turned out that the saturation of
BFloat16inputs was not actually guaranteed by the implementation: unlikeFloat32andFloat64,BFloat16was missing from the saturating conversion branch for theDateTimeandTimetargets insrc/Functions/FunctionsConversion.h(while being present in the corresponding branches for theDateandDate32targets), 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 addsBFloat16to 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 withstd::min/std::max, so finite values above the range oftime_tstill hit an undefined float-to-integer cast, and non-finite values (NaN,inf) produced architecture-dependent garbage instead of an error (forBFloat16they previously threw via theisFinitecheck in the generic conversion path). The shared helpersToDateTimeTransform64SignedandToTimeTransform64Signedare now hardened for all floating-point sources (BFloat16,Float32,Float64): non-finite inputs throwCANNOT_CONVERT_TYPE, matching integer targets, and finite values are clamped to the target range in theFloat64domain (which represents everyBFloat16/Float32value and the range boundaries exactly) before the conversion totime_t. TheAccurate/OrNullconversion strategies already bounds-check before calling the transform and are unchanged. The test coversnan/inf/-infand very large finite inputs for theDateTimeandTimetargets.A further review round pointed out that the sibling
toDatefloat path (ToDateTransformFromSecondsOrDays) had the same defect: no non-finite check and atime_tcast before clamping. It is now hardened with the same contract: non-finite inputs throwCANNOT_CONVERT_TYPE, and huge finite values are clamped in theFloat64domain before the cast, saturating to the upperDateboundary (2106-02-07).toDate32already clamped in the float domain and handledNaN, so it is unchanged. The test covers thetoDatecases as well.Another review round found the same cast-before-clamp defect on the unsigned side: the
UInt64helpers (ToDateTimeTransform64,ToTimeTransform64, and theUInt64path ofToDateTransformFromSecondsOrDays) converted the value withtime_t(from)before clamping, soUInt64values aboveInt64::max()wrapped to a negativetime_tand escaped the clamp entirely:toDateTime32(toUInt64(9223372036854775808), 'UTC')returned1970-01-01 00:00:00instead of saturating. These helpers now compare in the unsigned domain before any conversion totime_t, following the pattern already used byToDateTime64TransformUnsigned, making the documented(U)Int64saturation an actual contract. Wide integer types ((U)Int128/(U)Int256) keep their documented wrap-around behavior for theDateTimetarget, where they are converted by the generic numeric conversion path rather than by these transforms. The test coversUInt64values just aboveInt64::max()and atUInt64::max()for theDateTime,Time, andDatetargets.A further review round found two more defects of the same class around the
Timetarget. First, the accurate cast of a number toTimevalidated the value against the unsignedDateTimewindow[0, 0xFFFFFFFF]inTransformer, which is wrong in both directions forTime:accurateCast(-1, 'Time')was rejected even thoughTimeis a signed type that preserves negative numeric inputs, whileaccurateCast(4000000, 'Time')passed the check and was then silently saturated to999:59:59.Timenow has its own accurate bounds (-999:59:59to999:59:59), and the exception names the target type instead of its underlyingInt32. Second, that check only runs for the source types dispatched throughDateTimeTransformImpl, andUInt8/UInt16/UInt32(the type of the literal4000000) as well as the wide integer types had no numeric-to-Timebranch at all: they were converted by a plainstatic_cast, so an out-of-range value was stored unclamped and clamped only when printed, unlike the same value with anInt64orFloat64source. All numeric sources now go through the saturatingToTimeTransform64/ToTimeTransform64Signedhelpers, which compare against the boundaries in the domain of the source type, so a wide integer is no longer truncated by a cast totime_tfirst. The embedded documentation oftoTimestates the saturation and non-finite contract, and04092_date_plus_time(which asserted the previous, source-type-dependent behavior oftoTime(9999999)) now asserts the uniform saturation.The
toDate32transform got the same treatment: itsthrowbranches formatted the offending value asstatic_cast<Int64>(from), which is undefined behavior for aNaNor for a float outside of the range ofInt64(a latent fix - numeric-to-Date32is instantiated withdefault_date_time_overflow_behavior, so this branch is not reachable for numeric sources), and its saturating path had the sameUInt64wrap-around hole astoDate:toDate32(toUInt64(9223372036854775808))returned0000-01-01instead of saturating to2299-12-31.A final review round pointed out that the same cast-before-clamp hole remained for the wide integer sources of
toDateandtoDate32: unlike theDateTimetarget,ConvertImpldoes routeInt128,UInt128,Int256andUInt256throughToDateTransformFromSecondsOrDaysandToDate32TransformFromSecondsOrDays, and onlyUInt64was compared against the boundary before the conversion totime_t, so a wide integer aboveInt64::max()wrapped to a negativetime_tand 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)Int128and(U)Int256for bothtoDateandtoDate32.A further review round found the last hole of this family on the accurate-cast side:
FunctionCast::createWrapperpasses theDateTimeAccurate*ConvertStrategyAdditionsfor every numeric to date-or-time conversion, but the precheck inTransformer::vectoronly ran forDate,DateTimeandTime, soDate32fell through to the plain saturating transform:accurateCastOrNull(toUInt64(18446744073709551615), 'Date32')returned2299-12-31instead ofNULL, andaccurateCastsilently clamped instead of throwing.Date32now 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 ordinarytoDate32keeps saturating. TheOrDefaultflavours are built on the accurate cast, sotoDate32OrDefaultandaccurateCastOrDefault(..., 'Date32')of an out-of-range value now yield the default ofDate32, which is1900-01-01, instead of the saturated2299-12-31; the expected output of03212_variant_dynamic_cast_or_defaultis 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:01andaccurateCastOrNull(toFloat64(1704067200.5), 'Date32')returned2024-01-01instead ofNULL, violating theaccurateCastcontract (a non-integral1.5is rejected byaccurateCast(1.5, 'Int32')). The pre-existingDate/DateTimeaccurate branch had the same hole, e.g.accurateCast(toFloat64(1.5), 'DateTime')truncated to1970-01-01 00:00:01. A floating-point source must now also be integral (value == trunc(value)) to pass the accurate cast toDate,Date32,DateTimeorTime; the ordinary (saturating/truncating) conversions are unchanged.Changelog category (leave one):
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 ofUInt64values aboveInt64::max()toDateTimeandTimenow 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-Dateconversion path oftoDateand to the conversions ofUInt64and of wide integers ((U)Int128,(U)Int256) toDateandDate32, which could return a pre-epoch day instead of saturating. Conversion of a number toTimenow 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 toTimeno longer rejects the negative values thatTimesupports, nor silently saturates the values that do not fit into it. The accurate cast of a number toDate32(accurateCast,accurateCastOrNull) no longer silently saturates an out-of-range or non-finite value, but throws or returnsNULLas it already did forDateandDateTime, and theOrDefaultflavours return the default value ofDate32for such an input. The accurate cast of a non-integral floating-point number toDate,Date32,DateTimeorTimeis now rejected instead of being silently truncated. Also fixed thetoDateTime32function documentation, which mistakenly showedtoDateTime64examples and described theDateTime64value range.Documentation entry for user-facing changes
Version info
26.8.1.637(included in26.8and later)