Skip to content

Arithmetic fast path for addDays/addWeeks in fixed-offset time zones - #109836

Merged
yariks5s merged 19 commits into
ClickHouse:masterfrom
raimannma:adddays-fixed-offset-fast-path
Jul 21, 2026
Merged

yariks5s merged 19 commits into
ClickHouse:masterfrom
raimannma:adddays-fixed-offset-fast-path

Conversation

@raimannma

Copy link
Copy Markdown
Contributor

Adds an arithmetic fast path for addDays/addWeeks (and thus subtractDays/subtractWeeks) on DateTime/DateTime64 in fixed-offset time zones (UTC and other zones whose UTC offset never changes within the LUT range). In such zones every calendar day is exactly 86400 seconds, so day/week addition reduces to arithmetic on the unix timestamp and skips the calendar lookup table. Time zones with DST or historical offset changes keep the calendar path unchanged.

Measured ~3x faster for DateTime and ~1.35x for DateTime64 on UTC; no change for DST zones.

Changelog category (leave one):

  • Performance Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Speed up addDays, addWeeks, subtractDays, and subtractWeeks on DateTime and DateTime64 values in fixed-offset time zones (such as UTC) by taking an arithmetic fast path.

raimannma and others added 2 commits July 8, 2026 20:00
addDays/subtractDays/addWeeks/subtractWeeks on DateTime/DateTime64 went
through the per-row DateLUT calendar step even in UTC and other
fixed-offset time zones, where a day/week is a constant 86400/604800
seconds. addSeconds/addMinutes/addHours already add n*k to the unix
timestamp directly and are several times faster on the same data.

Add an offset_is_fixed flag to DateLUTImpl, computed while filling the
LUT: it is true iff the UTC offset never changes within the LUT range
(no midnight jumps between consecutive days and no intra-day offset
changes). When the flag is set, AddDaysImpl/AddWeeksImpl (and therefore
subtractDays/subtractWeeks and the DateTime +/- INTERVAL DAY/WEEK
operators) add delta * 86400 or delta * 604800 to the timestamp
directly, skipping the LUT lookup and, for DateTime64/Time64, the
std::div decomposition. Time zones with DST or any historical offset
change keep the calendar path, as do MONTH/QUARTER/YEAR intervals.

A parameterized unit test asserts for every known time zone that
reports a fixed offset that DateLUTImpl::addDays is bitwise-equal to
plain arithmetic across the LUT range.

Co-Authored-By: Claude Fable 5 <[email protected]>
@yariks5s yariks5s self-assigned this Jul 8, 2026
@yariks5s yariks5s added the can be tested Allows running workflows for external contributors label Jul 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [951d1ec]

Summary: ✅


AI Review

Summary

This PR adds an arithmetic fast path for addDays / addWeeks and the corresponding subtract variants on fixed-offset time zones by skipping calendar LUT lookups when the shift can be proven to stay inside the LUT. The current code preserves the old overflow and out-of-range behavior on the fallback path, the earlier boundary and INT64_MIN regressions raised in review are addressed, and I did not find a remaining correctness or evidence gap that should block the change.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jul 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 38 queries analysed

This PR adds an arithmetic fast path for addDays/addWeeks/subtractDays/subtractWeeks in fixed-offset time zones (UTC and similar) and leaves the calendar path for DST zones; nothing else in query execution changes. The one flagged item, ClickBench Q28, is a regex-replace plus aggregation that does not call any of those date functions, its CPU time is essentially unchanged (15377 vs 15414 ms), and its history is noisy — the +5.4% median shift is run-to-run variance and is correctly left as not_sure. No real regression or improvement is attributable to this change in the measured suites.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 28 not_sure 1038 1095 +5.4% 0.0002 cpu: Q28 is a regex-replace plus group-by; it never calls addDays/addWeeks/subtract*, the only functions this PR changes. CPU is flat (15377 vs 15414 ms) and history is noisy, so the +5.4% is run-to-run variance, not a PR effect.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: d625b733-6b00-4a25-a00f-b53be1a55e64
  • MIRAI run: 8ae6a375-b4d0-4160-ac4d-8e9dc7d7519c
  • PR check IDs:
    • clickbench_322388_1784464132
    • clickbench_322401_1784464132
    • clickbench_322407_1784464132
    • tpch_adapted_1_official_322413_1784464132
    • tpch_adapted_1_official_322424_1784464132
    • tpch_adapted_1_official_322435_1784464132

raimannma and others added 3 commits July 9, 2026 09:06
…set fast path

The arithmetic fast path for `addDays`/`addWeeks` in fixed-offset time
zones diverged from the calendar path once the input or the result left
the range of the date LUT: `DateLUTImpl::addDays` clamps the day index
to the LUT boundaries (via `findIndex` and `normalizeLUTIndex`), while
the fast path stored a raw out-of-range timestamp.

Add `DateLUTImpl::dayShiftStaysWithinLUT` and take the shortcut only
when both the input and the result stay inside the LUT, falling back to
the calendar path otherwise. The check works on the scaled values with
overflow-checked arithmetic, so the hot path does not divide by the
scale multiplier.

The boundary behavior is now byte-identical to master (verified against
an official 26.7.1.684 build), including the raw values that text
output would otherwise mask, and is pinned by the stateless test.

Co-Authored-By: Claude Fable 5 <[email protected]>
The arm_tidy build failed with cppcoreguidelines-init-variables on
`shift_scaled` and `result` in `DateLUTImpl.h`.

ClickHouse#109836

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/Common/DateLUTImpl.h Resolved
raimannma and others added 6 commits July 9, 2026 13:14
…ive sub-second values

