Skip to content

Fix key analysis for timezoneOffset and toTimeWithFixedDate over a range that spans a UTC offset change - #124474

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-timezone-offset-monotonicity-dst
Oct 10, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-timezone-offset-monotonicity-dst

Conversation

@groeneai

@groeneai groeneai commented Oct 7, 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 for conditions on timezoneOffset and toTimeWithFixedDate over a DateTime or DateTime64 column in a time zone with daylight saving time, when the key range spans a change of the UTC offset.

Description

Related: #124470 (also defines ToTimeWithFixedDateFactorImpl; the PR merged second keeps one definition, deriving from ToDayAndUTCOffsetFactorImpl)

On 26.3.33.24 and master, with dt DateTime('America/New_York') as the sorting key and one row per day of 2024 at local midnight, SELECT count() FROM t WHERE timezoneOffset(dt) = -14400 returns 0 instead of 238, and = -18000 returns 366 instead of 128.

Key analysis treats a function as monotonic on a range when its factor is equal at both ends. The factor of timezoneOffset was the local time of day, so a range from midnight to midnight across the whole summer was called monotonic and got the single value [-18000, -18000]. The factor of toTimeWithFixedDate was the local day, which ignores that the clock goes back on a fall-back day, so [01:50 EDT, 01:10 EST] became the empty range [01:50, 01:10].

Both now use the pair (local day, UTC offset). The lookup table holds at most one offset change per day, so equal pairs mean the offset is constant between the ends. Where the lookup table does not apply (DateTime64 within two days of the ends of its range, or beyond them), no monotonicity is claimed. Ranges within one day without an offset change can now be pruned for timezoneOffset; ranges across midnight or an offset change cannot.

Most test lines compare count() with a countIf over the table, for daily, hourly and per-minute data in America/New_York and for DateTime64 before 1970 and past 9999-12-31; two bound the rows read with max_rows_to_read to check that ranges within one day are still pruned. Nullable(DateTime(tz)) keys also need #121265, which fixes the time zone used.

toYYYYMMDDhhmmss (declared always monotonic) and toMinute in a zone with a 30-minute change such as Australia/Lord_Howe also skip rows on a fall-back; they need their own factors and are not changed here.


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

Version info

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

groeneai and others added 2 commits October 7, 2026 18:21
…UTC offset change

Key analysis calls a date/time function monotonic on a key range when its
factor transform gives the same value at both ends. The factor of
`timezoneOffset` was `toTimeWithFixedDate` (same local time of day), so a
range from local midnight in January to local midnight in December was
called monotonic although the offset changes twice in between: on
26.3.33.24 and master `timezoneOffset(dt) = -14400` over a
`DateTime('America/New_York')` key returned 0 rows instead of 238, and
`= -18000` returned 366 instead of 128. The factor of `toTimeWithFixedDate`
was `toDate` (same local day), which ignores that the wall clock goes back
on a fall-back day, so `[01:50 EDT, 01:10 EST]` became an empty range and
the granule was dropped.

Both functions now use the pair (unclamped local day, UTC offset) as the
factor. The lookup table stores at most one offset change per day, so equal
pairs mean the offset is constant on the range: `timezoneOffset` is then
constant and `toTimeWithFixedDate` increases. Outside the lookup table range
the cctz path clamps the day to [0000, 9999] while the time of day keeps
cycling, so there the factor is unique to the end point and nothing is
claimed. The `toTimeWithFixedDate` variant reads `DateTime64` through its
whole part like the function; the `timezoneOffset` factor has no
`DecimalComponents` overload, so `TransformDateTime64` floors it the same
way it floors the function's argument.

Ranges within one day without an offset change become prunable for
`timezoneOffset`; ranges across midnight or an offset change no longer are.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Condense the factor comment to its invariant and state the out-of-LUT case as one.

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 7, 2026
@groeneai

