Skip to content

Fix key analysis for toYYYYMMDDhhmmss, toHour and toMinute when the local clock goes back - #124530

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-local-clock-monotonicity-key-analysis
Oct 10, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-local-clock-monotonicity-key-analysis

Conversation

@groeneai

@groeneai groeneai commented Oct 8, 2026 •

Copy link
Copy Markdown
Collaborator

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 primary key, partition key and skip index analysis that could skip or over-count rows, and ORDER BY optimization that could return rows in the wrong order, for toYYYYMMDDhhmmss, toHour and toMinute over a DateTime or DateTime64 column when the local clock goes back, for example on the daylight saving time change in America/New_York or the 30-minute change in Australia/Lord_Howe.

Description

Related: #124474 (same mechanism for timezoneOffset and toTimeWithFixedDate)

On 26.3.33.24 and master, with dt DateTime('America/New_York') as the sorting key holding 01:50 EDT and 01:10 EST of 2024-11-03, SELECT count() FROM t WHERE toYYYYMMDDhhmmss(dt) = 20241103015000 returns 0 instead of 1, and ORDER BY toYYYYMMDDhhmmss(dt) LIMIT 1 returns the 01:50 row. toMinute(dt) = 50 in Australia/Lord_Howe and toHour(dt) = 3 in Pacific/Chatham also return 0 instead of 1.

Key analysis calls a function monotonic on a range when its factor is equal at both ends. toYYYYMMDDhhmmss was always monotonic, toHour used the local day and toMinute the start of the hour counted from local midnight; none of them sees the clock go back.

All three now use the local day, the UTC offset and the instant at which the clock showed the start of the current local day (toHour, toYYYYMMDDhhmmss) or hour (toMinute), so equal factors mean the clock did not go back between the ends. For toYYYYMMDDhhmmss the factor is constant for Date, Date32 and fixed-offset zones, which keep cross-day pruning.

The price: in a zone with offset changes, toYYYYMMDDhhmmss ranges across local midnight are no longer pruned (896 rows read instead of 64 for an equality in the test). ORDER BY toYYYYMMDDhhmmss(x) no longer reads in order, and a sorting key toYYYYMMDDhhmmss(x) no longer prunes by a condition on x, also in UTC: these callers do not see a time zone argument, and with one (toYYYYMMDDhhmmss(dt_utc, 'America/New_York')) the old claim is wrong.

Validation: 15 of the test's 23 lines differ on master, and 10 of 11 mutations of the fix fail it. Over 81 zones, 20,088 count() vs countIf pairs: 3,082 mismatches on master, 0 with the fix.

toString(dt, 'tz') has the same time zone argument hole; not changed here. Nullable(DateTime(tz)) keys also need #121265.


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

Version info

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

groeneai and others added 2 commits October 8, 2026 00:29
…ocal clock goes back

Key analysis calls a function monotonic on a range when its factor
transform is equal at both ends. toYYYYMMDDhhmmss had ZeroTransform
(always monotonic), toHour used the local day and toMinute
toStartOfHour, which counts hours elapsed since local midnight. None of
them changes when the local clock goes back (a DST fall-back, the
30-minute change in Australia/Lord_Howe, 03:45 -> 02:45 in
Pacific/Chatham, DateLUT repeating hour 23 on a day longer than 24
hours), so KeyCondition got a reversed or too narrow range and skipped
matching granules; read in order and constant wrapping trusted the
"always monotonic" claim.

The factor is now the local day, the UTC offset and the instant at
which the clock showed the start of the current local day (toHour,
toYYYYMMDDhhmmss) or hour (toMinute). timezoneOffset and the displayed
time split a lookup-table day at the same instant, and the table holds
at most one offset change per day, so equal day and offset put both
ends in one constant-offset run. There the third component only grows
(by the period at a wrap, by an hour at each hour DateLUT repeats as
23), so equal factors mean the clock moved forward with time between
the ends. Without the offset, a forward change on a day longer than 24
hours could bring the third component back to an earlier value.
Outside the lookup table no two points share a factor.

For toYYYYMMDDhhmmss the factor is constant for Date, Date32 and,
inside the lookup table, for a fixed-offset time zone, so cross-day
pruning is kept there. It does not keep the "always monotonic" claim:
read in order asks without the time zone argument, and with one
(toYYYYMMDDhhmmss(dt_utc, 'America/New_York')) the claim is wrong.

Measured over 81 time zones and every transition day of the DateTime
range (20,088 count() vs countIf pairs): 3,082 mismatches before, 0
after; 1,240 pre-1970 DateTime64 pairs in 5 zones: 171 before, 0 after.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten the ToClockPeriodStartFactorImpl comment to the invariant it relies on.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work labels Oct 8, 2026
@groeneai

