Skip to content

Honour date_time_overflow_behavior for numeric conversions - #117667

Merged
alexey-milovidov merged 58 commits into
masterfrom
fix-date-time-overflow-behavior-datetime64-100471
Oct 10, 2026
Merged

alexey-milovidov merged 58 commits into
masterfrom
fix-date-time-overflow-behavior-datetime64-100471

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

ConvertImpl passed the compile-time constant default_date_time_overflow_behavior (which is Ignore) instead of the forwarded template parameter in the fourteen branches that convert a number to Date, Date32, DateTime, Time, DateTime64 or Time64. The if constexpr (date_time_overflow_behavior == Throw) guards inside those transforms were therefore dead code, and an out-of-range value was silently clamped even with date_time_overflow_behavior = 'throw':

SELECT toDateTime64(99999999999999::UInt64, 3) SETTINGS date_time_overflow_behavior = 'throw';
-- 9999-12-31 23:59:59.000, instead of an error

FunctionCast::createDecimalWrapper, which handles CAST to DateTime64 and Time64, had the same hole: only the Date32 source dispatched on the setting, so every numeric CAST to those types used the default mode. accurateCastOrNull keeps the default mode there, because it reports an unrepresentable value as NULL rather than throwing.

Instantiating the previously dead throw paths surfaced two further problems, fixed here as well: the exception messages could not be formatted for BFloat16, UInt8 (which is char8_t) and the wide integers, and the boundary comparisons mixed a Float32 or an unsigned source with a time_t boundary that is not exactly representable in it - boundary checks now use the accurate comparisons. ToTime64TransformFloat also checked the DateTime64 bounds while clamping to the much narrower Time64 ones, so a value between them was clamped silently in the throw mode.

The accurate casts keep their own contract on top of that: accurateCast rejects an unrepresentable value and accurateCastOrNull reports it as NULL regardless of the overflow mode, so they must not reach the mode-specific transform, which would throw or clamp. Numeric sources and Date32 - the only date or time source that can overflow a high-precision DateTime64 - are therefore dispatched with the accurate strategy additions, which check the representable window up front.

That window is measured in ticks rather than in whole seconds, because a floating-point source can land inside the last representable second: at scale 9 the last whole second is 9223372036, yet 9223372036.5 still fits the Int64 ticks, and 999:59:59.5 is a perfectly good Time64(1) value. Saturation goes to the same extreme value of the target, so toDateTime64(1e30, 3) now yields 9999-12-31 23:59:59.999 rather than 9999-12-31 23:59:59.000. Detection of an unrepresentable value stays in the domain of the source, which for an integer or a Date32 day is a count of whole seconds.

A fraction that the target scale cannot express is still truncated rather than rejected, because DateTime64 and Time64 are Decimal carriers and accurateCast to a Decimal truncates the extra digits the same way - accurateCast(1.25::Float64, 'Decimal64(1)') is 1.2.

The setting is documented to cover conversions "when Date, Date32, DateTime, DateTime64 or integers are converted into Date, Date32, DateTime or DateTime64", so the tests that pinned the previous behaviour of numeric inputs saturating regardless of the mode, or saturating to the last whole second, are updated accordingly: 01734, 02477, 03011, 03365, 04050, 04092, 04402, 04403, 04545 and 04848.

Scope. Beyond CAST and the conversion functions, the Field materialization used by the INSERT ... VALUES expression fallback and the values table function is made mode-aware only for DateTime64 and Time64 targets (including a Date32 source that overflows a high-scale DateTime64), and numeric WITH FILL bounds only for DateTime64 sort keys (WITH FILL does not support Time64 sort keys). The Field materialization branches for Date, Date32, DateTime and Time in convertFieldToType keep their existing day-number semantics and do not consult date_time_overflow_behavior; the setting documentation in FormatFactorySettings.h states this, and aligning them is left for a follow-up.

Closes: #100471

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 to CHANGELOG.md):

Setting date_time_overflow_behavior is now honoured by CAST and the conversion functions for numeric conversions to Date, Date32, DateTime, Time, DateTime64 and Time64. For DateTime64 and Time64, the same now applies to the INSERT ... VALUES expression fallback and the values table function, and for DateTime64 sort keys to numeric WITH FILL bounds. Previously an out-of-range value was silently clamped even in the throw mode. accurateCast, accurateCastOrNull and accurateCastOrDefault no longer clamp an unrepresentable value into DateTime64 or Time64, and saturation now reaches the extreme representable tick of the target rather than the last whole second.


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