groeneai commented Oct 7, 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; 1 finding) plus my own review (3 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ The test cannot tell the new factor from declining monotonicity everywhere, and has no partition or skip-index table DISAGREE The contract is correct rows: base fails 10 of 11 lines and four deletion mutations each fail it. Pruning is measured, not asserted (EXPLAIN 43/43 granules on base, 26/43 with the fix). Partition minmax and minmax skip index use the same monotonicity check, 0 vs 238 on base, 238 with the fix
2 💡 toYYYYMMDDhhmmss is declared always monotonic and drops rows on a fall-back hour (0 instead of 1 on master and 26.3.33.24) AGREE Out of scope: keeping its cross-day pruning needs its own factor. Noted in the description
3 💡 toMinute in Australia/Lord_Howe drops rows after its 30-minute fall-back (0 instead of 1 on master) AGREE Out of scope, noted in the description
4 💡 The description understated the range where no monotonicity is claimed AGREE Reworded

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

Session id: cron:clickhouse-review-self-slot-58:20261007-182400

@groeneai

groeneai commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 05339_timezone_offset_monotonicity_dst.sql on the base binary: 10 of 11 lines differ from the countIf oracle on every run (20/20 randomized runs fail).
b Root cause explained? Yes. Key analysis calls a function monotonic when its factor is equal at both ends. The factors were the local time of day (timezoneOffset) and the local day (toTimeWithFixedDate); neither sees an offset change between the ends.
c Fix matches root cause? Yes. Both factors become (local day, UTC offset); the lookup table has at most one offset change per day, so equal factors mean a constant offset. No monotonicity is claimed outside the lookup table range.
d Test intent preserved / new tests added? Yes. New test, 11 lines, each count() with the key condition against countIf. Four deletion mutations of the fix each make it fail.
e Both directions demonstrated? Yes. Base 10/11 wrong, fix 11/11 right, via clickhouse local and clickhouse-test; 50/50 randomized runs pass on the fix.
f Fix is general across code paths? Yes. These are the two functions whose value depends on the UTC offset; toHour, toMinute, toSecond stay non-decreasing across hour/minute-aligned changes. Primary key, partition minmax and minmax skip index all measured fixed.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. 648 count/countIf pairs over 9 zones (negative DST, 30-minute DST, midnight changes, date line), DateTime, fractional DateTime64, pre-1970 values: 0 mismatches (76 on base). Nullable keys additionally need #121265.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change; only which key ranges are claimed monotonic.
i Invariants and contracts preserved? Yes. "Equal factors imply monotonic with is_positive = true on the range" now holds by construction of the lookup table; out-of-table ends never compare equal.

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

@clickhouse-gh

clickhouse-gh Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d10cea5]

Summary: ✅


AI Review

Summary

This PR changes the monotonicity factors for timezoneOffset and toTimeWithFixedDate so key analysis no longer assumes they are monotonic across DST offset changes in the default-column-timezone path. That closes the reported false-pruning cases, but one blocker remains: the supported toTimeWithFixedDate(datetime, timezone) form still computes monotonicity in the source column's timezone, so it can still misclassify a range as monotonic and skip or over-count rows when the explicit timezone differs.

Missing context / blind spots
  • ⚠️ I reviewed the code and tests only. This checkout has no usable local clickhouse binary / build directory, so I could not run tests/queries/0_stateless/05339_timezone_offset_monotonicity_dst.sql here.
Findings
❌ Blockers
  • [src/Functions/DateTimeTransforms.h:1375] toTimeWithFixedDate(datetime, timezone) is still analyzed in the source type's timezone because IFunctionDateOrDateTime::getMonotonicityForRange derives date_lut from the first argument type and cannot see the explicit timezone argument. A DateTime('America/New_York') range such as 2024-11-03 02:00:00 EST .. 2024-11-03 23:30:00 EST therefore keeps one (local day, UTC offset) factor here, but toTimeWithFixedDate(dt, 'UTC') crosses 2024-11-04 00:00:00 UTC and wraps in the middle. Key analysis can still produce a single interval for a non-monotonic range, so the row-skipping bug remains on this supported entrypoint.
    Suggested fix: either plumb the constant timezone argument into monotonicity, or conservatively decline monotonicity whenever toTimeWithFixedDate is called with the second argument.
Final Verdict

❌ Changes requested — the default-zone DST regression is fixed, but toTimeWithFixedDate(datetime, timezone) can still be mis-pruned.

LLVM Coverage Report

Measured on commit d10cea5.

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

Changed lines: Changed C/C++ lines covered: 6/9 (66.67%) · 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 7, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... label Oct 7, 2026
The existing lines only compare counts with and without the key
condition, so they also pass if `timezoneOffset` and
`toTimeWithFixedDate` stopped claiming monotonicity altogether. Add a
table with one granule per hour of a single local day and bound the rows
read with `max_rows_to_read`: the ranges inside the day that keep one UTC
offset must still be skipped. With a factor that never declares
monotonicity, 24 of 25 rows are read and both new lines fail. The
PartsSplitter injection is clamped to 0 and index analysis is enabled on
every parallel replica, as in 00926 and 00979, so that the bounds do not
depend on the randomized read plan.