The DateTime64/Time64 calendar path first does std::div(t, scale_multiplier)
and shifts the quotient, which truncates towards zero. For a negative t with a
nonzero sub-second remainder the quotient is one second higher than the raw
value's own day, so near the upper LUT edge the calendar path clamps the day
index while dayShiftStaysWithinLUT, which reasons about the raw scaled value,
still lets the arithmetic fast path through. addDays and addWeeks then diverged
from the byte-identical calendar result, e.g. addDays(toDateTime64('1969-12-31
23:59:59.999', 3, 'UTC'), 120530) returned 2299-12-31 23:59:59.999 instead of
2299-12-30 23:59:59.999.

Every such mismatch has a scaled result within one second of the upper bound, so
keep the fast path one second clear of it. The margin is zero for DateTime
(scale_multiplier == 1), leaving that path unchanged.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Master extended the representable DateTime64 range to [0000, 9999]
(ClickHouse#107907 and follow-ups). Out-of-LUT day arithmetic no longer clamps to
the LUT boundaries; `addDays` now takes a cctz escape path that computes
the value and saturates only at the representable calendar bounds. The
reference of `04511_add_days_fixed_offset_fast_path` was written against
the old clamping behavior, so the boundary section failed after merging
master.

Regenerate the reference and drop the comments that describe the removed
clamping. The fast path itself is unaffected: `dayShiftStaysWithinLUT`
only admits values strictly inside the LUT, where every day of a
fixed-offset time zone is 86400 seconds long, and the new
`isOutOfLUTRange` window is two days narrower than the LUT, which makes
the guard more conservative rather than less. Verified by rebuilding with
the fast-path call sites reverted to the calendar path: the output of the
test is identical with and without them.

Also correct two dates in the gtest comments - 10413792000 is
2300-01-01 00:00:00, so the last second of the LUT is 2299-12-31 23:59:59
and day index 146096 is 2299-12-31, not 2300-01-01.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
raimannma and others added 2 commits July 15, 2026 14:03
The fast path in `AddWeeksImpl` evaluated `delta * 7` in the caller before
`dayShiftStaysWithinLUT` could inspect it, so a huge delta such as
`addWeeks(..., 9223372036854775807)` made the signed multiply overflow before
the range check had a chance to decline it.

Compute the shift once through `__builtin_mul_overflow` and reuse the checked
value across the `DateTime64`, `Time64` and `UInt32` overloads. On overflow the
builtin still writes the wrapped product, so the calendar fallback keeps the
result it produced before and only the path selection changes.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The `UInt32` overload of `AddWeeksImpl::execute` computed the day shift
with `weeksToDays` but discarded it on the fallback path, passing the raw
`delta` to `DateLUTImpl::addWeeks`, which recomputes `delta * 7` itself.
That left the signed-overflow multiply in place for `DateTime`, while the
`DateTime64` and `Time64` overloads already reused the checked value.

Call `addDays` with the checked `days` instead. The result is unchanged:
`__builtin_mul_overflow` writes the same wrapped product the plain
multiply produced, so only the arithmetic is checked, not the outcome.

Cover the `DateTime` overload with a huge-delta `addWeeks` case; the test
previously exercised only `DateTime64` there.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@raimannma

Copy link
Copy Markdown
Contributor Author

@yariks5s anything left to do for me here?

yariks5s added 2 commits July 16, 2026 16:38
Select fixed-offset versus calendar implementations once per block for `addDays`, `addWeeks`, `subtractDays`, and `subtractWeeks`. This keeps the arithmetic fast path while restoring branch-free row loops for time zones with changing offsets.

Add vectorized `Time64` coverage for fixed and changing-offset time zones.

Related: ClickHouse#109836
Use the supported `toInt64` conversion instead of `reinterpretAsInt64`, which rejects `Time64`.

Related: ClickHouse#109836
@yariks5s

Copy link
Copy Markdown
Member

@yariks5s anything left to do for me here?

I think nothing from your side for now. This is a good change, thank you!

raimannma and others added 2 commits July 19, 2026 11:22
The subtract entry points negated the delta with a raw `-delta` before
the checked `weeksToDays` / `dayShiftStaysWithinLUT` guards ran, which
is signed-overflow UB for `delta == INT64_MIN`. Add a checked `negate`
helper that wraps like before but reports the overflow, and route an
overflowed negation to the calendar path so the fast-path guards only
ever see defined values.

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 19, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 78.20% 78.20% +0.00%

Changed lines: Changed C/C++ lines covered: 154/169 (91.12%) · Uncovered code

Full report · Diff report

@yariks5s
yariks5s added this pull request to the merge queue Jul 21, 2026
Merged via the queue into ClickHouse:master with commit dcb40fa Jul 21, 2026
350 of 352 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 21, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The arm_tidy build failed with cppcoreguidelines-init-variables on
`shift_scaled` and `result` in `DateLUTImpl.h`.

ClickHouse#109836

Co-Authored-By: Claude Fable 5 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Select fixed-offset versus calendar implementations once per block for `addDays`, `addWeeks`, `subtractDays`, and `subtractWeeks`. This keeps the arithmetic fast path while restoring branch-free row loops for time zones with changing offsets.

Add vectorized `Time64` coverage for fixed and changing-offset time zones.

Related: ClickHouse#109836
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Use the supported `toInt64` conversion instead of `reinterpretAsInt64`, which rejects `Time64`.

Related: ClickHouse#109836
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…set-fast-path

Arithmetic fast path for addDays/addWeeks in fixed-offset time zones
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-performance Pull request with some performance improvements 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.

3 participants