Repository navigation
Decide week-function monotonicity in the time zone of the argument - #118655
Conversation
```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]>
|
Workflow [PR], commit [dc88b28] Summary: ✅
AI ReviewSummaryThis PR fixes Final Verdict
LLVM Coverage Report |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units133 translation units recompiled, 1016 s compile time in total, 133 of them have a recent master baseline. |
`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]>
|
Addressed. The mode axis is real: Threading the constant Covered by four assertions in |
`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]>
…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
left a comment
There was a problem hiding this comment.
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.
…icity-timezone-117696
Co-Authored-By: Claude Fable 5.1 <[email protected]>
…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]>
|
🕵 Both points are right, thanks.
Also in this push: the factor now pairs the Monday-week and the Sunday-week as suggested in the inline thread ( |
…icity-timezone-117696
`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]>
…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]>
Closes: #117696
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix rows silently dropped by primary-key pruning when
toDayOfWeekis applied to aDateTimecolumn whose time zone differs from the session one, or over aDate32/DateTime64key that leaves theDaterange.toDayOfWeekwith a Sunday-firstweek_modecan use the primary key again.Description
IFunctionCustomWeek::getMonotonicityForRangecompared its factor inDateLUT::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, wheretoDayOfWeekdrops from 7 to 1; the range was claimed monotonic anyway, andKeyConditionmapped 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 withLowCardinality/Nullablealready 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.toWeekdoes not claim monotonicity at all (ToWeekImpl::hasMonotonicityisfalse, #90240), soKeyConditionnever reaches itsgetMonotonicityForRange.toStartOfWeek,toLastDayOfWeekandtoYearWeekuseZeroTransform- they are monotonic everywhere - and were not affected.toDayOfWeekhad a second, independent way to lose rows: its factor transform wasToMondayImpl, a whole Monday-week. Theweek_modeis a constant argument and is not visible togetMonotonicityForRange, and modes 2 and 3 number Sunday lowest, so a range inside one Monday-week is not monotonic there -toDayOfWeek(d, 3) = 1over aDatekey discarded the part holding the matching Sunday. Threading the mode through would need a function base that carries the constant arguments, so the newToDayOfWeekFactorImplpairs 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_modeproblem on master by declining monotonicity for the Sunday-first modes altogether inKeyCondition(FunctionWithOptionalConstArg), based on theToMondayImplfactor. The paired factor makes that carve-out redundant, so it is removed here, and the Sunday-first modes prune again;05186still checks that no row is lost and now checks that both numberings prune.The factor is the unclamped day number, not a
toMonday/toDateresult: those narrow the day number toUInt16, which aliases it modulo 65536 on the extended carriers, so1970-01-01and2149-06-07shared a factor and a range spanning them was reported monotonic; and it has noDecimalComponentsoverload, so aDateTime64is rounded down to the day rather than truncated towards zero, which had given a pre-epoch value at23:59:59.5the factor of the next day.The three-argument forms with an explicit time zone are not affected either way:
isKeyPossiblyWrappedByMonotonicFunctionsImplrejects any chain link with more than two arguments, so they never enter the monotonic chain andKeyConditionleaves the atom unknown.05229pins that.Not covered here:
toHour(factorToDateImpl<>) and, through the clampedToStartOfHourImpl/ToStartOfMinuteImplfactors,toMinuteandtoSecondhave the same pre-epochDateTime64factor defects. They are a separate family (IFunctionDateOrDateTime) and will be handled in a follow-up.Tests:
05227(time zone and theweek_modeaxis),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
26.10.1.1356-master(included in26.10and later)