Also cover the `DateTime64` overload of the `toTimeWithFixedDate` factor:
before the epoch, the function truncates a negative timestamp towards
zero, while the generic `DateTime64` path floors it. Without the
overload, 1969-10-26 01:59:59.000 and 01:59:59.500 -04:00 get the same
factor although the function maps them to 01:59:59 and 01:00:00, and the
row at 01:59:59 is skipped (0 instead of 1).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
static constexpr bool hasPreimage() { return false; }

using FactorTransform = ToDateImpl<>;
using FactorTransform = ToTimeWithFixedDateFactorImpl;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Switching toTimeWithFixedDate to this factor fixes the default-column-timezone path, but the supported toTimeWithFixedDate(datetime, timezone) form is still unsound. IFunctionDateOrDateTime::getMonotonicityForRange derives date_lut from the source type, not from the explicit timezone argument, so for DateTime('America/New_York') a range like 2024-11-03 02:00:00 EST .. 2024-11-03 23:30:00 EST gets the same (day, offset) here while toTimeWithFixedDate(dt, 'UTC') wraps at 2024-11-04 00:00:00 UTC in the middle. Key analysis can therefore still treat the function as monotonic and skip / over-count rows. We need to either thread the constant timezone argument into monotonicity or conservatively disable monotonicity when the second argument is present.

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.

For a follow-up.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The explicit time zone is already used here: FunctionWithOptionalConstArg::getMonotonicityForRange in KeyCondition.cpp rebuilds the argument type as DateTime(tz) / DateTime64(s, tz) from the constant argument before calling the function, so the factor reads that zone's LUT, not the column's.

Measured on current master (d741c98) and on this PR's CI build:

  • the case above (DateTime('America/New_York') key, 2024-11-03 02:00 to 23:30 EST, toTimeWithFixedDate(dt, 'UTC')): correct counts on both, with the index still used (Granules: 3/44);
  • the reverse case (DateTime('UTC') key, rows at 01:50 EDT and 01:10 EST, toTimeWithFixedDate(dt, 'America/New_York') equal to 01:50): master returns 0 rows instead of 1, this PR returns 1 through the primary key, the partition minmax and a minmax skip index.

So I don't see a follow-up to do. If you want the reverse case in the test, I can send it as a small separate PR.

@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.

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 2b83546 Oct 10, 2026
152 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 Oct 10, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @alexey-milovidov — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

@groeneai

Copy link
Copy Markdown
Collaborator Author

The Nullable(DateTime('tz')) key regression reported above (#125306) is fixed in #125327.

alexey-milovidov added a commit that referenced this pull request Oct 12, 2026
…h `DateTime64` down

The `fall64` case of `05339_timezone_offset_monotonicity_dst` (added in #124474) relied on
`toTimeWithFixedDate` truncating a pre-epoch `DateTime64` towards zero, which moved
`1969-10-26 05:59:59.500` UTC to the next second, after the fall-back. This PR rounds the
fractional part down, so both rows are at 01:59:59 -04:00, with and without the key
condition. The factor of `toTimeWithFixedDate` reads the same rounded whole part through
`TransformDateTime64`, so key analysis stays consistent with the function.

This failed the `Fast test` in the merge queue:
https://github.com/ClickHouse/ClickHouse/actions/runs/38282390263

Co-Authored-By: Claude Opus 5.5 <[email protected]>
clickgapai pushed a commit to clickgapai/ClickHouse that referenced this pull request Oct 15, 2026
…ullable keys

`IFunctionDateOrDateTime::getMonotonicityForRange` picked the lookup table with
`dynamic_cast<const TimezoneMixin *>(&type)` before unwrapping `LowCardinality`
and `Nullable`. The wrappers are not `TimezoneMixin`, so for a
`Nullable(DateTime('tz'))` key the factor was compared in the session time zone
while the function itself runs in the column's time zone. A range whose factor
is equal at both ends in the session zone but not in the column zone was
declared monotonic, and primary key / skip index analysis skipped matching
granules or over-counted rows.

This is the long-standing ClickHouse#121179 (`toHour`, `toDayOfMonth`, ... over such keys);
ClickHouse#124474 changed the `timezoneOffset` factor to (local day, UTC offset), which in
a UTC lookup table is constant over a whole UTC day, so sub-daily `Nullable`
`timezoneOffset` conditions started losing rows on master (ClickHouse#125306).

Take the time zone from the unwrapped type, as `IFunctionCustomWeek` does since
ClickHouse#118655. ClickHouse#121265 contains the same change to this file.

Closes ClickHouse#125306
Closes ClickHouse#121179

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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