Skip to content

Round pre-epoch DateTime64 down to whole seconds in toStartOf* - #122138

Merged
alexey-milovidov merged 14 commits into
masterfrom
fix-pre-epoch-datetime64-floor
Oct 15, 2026
Merged

alexey-milovidov merged 14 commits into
masterfrom
fix-pre-epoch-datetime64-floor

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

Before the epoch, the whole seconds of a DateTime64 with a fractional part were rounded towards zero. The rounding functions therefore moved the value to the next second and could return a result later than their argument:

SELECT toStartOfMinute(toDateTime64('1969-12-31 23:58:59.500', 3, 'UTC')) SETTINGS enable_extended_results_for_datetime_functions = 1;
-- was 1969-12-31 23:59:00.000, now 1969-12-31 23:58:00.000
  • TransformDateTime64: the branch for transforms that take DecimalComponents (toStartOfMinute, toStartOfFiveMinutes, toStartOfTenMinutes, toStartOfFifteenMinutes, toStartOfHour, toStartOfDay, timeSlot, toDate, toTimeWithFixedDate) now rounds the whole part towards negative infinity, as the fall-back branch already does since 6af79a9. All of these transforms use only the whole part.
  • toStartOfInterval, and dateTrunc, which delegates to it: ToStartOfInterval<...>::execute and the arithmetic fast path (libdivide) now floor instead of truncating. With an origin, t is the offset from the origin, which is never negative, so that path is unaffected.
  • toStartOfInterval with an origin and a MONTH, QUARTER or YEAR interval (a separate, older bug of the same kind, found in review): the number of months was decided by comparing only the days of month, while the result keeps the time of day of the origin, so an argument earlier in the day than the origin was put into the bucket that starts later that day. For example, toStartOfInterval(toDateTime('2023-10-08 09:08:06'), INTERVAL 1 MONTH, toDateTime('2023-09-08 09:08:07')) returned 2023-10-08 09:08:07. Also a bucket start that addMonths clips to the end of a shorter month was not rounded to itself: toStartOfInterval(toDateTime('2023-02-28 12:00:00'), INTERVAL 1 MONTH, toDateTime('2023-01-31 12:00:00')) returned 2023-01-31 12:00:00. The number of months is now the calendar month difference, and the function steps back one interval while the exact bucket start is after the argument. The origin is also rounded down, so a fractional origin before the epoch does not move to the next day. The bucket start is computed with addMonths on the origin itself, so it keeps the time of day of the origin also when the UTC offset changes on its day after midnight (found in review).

Values at or after the epoch, and values without a fractional part, are unchanged. The reference of 03800_extended_to_start_of_interval had the wrong value 01:46:41 for toStartOfInterval(toDateTime64('1967-06-20 01:46:40.024', 3), INTERVAL 1 SECOND). It now agrees with toStartOfSecond (01:46:40), which is what the test asserts.

Closes: #119967
Related: #122129

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 toStartOfMinute, toStartOfHour, toStartOfDay, toStartOfFiveMinutes, toStartOfTenMinutes, toStartOfFifteenMinutes, timeSlot, toTimeWithFixedDate, toStartOfInterval and dateTrunc returning a value one second later, possibly in the next interval, for a DateTime64 before 1970 with a fractional part. For example, toStartOfMinute(toDateTime64('1969-12-31 23:58:59.500', 3)) returned 23:59:00. Also fixed toStartOfInterval with an origin and a MONTH, QUARTER or YEAR interval returning a value after its argument when the argument was earlier in the day than the origin, and rounding a bucket start clipped to the end of a shorter month to the previous bucket.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

🤖 Generated with Claude Code


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

Version info

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

Before the epoch, the whole seconds of a `DateTime64` with a fractional part were rounded towards zero, so
the rounding functions moved the value to the next second and could return a result later than the argument:
`toStartOfMinute(toDateTime64('1969-12-31 23:58:59.500', 3, 'UTC'))` returned `23:59:00`.

