Skip to content

Speed up to_utc_timestamp and from_utc_timestamp on DateTime64 - #115838

Merged
nihalzp merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-115802-datetime64-utc-timestamp-perf
Aug 23, 2026
Merged

nihalzp merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-115802-datetime64-utc-timestamp-perf

Conversation

@groeneai

@groeneai groeneai commented Aug 21, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Performance Improvement

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

Speed up toUTCTimestamp/to_utc_timestamp and fromUTCTimestamp/from_utc_timestamp on DateTime64 arguments, restoring the throughput they had before the overflow fix in #109738. Results are unchanged. Closes #115802.

Description

Closes: #115802

My #109738 fixed a signed-overflow and a wrong-offset-at-a-boundary bug on the DateTime64 path of these functions, but it did the arithmetic and the clamp in Int128, once per row. Int128 here is wide::integer<128, signed>, a software big-integer, so operator* sign-normalizes through branches before a native multiply and reassembles a two-UInt64 struct. Each row gained that call plus two 128-bit compares and selects where it previously had one imul and one add. The DateTime branch was untouched and did not regress.

The wide arithmetic is redundant. The floored split guarantees seconds * scale_multiplier + micros == value exactly, so shifting the seconds by the offset and reassembling equals shifting the underlying value by offset * scale_multiplier; the Int128 multiply only re-derived its own input. This PR shifts the underlying value directly with a saturating Int64 add/sub (common::addOverflow/subOverflow: one add/sub plus a flag test).

offset * scale_multiplier cannot overflow Int64: scanning timeZoneOffset over all 597 shipped time zones (4.18M samples, including out-of-LUT extremes) gives max|offset| = 130800, and scale_multiplier <= 10^9, so the product stays 70000x below the Int64 limit. Both semantics from #109738 are kept: the split still floors, and the result is still saturated.

Measured on the queries from tests/performance/utc_timestamp_transform.xml (10M rows, max_threads=1, optimized build, arms differing by exactly this hunk): 0.102s -> 0.062s, against 0.061s before #109738. The DateTime queries are the control and stay at 0.033s throughout. That is x86_64, so the ratio is smaller than the ARM 2.7x in the issue, but the fix returns to the pre-#109738 cost rather than narrowing the gap.

Results are bit-identical to master over 12.9M (value, scale, timezone, direction) cases plus 112K cases built on the 1,056 real offset-transition seconds. 03891_utc_timestamp_datetime64_overflow passes byte-identical, and still reddens if the saturation is dropped, its direction flipped, or the floor correction removed.


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

Version info

  • Merged into: 26.8.1.1944 (included in 26.8 and later)

The DateTime64 branch of UTCTimestampTransform::executeImpl regressed about
1.65x when ClickHouse#109738 fixed a signed overflow and a wrong-offset-at-a-boundary
bug there. That fix promoted the per-row arithmetic to Int128 and clamped in
Int128. Int128 in ClickHouse is wide::integer<128, signed>, a software
big-integer: its operator* sign-normalizes through branches before reaching a
native multiply and then reassembles a two-UInt64 struct. Every row gained
that call plus two 128-bit compares and selects in place of one imul and one
add, which is not vectorizable.

The wide arithmetic was redundant. The floored split guarantees
seconds * scale_multiplier + micros == value exactly, so shifting the seconds
by the timezone offset and reassembling equals shifting the underlying value
by offset * scale_multiplier. The Int128 multiply only re-derived its own
input. Shift the underlying value directly instead, with a saturating Int64
add/sub via common::addOverflow / common::subOverflow, which compile to one
add/sub plus a flag test.

offset * scale_multiplier cannot overflow Int64: scanning timeZoneOffset over
all 597 shipped time zones and 4.18 million samples, including out-of-LUT
extremes, gives a maximum absolute offset of 130800, and scale_multiplier is
at most 10^9 because DataTypeDateTime64 rejects scale > 9. The product stays
below 1.4e14 against an Int64 limit of 9.2e18.

Both semantics from ClickHouse#109738 are preserved: the seconds split still floors, so
timezoneOffset() reads the floor second, and the result is still saturated
into Int64 rather than overflowing.

Measured on the queries in tests/performance/utc_timestamp_transform.xml
(10 million rows, max_threads=1, optimized build, arms differing by exactly
this hunk): 0.102s to 0.062s, against 0.061s before ClickHouse#109738. The DateTime
queries of the same test are the control and stay at 0.033s.

