Skip to content

Fix DECIMAL_OVERFLOW in changeYear/changeXxx for nanosecond DateTime64 - #108681

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
takumihara:fix-changeyear-nanosecond-datetime64-overflow
Jul 2, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
takumihara:fix-changeyear-nanosecond-datetime64-overflow

Conversation

@takumihara

@takumihara takumihara commented Jun 27, 2026 •

Copy link
Copy Markdown
Contributor

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):

Fixed DateTime64 bugs in changeYear, changeMonth, changeDay, changeHour, changeMinute and changeSecond: nanosecond-precision (scale 9) inputs no longer throw DECIMAL_OVERFLOW, and pre-epoch sub-second inputs now return the correct calendar second.

Summary

changeYear, changeMonth, changeDay, changeHour, changeMinute and changeSecond share getChangedDate. This PR fixes two DateTime64 issues in that shared path:

  1. Overflow on every scale-9 input. getChangedDate precomputes the max_date boundary for year 2299 as a DateTime64. At scale 9 that value (2299 * 10^9 seconds) does not fit into Int64, so DecimalUtils::dateTimeFromComponents threw DECIMAL_OVERFLOW before the result was ever computed, and every scale-9 input failed. The fix builds both the boundary and the final candidate with the non-throwing tryGetDateTimeFromComponents, and on overflow clamps to the nearest representable boundary (std::numeric_limits<Int64>::max() = 2262-04-11 23:47:16.854775807, the maximum representable scale-9 DateTime64, or the minimum for negative values).

  2. Pre-epoch sub-second split. The DateTime64 input path split the stored value into whole seconds and a fraction with plain / and %, which truncate toward zero. For a pre-epoch value with a non-zero fraction the whole-seconds part was rounded toward zero instead of toward negative infinity, so the calendar fields were read off the next boundary and the resulting second was wrong (e.g. changeSecond('1969-12-31 23:59:58.500', 30) returned ...:29.500 instead of ...:30.500). The fix floor-normalizes the split (adds one degree to a negative fraction and decrements the whole seconds), so the calendar fields match the actual instant. This affects any sub-second scale, including 3 and 9.

Closes #72019

Version info

  • Merged into: 26.7.1.417 (included in 26.7 and later)

changeYear, changeMonth, changeDay, changeHour, changeMinute and changeSecond
share getChangedDate(), which precomputes the max_date boundary for year 2299
as a DateTime64. At scale 9 that value (2299 * 10^9 seconds) does not fit into
Int64, so DecimalUtils::dateTimeFromComponents threw DECIMAL_OVERFLOW before the
actual result was ever computed and every scale-9 input failed.

Use the non-throwing tryGetDateTimeFromComponents and fall back to
std::numeric_limits<Int64>::max() (2262-04-11 23:47:16.854775807, the maximum
representable scale-9 DateTime64) when the year-2299 boundary overflows. Behavior
is unchanged for scales <= 8.

Closes ClickHouse#72019
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jun 30, 2026
@alexey-milovidov alexey-milovidov self-assigned this Jun 30, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c1703cf]

Summary: ✅


AI Review

Summary

This PR now fixes two DateTime64 correctness issues in changeYear, changeMonth, changeDay, changeHour, changeMinute, and changeSecond: the scale-9 overflow path clamps to the representable boundary instead of throwing DECIMAL_OVERFLOW, and pre-epoch sub-second values are split on the correct whole second before rewriting calendar fields. I did not find any remaining correctness issues in the current diff.

PR Metadata
  • Changelog category is correct: Bug Fix.
  • Changelog entry is required for Bug Fix. The current entry is now stale relative to the final diff, because commit c1703cf5d36 also fixes pre-epoch sub-second DateTime64 behavior at scale 3/9, so the body's "Behavior is unchanged for scales <= 8" claim is no longer accurate.
  • Suggested replacement: Fixed DateTime64 bugs in changeYear, changeMonth, changeDay, changeHour, changeMinute, and changeSecond: nanosecond-precision inputs no longer throw DECIMAL_OVERFLOW, and pre-epoch sub-second inputs now preserve the correct calendar second.