- `TransformDateTime64`: the branch for transforms taking `DecimalComponents` (`toStartOfMinute`,
  `toStartOfFiveMinutes`, `toStartOfTenMinutes`, `toStartOfFifteenMinutes`, `toStartOfHour`, `toStartOfDay`,
  `timeSlot`, `toDate`, `toTimeWithFixedDate`) now rounds the whole part towards negative infinity, as the
  fall-back branch already did.
- `toStartOfInterval` (and `dateTrunc`, which delegates to it): `ToStartOfInterval<...>::execute` and the
  arithmetic fast path floor instead of truncating.

Closes: #119967

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

clickhouse-gh Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2a609e3]

Summary: ✅


AI Review

Summary

The PR floors fractional pre-epoch DateTime64 values consistently and corrects origin-based calendar interval boundaries. One new DST regression remains: month-based intervals can move their first bucket before the exact origin.

Findings

❌ Blockers

  • src/Functions/DateTimeTransforms.h:1302: A zero-month candidate must preserve the origin, but DateLUTImpl::addMonths normalizes the second occurrence of a repeated DST hour to the first. On the PR's CI binary, an origin at 2021-10-31 01:30:00 UTC in Europe/Amsterdam rounds to 2021-10-31 00:30:00 UTC, one hour before itself. This affects MONTH, QUARTER, and YEAR, with both DateTime and fractional DateTime64, throughout the first bucket and when the step-back loop reaches zero months. Return an exact zero offset for zero-month candidates in both paths.
WITH toTimeZone(toDateTime('2021-10-31 01:30:00', 'UTC'), 'Europe/Amsterdam') AS origin
SELECT
    toTimeZone(origin, 'UTC'),
    toTimeZone(toStartOfInterval(origin, INTERVAL 1 MONTH, origin, 'Europe/Amsterdam'), 'UTC');
-- Actual:   2021-10-31 01:30:00    2021-10-31 00:30:00
-- Expected: 2021-10-31 01:30:00    2021-10-31 01:30:00
Tests
  • ⚠️ Add focused coverage asserting that an origin in the second occurrence of a DST hour rounds to its exact timestamp, including a value that makes the calendar candidate step back to zero months. Compare timestamps or UTC renderings: local strings alone hide the one-hour error.
Final Verdict