groeneai commented Oct 8, 2026

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

Pre-publication review by an independent model (engine: codex; 2 rounds, 6 findings) plus the reviewer's own cold review (1 finding).

# Sev Finding Verdict Evidence / action
1 ⚠️ Equal factors did not prove the field never went back (DateLUT's hour-23 clamp on a lookup-table day longer than 24 hours) AGREE, fixed @ 0a4d876 the factor now includes the UTC offset
2 ⚠️ ORDER BY lines did not pin optimize_read_in_order AGREE, fixed @ 0a4d876 -- Random settings limits: optimize_read_in_order=(1, 1)
3 💡 No DateTime64 case AGREE, fixed @ 0a4d876 one DateTime64(3) line
4 ⚠️ No partition key or skip index case DISAGREE the change is in the factor types only; every consumer goes through getMonotonicityForRange, and the test already fails on master through two of them
5 💡 No pruning oracle for toHour and toMinute AGREE, fixed @ 0a4d876 max_rows_to_read lines for both
6 ⚠️ No test exercises the UTC offset component DISAGREE no shipped zone can: over 597 zones and every transition day of 1900..2299 no (day, instant) factor repeats after a different one; the component makes the claim hold for any lookup table
7 💡 No Date32 pruning line for toYYYYMMDDhhmmss AGREE, not fixed can only cost rows read, never a result; same constant as the Date line

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-self-slot-58:20261008-003400

@groeneai

groeneai commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 05340_local_time_monotonicity_clock_change.sql on the base binary: 15 of 23 lines wrong on every run (20/20 randomized runner runs fail).
b Root cause explained? Yes. A function is claimed monotonic when its factor is equal at both ends; the old factors (none for toYYYYMMDDhhmmss, local day for toHour, start of hour from local midnight for toMinute) do not change when the local clock goes back.
c Fix matches root cause? Yes. The factor is the local day, the UTC offset and the instant at which the clock showed the start of the current local day or hour.
d Test intent preserved / new tests added? Yes. New 23-line test: key condition vs countIf truth (DateTime, DateTime64), read in order, constant wrapping, five max_rows_to_read pruning guards; 10 of 11 mutations fail it.
e Both directions demonstrated? Yes. Base 15/23 wrong, fix 23/23 right; 50/50 randomized runs pass on the fix.
f Fix is general across code paths? Yes. Primary key, part statistics, read in order and constant wrapping all go through the same claim.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. 0 mismatches over 20,088 count() vs countIf pairs in 81 zones and 1,240 pre-1970 DateTime64 pairs (3,253 on base).
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change; only which ranges are claimed monotonic.
i Invariants and contracts preserved? Yes. Equal day and offset put both ends in one constant-offset run of one lookup-table day, where the third component only grows; out-of-table ends never compare equal.

Session id: cron:clickhouse-impl-self-slot-57:20261007-232600

@clickhouse-gh

clickhouse-gh Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [56cad74]

Summary: ✅


AI Review

Summary

This PR tightens monotonicity analysis for toYYYYMMDDhhmmss, toHour, and toMinute so MergeTree key analysis stops assuming those transforms stay monotonic across local-clock rollbacks. I read the current diff, the full PR discussion, and the current code paths that consume monotonicity, including the optional-timezone handling in KeyCondition, and I did not find a correctness issue in the patch.

Final Verdict

✅ No findings. The implementation matches the stated bug, the new stateless coverage exercises the important planner paths, and the current Praktika reports are green.

LLVM Coverage Report

Measured on commit 56cad74.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 92.10% 91.80% -0.30%
Branches 79.70% 79.70% +0.00%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 8, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... label Oct 8, 2026
@nihalzp nihalzp self-assigned this Oct 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 56cad740b with master 756552d66 (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

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.

Object file sizes

32 object files changed (+17.96 KiB total), 0 added.

Object file Master PR Δ
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/toYYYYMMDDhhmmss.cpp.o 315.05 KiB 334.65 KiB +19.60 KiB (+6.22%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good.

@alexey-milovidov alexey-milovidov self-assigned this Oct 10, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 10, 2026
Merged via the queue into ClickHouse:master with commit b0ae0f2 Oct 10, 2026
152 of 153 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 10, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 22, 2026
toHour and toTimeWithFixedDate over a pre-epoch DateTime and DateTime64 are
fixed on master by ClickHouse#124530 and ClickHouse#124474, so their queries pass there and no
longer test this change. toTimeWithFixedDate also rounds a pre-epoch
DateTime64 down to whole seconds on master now, so the expected row of the
removed DateTime64 case no longer exists.

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

can be tested Allows running workflows for external contributors comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work 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.

4 participants