Version info

  • Merged into: 26.10.1.2031-master (included in 26.10 and later)

`ConvertImpl` passed the compile-time constant `default_date_time_overflow_behavior`
(which is `Ignore`) instead of the forwarded template parameter in the fourteen
branches that convert a number to `Date`, `Date32`, `DateTime`, `Time`, `DateTime64`
or `Time64`. The `if constexpr (date_time_overflow_behavior == Throw)` guards inside
those transforms were therefore dead code, and an out-of-range value was silently
clamped even with `date_time_overflow_behavior = 'throw'`.

`FunctionCast::createDecimalWrapper`, which handles `CAST` to `DateTime64` and
`Time64`, had the same hole: only the `Date32` source dispatched on the setting, so
every numeric `CAST` to those types used the default mode. `accurateCastOrNull` keeps
the default mode there, because it reports an unrepresentable value as NULL.

Instantiating the previously dead throw paths surfaced two further problems, fixed
here as well: the exception messages could not be formatted for `BFloat16`, `UInt8`
(which is `char8_t`) and the wide integers, and the boundary comparisons mixed a
`Float32` or an unsigned source with a `time_t` boundary that is not exactly
representable in it. Boundary checks now use the `accurate` comparisons.
`ToTime64TransformFloat` also checked the `DateTime64` bounds while clamping to the
much narrower `Time64` ones, so a value between them was clamped silently in the
`throw` mode.

The setting is documented to cover conversions "when Date, Date32, DateTime,
DateTime64 or integers are converted into Date, Date32, DateTime or DateTime64",
so tests `04092`, `04402` and `04545`, which pinned the previous behaviour of
numeric inputs saturating regardless of the mode, are updated accordingly.

Closes: #100471
@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3a56345]

Summary: ✅


AI Review

Summary

This PR closes a long list of real date_time_overflow_behavior gaps across numeric conversions, CAST, DateTime64 / Time64 Field materialization, values, and WITH FILL, but I cannot approve it yet because one new correctness gap remains on the JIT path: compiled if / multiIf still reinterpret temporal scale lifts as raw integers instead of rescaling them, so they can produce wrong DateTime64 / Time64 values under compile_expressions.

Findings

❌ Blockers

  • [src/Functions/FunctionIfBase.h:78] The new JIT cast still only rescales true Decimal types. DateTime64 / Time64 are not in WhichDataType::isDecimal(), so compiled if / multiIf arms such as DateTime -> DateTime64, Time -> Time64, or DateTime64(0) -> DateTime64(3) fall back to a plain integer cast and keep raw seconds instead of 10^scale ticks. That makes compiled results wrong even when the lift is representable; e.g. the first arm of multiIf(cond, toDateTime64('2025-01-01 00:00:01', 0), toDateTime64('2025-01-01 00:00:00.000', 3)) becomes 1735689601 ticks in a DateTime64(3) result instead of 1735689601000.
    Suggested fix: either extend nativeCastWithDecimalScale to rescale temporal arms too, or conservatively make any DateTime64 / Time64 result with a differing branch type or scale non-compilable until the native cast matches the interpreted path.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: fix or gate the compiled if / multiIf temporal scale-lift path, and add a focused compile_expressions=1 regression that mixes DateTime / Time or differing DateTime64 / Time64 scales in those functions.

LLVM Coverage Report

Measured on commit 3a56345.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 92.10% 92.20% +0.10%
Branches 79.60% 79.60% +0.00%

Changed lines: Changed C/C++ lines covered: 551/587 (93.87%) · 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 2, 2026
@yariks5s yariks5s self-assigned this Sep 2, 2026
Comment thread src/Functions/FunctionsConversion.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

⚠️ Significant changes: object file sizes.

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.

Object file sizes ⚠️