Results are bit-identical to master, verified over 12.9 million
(value, scale, timezone, direction) cases plus 112 thousand cases built on the
1056 real offset-transition seconds, and 03891 passes byte-identical while
still reddening if the saturation is dropped, its direction flipped, or the
floor correction removed.

Closes ClickHouse#115802
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Aug 21, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

An independent cold review of this diff plus a second-model gate pass, adjudicated against the
recorded validation evidence. No blockers or majors were found by either.

# Finding Verdict
1 💡 The measured speedup was stated without naming the architecture, so it read as contradicting the 2.7x in the issue. Agreed, fixed in the description: the numbers here are x86_64, the issue's are ARM, and the point that survives either way is that the DateTime64 queries return to their pre-#109738 cost rather than merely narrowing the gap.
2 💡 The visible issue link said Related: while the changelog entry said Closes. Agreed, fixed: the visible link is now Closes:, consistent with the changelog entry, since this PR does resolve the issue.
3 ⚠️ The in-diff comment asserts |offset| < 2^18 as a flat inequality. Disagreed. The bound is derivable, not merely observed: DateLUTImpl::timezoneOffset composes a fold of a % 86400 (DateLUTImpl.h:891-895), an Int8 change amount scaled by OffsetChangeFactor = 900 (:197-213, so at most 114300), and offset_at_start_of_epoch (a cctz int), with the out-of-LUT path clamping t into the representable range first (DateLUTImpl.cpp:320-325). The conclusion is also insensitive to the exact bound: even at an absurd int32 offset, 2^31 * 10^9 is 2.15e18 against an Int64 limit of 9.22e18. Left as written.

Independently of the recorded evidence, I re-derived the algebraic identity the fix rests on and
modelled both the old Int128 semantics and the new saturating Int64 ones over 1,804,500
(value, scale, offset, direction) cases biased to the Int64 boundaries: no mismatches, while
flipping the saturation-end selection produces 2,830, so the check discriminates. I also confirmed
that neither seconds - 1 nor offset * scale_multiplier can overflow at any reachable input, so
the change does not reintroduce the signed overflow #109738 fixed.

Gate: 0 findings, full coverage of the changed file, its callers, the overflow and
timezone-offset helpers, the sibling DateTime64 transforms, and the regression test.

Session id: cron:clickhouse-review-slot-8:20260821-172900

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The four queries from tests/performance/utc_timestamp_transform.xml (10M rows, max_threads=1) run through clickhouse local on a pinned core, median of 7 timed runs after a discarded warm-up. The DateTime64 queries take 0.102s with the current code and 0.061s without it, every run, spread under 2ms. Not a low-rate effect.
b Root cause explained? Yes. #109738 moved the per-row DateTime64 arithmetic to Int128 and added an Int128 clamp. Int128 is wide::integer<128, signed> (base/base/extended_types.h:10), a software big-integer: operator* sign-normalizes through branches (wide_integer_impl.h:1055-1063) before a native multiply (:905-915) and reassembles a two-UInt64 struct. Each row gained that call plus two 128-bit compares and selects in place of one imul and one add. The DateTime branch was untouched and did not regress.
c Fix matches root cause? Yes. The floored split makes seconds * scale_multiplier + micros == value exact, so the Int128 multiply only re-derived its own input. The fix shifts the underlying value by offset * scale_multiplier with a saturating Int64 add/sub, removing the wide arithmetic instead of tuning around it. No bound widened, no check dropped, no dataset shrunk.
d Test intent preserved / new tests added? Preserved. 03891_utc_timestamp_datetime64_overflow passes byte-identical to its committed .reference, and I verified it still reddens when the saturation is removed (10 lines), its direction flipped (10 lines), or the floor correction removed (8 lines), plus on the pre-#109738 code (18 lines). No new test: results are bit-identical to master, so there is no new behaviour to pin, and a wall-clock assertion does not belong in a stateless test.
e Both directions demonstrated? Yes. Same harness, same core, arms differing by exactly this hunk on one base tree: 0.102s without the fix, 0.062s with it, against 0.061s before #109738. The DateTime queries are the control and read 0.033s in all three arms.
f Fix is general across code paths? Yes. Both directions of the function (to_utc/from_utc, one loop behind a flag) are fixed, and all four registered aliases resolve into it. The sibling site #109738 also touched, the DateTime64 to Time64 floor split (FunctionsConversion.h:2321-2329), is Int64 with % 86400 throughout, so it carries neither the regressing mechanism nor the identity and is deliberately unchanged. No other Int128 per-row loop of this shape exists in src/Functions.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Bit-identical to master over 12,851,520 cases (40,161 underlying values including Int64 extremes, saturation-boundary neighbourhoods and uniform random, x 10 scales x 16 time zones x both directions) plus 111,936 cases built from the 1,056 real offset-transition seconds with negative sub-second fractions. Also Const, Nullable, NULL, Nullable at the Int64 boundary, Array via arrayMap, empty column, and all 10 scales at both boundaries. LowCardinality(DateTime64) is not a constructible type, so it does not apply.
h Backward compatible? (maintainer-approved exception only) Yes, trivially: results are bit-identical to master by measurement, so there is no user-visible behavioural delta. No setting added or defaulted, hence no SettingsChangesHistory.cpp entry; no serialization format touched.
i Invariants and contracts preserved? Yes. Both invariants #109738 established still hold: the seconds split still floors, so timezoneOffset() still reads the floor second, and the result is still saturated into Int64 rather than overflowing. The mutation runs above show the test catches the loss of either. offset * scale_multiplier cannot overflow: measured max abs(offset) = 130800 over all 597 shipped time zones and 4.18M samples, and scale_multiplier <= 10^9, so the product stays 70000x below the Int64 limit. No allocation, ownership, locking or error path changed; the loop stays a pure element-wise transform with both throws outside it.

