Skip to content

Decide week-function monotonicity in the time zone of the argument - #118655

Merged
alexey-milovidov merged 12 commits into
masterfrom
custom-week-monotonicity-timezone-117696
Oct 2, 2026
Merged

alexey-milovidov merged 12 commits into
masterfrom
custom-week-monotonicity-timezone-117696

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 7, 2026 •

Copy link
Copy Markdown
Member

Closes: #117696

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):

Fix rows silently dropped by primary-key pruning when toDayOfWeek is applied to a DateTime column whose time zone differs from the session one, or over a Date32/DateTime64 key that leaves the Date range. toDayOfWeek with a Sunday-first week_mode can use the primary key again.

Description

CREATE TABLE tz (dt DateTime('Asia/Tokyo')) ENGINE = MergeTree ORDER BY dt;
INSERT INTO tz SELECT toDateTime('2026-08-09 10:00:00', 'UTC') + 3600 * number FROM numbers(11);

SELECT countIf(toDayOfWeek(dt) = 7) FROM tz;      -- 5
SELECT count() FROM tz WHERE toDayOfWeek(dt) = 7; -- 0, the rows are dropped by pruning

IFunctionCustomWeek::getMonotonicityForRange compared its factor in DateLUT::instance() - the session time zone - while the function itself is executed with the time zone taken from its argument's type (extractTimeZoneFromFunctionArguments). A key range that lies inside one week of the session time zone can straddle a week boundary of the column's time zone, where toDayOfWeek drops from 7 to 1; the range was claimed monotonic anyway, and KeyCondition mapped it to an inverted, empty range and pruned granules that hold matching rows.

The single-argument date/time family already reads the time zone from the argument type in IFunctionDateOrDateTime::getMonotonicityForRange; the custom-week family now does the same (on the type with LowCardinality/Nullable already unwrapped). The comment claiming that the non-local time zone does not matter here was stale.