Missing context / blind spots
  • ⚠️ I reviewed the current code and the added regression tests, but I did not run the changed stateless test locally because this checkout has no build directory or binary. The current Bugfix validation jobs on commit c1703cf5 flaked during server startup before 04413_changeyear_nanosecond_datetime64 ran, so a green rerun would close that validation gap.
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 30, 2026
Comment thread src/Functions/changeDate.cpp Resolved
The previous fix clamped only the precomputed `max_date` upper bound, but
the actual candidate timestamp was still built with the throwing
`DecimalUtils::dateTimeFromComponents`. For an in-range component change
whose result lands past the maximum representable scale-9 value
(`2262-04-11 23:47:16.854775807`) but at or below the `max_year` of 2299,
the early `return max_date` clamp is skipped, so the throwing construction
was reached and `changeYear(toDateTime64('2024-01-01 00:00:00.000000000', 9), 2299)`
still failed with `DECIMAL_OVERFLOW`. The same applied to `changeMonth`,
`changeDay`, `changeHour`, `changeMinute` and `changeSecond` when an
in-range component change moved a value past the boundary.

Build the final candidate with the non-throwing `tryGetDateTimeFromComponents`
and, on overflow, clamp to the nearest representable boundary (the sign of the
whole-seconds value picks `min_date`/`max_date`); the existing min/max checks
finish the clamp. Behavior is unchanged for scales <= 8 and for values that
fit.

Extends the regression test `04413_changeyear_nanosecond_datetime64` with
years 2263-2299 and representable-to-over-boundary component changes.

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

Copy link
Copy Markdown
Member

Pushed a follow-up commit (d94da7b) that completes the overflow handling flagged by the AI review.

What was still wrong: the previous change clamped only the precomputed max_date upper bound, but the actual candidate timestamp was still built with the throwing DecimalUtils::dateTimeFromComponents. When an in-range component change produces a result past the maximum representable scale-9 value (2262-04-11 23:47:16.854775807) yet still <= max_year (2299), the early return max_date is skipped, so the throwing construction was reached. As the reviewer noted, changeYear(toDateTime64('2024-01-01 00:00:00.000000000', 9), 2299) still failed with DECIMAL_OVERFLOW (verified on the current binary), and the same applied to changeMonth/changeDay/changeHour/changeMinute/changeSecond.

Fix: build the final candidate with the non-throwing tryGetDateTimeFromComponents and, on overflow, clamp to the nearest representable boundary (the sign of the whole-seconds value selects min_date/max_date); the existing min/max checks finish the clamp. Behavior is unchanged for scales <= 8 and for values that fit.

Tests: extended 04413_changeyear_nanosecond_datetime64 with the boundary years 2263–2299 and representable-to-over-boundary component changes. Built locally (Debug, clang) and ran the test — all cases now clamp cleanly with no DECIMAL_OVERFLOW:

changeYear(toDateTime64('2024-01-01 00:00:00.000000000', 9), 2299) -> 2262-04-11 23:47:16.854775807
changeYear(..., 2263)                                              -> 2262-04-11 23:47:16.854775807
changeYear(..., 2262)                                              -> 2262-01-01 00:00:00.000000000
changeMonth(toDateTime64('2262-01-01 00:00:00.000000000', 9), 12)  -> 2262-04-11 23:47:16.854775807
changeDay(toDateTime64('2262-04-01 00:00:00.000000000', 9), 30)    -> 2262-04-11 23:47:16.854775807
changeDay(toDateTime64('2262-04-01 00:00:00.000000000', 9), 10)    -> 2262-04-10 00:00:00.000000000

The only red check on the previous commit was Stress test (arm_debug) with future_error: The associated promise has been destructed ... (STID 2508-3fb1), which is an unrelated known flake (23 occurrences on master over the last 30 days).