Session id: cron:clickhouse-impl-slot-40:20260821-162100

@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a90db33]

Summary: ✅


AI Review

Summary

This PR rewrites the DateTime64 path of toUTCTimestamp / fromUTCTimestamp to replace the per-row Int128 recomposition with a direct saturating Int64 shift by timezoneOffset * scale_multiplier. I did not find any blocker or major issue in the current patch: the floor-second logic used for DST-boundary offset lookup is preserved, the new saturation logic matches the old clamped Int128 behavior for the same mathematical expression, and the existing regression test coverage around overflow and boundary seconds remains aligned with the contract.

Final Verdict

✅ No actionable review findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.00% 87.00% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 13/13 (100.00%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @george-larionov @nihalzp, could you review this? The DateTime64 branch of toUTCTimestamp/fromUTCTimestamp did its per-row arithmetic in Int128, which is a software big-integer here, but the floored seconds split makes that wide math algebraically redundant, so this shifts the underlying value directly with a saturating Int64 add/sub and results stay bit-identical.

The arm_tidy build runs clang-tidy with -warnings-as-errors, and
cppcoreguidelines-init-variables is one of only two cppcoreguidelines
checks enabled in .clang-tidy. It flagged the declaration of `res`,
failing the build:

  src/Functions/UTCTimestampTransform.cpp:157:27: error: variable 'res'
  is not initialized [cppcoreguidelines-init-variables,-warnings-as-errors]

`res` is a pure out-parameter of common::subOverflow/addOverflow, which
wrap __builtin_ssubl_overflow/__builtin_saddl_overflow and always write
it, so this was a lint-policy failure rather than a real uninitialized
read. Initializing at the declaration matches how the rest of the
codebase declares these out-parameters (DecimalFunctions.h,
HashTable.h, CompressionCodecMultiple.cpp).

The initializer is dead: rebuilding with an arbitrary initial value
instead of 0 produces a byte-identical object file, so codegen and the
measured performance of the DateTime64 path are unchanged.

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

clickhouse-gh Bot commented Aug 21, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a90db33cf with master 400ba9d99 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 704.52 MiB 701.50 MiB -3.02 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×1.09 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +324.0 s (+9%) in total before that adjustment.

Job report

@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 5fa4d207-a551-4a11-92fe-5198fde49dcc
  • MIRAI run: 57d5c310-cde0-49d7-9d60-0debf4648a1b
  • PR check IDs:
    • clickbench_28681_1787352157
    • clickbench_28687_1787352157
    • clickbench_28699_1787352158
    • tpch_adapted_1_official_28716_1787352157
    • tpch_adapted_1_official_28726_1787352157
    • tpch_adapted_1_official_28754_1787352157

@nihalzp nihalzp self-assigned this Aug 22, 2026
@nihalzp
nihalzp added this pull request to the merge queue Aug 23, 2026
Merged via the queue into ClickHouse:master with commit f3723c9 Aug 23, 2026
177 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 23, 2026
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 groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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.

to_utc_timestamp and from_utc_timestamp are ~2.7x slower for DateTime64 after the overflow fix

3 participants