Skip to content

Saturate a 128- or 256-bit integer converted to DateTime, DateTime64, Time64 - #118717

Merged
alexey-milovidov merged 4 commits into
masterfrom
big-integer-to-datetime-overflow-117682
Sep 13, 2026
Merged

alexey-milovidov merged 4 commits into
masterfrom
big-integer-to-datetime-overflow-117682

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 8, 2026 •

Copy link
Copy Markdown
Member

Closes: #117682

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 128- and 256-bit integers to DateTime, DateTime64 and Time64 now saturate like the 64-bit ones instead of wrapping or storing an out-of-range value, which also silently dropped rows through primary-key pruning.

Description

The special-case branch lists of ConvertImpl for the DateTime, DateTime64 and Time64 targets enumerated Int8/Int16/Int32, (U)Int64 and the floats, so (U)Int128 and (U)Int256 fell through to the generic numeric path - a plain narrowing cast. The Date target already lists them.

So toDateTime(toUInt128(4294967301)) returned 1970-01-01 00:00:05 where the UInt64 value saturates to 2106-02-07 06:28:15, a negative Int128 wrapped into the far future instead of clamping to 1970, and toDateTime64/toTime64 stored raw ticks beyond the documented maximum. And because ToDateTimeMonotonicity reports a numeric source as monotonic, primary-key analysis over a UInt128 key trusted a wrapping conversion: a part whose maximum wrapped made the transformed range look empty and the whole part was discarded, so SELECT count() FROM big WHERE toDateTime(n) = toDateTime(toUInt64(1000000)) returned 0 while countIf counts 1.

The wide integers are now listed in those branches, so they use the same saturating transforms; with saturation the monotonicity the functions claim holds again.

The transforms themselves clamped by casting the value to time_t/Int64 first, which truncates a 128- or 256-bit value into the range before the clamp sees it, so they now compare in the source domain when the source is wider - the same reasoning the existing unsigned-domain comparison for UInt64 documents.


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

… Time64

The special-case branch lists of `ConvertImpl` for the `DateTime`, `DateTime64`
and `Time64` targets enumerated `Int8`/`Int16`/`Int32`, `(U)Int64` and the
floats, so `(U)Int128` and `(U)Int256` fell through to the generic numeric path
- a plain narrowing cast. The `Date` target already lists them.

So `toDateTime(toUInt128(4294967301))` returned `1970-01-01 00:00:05` where the
same `UInt64` value saturates to `2106-02-07 06:28:15`, a negative `Int128`
wrapped into the far future instead of clamping to 1970, and
`toDateTime64`/`toTime64` stored raw ticks beyond the documented maximum.

And because `ToDateTimeMonotonicity` reports a numeric source as monotonic,
primary-key analysis over a `UInt128` key trusted a wrapping conversion: a part
whose maximum wrapped made the transformed range look empty and the part was
discarded, so `SELECT count() FROM big WHERE toDateTime(n) = toDateTime(toUInt64(1000000))`
returned 0 while `countIf` counts 1.

The wide integers are listed in those branches now, so they use the same
saturating transforms; with saturation the monotonicity the functions claim
holds again.

The transforms themselves clamped by casting the value to `time_t`/`Int64`
first, which truncates a 128- or 256-bit value into the range before the clamp
sees it, so they compare in the source domain when the source is wider - the
same reasoning the existing unsigned-domain comparison for `UInt64` documents.

Closes: #117682

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5ae9033]

Summary: ✅


AI Review

Summary

The current diff adds the remaining wide-integer saturation fix for toDateTime/toDateTime32, updates the structured documentation, and adds a focused regression test for both conversion behavior and primary-key pruning. I did not find a remaining correctness issue in the code or tests after checking the full thread history and the current merge result.

PR Metadata
  • Changelog category: Bug Fix is still the right category.
  • Changelog entry: required, but the current text is now broader than the actual diff. DateTime64 and Time64 saturation are already on master; this PR now contributes the DateTime/DateTime32 part plus the regression coverage. Suggested replacement: Conversions of 128- and 256-bit integers to \DateTime` now saturate like the 64-bit ones instead of wrapping, which also restores correct primary-key pruning for `toDateTime` over wide integer keys.`