❌ Block. Preserve zero-month candidates exactly and cover the repeated-hour origin regression before merging.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 25, 2026
Comment thread src/Functions/DateTimeTransforms.h Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-datetime Date/DateTime/TimeZone datatypes and date-time semantics. label Sep 25, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 2a609e31c with master 3c89cde6c (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 3f605c455; 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

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

Symbol sizes
Binary Symbol Master PR Δ
programs/clickhouse-keeper __cxx_global_var_init.874 174.90 KiB removed -174.90 KiB (-100.00%)
programs/clickhouse __cxx_global_var_init.874 174.90 KiB removed -174.90 KiB (-100.00%)
programs/clickhouse-keeper DB::swapFuncs() new 112.88 KiB +112.88 KiB
programs/clickhouse DB::swapFuncs() new 112.88 KiB +112.88 KiB

Job report

… after its argument

With an origin and a `MONTH`, `QUARTER` or `YEAR` interval, the number of months to add was decided by
comparing only the days of month of the argument and the origin, while the result keeps the time of
day of the origin. An argument on the same day of month as a bucket start, but earlier in the day than
the origin, was therefore assigned the bucket that starts later that day, for example
`toStartOfInterval(toDateTime('2023-10-08 09:08:06'), INTERVAL 1 MONTH, toDateTime('2023-09-08 09:08:07'))`
returned `2023-10-08 09:08:07`. This also applies to `DateTime` and to whole seconds, not only to a
fractional origin. Step back by one interval when the bucket start is after the argument.

Addresses the AI review of #122138

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Comment thread src/Functions/DateTimeTransforms.h Resolved
`offset * scale_multiplier > t` could overflow `Int64` for a `DateTime64(9)`
near the top of its range. Since `offset` is a whole number of seconds and
`t` is non-negative on the origin overload, `offset > scaled_time` is
equivalent and cannot overflow.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Comment thread src/Functions/DateTimeTransforms.h Resolved
alexey-milovidov and others added 4 commits October 3, 2026 07:05
…check its start exactly

`toStartOfInterval` with an origin and a `MONTH`, `QUARTER` or `YEAR` interval
estimated the bucket by comparing days of month, which is wrong when `addMonths`
clips the bucket start to the end of a shorter month: a bucket boundary such as
`2023-02-28 12:00:00` for the origin `2023-01-31 12:00:00` was rounded to the
previous bucket. Also the origin was rounded towards zero, so a fractional
origin before the epoch could move to the next day and the buckets did not
match the origin.

Now the origin is rounded down, the candidate is the calendar month difference
(rounded down to a multiple of the interval), and the candidate is stepped back
while its exact start is after the argument.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…TH` interval and an origin

Do not pass a value before the origin, which is an error, and add the reference.

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

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122138&sha=latest&name_0=PR&name_1=Stateless%20tests%20(arm_binary%2C%20s3%20storage%2C%20DBReplicated%2C%20parallel%2C%201%2F2) and provide a fix in a separate PR. If the fix is already in progress, link it here.

05237_with_expression_alias_scope_descendant fails in Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) across many unrelated PRs (about 200 failures between 2026-10-02 and 2026-10-04 in CIDB); this PR only touches toStartOf* for DateTime64.

@groeneai

groeneai commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator

The fix is in progress: #123790 (it includes the change from my #123774, closed in its favor). In its own run on 2a290a03b667, 05237_with_expression_alias_scope_descendant passes in the arm_binary DBReplicated job.

The failure here is on the old head bde218e590c7 and has the same diff as on the other PRs: under DatabaseReplicated, the DDL path qualified nested, an alias declared inside the WITH expression, with the database, so the view read the table nested (10) instead of the alias (100). It is deterministic in that job; the 64 reruns pass because the diagnostics rerun runs without --replicated-database (my open #112247 fixes that).

The new head 6feee804cd21 will not run this job: it includes #123789, which reverted the arm_binary DBReplicated jobs. #123790 brings them back together with the fix.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122138&sha=6feee804cd21530f0bb866792382f96f30fb69af&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

05054_adaptive_aggregator_baseline_spill_residue printed parts stay far below the block count 0 instead of 1; 46 reruns with the same settings passed, and CIDB shows other failures in unrelated PRs (2026-10-01, 2026-10-05). This PR only touches toStartOf* for DateTime64.

Thanks for the update on #123790. I merged the latest master (a clean merge with no overlap with the PR files), rebuilt, and checked the PR's tests locally.

@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator

Acknowledged. No fix for 05054_adaptive_aggregator_baseline_spill_residue is in progress yet, so I am investigating it now; I will follow up here with the fixing PR (or my findings) shortly.

@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator

The fix is in #124148. The scenario 1 part-count line measures scheduling: a frozen thread that gets no CPU through the rest of the stream keeps query memory over the threshold, so the fixed engine can write a part per block (I reproduced the CI line under the thread fuzzer). It also passes without the residue release (53-58 parts against the bound of 60), so I removed it. The release stays covered by residue released and released with live states.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122138&sha=21f859aa058297b44e5cd9424dc90c3413d39138&name_0=PR&name_1=Fast%20test%20%28arm_darwin%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

03312_squashing_with_low_card_mem_usage failed in Fast test (arm_darwin) with Cannot reserve 317.82 MiB, not enough space. (NOT_ENOUGH_SPACE): the runner ran out of disk space during a 5-million-row insert. This PR only touches toStartOf* for DateTime64.

Thanks for #124148. I merged the latest master again (a clean merge with no overlap with the PR files), rebuilt, and checked the PR tests and 03800_extended_to_start_of_interval locally.

Comment thread src/Functions/DateTimeTransforms.h Resolved
@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator

The runner disk was already full when this job started on ip-10-0-41-191: / was at 97% (3.6G free) at the start and 99% (1.6G free) at the end. The job just before it on the same host (#122129, which finished 44 s earlier) ended with 1.6G free and failed on the same test. All 7 NOT_ENOUGH_SPACE failures today (5 PRs) came from 3 hosts, each starting the job at 95-97% used.

What I measured from the logs of about 290 Fast test (arm_darwin) jobs since 2026-09-28:

  • After Clean up macOS runners: disable file-change history, Time Machine and desktop agents, erase logs at boot, reboot every three days #121990, every host stayed at 41-56% used. From 2026-10-03 on, hosts one by one began keeping about 0.7 GB per job that the workspace wipe at checkout does not free.
  • It depends on the host, not the code. In the same 8 hours on 2026-10-05, ip-10-0-53-90 and ip-10-0-56-121 stayed flat at 42-46% over 33 jobs, while the other 8 hosts grew (ip-10-0-41-191 went from 82% to 93% over 15 jobs).
  • A reboot clears it. ip-10-0-56-121, ip-10-0-41-191 and ip-10-0-42-238 dropped back to 43% on the same instance id. Six hosts were at 71-97% at their latest sampled job today, so more failures like this one will follow.

The fix in progress is #113605. It runs the runner-init free-space check (fails below 2.86 GiB or 5% free) before and after every job on macOS too; on master that check does not run on macOS. On macOS a failed check makes user_data reboot the instance, so ip-10-0-41-191 would have rebooted after #122129's job instead of taking this one. The PR is waiting for review and deploy by the runner owners (@ leshikus).

I'm investigating what accumulates on the affected hosts and will follow up here with a PR or my findings.

@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator

Follow-up: I opened #124316. It does not fix the failure. It makes Fast test (arm_darwin) print the host state at the start and end of every job (uptime and boot time, swap usage, the provisioned and running runner-init versions, Capacity Consumed per APFS volume, deleted-but-open files, the largest processes), so the next job on a filling host shows what holds the space. The PR's own CI run samples one host.

One finding so far: the sampled job logs show no reboot of ip-10-0-41-191 for 7 days (above 50% used from 2026-09-28 until it was full on 2026-10-06), although #121990 gives macOS runners a 3-day lifetime. #113605 is still the fix that stops a full host from taking jobs.

…nth buckets across DST

The bucket start for `MONTH`, `QUARTER` and `YEAR` with an origin was the origin plus the
difference between the local midnights of the two days. When the UTC offset changes on the day
of the bucket start between midnight and the time of day of the origin, this lands an hour off:
with origin `2021-02-28 03:30:00` in `Europe/Amsterdam`, the March bucket started at `04:30`, and
`2021-03-28 03:45:00` was put into the February bucket. Use `addMonths` on the origin itself,
which keeps its wall-clock time of day.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
aschoube pushed a commit to aschoube/ClickHouse that referenced this pull request Oct 8, 2026
…win)

The macOS runners fill their 100G EBS boot container again (Code 243
NOT_ENOUGH_SPACE, e.g. job 112074232546 on ClickHouse#122138 started with / 97% full).
The job logs show the growth is host state outside the job workspace: the
same jobs leave almost nothing behind on some hosts and 0.6-0.75 GB per job
on others, and only a reboot (same instance id) resets a host to 43-45%. No
host went back to that level between 2026-09-28 and 2026-10-04, although
runner-init v77 (ClickHouse#121990) gives macOS runners a 3-day lifetime. GNU df on
APFS prints one container-wide number for every volume, so the existing
df -h output cannot say what grows, and the hosts cannot be inspected
directly.

Print, at job start (what earlier jobs left behind) and at job end: uptime,
boot time, memory size, swap usage, memory pressure level, the provisioned
and running runner-init versions, the swap files, Capacity Consumed per
APFS volume, deleted-but-open regular files with their holders, and the 10
largest processes by memory. At job start, when the data volume is at least
60% used, also list directories of 1 GiB or more (healthy hosts sit at
42-50%, so this only runs on a filling host).

Everything is read-only. diskutil, lsof and du run under GNU timeout (30,
60, 120 s; gnubin is first in the macOS job PATH), outside sudo so that
sudo's secure_path does not hide it; sudo -n never prompts; listings are
head-bounded. The test exit code is captured before the end call and the
teardown still always runs (no set -e).

The wrapper is in darwin_fast_test_digest_config, so a change to it runs
the job, and this commit's own CI samples one host. The fix for whatever
the output names follows separately.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
arc1999 pushed a commit to arc1999/ClickHouse that referenced this pull request Oct 9, 2026
`parts stay far below the block count` failed twice in `Stateless tests
(arm_binary, parallel)` (PRs ClickHouse#123144 and ClickHouse#122138) and cannot tell the
defect from a thread that was descheduled.

The baseline spill decision reads query-wide memory. A frozen thread that
gets no CPU while the others thaw and finish the stream keeps its frozen
table and staged records resident (20.5-25 MiB measured), so the thawed
threads spill one part per block with the residue release in place. Under
the SIGPROF half of the CI thread fuzzer (P=0.02, up to 2 s) the fixed
engine writes 61-62 parts and prints exactly the CI line.

The line is also vacuous. Without the release (master before ClickHouse#117326, or
the release block deleted) scenario 1 writes 53-58 parts, under the bound
of 60, so the line passes on the defect. It became so when the rows were
cut from 3M to 1M (499b6e7, bce9bf4) while the thaw point stayed
at 524288 staged records, about 52 blocks before the end of the stream.

The release stays covered by `residue released` and by scenario 4's
`released with live states`: both read 0 on the two defect binaries in
every run and 1 on the fixed engine in every run.

Measured with clickhouse-local (amd_binary of master a2e4282 unless
noted):
- new test: identical to the reference on the debug, ASan and amd_binary
  builds; clickhouse-test --test-runs 50 -j 50 on debug: 50/50 OK;
  thread fuzzer P=0.1/100 ms and P=0.02/2 s, 400 runs each: 0 diffs.
  The current test on the same rig: 1/800 (`parts stay far below the
  block count 0`).
- defect binaries: the new test fails 6/6 on the two counter lines; the
  current parts line passes 6/6.

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

@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.

This is great!

@alexey-milovidov alexey-milovidov self-assigned this Oct 12, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 12, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Oct 12, 2026
alexey-milovidov and others added 4 commits October 12, 2026 21:11
…h `DateTime64` down

The `fall64` case of `05339_timezone_offset_monotonicity_dst` (added in #124474) relied on
`toTimeWithFixedDate` truncating a pre-epoch `DateTime64` towards zero, which moved
`1969-10-26 05:59:59.500` UTC to the next second, after the fall-back. This PR rounds the
fractional part down, so both rows are at 01:59:59 -04:00, with and without the key
condition. The factor of `toTimeWithFixedDate` reads the same rounded whole part through
`TransformDateTime64`, so key analysis stays consistent with the function.

This failed the `Fast test` in the merge queue:
https://github.com/ClickHouse/ClickHouse/actions/runs/38282390263

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Functions/DateTimeTransforms.h Resolved
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 15, 2026
Merged via the queue into master with commit c2b45e2 Oct 15, 2026
178 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-pre-epoch-datetime64-floor branch October 15, 2026 02:21
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 15, 2026
tuanpach pushed a commit to tuanpach/ClickHouse that referenced this pull request Oct 19, 2026
…hour

`toStartOfInterval` with an origin and a `MONTH`, `QUARTER` or `YEAR`
interval computed the start of the zero-month bucket as
`addMonths(origin, 0) - origin`. `DateLUTImpl::addMonths` converts to the
wall clock and back, so it maps an instant in the second occurrence of a
repeated hour to the first one, and the origin was rounded to an hour
before itself (e.g. `Europe/Amsterdam`, 2021-10-31 01:30 UTC). The
zero-month candidate now gets an exact zero offset, both initially and
after stepping back; nonzero candidates are unchanged.

Follow-up to ClickHouse#122138, reported in
ClickHouse#122138 (comment)

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

Labels

comp-datetime Date/DateTime/TimeZone datatypes and date-time semantics. 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.

Pre-epoch DateTime64 fraction truncated toward zero: toStartOf* rounds up

3 participants