Repository navigation
Make toStartOfInterval return the type of its argument - #122129
Conversation
`toStartOfInterval` chose its result type by the interval unit: `Date` for `WEEK` and longer, `DateTime`
for `DAY` down to `SECOND`. A `Date32` or `DateTime64` argument outside the range of the narrower type was
wrapped, e.g. `toStartOfInterval(toDate32('1900-01-01'), INTERVAL 1 DAY)` returned `2036-02-07 06:28:16`,
and the rounding of a `Date` to days produced a `DateTime`.
Now the result has the type of the argument: `Date` for `Date`, `Date32` for `Date32`, `DateTime` for
`DateTime`, and `DateTime64` of the same scale for `DateTime64`. The value computed by `ToStartOfInterval`
(a day number, seconds, or ticks of a subsecond unit) is converted to the representation of the result type.
For the origin overload with an argument finer than a subsecond unit, the grid anchored at the origin is
computed in the scale of the argument, so the part of the origin finer than the unit is kept.
The old behavior is available with `to_start_of_interval_preserves_argument_type = 0`.
#117396 (comment)
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
|
Workflow [PR], commit [05e0160] Summary: ✅
AI ReviewSummary
Missing context / blind spots
Final VerdictStatus: ✅ Approve |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes6 object files changed (+197.92 KiB total), 0 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units9 translation units recompiled, 30 s compile time in total, 9 of them have a recent master baseline. |
…l-preserve-type Resolve the conflict with the move of the settings changes history into the setting declarations (ee6b44f): the history records this PR added to `SettingsChangesHistory.cpp` now live as trailing arguments of the `DECLARE` of each setting. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…terval` result type `toStartOfInterval` now returns the type of its argument, and accepts a time zone argument with a `Date`, so the `year` and `month` cases with `Date` no longer throw, and `DateTime64` keeps its type. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122129&sha=713b6bf37d9f4c73a16645c73673ed75055d1032&name_0=PR PR: #122129 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…` for `Date`, reword the docs The time zone argument has no effect on a `Date` or `Date32` argument, but a wrong time zone name is now rejected instead of being silently ignored, in both the 3-argument and the 4-argument (origin) overloads. The documentation now says that `toStartOfInterval(t, INTERVAL 1 DAY)` rounds to the same boundary as `toStartOfDay(t)`, since the result types may differ. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ith `to_start_of_interval_preserves_argument_type` The legacy mode must reproduce the previous results exactly, so the extra saturation for a result of the argument type is now applied only when the setting is enabled. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 CI notes for df40de3:
|
|
The |
…_start_of_interval_preserves_argument_type` With the setting disabled, a subsecond unit of the `origin` overload already yields a result of the unit's scale, so the branch could not trigger, but make the dependency explicit and pin the legacy results of the `origin` overload (the values of `02916_to_start_of_interval_with_origin` before 26.10) in the test. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged The only red job on |
|
🕵 Merged The only red job on |
…ale `toStartOfInterval` fast path A `DateTime64(0)` argument has the same scale multiplier as the legacy `DateTime` result, so it took the equal-scale fast path, which wrapped out-of-range values instead of clamping them. Use `saturatingResultCast` there as in the other loops. Co-Authored-By: Claude Opus 5.5 <[email protected]>
yariks5s
left a comment
There was a problem hiding this comment.
This PR looks good, but I would simplify it by:
- Using signed timestamps for rounding and clamping only the final result. This fixes the epoch issue and removes the 40-day workaround and second pass
- Exposing the LUT bounds directly instead of finding them with binary searches
- Sharing one subsecond-rounding helper that accepts input/output scales and an optional origin
- Deciding the required precision in the return-type resolver, so execution never silently discards an interval boundary
We can check if it is possible
Also, the last bot's comment make sense. and I found one more issue you can see below
…ond bucket boundaries representable With `to_start_of_interval_preserves_argument_type`, a `DateTime` rounded to days or longer units used the unsigned overload of `ToStartOfInterval`, which clamps a day before the epoch to the first day after it. In a time zone with a negative offset that day starts after the timestamp zero, so the result exceeded the argument (e.g. `toStartOfInterval(toDateTime(0, 'America/New_York'), INTERVAL 1 MONTH)` returned `18000`). The clamping `DateTime` result now uses the signed overload and saturates the resulting seconds. The legacy behavior keeps the unsigned overload. A subsecond unit finer than the scale of a `DateTime64` argument (e.g. `INTERVAL 1500 MILLISECOND` for a `DateTime64(0)`) produced bucket boundaries that the argument scale could not represent, so rounding a result again moved it. The result now has the scale of the unit in that case, as in the legacy behavior. The references of the tests that pinned the narrower scale are updated. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…_preserves_argument_type`; fix a performance regression
`dateTrunc` delegates to `toStartOfInterval`, and the delegate inherited the
new setting, so its near-epoch results changed: e.g.
`dateTrunc('day', toDateTime(0, 'Asia/Tokyo'))` returned
`1970-01-01 09:00:00` instead of `1970-01-02 00:00:00`. `dateTrunc` now uses
a `toStartOfInterval` resolver in the legacy mode
(`createLegacyToStartOfIntervalOverloadResolver`), and the test checks the
near-epoch values with the setting enabled and disabled.
With the setting enabled, a `DateTime` argument rounded to a `DateTime`
went through the signed overload of `ToStartOfInterval` for every row, to
clamp the results before the epoch. Where the modular fast path does not
apply (e.g. `Asia/Kolkata` with `INTERVAL 2 SECOND` or `INTERVAL 1 HOUR`),
that made the query up to 1.9 times slower in the performance test
`to_start_of_interval`. When every value of the column is later than the
epoch by more than the length of the interval and two days, the start of
each interval is not before the epoch, and the unsigned overload gives the
same results without clamping, so it is used then.
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122129&sha=677620d65df4d4fcf0af56e6d89f80882f06ccbf&name_0=PR&name_1=Performance%20Comparison%20%28arm_release%2C%20master_head%2C%203%2F6%29
#122129
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 The performance test |
…ving the argument type The test was added on master after this branch was last updated. `kqlBin` with a calendar-length bin delegates to `toStartOfInterval`, which now returns `DateTime` for a `DateTime` argument with a month interval instead of `Date`, as intended by `to_start_of_interval_preserves_argument_type`. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122129&sha=latest&name_0=PR&name_1=Fast%20test #122129 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged |
|
🕵 CI on @yariks5s, about the four simplifications in your review summary (the inline threads are already resolved):
|
|
🕵 Merged The only red job on |
|
🕵 Merged Both red tests on
|
…e32 range they wrap With the legacy result types (to_start_of_interval_preserves_argument_type = 0, which any compatibility below 26.11 restores, and the only behaviour of every release up to 26.10; for dateTrunc, function_date_trunc_return_type_behavior = 1) a Date32 argument is rounded into Date (WEEK..YEAR) or DateTime (DAY) and stored with a plain cast, so dates before 1970 and after 2149 (2106 for DateTime) wrap. getMonotonicityForRange nevertheless returned is_monotonic and is_always_monotonic unconditionally, so: - KeyCondition mapped mark ranges through a decreasing function and pruned granules wrongly in both directions (ORDER BY d: rows dropped, DESC: kept); - matchesExactContinuousRange derived exact ranges through it, so the exact count path counted rows without the filter, and when a skip index had trimmed the selected ranges at analysis time the exact range ended past the selected one: chassert(exact_ranges[i].end <= range.end) (AST fuzzer, STID 2508-5221); - sort-order propagation treated the rounding as order preserving, so ORDER BY toStartOfInterval(d, ...) returned rows out of order; - KeyCondition pushed a condition on d through a sorting or partition key toStartOfInterval(d, ...), whose stored values wrap, and skipped matching granules and partitions. When the argument, with LowCardinality and Nullable removed, is Date32 and the result type is Date or DateTime, getMonotonicityForRange now rounds both bounds of the range with the same ToStartOfInterval<unit>::execute overload the function executes. The rounding is non-decreasing in that wide type, so the range maps without wrapping iff both rounded bounds fit the result type ([0, 65535] days for Date, [0, UInt32 max] seconds for DateTime in the result's time zone). Then only is_monotonic is claimed for the range; otherwise, and for an unbounded or non-integer bound or a non-constant interval, nothing is claimed. is_always_monotonic is never claimed for these results: the function is not monotonic on its whole domain, and the functions stress test treats is_always_monotonic on some ranges with is_monotonic false on others as broken monotonicity. is_always_monotonic_where_defined is not claimed either: a sorting or partition key toStartOfInterval(d32, ...) stores the wrapped values, so a condition on d pushed through it pruned matching rows (the reasoning of ClickHouse#125960 for toDate). Values, result types and settings do not change: saturating the Date32 values was rejected during the review of ClickHouse#110344 (see ClickHouse#116945), because the legacy setting exists to restore the old results exactly. This re-applies the monotonicity guard of the closed ClickHouse#117396 to the legacy result types that ClickHouse#122129 kept. Cost, legacy mode with a Date32 key only: a range whose rounding wraps is not pruned through the function, and the exact count and ordering optimizations are not used for these narrowing roundings, and a condition on the column is not pushed through such a key expression. Closes ClickHouse#116945 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Since ClickHouse#122129 (`to_start_of_interval_preserves_argument_type`, default on), `toStartOfInterval` returns the type of its argument, so `kqlBin` over a `DateTime64` with a calendar interval now gives `2026-08-01 00:00:00.0000000` instead of the `Date` `2026-08-01`. The unwrapped form gives the same value, so the `LowCardinality` arm stays transparent; only the expected value moves. Co-Authored-By: Claude Opus 5.5 <[email protected]>
toStartOfIntervalchose its result type by the interval unit:DateforWEEKand longer,DateTimeforDAYdown toSECOND, andDateTime64of the unit's scale for the subsecond units. An argument outside the range of the narrower type was wrapped:Now the result has the same type as the argument:
DateforDate,Date32forDate32,DateTimeforDateTime, andDateTime64of the same scale forDateTime64, regardless of the unit. The only exception is a subsecond unit finer than the scale of aDateTime64argument (e.g.INTERVAL 1500 MILLISECONDfor aDateTime64(0)): the result has the scale of the unit then, because the argument scale cannot represent the bucket boundaries. The old behavior stays available with the new settingto_start_of_interval_preserves_argument_type = 0, which is inSettingsChangesHistoryforcompatibility.Implementation notes:
ToStartOfInterval<unit>returns a day number, seconds, or ticks of a subsecond unit.convertToResultRepresentationconverts that value to the result type's representation (fromDayNum/toDayNum/ rescaling with an overflow check). The arithmetic fast path forSECOND/MINUTE/HOURmultiplies by the result scale.Date/DateTimeresult clamps instead of wrapping, e.g. rounding1970-01-01down to a week gives1970-01-01, not2149-06-04. A clampingDateTimeresult is computed through the signed day number, so a boundary before the epoch in a time zone with a negative offset clamps to the timestamp zero instead of the local midnight after it.toStartOfInterval(toDateTime64('... 12.987654321', 9), INTERVAL 1 MILLISECOND, toDateTime64('... 12.123456789', 9))now returns12.987456789, not12.987. Before the epoch the old result could even be earlier than the origin.Dateargument is accepted and has no effect, as forDate32(but an invalid time zone name is still rejected), sotoStartOfInterval(date, INTERVAL 1 DAY, 'tz')keeps working. Its result is now aDate.dateTruncdelegates totoStartOfIntervalbut passes its own result type, so it is unchanged.toStartOfIntervalover aDate32key: missing rows and phantomcount()for out-of-range values #116945, since the function no longer wraps. With the legacy setting the wrap is still there.Existing tests that are about the legacy types (narrowing overflow,
enable_extended_results_for_datetime_functions, clamping in the fast path, and the time-zone test that usestoString(..., tz)on the result) now pin the setting to0. The other affected references changed only in type or scale, except for the origin-overload fix above.Note on upgrades: a table whose partition or sorting key uses
toStartOfIntervalwith a unit that changes the result type gets a different key type on the new version, e.g.PARTITION BY toStartOfInterval(ts, INTERVAL 1 MONTH)on aDateTimecolumn (wasDate, nowDateTime), or on aDateTime64column. Such tables needto_start_of_interval_preserves_argument_type = 0in the server's default profile.function_date_trunc_return_type_behaviorhas the same property fordateTrunc.Requested in #117396 (comment)
Related: #117396
Related: #116945
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
The function
toStartOfInterval(and its aliasestime_bucketanddate_bin) now returns a value of the same type as its argument (Date,Date32,DateTime, orDateTime64with the same scale) instead of a type determined by the interval unit, which wrapped values outside the range ofDateandDateTime. For example,toStartOfInterval(toDate32('1900-01-01'), INTERVAL 1 DAY)returned2036-02-07 06:28:16and now returns1900-01-01. Setto_start_of_interval_preserves_argument_type = 0to restore the previous behavior, in particular for tables whose partition or sorting key usestoStartOfIntervalwith a unit that changes the result type.Documentation entry for user-facing changes
🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/122129]
Version info
26.11.1.910-master(included in26.11and later)