Final Verdict

✅ No blocking code issues in the current diff. Update the changelog entry so it matches the remaining DateTime-only change before merge.

LLVM Coverage Report

Measured on commit 5ae9033.

Metric Baseline Current Δ
Lines 89.00% 89.00% +0.00%
Functions 91.70% 91.80% +0.10%
Branches 81.30% 81.30% +0.00%

Changed lines: Changed C/C++ lines covered: 15/16 (93.75%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 8, 2026
Comment thread src/Functions/FunctionsConversion.h Resolved
Comment thread src/Functions/FunctionsConversion.h Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... label Sep 8, 2026
`UInt32` was not listed in the unsigned `DateTime64`/`Time64` branch, so
`toTime64(toUInt32(4000000), 0)` still stored a value above the `Time64` maximum
while the same `UInt64` value clamps. Every `UInt32` is in range for
`DateTime64`, so routing it through the same transform answers exactly what the
generic path answered there.

The structured documentation of `toDateTime32` still said that the wide integers
wrap instead of saturating; it now lists them among the supported sources.

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

Copy link
Copy Markdown
Member Author

Addressed both points: UInt32 is routed through the unsigned transform as well, so toTime64(toUInt32(4000000), 0) clamps to 999:59:59 like the UInt64 value (asserted in 05156, with a toDateTime64 control that shows the DateTime64 answer is unchanged), and the structured documentation of toDateTime32 now lists the wide integers among the supported sources instead of saying they wrap.

Comment thread src/Functions/FunctionsConversion.h Resolved
`clang-tidy` rejects an uninitialized local under
`cppcoreguidelines-init-variables`, even though both branches of the
following `if constexpr` assign it.
@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 5ae903315 with master e2ca0b04e (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

40 translation units recompiled, 273 s compile time in total, 40 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×1.06 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +17.0 s (+7%) in total before that adjustment.

Job report

…time-overflow-117682

Master landed a superseding implementation of the `DateTime64` and `Time64`
saturation (it now clamps to the maximum tick and routes the wide integer
sources through the saturating transforms), so the conflicting hunks in
`ToDateTime64TransformUnsigned`, `ToDateTime64TransformSigned`,
`ToTime64TransformUnsigned`, `ToTime64TransformSigned` and the `ConvertImpl`
dispatch are resolved in favour of master. What this branch still adds is the
`DateTime` target, which master does not cover: the big-integer clamp in
`ToDateTimeTransform64Signed` and the `(U)Int128`/`(U)Int256` dispatch entries
for `DataTypeDateTime`.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Sep 13, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 13, 2026
Merged via the queue into master with commit 607e700 Sep 13, 2026
177 checks passed
@alexey-milovidov
alexey-milovidov deleted the big-integer-to-datetime-overflow-117682 branch September 13, 2026 05:30
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 13, 2026
alexey-milovidov added a commit that referenced this pull request Sep 16, 2026
…_overflow_behavior-ignored

Master merged #118717, which saturates numeric conversions to `DateTime64` / `Time64` to the
maximum or minimum tick in every non-throwing mode and routes the wide integers through the
saturating transforms. The transforms are taken from master; this branch keeps threading
`date_time_overflow_behavior` into the numeric dispatch so that `throw` is honored, makes the
float `throw` check tick-precise, and keeps the `UInt8` / `BFloat16` message-formatter guards.
The `04402` section claiming numeric `toDateTime64` ignores the setting stays deleted.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
alexey-milovidov added a commit that referenced this pull request Sep 16, 2026
…nored

`05042` and `05156` (from #118717) pinned numeric `toDateTime64` / `toTime64` saturating under `throw`;
they now expect `VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE`. `NaN` keeps master's `DECIMAL_OVERFLOW` in every
mode in `04050`, and `04402` takes master's `toStartOfSecond` comparison for the `Date32` -> `DateTime64(9)`
boundary.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Sep 18, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 22, 2026
ConvertImpl's if-constexpr chain reaches Enum8/Enum16 as genuine FromDataTypes
(callOnTypeIndex.h maps TypeIndex::Enum8 to DataTypeEnum<Int8>), but the two
special-case branch lists for a date/time target enumerate the concrete integer
and float types and never name the Enums, and IsDataTypeNumber<DataTypeEnum<T>>
is unspecialised, so the IsDataTypeNumber-gated branches miss them too. An enum
source therefore fell through to the generic numeric path and was converted by
a plain static_cast, which is modular rather than saturating:
static_cast<UInt32>(Int8(-1)) is 4294967295.

ToDateTimeMonotonicity meanwhile accepts any source for which
isValueRepresentedByNumber() holds, true for Enum, and returns always-monotonic,
so KeyCondition::applyMonotonicFunctionsChainToRange mapped the key range
through the wrapping conversion with no guard against left > right. A range
spanning zero came out inverted: granules holding matching rows were discarded,
and MergeTreeSetIndex::checkInRange tripped its own begin > end consistency
check, which throws LOGICAL_ERROR under ifndef NDEBUG and returns {true, true}
in release. So the debug abort is the CI signature and the wrong query results
are the release-visible face of one defect.

Adding the two types to the two branch lists makes an enum equivalent to the
integer it is stored as at this seam: same FieldType, same ColumnVector, same
transform instantiation, and the same non-strict Monotonicity the struct already
returns for Int8/Int16, which is right for a saturating many-to-one map. No
monotonicity struct is touched and no new monotonicity semantics are introduced.
This is the design ClickHouse#118717 used for (U)Int128/(U)Int256 against the same defect,
and it restores the invariant ClickHouse#117394 states for numeric arguments.

Measured on 26.8.11.7 (LTS), each enum beside the integer it is stored as:

    toDateTime(Enum8('neg' = -1))       2106-02-07 06:28:15   vs 1970-01-01 00:00:00
    toDate(Enum8('neg' = -1))           2149-06-06            vs 1970-01-01
    toDateTime(Enum16('lo' = -32768))   2106-02-06 21:22:08   vs 1970-01-01 00:00:00
    toDate(Enum16('lo' = -32768))       2059-09-19            vs 1970-01-01

Over a MergeTree table keyed by Enum16('neg' = -1, 'zero' = 0) holding both
members, SELECT count() FROM t WHERE toDateTime(x) = toDateTime(0) returned 0
where the same predicate counted without the index returned 1, and the IN form
aborted a debug build in checkInRange. In-range enum values are unaffected: every
positive member is inside both result ranges.

Four other branch lists name Int8/Int16 and still omit the Enums, and are
deliberately not mirrored here because no carrier was measured behind them:
to Date32 (static_cast<Int32> of Int8/Int16 is exact over the whole enum range),
to Time (Time caps at plus or minus 3599999 seconds, so the whole enum range is
inside it), and to DateTime64 and Time64 (an enum source is rejected with
Code: 70, so the conversion is unreachable).

date_time_overflow_behavior has no effect for an enum source before or after
this change: the GENERATE_OVERFLOW_MODE_CASE switch sits inside a predicate that
is false for Enum, so ConvertImpl is always instantiated with the default Ignore.
Measured under ignore, saturate and throw, an enum agrees with Int8 in all three.
That is the pre-existing family-wide gap ClickHouse#118717's own merged test records, and
it is out of scope here.

05076_datetime_conversion_monotonicity_static_cast is deleted rather than
rebaselined: its wide-integer arms encode the pre-ClickHouse#118717 wrapping semantics, so
four of its reference values now pin behaviour master deliberately changed. The
new 05238_enum_to_datetime_overflow covers the conversion image beside the
integer, in-range controls, the CAST and wrapper forms, the overflow modes, and
the primary-key arms including the one that reproduces the assertion.

Related: ClickHouse#113515
Related: ClickHouse#116946
Related: ClickHouse#118717

Co-Authored-By: Claude Opus 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

2 participants