Of the custom-week functions, this half affects only toDayOfWeek. toWeek does not claim monotonicity at all (ToWeekImpl::hasMonotonicity is false, #90240), so KeyCondition never reaches its getMonotonicityForRange. toStartOfWeek, toLastDayOfWeek and toYearWeek use ZeroTransform - they are monotonic everywhere - and were not affected.

toDayOfWeek had a second, independent way to lose rows: its factor transform was ToMondayImpl, a whole Monday-week. The week_mode is a constant argument and is not visible to getMonotonicityForRange, and modes 2 and 3 number Sunday lowest, so a range inside one Monday-week is not monotonic there - toDayOfWeek(d, 3) = 1 over a Date key discarded the part holding the matching Sunday. Threading the mode through would need a function base that carries the constant arguments, so the new ToDayOfWeekFactorImpl pairs both weeks instead: two days share the factor iff they lie in the same Monday-week and the same Sunday-week, that is, in the same Monday-to-Saturday run or on the same Sunday. A range inside such a run - up to six days - is monotonic for every mode and still prunes; only the ranges with a Sunday boundary inside them are given up.

Meanwhile #117683 fixed the same week_mode problem on master by declining monotonicity for the Sunday-first modes altogether in KeyCondition (FunctionWithOptionalConstArg), based on the ToMondayImpl factor. The paired factor makes that carve-out redundant, so it is removed here, and the Sunday-first modes prune again; 05186 still checks that no row is lost and now checks that both numberings prune.

The factor is the unclamped day number, not a toMonday/toDate result: those narrow the day number to UInt16, which aliases it modulo 65536 on the extended carriers, so 1970-01-01 and 2149-06-07 shared a factor and a range spanning them was reported monotonic; and it has no DecimalComponents overload, so a DateTime64 is rounded down to the day rather than truncated towards zero, which had given a pre-epoch value at 23:59:59.5 the factor of the next day.

The three-argument forms with an explicit time zone are not affected either way: isKeyPossiblyWrappedByMonotonicFunctionsImpl rejects any chain link with more than two arguments, so they never enter the monotonic chain and KeyCondition leaves the atom unknown. 05229 pins that.

Not covered here: toHour (factor ToDateImpl<>) and, through the clamped ToStartOfHourImpl/ToStartOfMinuteImpl factors, toMinute and toSecond have the same pre-epoch DateTime64 factor defects. They are a separate family (IFunctionDateOrDateTime) and will be handled in a follow-up.

Tests: 05227 (time zone and the week_mode axis), 05228 (extended carriers and the negative fraction), 05229 (explicit time zone), 05230 (the recovered multi-day pruning, in every mode).


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

Version info

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

```sql
CREATE TABLE tz (dt DateTime('Asia/Tokyo')) ENGINE = MergeTree ORDER BY dt;
INSERT INTO tz SELECT toDateTime('2026-08-09 10:00:00', 'UTC') + 3600 * number FROM numbers(11);

SELECT countIf(toDayOfWeek(dt) = 7) FROM tz;      -- 5
SELECT count() FROM tz WHERE toDayOfWeek(dt) = 7; -- 0, rows dropped by pruning
```

`IFunctionCustomWeek::getMonotonicityForRange` compared its `ToMonday` /
`ToStartOfYear` factor in `DateLUT::instance()` - the session time zone - while
the function itself is executed with the time zone taken from its argument's
type (`extractTimeZoneFromFunctionArguments`). A key range that lies inside one
week of the session time zone can straddle a week boundary of the column's time
zone, where `toDayOfWeek` drops from 7 to 1. The range was claimed monotonic
anyway, so `KeyCondition` mapped it to an inverted, empty range and pruned
granules holding matching rows.

The single-argument date/time family already reads the time zone from the
argument type in `IFunctionDateOrDateTime::getMonotonicityForRange`; the
custom-week family now does the same. The comment claiming that the non-local
time zone does not matter here was stale.

Closes: #117696

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [dc88b28]

Summary: ✅


AI Review

Summary

This PR fixes toDayOfWeek monotonicity analysis so range pruning uses the argument's effective time zone and a factor that stays sound for Sunday-first week_modes and extended Date32/DateTime64 carriers. I re-checked the current diff, the added stateless regressions, and all prior review discussion; the addressed issues are indeed fixed in the current code, and I did not find a remaining correctness or safety problem in scope.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

⚠️ No coverage measurement for commit dc88b28: incomplete coverage measurement: 1 of 21 shard profiles are missing: LLVM_COVERAGE_FILE_it_3.profdata.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 7, 2026
Comment thread src/Functions/IFunctionCustomWeek.h Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... label Sep 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing dc88b2830 with master d046101ce (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.

Compile time of recompiled translation units

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

Job report

`toDayOfWeek` numbers Sunday lowest in the Sunday-first modes (2 and 3), so a
range inside one Monday-week is not monotonic there, while the factor transform
of the function was `ToMondayImpl` - and the `mode`, a constant argument, is not
visible to `getMonotonicityForRange`. `toDayOfWeek(d, 3) = 1` over a `Date` key
therefore lost the Sunday row: the part was discarded by the statistics and
primary-key analysis that trusted the claim.

The factor is the day now, as `ToHourImpl` already does: the day of the week is
constant within a day for every mode, so the claim holds, and a range inside one
day - the common case for a granule - still prunes.

Closes: #117696

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed. The mode axis is real: toDayOfWeek numbers Sunday lowest in modes 2 and 3, so a range inside one Monday-week is not monotonic there while the factor transform was ToMondayImpl. toDayOfWeek(d, 3) = 1 over a Date key lost the Sunday row - the part was discarded, in that repro by the statistics analysis rather than the primary key.

Threading the constant mode into getMonotonicityForRange would need a function base that carries the constant arguments (the FunctionBinaryArithmeticWithConstants pattern), so instead the factor is now the day, as ToHourImpl already uses: the day of the week is constant within a day for every mode, so the claim holds for all of them, and a range inside one day - what a granule usually is - still prunes. A range that spans days but stays inside one Monday-week no longer prunes, which is the narrow case that claim covered.

Covered by four assertions in 05143 over a Monday-to-Sunday range: modes 3, 2, the default, and mode 1.

Comment thread src/Functions/DateTimeTransforms.h Resolved
`ToDayOfWeekImpl::FactorTransform` was `ToDateImpl<>`, which is not a
day-number-preserving transform on the extended carriers.

`default_date_time_overflow_behavior` is `Ignore`, so `ToDateImpl<>::execute`
narrows the day number with a bare `static_cast<UInt16>`. That aliases it
modulo 65536: `1970-01-01` (day 0) and `2149-06-07` (day 65536) get the same
factor, so a `Date32` or `DateTime64` range spanning them was reported
monotonic even though `toDayOfWeek` wraps many times inside it. The derived
range was `[4, 6]` and the granule holding a matching Monday was pruned away.

`ToDateImpl<>` also has an `execute` overload taking the decimal components of
a `DateTime64`, which `TransformDateTime64` prefers over its own fallback - and
that fallback is what rounds a negative value down. The factor therefore read
the whole part truncated towards zero, so a pre-epoch value at `23:59:59.5` got
the factor of the *next* day. A range from such a Sunday into the following
Monday looked monotonic, and because the claim is an increasing one the derived
range ran backwards, from `7` to `1`, and discarded every row.

`ToDate32Impl` has neither an `executeExtendedResult` nor a decimal-components
overload, so `extendedFactorForMonotonicity` and `TransformDateTime64` both
land on `execute(Int32)` / `execute(Int64)` and keep the exact - and, before
the epoch, floor-rounded - day number. For a `Date` or `DateTime` key the two
factors return the identical day number, so pruning there is unchanged.

Covered by `05144_day_of_week_monotonicity_extended_dates`: the `Date32` and
`DateTime64` aliasing, the negative-fraction range in the two modes that number
Sunday above Monday, and a single-day positive control that still prunes under
`force_primary_key = 1`. All six regression assertions return `0` without this
change.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Comment thread src/Functions/IFunctionCustomWeek.h Resolved

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Sep 8, 2026
…or the key

A review asked whether the three-argument forms - `toDayOfWeek(dt, mode, 'Asia/Tokyo')`,
`toStartOfWeek(dt, mode, 'Asia/Tokyo')` - can still prune wrongly, because the monotonic
function chain of `KeyCondition` carries at most one constant argument, so dropping the
`week_mode` and `timezone` constants would map the key bounds by the default-mode,
session-time-zone function.

They cannot: `isKeyPossiblyWrappedByMonotonicFunctionsImpl` rejects any chain link with more
than two arguments, so such an atom never enters the chain and `KeyCondition` reports
`Condition: true` for it. The new test pins that, over the shape the review named - a
`DateTime('UTC')` range that stays inside one UTC day but crosses midnight in the explicit
time zone - for `toDayOfWeek`, `toStartOfWeek`, `toLastDayOfWeek` and `toYearWeek`. The last
three claim monotonicity unconditionally, so they are the case that would prune: with the
time zone dropped the range maps to the UTC week of `2026-08-03` and none of the needles falls
inside it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

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

This fixes the pre-epoch DateTime64 factor truncation only for toDayOfWeek. What about toHour, toMinute and toSecond, those still have the issue right??.

Also the PR description mention toWeek and toStartOfWeek as fixed, and neither was affected.

Comment thread src/Functions/DateTimeTransforms.h Resolved
alexey-milovidov and others added 3 commits September 17, 2026 16:18
…yOfWeek` factor

`toDayOfWeek` is monotonic on a range iff the range stays inside one week in
the ordering of its `week_mode`: a Monday-week for modes 0 and 1, a Sunday-week
for modes 2 and 3. The previous round made the factor the day, which holds for
every mode but gives up pruning for any range that spans a day boundary. The
new `ToDayOfWeekFactorImpl` pairs both weeks instead: two days share the factor
iff they lie in the same Monday-to-Saturday run or on the same Sunday, so a
range inside such a run - up to six days - still prunes for every mode, and the
ranges that straddle a Sunday boundary, where the Sunday-first modes run
backwards, do not.

The factor is the unclamped day number of the Monday (or of the Sunday itself),
so the `UInt16` aliasing of `toMonday`/`toDate` on the extended carriers does
not come back, and it has no `DecimalComponents` overload, so `DateTime64` is
rounded down to the day before the epoch as well. `05228` keeps pinning both.

`05230` pins the recovered pruning with `max_rows_to_read` over a
one-row-per-granule week, in all four modes, and `05227` gains a `toWeek`
year-boundary case that shows the time zone half of the fix also matters for
`toWeek` (its factor is the start of the year).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Both points are right, thanks.

toHour, toMinute and toSecond: yes, they still have the pre-epoch DateTime64 factor defects. toHour uses ToDateImpl<> (the UInt16 aliasing plus the truncation towards zero of the whole part), and toMinute/toSecond use ToStartOfHourImpl/ToStartOfMinuteImpl, whose DecimalComponents overloads clamp every pre-epoch value to 0, so all pre-epoch hours share one factor. They belong to the IFunctionDateOrDateTime family rather than the custom-week one, so I have kept them out of this PR and noted them in the description as a follow-up.

toWeek / toStartOfWeek: toStartOfWeek (and toLastDayOfWeek, toYearWeek) use ZeroTransform and were never affected; the changelog entry now names only toDayOfWeek and toWeek. toWeek is affected by the time zone half of the fix, since its factor is the start of the year: 05227 gained a case where Tokyo enters 2026 at 15:00 UTC on 2025-12-31 and toWeek drops from 52 to 0 inside one UTC day, which pruned every row before the fix.

Also in this push: the factor now pairs the Monday-week and the Sunday-week as suggested in the inline thread (ToDayOfWeekFactorImpl), the tests are renumbered to 05227-05230 because 05144/05145 were taken on master, and master is merged.

Comment thread src/Functions/IFunctionCustomWeek.h Resolved
alexey-milovidov and others added 4 commits September 23, 2026 23:27
`ToWeekImpl::hasMonotonicity` is `false` (#90240), so
`KeyCondition` never asks `toWeek` for its monotonicity on a range and this change cannot alter its
pruning. The `toWeek` cases did not exercise the fix; only `toDayOfWeek` is affected.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
#117683 declined monotonicity for `toDayOfWeek` with a
Sunday-first mode in `FunctionWithOptionalConstArg`, because the factor transform was `ToMondayImpl`.
This branch replaces that factor with `ToDayOfWeekFactorImpl`, which pairs the Monday-week with the
Sunday-week and is sound for every mode, so the carve-out is redundant and only disabled the pruning
that `05230` pins for modes 2 and 3. `05186` keeps checking that no row is lost; its last assertion
now checks that both numberings prune.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 2, 2026
Merged via the queue into master with commit a8d6661 Oct 2, 2026
150 checks passed
@alexey-milovidov
alexey-milovidov deleted the custom-week-monotonicity-timezone-117696 branch October 2, 2026 23:51
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 2, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... 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.

toDayOfWeek over a timezone-carrying DateTime primary key silently drops rows (monotonicity computed in server timezone, values in column timezone)

3 participants