Comment thread src/Functions/changeDate.cpp Resolved
The `DateTime64` path in `changeDate.cpp` split the stored value into whole
seconds and a fraction with plain `/` and `%`, which truncate toward zero.
For pre-epoch values with a non-zero fraction the whole-seconds part was
rounded toward zero instead of toward negative infinity, so the calendar
fields were extracted from the next calendar boundary. For example,
`changeYear(toDateTime64('1969-12-31 23:59:59.500', 3, 'UTC'), 1969)`
decomposed the input as `1970-01-01 00:00:00` minus 500 ms and returned
`1968-12-31 23:59:59.500` instead of leaving the value untouched. The same
one-boundary shift affected `changeMonth`, `changeDay`, `changeHour`,
`changeMinute` and `changeSecond` for any pre-epoch value in the last
fractional second before the relevant boundary (and `changeSecond` for any
pre-epoch sub-second value).

Round the whole-seconds part toward negative infinity and carry the borrow
into a non-negative fraction before extracting the calendar components. This
matches the additive-fraction convention used by
`DecimalUtils::dateTimeFromComponents`. Positive values and values that are
exactly on a whole second are unaffected.

Extends test `04413_changeyear_nanosecond_datetime64` with pre-epoch
sub-second regression cases at scale 3 and scale 9.

This addresses the AI review finding on
ClickHouse#108681
@alexey-milovidov

Copy link
Copy Markdown
Member

Pushed a follow-up commit (c1703cf5d36) addressing the AI review finding about the pre-epoch DateTime64 split.

What was wrong: the DateTime64 input path split the stored value into whole seconds and a fraction with plain / and %, which truncate toward zero. For a pre-epoch value with a non-zero fraction the whole-seconds part was rounded toward zero instead of toward negative infinity, so the calendar components were read off the next calendar boundary. For example, changeYear(toDateTime64('1969-12-31 23:59:59.500', 3, 'UTC'), 1969) decomposed the input as 1970-01-01 00:00:00 minus 500 ms and returned 1968-12-31 23:59:59.500 instead of leaving the value untouched. The same one-boundary shift affected changeMonth, changeDay, changeHour, changeMinute and changeSecond, and changeSecond was wrong for any pre-epoch sub-second value.

Fix: round the whole-seconds part toward negative infinity and carry the borrow into a non-negative fraction before extracting the calendar components (matching the additive-fraction convention of DecimalUtils::dateTimeFromComponents). Positive values and values exactly on a whole second are unaffected.

Verified locally on a debug build (ninja clickhouse, exit 0, no warnings): all previously wrong cases now return the expected result, the extended 04413_changeyear_nanosecond_datetime64 test passes, and the pre-existing 41 reference lines are byte-identical.

@alexey-milovidov

Copy link
Copy Markdown
Member

The two red Bugfix validation (functional tests, amd64/aarch64) jobs on c1703cf5 are a transient CI infrastructure flake, not a real failure of this change, and just need a re-run once the workflow finishes.

The bugfix-validation job downloads a prebuilt master binary (here build_amd_asan_ubsan at 51b71515) and runs only the PR's changed test files against it — the PR's own source is not compiled into that binary. On this run the downloaded server exited with code 115 during startup, before any test ran and before it could even open its log files (no clickhouse-server.err.log was created), so 04413_changeyear_nanosecond_datetime64 never executed.

Evidence that this is infrastructure, not the change:

The rest of CI is still in progress.

@clickhouse-gh

clickhouse-gh Bot commented Jul 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.50% 85.50% +0.00%
Functions 92.60% 92.70% +0.10%
Branches 77.60% 77.70% +0.10%