52 object files changed (+4.08 MiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Functions/FunctionsConversion.cpp.o 21.44 MiB 24.36 MiB +2.92 MiB (+13.62%)
src/CMakeFiles/dbms.dir/Functions/FunctionsConversion_impl17.cpp.o 836.39 KiB 1.09 MiB +281.22 KiB (+33.62%)
src/CMakeFiles/dbms.dir/Functions/FunctionsConversion_impl3.cpp.o 1.58 MiB 1.85 MiB +274.23 KiB (+16.97%)
src/CMakeFiles/dbms.dir/Functions/FunctionsConversion_impl19.cpp.o 559.35 KiB 738.82 KiB +179.47 KiB (+32.09%)
src/CMakeFiles/dbms.dir/Functions/FunctionsConversion_impl15.cpp.o 505.61 KiB 664.61 KiB +159.00 KiB (+31.45%)
src/CMakeFiles/dbms.dir/Functions/FunctionsConversion_impl18.cpp.o 483.48 KiB 622.19 KiB +138.71 KiB (+28.69%)
src/CMakeFiles/dbms.dir/Functions/FunctionsConversion_impl16.cpp.o 447.20 KiB 583.77 KiB +136.57 KiB (+30.54%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Symbol sizes
Binary Symbol Master PR Δ
programs/clickhouse DB::detail::FunctionCast::createWrapper<DB::DataTypeTime>(std::__1::shared_ptr<DB::IDataType const>… 8.16 KiB 91.59 KiB +83.43 KiB (+1021.91%)
programs/clickhouse-keeper DB::detail::FunctionCast::createWrapper<DB::DataTypeTime>(std::__1::shared_ptr<DB::IDataType const>… 8.16 KiB 91.59 KiB +83.43 KiB (+1021.91%)

Job report

@clickhouse-gh clickhouse-gh Bot added the comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... label Sep 4, 2026
…`DateTime64` and `Time64`

`createDecimalWrapper` routed `accurateCast`, `accurateCastOrNull` and therefore
`accurateCastOrDefault` from a number to `DateTime64` / `Time64` through the plain
conversion, so an out-of-range value was silently clamped (or, in the `throw` mode of
`date_time_overflow_behavior`, turned into an exception instead of NULL). Now the numeric
sources are dispatched with `AccurateConvertStrategyAdditions` /
`AccurateOrNullConvertStrategyAdditions`, and `Transformer` checks the representable
whole-seconds window of the result up front: `accurateCast` throws `CANNOT_CONVERT_TYPE`
regardless of the overflow mode, `accurateCastOrNull` returns NULL. The additions structs
move to `DateTimeTransforms.h` so the transformer can see them, and `ConvertImpl` reads the
target scale from them.

The test is renumbered from 05057 to 05099 to avoid a number collision with master, and it
now covers the accurate casts in every overflow mode.

Addresses the review comment #117667 (comment)
Comment thread src/Functions/DateTimeTransforms.h Resolved
Comment thread src/Functions/FunctionsConversion.h Resolved
Comment thread src/Functions/FunctionsConversion.cpp Resolved
…`Time64` in ticks

`clang-tidy` rejected the two uninitialized bound variables of the accurate pre-check in
`Transformer`; they are gone, because the check now reads its bounds from the transform.

Three review findings from `clickhouse-gh`:

1. The floating-point numeric transforms compared the source against the last representable whole
   *second*, so a value inside that second was reported as an overflow even though it is
   representable: at scale 9 the last whole second is `9223372036`, yet `9223372036.5` fits the
   `Int64` ticks, and `999:59:59.5` is a perfectly good `Time64(1)` value. The bound is now the last
   representable *tick*, in both the mode-specific transforms and the `accurateCast` pre-check, which
   reads it from the transform so the two cannot drift apart. `floatBoundNotAbove` /
   `floatBoundNotBelow` keep the rounding of the bound from crossing the real one, so the product
   always fits the `Int64` and a NaN still ends up in `convertToDecimal`, which reports it as before.

2. For consistency the integer and `Date32` transforms now saturate to the same extreme value of the
   target - the last representable tick - instead of the last representable whole second. Detection of
   an unrepresentable value stays in the domain of the source, which is a count of whole seconds (or a
   whole day), so the `throw` mode and the accurate casts are unaffected. Without this,
   `toDateTime64(-999999999999.0, 9)` and `toDateTime64(-999999999999, 9)` would saturate to two
   different values.

3. `accurateCast` / `accurateCastOrNull` / `accurateCastOrDefault` from `Date32` to a high-precision
   `DateTime64` went through the plain saturating path, so `accurateCastOrNull(toDate32('2299-12-31'),
   'DateTime64(9)')` returned the clamped boundary instead of NULL. `Date32` is the only date or time
   source that can overflow the target, and it is now dispatched with the accurate additions and
   checked against `getDateTime64DayNumRange`.

A fraction that the target scale cannot express is still truncated rather than rejected, because
`DateTime64` and `Time64` are `Decimal` carriers and `accurateCast` to a `Decimal` truncates the
extra digits the same way - `accurateCast(1.25::Float64, 'Decimal64(1)')` is `1.2`. The new test
pins that down next to the two new boundary cases.
Comment thread src/Functions/FunctionsConversion.cpp Resolved
Rescaling a `DateTime64` to a finer scale can leave the representable window of the target: the ticks are an
`Int64`, so a scale-0 value in the year 2299 has no scale-9 representation at all. That conversion took the
generic decimal path, where plain `convertDecimals` reports the overflow as `DECIMAL_OVERFLOW` - which neither
honours `date_time_overflow_behavior` nor lets `accurateCastOrNull` report the value as `NULL`.

It now follows the same rules as the other conversions to `DateTime64`: the accurate casts reject the value
(`accurateCastOrNull` returns `NULL`), the `throw` mode reports `VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE`, and the
`saturate` and `ignore` modes clamp to the extreme representable tick of the target.

Also update the documented output of `toDateTime64`: saturation now goes to the last representable tick,
`9999-12-31 23:59:59.999`, which is what the `Docs examples` job observes.

Finally, group the queries of `04848_date32_to_datetime64_scale_overflow` so that all the failing ones run in a
single `clickhouse-local`: formatting an exception message symbolizes the stack trace, which costs tens of
seconds per process in a sanitizer build and made the test exceed the 180 s limit in the flaky check.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status of the current red CI:

  • Docs examples -> real, caused by this PR: saturation now goes to the last representable tick, so the documented output of toDateTime64 is 9999-12-31 23:59:59.999. Fixed in 7dc205f (FunctionsConversion_reg.cpp; the generated pages under docs/ are regenerated by the docs autogeneration workflow).
  • Stateless tests (amd_msan, flaky check) -> 04848_date32_to_datetime64_scale_overflow exceeded the 180 s limit. Every query that is expected to fail spawned its own clickhouse-local, and formatting an exception message symbolizes the stack trace, which costs ~35 s per fresh process under MSan. The failing queries are now grouped into a single process (7 processes that throw -> 2). Fixed in 7dc205f.
  • Upgrade check (amd_release) -> unrelated: the log errors are Code: 47. DB::Exception: Unknown expression identifier \b`fromMutatePlainMergeTreeTask`, i.e. a mutation with a stale expression, with nothing to do with date/time conversions.

@groeneai, please investigate the Upgrade check (amd_release) failure (https://github.com/ClickHouse/ClickHouse/actions/runs/34108679567/job/101744695367) and provide a fix in a separate PR; if a fix is already in progress, link it here.

Comment thread src/Functions/FunctionsConversion.cpp Resolved
@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator

I confirmed the mechanism from that job's clickhouse-server.upgrade.log. The wedged part is all_1_1_1 of test_5.t_stale_part_type_5, from 04653_mutation_rewrite_stale_part_column_type.

Before the restart: DETACH PART 'all_1_1_0' replaced the part with an empty one (Detached all_1_1_0 part by replacing it with new empty all_1_1_1 part), clearEmptyParts logged Will drop empty part all_1_1_1 but never got to remove it, and MODIFY COLUMN b Nullable(String) was recorded as mutation 2. ATTACH PART then brought the data back as all_3_3_0, and RENAME COLUMN b TO d (mutation 4) took b out of the metadata.

After the restart the empty part loads Active again with mutation 2 still unapplied, and the mutation selector reaches it before clearEmptyParts does: 66 attempts on all_1_1_1_2 between 15:07:05.767 and 15:07:43.377, each failing to resolve mutation 2's b, ending at Will drop empty part all_1_1_1 at 15:07:43.434. It is bounded and self-clearing, but every attempt logs the <Error> line the check greps for.

A fix is in progress: #118499. It postpones mutating a zero-row part while remove_empty_parts is on and asks the cleanup thread for an immediate clearEmptyParts, so the part is dropped rather than mutated.

Comment thread src/Functions/FunctionsConversion.h Resolved
alexey-milovidov and others added 2 commits September 12, 2026 02:51
…-100471

# Conflicts:
#	src/Functions/DateTimeTransforms.h
#	src/Functions/FunctionsConversion.h
#	tests/queries/0_stateless/04402_datetime64_extended_range_review_fixes.sql
#	tests/queries/0_stateless/04403_totime64_saturate_clamp.sql
#	tests/queries/0_stateless/04848_date32_to_datetime64_scale_overflow.reference
…ing integer sources

Two conversions to `DateTime64` and `Time64` still bypassed the overflow-aware transforms, which the review
of the pull request pointed out:

- A `UInt32` source of a `Time64` stored its value raw, so `CAST(3600000::UInt32, 'Time64(3)')` neither threw
  in the `throw` mode nor clamped in the others. Every unsigned carrier now goes through
  `ToDateTime64TransformUnsigned` / `ToTime64TransformUnsigned`, including `UInt8` and `UInt16`, which cannot
  overflow either target and for which the transform is only a pass-through. `master` had meanwhile routed the
  wide unsigned types there with the default mode; they now carry `date_time_overflow_behavior` and the scale
  of the target like the signed ones.
- A `Decimal` source took the generic decimal conversion and reported an out-of-range value as
  `DECIMAL_OVERFLOW`, ignoring both the overflow mode and the accurate casts. `Decimal` is a count of seconds
  with a fractional part, just like a number, so it now follows the same rules: `accurateCast` rejects an
  unrepresentable value, `accurateCastOrNull` reports it as `NULL`, the `throw` mode reports
  `VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE` and the other modes clamp to the extreme representable tick. The branch
  that already did this for the rescaling of a `DateTime64` is generalized, and it now also checks the calendar
  (or clock) window of the target rather than only the `Int64` ticks: a `Decimal64(3)` of 10^12 seconds rescales
  without overflowing yet is no `DateTime64`.

Tests: `05099` gains the integer and the `Decimal` regressions. Four tests observed the behaviour that was
missing and are updated:

- `05042` asserted that a numeric source keeps saturating under `throw` "because the transforms are dispatched
  with Ignore"; that is exactly what this pull request fixes, so the case now expects the error, and the note
  about the accurate casts is narrowed to the one gap that is left (a wide integer source, which
  `createDecimalWrapper` rejects outright).
- `04092` and `03365_time_datetime_operations` constructed a `Time64` holding 1.2 billion seconds from a
  `Decimal128` - the one numeric conversion that still stored a value outside the clock window - to bring an
  intermediate overflow of `Date32 + Time64` back into range. No `Time64` is outside its window any more, so
  the cases saturate (or report the overflow in the `throw` mode).
- `04883` covers the `convertFieldToType` guard against a wrapping `Time64` rescale. Where a reader can fall
  back to a `CAST`, the value now saturates instead of surfacing `DECIMAL_OVERFLOW`; the arms assert the
  saturated value, which still tells the guarded binary from the unguarded one, and the `IN` arms that only go
  through `convertFieldToType` keep asserting `DECIMAL_OVERFLOW`.

`04848` did not actually verify its own expectation: `clickhouse-local --ignore-error` no longer prints the
exception it swallows, so `grep -c` counted zero errors and the reference was never reached. The failing
queries are fed through stdin instead, where the client checks the `serverError` hints itself and continues.

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

Copy link
Copy Markdown
Member Author

🕵 Status of the red CI at 9332081395aa, and what the new commit does.

All 41 failing stateless jobs were the same test, 04848_date32_to_datetime64_scale_overflow, and the failure was in the test, not in the conversion. Grouping its throwing queries into one clickhouse-local --ignore-error (to keep the MSan flaky check under the 180 s limit) silently stopped asserting anything: --ignore-error no longer prints the exception it swallows, so grep -c "VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE" counted 0 where the reference says 2 and 5. The reference was derived by hand in the previous pass and never run, so this was not caught locally. The failing queries now go through stdin, where the client checks the serverError hints itself and continues to the next query - one process, and an unmet hint shows up in the output.

The same commit closes the two open review threads (Decimal sources and the rest of the integer surface); details are in the replies there. Four tests on master observed the behaviour that was missing and are updated with it:

  • 05042_datetime64_saturate_to_max_tick asserted that a numeric source keeps saturating under throw "because the transforms are dispatched with Ignore" - that is what this pull request fixes, so the case expects the error now.
  • 04092_date_plus_time and 03365_time_datetime_operations built a Time64 of -1.2 billion seconds from a Decimal128 - the last numeric conversion that could store a value outside the clock window of the type - to bring an intermediate overflow of Date32 + Time64 back into range.
  • 04883_time64_convert_field_scale_overflow asserted DECIMAL_OVERFLOW where the reader can fall back to a CAST; those arms assert the saturated value instead, which still tells a guarded binary from an unguarded one, while the IN arms that only go through convertFieldToType keep asserting DECIMAL_OVERFLOW.

Verified locally on this branch: 04848 (all formats), 05099, 05042, 04092, 04883, 03365_time_datetime_operations, 04402, 04403, 03011, 01734, 01702, 02477_age_datetime64, 04050, 04545, plus a sweep of every tests/queries/0_stateless/*.sql mentioning DateTime64 or Time64 (485 tests) - no difference against the references other than the tests above and the ones that need a server, a cluster or system.query_log.

Upgrade check (amd_release) stays unrelated and is tracked by #118499 (still open), as @groeneai confirmed above.

alexey-milovidov and others added 2 commits September 12, 2026 07:29
`04408_decimal_constant_exact_serialization_dist` built its `Time64(9)` constants
from `toDecimal64('999999999.123456789', 9)`, i.e. from a value ~278000 hours past
the clock window of `Time64`. That was the loophole this pull request closes for a
`Decimal` source, so the conversion now saturates to the last representable tick and
the test printed `999:59:59.999999999`.

The constants become `3599999.123456789` seconds, which is exactly the maximum whole
second of the window (`999:59:59.123456789`), so the reference is unchanged and the
queries keep asserting that a decimal-backed constant reaches every shard with its
value and its `Time64` type intact. The comment no longer claims that a `Float64`
carrier would lose ticks: inside the clock window every scale-9 tick is exactly
representable in a `Float64`, and what a bare literal loses there is the type.

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

Copy link
Copy Markdown
Member Author

🕵 Status of the red CI at 6694f16787a7, fixed in 368d006c1e5d (on top of a fresh master merge).

The only real red was Fast test -> 04408_decimal_constant_exact_serialization_dist, and it is the same class of case as the three tests adapted in the previous commit: it built its Time64(9) constants from toDecimal64('999999999.123456789', 9), i.e. about 278000 hours past the clock window of Time64. A Decimal source was the last numeric conversion that could store such a value raw, so it now saturates and the test printed 999:59:59.999999999 instead of 999:59:59.123456789.

The constants are now 3599999.123456789 seconds - exactly the maximum whole second of the window - so the printed value, and therefore the whole reference, is unchanged, and the queries keep asserting what they were written for: a decimal-backed constant must reach every shard with its value and its Time64 type intact (a bare literal comes back as a Float64, and the differing column name makes the query fail with NOT_FOUND_COLUMN_IN_BLOCK). The comment above them no longer claims that a Float64 carrier loses ticks: inside the clock window the largest tick is 3599999999999999, well under 2^53, so every scale-9 Time64 value is exactly representable in a Float64 - what a bare literal loses there is the type, not the ticks (checked with CAST(toFloat64('3599999.123456789') AS Time64(9))).

Finish Workflow was only the cascading "no Bugfix validation job reported OK" - every validation job was DROPPED after the Fast test failure.

Verified locally against this branch's binary: 04408, 05099, 05042, 04883, 04092, 03365_time_datetime_operations, 04848 - all pass.

@clickhouse-gh clickhouse-gh Bot added comp-datetime Date/DateTime/TimeZone datatypes and date-time semantics. and removed comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... labels Sep 12, 2026
The saturating `Decimal` -> `Time64` conversion means the first `INSERT` of
`04883_time64_convert_field_scale_overflow` no longer throws, so the table has
two parts and the row order of the final `SELECT` is not deterministic. Order
the read by the value.

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

groeneai commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator

The ALTER-side fix is #123561: ALTER ... MODIFY TTL now also analyzes the new TTL in the global context, as the table loader does, and rejects a TTL the table could not be loaded with (a table function such as remoteSecure in the subquery, a view over one, a parameterized view, a temporary table).

valerypetrov pushed a commit to valerypetrov/ClickHouse that referenced this pull request Oct 2, 2026
The merge queue re-tests a PR merged with the latest base branch, so it can
reject a PR whose own CI is green, typically because of a semantic conflict
with the base branch: a newly added test that pins behaviour the PR changes,
or an API the PR uses that changed. Such a PR stays `CLEAN` and green, so
nothing in the tooling noticed it:

- `utils/continue-all-prs.sh` reported it as `GREEN` and never dispatched it.
  The pre-check now also reads the latest merge-queue event; a removal (other
  than `merged`) after the last commit, with the PR not back in the queue and
  no comment from the current user since, is a pending item that names the
  tested merge-queue commit. The triage prompt says that a clean merge alone
  does not resolve it.
- `.claude/tools/fetch_ci_report.js` with a PR URL showed only the PR workflow.
  It now detects the removal, takes the `MergeQueueCI` report link from the
  statuses of the tested commit, and adds that run's failed jobs. It also took
  the report links from the newest bot comment that had any, so a later
  `:build-profile-diff:` comment hid the whole PR workflow (only "Build profile
  diff" was shown); the `:report:` comment is now preferred, and every
  top-level report is expanded into its jobs.
- The `continue-pr` and `continue-pr-auto` skills now check for a merge-queue
  rejection first in step 4, explain how to reach its report, and merge the
  base branch for it in step 3.

Examples: ClickHouse#117667 (merge-queue
`Fast test` failed on `05315_jit_multiif_decimal_scale_lift_overflow`, added on
`master`) and ClickHouse#120910 (merge-queue
`Build (amd_binary)` failed because `master` changed the type of
`read_until_position`).

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

Copy link
Copy Markdown
Member Author

🕵 Status 2026-10-04: the only red at b1c6ff20128 was Stress test (amd_msan) (Cannot start clickhouse-server on the fuzzer clone of 05292). @groeneai, thanks: the fix #123423 is now on master, and #123561 tracks the ALTER ... MODIFY TTL gap.

Merged master (feac45ab306, clean, includes #123423). Master changes to FunctionsConversion.h, DateTimeTransforms.h and convertFieldToType.cpp do not overlap this PR. Rebuilt and ran 19 of the PR's tests on the merged binary; all pass. 05315 returned the expected clamped values; only its system.query_log check could not run, because that table does not exist under the minimal local config. 04408_..._dist needs the 127.0.0.2 shard and was not run locally. All review threads are resolved.

Comment thread src/Planner/PlannerSorting.cpp Resolved
Comment thread src/Interpreters/convertFieldToType.cpp Resolved
Comment thread src/Functions/FunctionsConversion.cpp Resolved
alexey-milovidov and others added 3 commits October 4, 2026 03:29
…sion

A `Time64` produced by interval arithmetic can lie outside the clock window
(e.g. `addSeconds(toTime64('00:00:00', 0), 4000000)`), and rescaling it to
another `Time64` only checked the `Int64` ticks. Such a value survived
`CAST(... AS Time64(3))` under `date_time_overflow_behavior = 'throw'`, and
`accurateCastOrNull` returned it instead of `NULL`. Apply the same
`minTicksForTime64` / `maxTicksForTime64` gate as for the numeric and
`Decimal` sources: the accurate casts reject the value, `throw` raises
`VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE`, and `saturate` / `ignore` clamp.

The implicit cast in `if` / `multiIf` lifting a `Time64` branch to a larger
scale now clamps too (as it already does for `DateTime64`), so `05315` pins
the clamped value instead of `DECIMAL_OVERFLOW`.

#117667

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…zation path

Returning Null for `NaN` from `dateTime64OutOfWindow` let the `VALUES`
expression fallback with `input_format_null_as_default` silently insert the
column default. Throw `DECIMAL_OVERFLOW` instead, like `CAST(nan AS
DateTime64(...))` does under every `date_time_overflow_behavior`.

#117667

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`convertDateTime64FillBound` skipped already-typed `DateTime64` bounds, so a
coarser bound such as `FROM toDateTime64('2299-12-31 00:00:00', 0, 'UTC')` on
a `DateTime64(9)` sort key never took the setting-aware conversion. Convert a
`DateTime64` bound whose type differs from the sort key as well.

Add a test for the three review follow-ups.

#117667

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Functions/FunctionIfBase.h Resolved
middas-0706 pushed a commit to middas-0706/ClickHouse that referenced this pull request Oct 8, 2026
…d with

CREATE TABLE and the table loader analyze a table TTL in the global
context. ALTER ... MODIFY TTL analyzed it only in its own query context,
where a table function, a view over one, a parameterized view and a
session temporary table resolve. Such a TTL was stored, after which the
table could not be loaded: ATTACH and every query after a restart failed
with THERE_IS_NO_QUERY (or UNKNOWN_TABLE), a server with synchronous
table loading did not start, and for ReplicatedMergeTree every replica's
ALTER_METADATA entry failed the same way.

checkAlterEligibility now also analyzes a modified table TTL exactly as
the loader does (global context, TTLValidationMode::Attach) and rejects
the ALTER with the loader's error before any metadata is written. The
analysis with the ALTER's context is unchanged and still runs first.
Replays on other replicas are not checked again, as for the other
checks of that function.

Found by the stress test on ClickHouse#117667, where the AST fuzzer replayed a
MODIFY TTL with remoteSecure in a comma join of the TTL subquery.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 10, 2026
Merged via the queue into master with commit cdab39d Oct 10, 2026
149 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-date-time-overflow-behavior-datetime64-100471 branch October 10, 2026 18:06
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 10, 2026
alexey-milovidov added a commit that referenced this pull request Oct 11, 2026
…as `CAST`

Since #117667 the analyzer converts a numeric `FROM` / `TO`
bound of a `DateTime64` sort key to the key type in `PlannerSorting`, following
`date_time_overflow_behavior`. With the default `ignore` an out-of-calendar bound is clamped to the
calendar boundary before `FillingTransform` sees it, so these cases are no longer rejected with
`INVALID_WITH_FILL_EXPRESSION`: they now fill up to the clamped bound, and with `throw` they are
rejected with `VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE`. An exclusive `TO` one step past the calendar is
clamped too, so the last tick of the calendar is no longer generated.

The descending case anchored at `toDateTime64('0000-01-01 00:00:01', ...)` relied on being rejected up
front: that string parses as a 2026 timestamp, so with the clamped `TO` it would fill about 10^12 rows.
It now starts from `toDateTime64(-62167219199, 0, 'UTC')`.

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

Copy link
Copy Markdown
Contributor

@alexey-milovidov @yariks5s — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 16, 2026
…er exactly

A constant printed into the query for another server (`ConstantNode::toASTImpl`, and the filter
pushdown in `ReadFromRemote`) is converted back there by a cast. For these three types every such
form is range-checked, so a value past the range, which arithmetic produces freely
(`toDate32('9999-12-31') + 1`, `toTime('999:59:59') + 1`), reaches the receiver as the boundary:
- `Date32` was sent as date text, which saturates at `0000-01-01` / `9999-12-31` already on the
  sender, or in the pushdown as the raw day number, which a cast reads as a Unix timestamp past
  `DATE_LUT_MAX_EXTEND_DAY_NUM` (2932897 -> day 33);
- `Time` as its second count, and `Int -> Time` saturates at 999:59:59 on 26.8+;
- `Time64` through the exact decimal carrier of ClickHouse#95055, and `Decimal -> Time64` saturates since ClickHouse#117667.
So `remote()`, `Distributed`, parallel replicas and the pushdown filtered on another value than the
initiator (local 1 row, remote 0), and `date_time_overflow_behavior = 'throw'` made the receiver throw.

Such a value is now sent as an in-range value of the same type plus an offset, because arithmetic is
the one operation that is not range-checked:
`_CAST(plus(_CAST(0, 'Date32'), 2932897), 'Date32')`, `_CAST(plus(_CAST(0, 'Time'), 3600000), 'Time')`,
and for `Time64` the sub-second part through the existing carrier plus the whole seconds:
`_CAST(plus(_CAST(_CAST('0.999', 'Decimal32(3)'), 'Time64(3)'), 3600000), 'Time64(3)')`.
`reinterpret`, used for `DateTime64` in the previous commit, does not accept these types on any
released version (`Code: 43`), so it would turn a wrong answer into an error on every older receiver.
The forms above were measured exact on 26.3.33.24, 26.8.21.12 and 26.9 receivers under `ignore`,
`throw` and `saturate`, including the Int32 extremes for Date32/Time, the Int64 extremes for Time64(0),
and Time64(9) near the Int64 tick limit.

Only values past the range change their wire text. `constantNeedsExactLiteralSerialization` sends a
constant through the exact walk when its type needs it or when it holds an out-of-range `Date32`/`Time`
value, so every in-range top-level constant keeps its text byte for byte (measured). Inside the walk an
in-range `Date32`/`Time` leaf is cast to its type, so an array mixing in-range and out-of-range values
has one element type; without the cast the receiver throws `NO_COMMON_TYPE` under
`use_variant_as_common_type = 0`. The walk also learns `LowCardinality`, which `allow_suspicious_low_cardinality_types`
allows around `Date32`/`Time` and which used to send `_CAST(2932897, 'LowCardinality(Date32)')` (day 33).

JSON typed paths are not affected: the value is already saturated when the JSON constant is built,
locally too. The test of the previous commit is renamed to a type-neutral name and extended.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov added a commit that referenced this pull request Oct 17, 2026
`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]>
shankar-iyer pushed a commit to shankar-iyer/ClickHouse that referenced this pull request Oct 23, 2026
shankar-iyer pushed a commit to shankar-iyer/ClickHouse that referenced this pull request Oct 23, 2026
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

Development

Successfully merging this pull request may close these issues.

date_time_overflow_behavior='throw' silently ignored for Int/UInt/Float -> DateTime64 and Time64 casts

5 participants