Repository navigation
Fix signed integer overflow in the origin overload of toStartOfInterval - #112045
Conversation
…rigin` of `toStartOfInterval` The three-argument overload of `toStartOfInterval` computed the result as `origin + offset` without an overflow check. For an origin near the lower bound of `Int64` in a time zone east of UTC the offset is negative - the interval boundary in local time lies before the origin - so the addition wrapped around and produced a bogus value instead of an error. The UBSan build reported it as `signed integer overflow: -9223372036854775807 + -7200000000000 cannot be represented in type 'Int64'` at `src/Functions/toStartOfInterval.cpp:293`, found by the AST fuzzer in the `Stress test (arm_asan_ubsan)` job. Use `common::addOverflow` and throw `DECIMAL_OVERFLOW`, matching the check already applied to the `time_arg - origin` subtraction a few lines above. Verified with an A/B build: before the fix `toStartOfInterval(reinterpret(toInt64(-9223372036854775807), 'DateTime64(9, \'Asia/Istanbul\')'), toIntervalHour(3), <same origin>)` returns the wrapped `2262-04-12 00:47:16.854775809`; after the fix it throws `DECIMAL_OVERFLOW`. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108977&sha=7dbcb13520f1a4671a9453f2fdd71a51e4f3a45f&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%29 Related: #108977
|
Workflow [PR], commit [ba1874d] Summary: ✅
AI ReviewSummaryThis PR fixes the signed-overflow UB in the Findings
Final VerdictStatus:
|
|
This closes the UBSan report, and I agree with the guard. Before it lands I want to flag one Your guard becomes unreachable if the offset is made non-negative. The offset is negative only
I also swept the calendar units, which such a change does not touch: 1920 probes over 8 time The part I would like your opinion on is separate from time zones. Your description reads the Master's boundaries sit at origin + 0, 5, 10, 15, 20, 24, 29, ... hours, so the grid resets at SELECT toStartOfInterval(toDateTime('2023-01-02 04:30:00', 'UTC'), toIntervalHour(5),
toDateTime('2023-01-01 00:00:00', 'UTC'));
-- 2023-01-02 00:00:00; the boundary 25 h after the origin would be 2023-01-02 01:00:00That is What makes me think the whole-second units are the odd ones out rather than this being a matter of
One consequence for SELECT toStartOfInterval(toDateTime64('2026-07-27 13:45:12.345', 3, 'Asia/Istanbul'),
toIntervalDay(2), toDateTime64('2026-07-01 00:00:00.000', 3, 'Asia/Istanbul'));has reference So: is the For the record, the same overflow is also on the finish ledger of #108977 and #110955; I will link Measurements are from |
…al-origin-offset-overflow
|
|
||
| result_data[i] = static_cast<ResultDataType::FieldType>(origin + offset); | ||
| Int64 result = 0; | ||
| if (common::addOverflow(origin, offset, result)) |
There was a problem hiding this comment.
This turns valid origin-anchored inputs into DECIMAL_OVERFLOW. The docs for the second overload say it emulates time_bucket() / date_bin(), so toStartOfInterval(origin, INTERVAL 3 HOUR, origin) must floor back to origin itself. On this path time_diff is 0, but SECOND / HOUR / DAY still ignore the supplied origin and round time_diff against the timezone's epoch/midnight rules, which produces a bogus negative offset for zones east of UTC (-7200 for the Istanbul HOUR case, -19800 for the Kolkata DAY case). addOverflow then converts that wrong offset into an exception, and the new 04648 expectations on lines 8-10 and 17 lock the broken semantics in.
Please fix those unit implementations to round on the lattice anchored at origin (as the subsecond and calendar-unit paths already do), and flip the regression to assert toStartOfInterval(origin, step, origin) = origin plus an on-grid ordinary DAY / HOUR / half-hour-zone SECOND case.
There was a problem hiding this comment.
The guard does not turn any previously-correct input into an error: it is only reachable when
origin + offset leaves Int64, i.e. when the origin is within one rounding offset of the type's
bounds (the three cases in 04648 all use Int64 min or min + 1). For every ordinary origin the
addition is unchanged, and for the inputs that now throw the old code did not return origin either
— it wrapped around, which is the signed-overflow UB that UBSan reported
(-9223372036854775807 + -7200000000000). Replacing wraparound with DECIMAL_OVERFLOW is strictly
an improvement, and toStartOfInterval(origin, step, origin) = origin does not hold on this path
before the change either.
The substantive point — that the SECOND / HOUR / DAY units of this overload round on the grid
anchored at the local midnight (via toStartOfHourInterval / toStartOfDayInterval) rather than on
the grid anchored at origin, unlike the subsecond and MINUTE units of the same overload — is
real, pre-existing, and independent of this fix; @groeneai measured it in detail in the PR comment
above and has a branch for it. Making those buckets strictly periodic from the origin changes the
result of a widely used function, so it is a separate change and a maintainer decision, not
something to fold into an overflow guard.
I have annotated the "Ordinary values must be unaffected" group in 04648 to say explicitly that it
pins today's midnight-anchored rounding and that the DAY reference value changes if the buckets are
ever made periodic, so the test is not read as blessing the current semantics.
There was a problem hiding this comment.
Agreed on the separation. The guard and the anchoring are independent, and the anchoring change does not belong in this PR.
Your annotation on the "Ordinary values must be unaffected" group is precisely right, and I checked it against the branch rather than assuming. Of the four queries in that group, only the second one moves:
| query | master | origin-anchored |
|---|---|---|
toIntervalHour(3), UTC |
2026-07-27 12:00:00.000 |
unchanged |
toIntervalDay(2), Istanbul |
2026-07-26 22:00:00.000 |
2026-07-27 00:00:00.000 |
toIntervalMonth(1), Istanbul |
2026-07-15 00:00:00 |
unchanged |
toIntervalWeek(2) |
2026-07-20 |
unchanged |
One refinement to the condition as you worded it: the divergence is not only about the time zone offset. In UTC the whole-second units go off grid whenever the interval count does not tile the day, that is when it does not divide 24. Sweeping 768 probes (4 zones x {SECOND, MINUTE, HOUR, DAY} x 12 interval counts x 4 durations), 288 differ: MINUTE 0, SECOND 7, HOUR 137, DAY 144. UTC HOUR differs for counts 5, 7, 10 and 11 and never for 1, 2, 3, 4, 6, 8, 12 or 24, and in UTC it also needs the value to cross a midnight, while the offset zones diverge inside a single day as well.
On how widely the results would actually move, which I take to be the real cost of the change: I ran every test in the tree that uses the three-argument overload through both binaries, 11 files including 02916_to_start_of_interval_with_origin (59 output lines, 10 HOUR and 5 DAY origin cases), 00189_time_zones_long (313 lines) and 04500_toStartOfInterval_origin_subscale. No reference value changes. The only diff I saw was in 04621, and that is my branch being behind your d4e0352, not the fix: my merge base predates that commit and my diff does not touch the subsecond path. The reason 02916 is unaffected is that master is already origin-anchored for the cases it pins, for instance toStartOfInterval(toDateTime('2023-10-09 10:11:12'), toIntervalHour(1), toDateTime('2023-10-09 09:10:07')) gives 2023-10-09 10:10:07 either way. So the observable change is confined to intervals that do not tile the day from midnight, and today none of them is pinned anywhere.
You are also right that toStartOfInterval(origin, step, origin) = origin does not hold on this path today. I read that as the clearest statement of the defect: it returns 0 for toIntervalHour(3) in Istanbul and for toIntervalDay(2) in Kolkata on master, and 1 on the branch. And as noted above, once the offset is origin-anchored it is a non-negative multiple of the step on the whole-second path, so addOverflow there has no reachable input left; that is a consequence for this PR's guard, not an objection to it.
That leaves the decision you flagged as a maintainer call, which is the one thing I cannot make myself. Would you like the origin-anchored change pursued as its own PR? The branch, a 27-value test and both-direction verification already exist, and I would rebase it and write the description around the semantic change. If instead the midnight-anchored grid is the intended behaviour, then the right deliverable is documentation saying that the whole-second units of this overload are not periodic from origin, alongside your 04648 annotation, and I will drop the branch. Either answer works for me; I would just rather not land a semantic change to this function without you choosing it.
The message mixed scales: `time_arg` was already multiplied by `SECONDS_PER_DAY` for date results while `origin` had been divided back, so the two printed numbers were in different units. Print the two values that are actually added instead. Also state in `04648_toStartOfInterval_origin_result_overflow` that the `SECOND`, `HOUR` and `DAY` units of this overload round on the grid anchored at the local midnight rather than at the origin, so the test is not read as asserting that the current bucketing is the intended one.
…al-origin-offset-overflow
|
@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112045&sha=6c7ac2f6fa2f42fad0b432647d063876394a67c5&name_0=PR&name_1=Integration%20tests%20%28amd_tsan%2C%204%2F6%29 and provide a fix in a separate PR. If the fix is already in progress, link it here. The failed test is |
|
Confirmed, not caused by this change. Keying CIDB on the No fix is in progress. I file-listed every open PR of mine that touches the files on this path and none of them touches Root cause: That hazard is already handled one level up. The fix will keep the eager removal on a healthy session so the |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 8/8 (100.00%) · Uncovered code |
|
Filed as #112829.
Two new failpoints make it deterministic, and the seven new integration tests cover both halves of the error classifier plus |
Related: #108977
Closes: #112184
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a signed integer overflow in the three-argument overload of
toStartOfInterval: for anoriginargument near the lower bound ofInt64the function returned a wrapped-around value instead of reporting an error.Description
The three-argument overload of
toStartOfIntervalcomputed the result asorigin + offsetwithout an overflow check. For an origin near the lower bound ofInt64in a time zone east of UTC the rounding offset is negative — the interval boundary in local time lies before the origin — so the addition wrapped around and produced a bogus value instead of an error.The UBSan build reported it as:
found by the AST fuzzer in the
Stress test (arm_asan_ubsan)job of an unrelated pull request. The fix usescommon::addOverflowand throwsDECIMAL_OVERFLOW, matching the check already applied to thetime_arg - originsubtraction a few lines above.Verified with an A/B build:
2262-04-12 00:47:16.854775809;DECIMAL_OVERFLOW.New stateless test
04648_toStartOfInterval_origin_result_overflowcovers the overflowing cases (HourandDayintervals in several time zones), the non-overflowing UTC case at the same origin, and ordinary values. Checked under bothenable_analyzer=1andenable_analyzer=0.CI report where the failure was observed: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108977&sha=7dbcb13520f1a4671a9453f2fdd71a51e4f3a45f&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%29
The same overflow also fired on plain
master, in theStress test (arm_asan_ubsan, s3)job, this time with aDayinterval, where the offset is the whole time-zone offset:CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=1d4408f794c389928bda6b52615aa612c12b938b&name_0=MasterCI&name_1=Stress%20test%20%28arm_asan_ubsan%2C%20s3%29