Changed lines: Changed C/C++ lines covered: 30/31 (96.77%) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 2, 2026
Merged via the queue into ClickHouse:master with commit bdc4547 Jul 2, 2026
345 of 348 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 2, 2026
alexey-milovidov added a commit that referenced this pull request Jul 2, 2026
The regression test `04413_changeyear_nanosecond_datetime64` came from `master`
(via #108681) through today's merge and still encoded the former
`[1900-01-01, 2299-12-31]` clamp boundaries. After this PR widens `DateTime64`
to `[0000-01-01, 9999-12-31]`, the out-of-range `changeXxx` clamp results
legitimately change:

- At scale 9 the range is limited by the `Int64` tick storage to
  `[1677-09-21 00:12:43.145224192, 2262-04-11 23:47:16.854775807]`, so an
  invalid or out-of-range component now clamps to the true scale-9 minimum
  `1677-09-21 00:12:43.145224192` instead of the former `1900-01-01`. This is
  symmetric with the scale-9 maximum `2262-04-11 23:47:16.854775807` that the
  reference already accepts.
- At scale 3 and 6 the year `2500` is now representable, so
  `changeYear(..., 2500)` returns `2500-01-01` instead of the former clamp
  `2299-12-31`.

`getChangedDate` in `changeDate.cpp` already computes these boundaries
correctly; only the reference was stale (the earlier merge assumed this test
still passed). Verified against the deterministic CI output, which failed
identically across every stateless configuration:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107907&sha=2e78058b12f04857839a021b535ec9e11d687b0b&name_0=PR

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@@ -0,0 +1,74 @@
-- Tags: no-fasttest

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Why is FastTest excluded? @takumihara

zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The `DateTime64` path in `changeDate.cpp` split the stored value into whole
seconds and a fraction with plain `/` and `%`, which truncate toward zero.
For pre-epoch values with a non-zero fraction the whole-seconds part was
rounded toward zero instead of toward negative infinity, so the calendar
fields were extracted from the next calendar boundary. For example,
`changeYear(toDateTime64('1969-12-31 23:59:59.500', 3, 'UTC'), 1969)`
decomposed the input as `1970-01-01 00:00:00` minus 500 ms and returned
`1968-12-31 23:59:59.500` instead of leaving the value untouched. The same
one-boundary shift affected `changeMonth`, `changeDay`, `changeHour`,
`changeMinute` and `changeSecond` for any pre-epoch value in the last
fractional second before the relevant boundary (and `changeSecond` for any
pre-epoch sub-second value).

Round the whole-seconds part toward negative infinity and carry the borrow
into a non-negative fraction before extracting the calendar components. This
matches the additive-fraction convention used by
`DecimalUtils::dateTimeFromComponents`. Positive values and values that are
exactly on a whole second are unaffected.

Extends test `04413_changeyear_nanosecond_datetime64` with pre-epoch
sub-second regression cases at scale 3 and scale 9.

This addresses the AI review finding on
ClickHouse#108681
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…anosecond-datetime64-overflow

Fix DECIMAL_OVERFLOW in changeYear/changeXxx for nanosecond DateTime64
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The regression test `04413_changeyear_nanosecond_datetime64` came from `master`
(via ClickHouse#108681) through today's merge and still encoded the former
`[1900-01-01, 2299-12-31]` clamp boundaries. After this PR widens `DateTime64`
to `[0000-01-01, 9999-12-31]`, the out-of-range `changeXxx` clamp results
legitimately change:

- At scale 9 the range is limited by the `Int64` tick storage to
  `[1677-09-21 00:12:43.145224192, 2262-04-11 23:47:16.854775807]`, so an
  invalid or out-of-range component now clamps to the true scale-9 minimum
  `1677-09-21 00:12:43.145224192` instead of the former `1900-01-01`. This is
  symmetric with the scale-9 maximum `2262-04-11 23:47:16.854775807` that the
  reference already accepts.
- At scale 3 and 6 the year `2500` is now representable, so
  `changeYear(..., 2500)` returns `2500-01-01` instead of the former clamp
  `2299-12-31`.

`getChangedDate` in `changeDate.cpp` already computes these boundaries
correctly; only the reference was stale (the earlier merge assumed this test
still passed). Verified against the deterministic CI output, which failed
identically across every stateless configuration:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107907&sha=2e78058b12f04857839a021b535ec9e11d687b0b&name_0=PR

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

Labels

can be tested Allows running workflows for external contributors 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.

Function changeYear is allergic to nanosecond-precision DateTime64 inputs

4 participants