Repository navigation
Fix wrong primary-key pruning for toStartOfDay and relative-number functions on out-of-range DateTime64 - #110344
Conversation
…nctions on out-of-range DateTime64 The ZeroTransform-factor date/time functions (toStartOfDay, toRelativeSecondNum, toRelativeMinuteNum, toRelativeHourNum, toRelativeDayNum, toRelativeWeekNum, toMonthNumSinceEpoch, toYearNumSinceEpoch) report themselves as always monotonic to the primary index. Their standard-precision DateTime64 code paths narrowed the result to UInt32/UInt16 without saturating, so for arguments outside that range (before 1970 or beyond 2106) the value wrapped and the function was no longer monotonic. This made primary-key pruning drop granules containing matching rows (wrong count()) and tripped the exact_ranges assertion in the trivial-count projection optimization (found by the AST fuzzer, amd_msan). The DateTime64 execute overloads now saturate to [0, result-type max], mirroring the earlier Date32 fix (PR ClickHouse#108018). Adds a regression test and updates the references of two tests that asserted the previous wrapped standard-precision results. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-0:20260714-064400 |
|
Workflow [PR], commit [23c636c] Summary: ✅
AI ReviewSummaryThis PR fixes most of the out-of-range monotonicity breaks around Findings❌ Blockers
Final VerdictChanges requested: the LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 46/47 (97.87%) · Uncovered code |
…me64
The test evaluates `toStartOfDay(toDateTime64('1920-02-02 10:23:33.789', 3, 'UTC'))`
with `enable_extended_results_for_datetime_functions = false`. The reference encoded
the wrapped value `2056-03-09 06:28:16` produced by the old non-saturating
`static_cast<UInt32>`; with saturation the result is now `1970-01-01 00:00:00`.
CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110344&sha=85ceda19dd53ff8a6c8711a1b8af3c7f46155a6d&name_0=PR&name_1=Fast%20test
PR: ClickHouse#110344
… and toStartOfInterval
The same ZeroTransform-factor monotonicity bug fixed for toStartOfDay was still
present in the sibling round-down transforms and in the default toStartOfInterval
overload. toStartOf{Minute,FiveMinutes,TenMinutes,FifteenMinutes,Hour} and timeSlot
narrowed their seconds-valued DateTime64 result to UInt32 with a raw cast, and the
default toStartOfInterval stored its Int64 result into the narrowing Date (UInt16)
and DateTime (UInt32) result columns without saturating. All of these report
is_always_monotonic to the primary index, so for arguments outside the UInt32/UInt16
range the wrapped value broke monotonicity and made primary-key pruning drop (or
over-count) granules with matching rows.
These paths now saturate to [0, result-type max], mirroring the toStartOfDay fix.
For toStartOfInterval the saturation applies only to the narrowing Date/DateTime
results; the wider Date32 (Int32) and DateTime64 (Int64) extended-results paths hold
the full range and are cast through unchanged.
toRelativeMonthNum, toRelativeQuarterNum and toRelativeYearNum were reviewed and do
not need this treatment: their result is derived from the calendar year, which the
DateLUT clamps to [1900, 2299], so the value stays well within UInt16 across the whole
representable DateTime64 range and never wraps.
Extends the 04538 regression test with above/below-wrap rows for the newly covered
functions.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Thanks, both paths verified locally against a debug build. Finding 1 (round-down transforms +
Finding 2 ( |
The default-overload saturating cast added in the previous commit clamped the narrowing Date/DateTime result for every argument type. Date and Date32 arguments never reach the out-of-range wrap the fix targets, and their out-of-range interval rounding is already defined in DateLUTImpl, so clamping there changed correct results (04545 WEEK/DAY on Date32 buckets). Gate the saturation on a DateTime64 argument; other argument types keep the plain cast, byte-identical to master.
The DateTime64 saturation added for toStartOf{Hour,Minute,FiveMinutes,
TenMinutes,FifteenMinutes} and timeSlot now clamps a pre-1970 (negative
epoch-seconds) argument to 1970-01-01 00:00:00 with extended results off,
instead of wrapping to 2056-03-09. This matches the already-correct
toStartOfDay row on the same input. Reference regenerated from the built
binary and verified byte-identical.
|
Follow-up on the widened saturation (pushed e128607): the previous commit's
Fix:
Verified on a local merged-with-master build: |
| /// always-monotonic), so its narrowing standard-precision results (Date/DateTime) must saturate | ||
| /// rather than wrap for out-of-range DateTime64 arguments. Only DateTime64 arguments reach those | ||
| /// out-of-range values; Date/Date32/DateTime rounding is defined in DateLUTImpl and is left intact. | ||
| constexpr bool saturate = std::is_same_v<TimeDataType, DataTypeDateTime64>; |
There was a problem hiding this comment.
This still leaves the monotonicity bug on the Date / Date32 carriers. Here saturate is false for every non-DateTime64 input, but the default overload still returns narrowing DateTime / Date results for those types. For example, toStartOfInterval(toDate32('1969-12-31'), INTERVAL 10 DAY) floors to 1969-12-22 00:00:00, then this branch does a plain static_cast<UInt32> and wraps that negative timestamp above the epoch; toStartOfInterval(toDate('2106-02-08'), INTERVAL 1 DAY) overflows on the high side for the same reason. Since getMonotonicityForRange is still is_always_monotonic = true, a Date / Date32 primary key can still mis-prune here after this patch. Either these narrowing standard-precision results also need saturation (with the expectations updated accordingly), or toStartOfInterval should stop advertising global monotonicity for carriers that cannot represent the rounded value.
…val for out-of-range pruning A Date beyond 2106-02-07 (Date max is 2149-06-06) floors to a start-of-day / seconds-since-epoch value that overflows the UInt32 result, so the UInt16 Date overloads of toStartOfDay and toRelativeSecondNum, and ToStartOfInterval<Day> on a Date argument, wrapped while getMonotonicityForRange kept advertising always-monotonic. A Date primary key could therefore mis-prune. Date is unsigned / epoch-based, so the results are clamped to the UInt32 maximum, matching the DateTime64 carrier already fixed here. Date32 is intentionally left unchanged: its pre-epoch values cannot be represented monotonically in the UInt32 codomain and clamping them would collapse distinct pre-epoch buckets (see 04545).
|
Both Date-carrier paths verified against a debug build and fixed in 65c2640. Finding 1 ( Finding 2 (
|
The round-2 Date/Date32 saturation change added saturatingResultCast as a static free function inside the anonymous namespace. Anonymous-namespace functions already have internal linkage, so clang-tidy readability-static-definition-in-anonymous-namespace rejects the redundant static under warnings-as-errors, failing Build (arm_tidy). Drop the keyword; no behavior change. Co-Authored-By: Claude Opus 4.8 <[email protected]>
CI finish ledger — 006dde1Every failure below has an owner: a fixing PR, or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only
Session id: cron:our-pr-ci-monitor:20260720-213000 |
|
Fixing PR for the The failure is not caused by this PR and is not a |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 31/31 (100.00%) · Uncovered code |
Master gained an arithmetic fast path for toStartOfInterval with SECOND,
MINUTE and HOUR intervals (tryExecuteArithmeticRounding). It writes the
rounded value into the result column with a plain static_cast, which
reintroduces the wrap this branch removes: with a DateTime64 argument
beyond 2106 the fast path produced 2063-11-24 17:31:44 for
toStartOfInterval(toDateTime64('2200-01-01', 5), INTERVAL 1 HOUR) while
the dedicated toStartOfHour saturated to 2106-02-07 06:28:15. The
function still reports itself as always monotonic, so a DateTime64
primary key could mis-prune again for exactly those three interval kinds.
The fast path now takes the same compile-time saturate flag as the
generic loop and routes all three of its stores through
saturatingResultCast, so both paths agree for every argument type.
Master's own 04509_to_start_of_interval_fast_path asserted the wrapped
pre-epoch values. Its "out of LUT range" equivalence checks compare
toStartOfInterval against the dedicated toStartOf* functions using the
standard-precision DateTime result, and every value in those ranges
saturates to a bound of that type, so both sides of the comparison
became constant and the check could no longer fail: measured 80000 of
80000 rows clamped, 2 distinct results. The checks now run with
enable_extended_results_for_datetime_functions = 1, where the result is
a DateTime64 and no clamping occurs (8638 distinct results), and the
pre-epoch values are asserted for both settings. Verified by deleting
master's isTimeInLUTRange escape and confirming the restored checks fail
(0 -> 65685 and 0 -> 87580), which they would not have done before.
Also collapsed the duplicated per-site saturation comments this branch
had accumulated over its review rounds down to the local invariant.
optimize_use_implicit_projections has no effect unless optimize_use_projections is also on, and the functional test runner randomizes the latter. In a run where it was off the check degraded into an ordinary read: it still returned 4, so it passed while no longer exercising the trivial-count projection path that the exact_ranges assertion lives on. Confirmed with EXPLAIN, which shows the projection step only when the setting is pinned.
The check is meant to cover the trivial-count projection path, where the exact_ranges assertion lives, but an ordinary read returns the same count, so it passed whether or not that path was taken. The projection gates are randomized by the test runner, so this happened in practice. force_optimize_projection cannot be used here: it only throws while a MergeTree read is still present in the plan (optimizeTree.cpp checks has_reading_from_mt), and the trivial-count projection replaces that read, so the setting is silently satisfied. An EXPLAIN assertion on _exact_count_projection is used instead; it returns 0 when the gates are off and 1 when the projection is selected.
|
Merged master. The conflict was in Master gained an arithmetic fast path for SELECT toStartOfInterval(toDateTime64('2200-01-01 00:00:00', 5, 'UTC'), INTERVAL 1 HOUR),
toStartOfHour(toDateTime64('2200-01-01 00:00:00', 5, 'UTC'));
-- before: 2063-11-24 17:31:44 2106-02-07 06:28:15
-- after: 2106-02-07 06:28:15 2106-02-07 06:28:15Since the function still reports itself as always monotonic, a One thing worth flagging in master's own Also fixed a vacuous check of my own: the trivial-count projection arm of Verified on a merged-with-master debug build (Build ID One residual for @yariks5s, unchanged by this merge and not something I want to alter unilaterally: saturating |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 units131 translation units recompiled, 1332 s compile time in total, 131 of them have a recent master baseline. |
CI finish ledger - 23c636cCI is fully finished on this head and no check failed: 160 success, 17 skipped, 0 queued or in progress. The praktika report is top-level
Two notes:
Session id: cron:our-pr-ci-monitor:20260813-220000 |
|
Dear @yariks5s, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
3cf20c6
…Day and relative-number functions on out-of-range DateTime64
Backport #110344 to 26.8: Fix wrong primary-key pruning for toStartOfDay and relative-number functions on out-of-range DateTime64
|
The 26.6 and 26.7 legs of this backport did not land, and the automation now records the wave as complete, so re-applying a must-backport label will not restart it. Writing the mechanism down because it is not obvious from the labels.
I measured the conflict on both branches before the close and posted it on those two PRs. There is one real content conflict, in |
…that need not clamp `ToStartOfInterval<Day>::execute(UInt16 d, ...)` clamped its own result into `[0, UInt32::max]`. A transform is passed only the argument value, so it cannot see the result type, and the result type is what decides whether clamping is needed at all: the overload resolver widens the `DAY` result of a `Date` argument from `DateTime` to `DateTime64(0)` when `enable_extended_results_for_datetime_functions = 1`, and `DateTime64(0)` represents the whole `Date` domain exactly. The clamp fired anyway, so the widened column carried the narrow type's saturation boundary. Flooring a `Date` to whole days yields seconds, and 65535 * 86400 = 5,662,224,000 exceeds `UInt32::max`, so every `Date` from 2106-02-08 to 2149-06-06 returned the same instant 2106-02-07 06:28:15 (not even a start of day). Measured: `uniqExact` of the result over those 15825 dates was 1, i.e. the function was constant over the top 43 years of the `Date` domain, so any grouping, joining or filtering on it merged them. The clamp's lower bound bit symmetrically: east of UTC the true start of 1970-01-01 is negative (-32400 in `Asia/Tokyo`) and was replaced by 0, so the widened value rendered as 1970-01-01 09:00:00. This is a two-commit regression of ClickHouse#110344. 5549808 introduced `saturate = std::is_same_v<TimeDataType, DataTypeDateTime64>` on the stated premise that `Date` and `Date32` arguments never reach the out-of-range wrap, which is false for `(Date, DAY)` for the arithmetic above. 65c2640 retracted that but re-established the protection inside the transform rather than at the result-type-aware cast, which is the layering this commit corrects: the transform now reports the true floored value, like its `Date32` sibling overload, and `saturatingResultCast<saturate, FieldType>` clamps when, and only when, `FieldType` is narrow. `Date32` is deliberately left out of the `saturate` predicate. Clamping its pre-epoch values into an unsigned codomain would collapse distinct pre-epoch buckets, which 04545's `DAY` bucket-equality assertions cover, and the `Date32` narrowing question is owned by ClickHouse#117396. The default configuration is unchanged, verified by diffing a 13-carrier probe across the two binaries: `date_trunc('day', <Date>)` at all three `function_date_trunc_return_type_behavior` values (it executes the same instantiation and lands on the new `saturate` term with a `UInt32` field type), `WEEK`/`MONTH`/`QUARTER`/`YEAR`, `Date32`, the origin overload, `toStartOfDay`, `toRelativeSecondNum`, and `DateTime`/`DateTime64` arguments are all byte-identical. Only the widened `Date` + `DAY` results move. The two edits are independently load-bearing, which the tests enforce. Dropping the transform's clamp without extending `saturate` makes 04538_datetime64_zerotransform_monotonicity_pruning fail: the value wraps through `static_cast<UInt32>`, the function stops being monotonic and primary-key pruning drops granules containing matching rows. Extending `saturate` without dropping the clamp leaves the widened result wrong. The new assertions in 04545 emit real values at both settings rather than booleans, so the `= 1` group catches a missing first edit and the `= 0` group a missing second one. Co-Authored-By: Claude Opus 5 <[email protected]>
…e32 range they wrap With the legacy result types (to_start_of_interval_preserves_argument_type = 0, which any compatibility below 26.11 restores, and the only behaviour of every release up to 26.10; for dateTrunc, function_date_trunc_return_type_behavior = 1) a Date32 argument is rounded into Date (WEEK..YEAR) or DateTime (DAY) and stored with a plain cast, so dates before 1970 and after 2149 (2106 for DateTime) wrap. getMonotonicityForRange nevertheless returned is_monotonic and is_always_monotonic unconditionally, so: - KeyCondition mapped mark ranges through a decreasing function and pruned granules wrongly in both directions (ORDER BY d: rows dropped, DESC: kept); - matchesExactContinuousRange derived exact ranges through it, so the exact count path counted rows without the filter, and when a skip index had trimmed the selected ranges at analysis time the exact range ended past the selected one: chassert(exact_ranges[i].end <= range.end) (AST fuzzer, STID 2508-5221); - sort-order propagation treated the rounding as order preserving, so ORDER BY toStartOfInterval(d, ...) returned rows out of order; - KeyCondition pushed a condition on d through a sorting or partition key toStartOfInterval(d, ...), whose stored values wrap, and skipped matching granules and partitions. When the argument, with LowCardinality and Nullable removed, is Date32 and the result type is Date or DateTime, getMonotonicityForRange now rounds both bounds of the range with the same ToStartOfInterval<unit>::execute overload the function executes. The rounding is non-decreasing in that wide type, so the range maps without wrapping iff both rounded bounds fit the result type ([0, 65535] days for Date, [0, UInt32 max] seconds for DateTime in the result's time zone). Then only is_monotonic is claimed for the range; otherwise, and for an unbounded or non-integer bound or a non-constant interval, nothing is claimed. is_always_monotonic is never claimed for these results: the function is not monotonic on its whole domain, and the functions stress test treats is_always_monotonic on some ranges with is_monotonic false on others as broken monotonicity. is_always_monotonic_where_defined is not claimed either: a sorting or partition key toStartOfInterval(d32, ...) stores the wrapped values, so a condition on d pushed through it pruned matching rows (the reasoning of ClickHouse#125960 for toDate). Values, result types and settings do not change: saturating the Date32 values was rejected during the review of ClickHouse#110344 (see ClickHouse#116945), because the legacy setting exists to restore the old results exactly. This re-applies the monotonicity guard of the closed ClickHouse#117396 to the legacy result types that ClickHouse#122129 kept. Cost, legacy mode with a Date32 key only: a range whose rounding wraps is not pruned through the function, and the exact count and ordering optimizations are not used for these narrowing roundings, and a condition on the column is not pushed through such a key expression. Closes ClickHouse#116945 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tive-number transforms
In a time zone east of UTC the Date 1970-01-01 (DayNum 0, the Date default value) starts before
the Unix epoch, e.g. at -3600 s in Europe/Berlin. The UInt16 overloads of ToRelativeHourNumImpl,
ToRelativeMinuteNumImpl, ToRelativeSecondNumImpl and ToRelativeSubsecondNumImpl ignored
ResultPrecision::Extended and narrowed that negative start to UInt32 (minute, hour) or went through
fromDayNum(DayNum), which saturates to the next day and is clamped to UInt32 (second, subsecond):
- dateDiff/age/timeDiff over a Date with units hour..nanosecond were off by 2^32 or by a whole day
for 1970-01-01 east of UTC (Europe/Berlin: dateDiff('second', toDate(0), toDate(1)) = 0,
'minute' = -4294965856), and second-based results were clamped for any Date after 2106-02-07.
- toRelativeMinuteNum (every east zone) and toRelativeHourNum (beyond +12:00) of that day wrapped
to ~2^32 although FactorTransform = ZeroTransform claims always-monotonic, so primary key,
minmax partition and statistics pruning dropped rows and reading in order returned them out of
order.
Give the UInt16 overloads the shape the Int32 (Date32, ClickHouse#108018) and Int64 (DateTime64, ClickHouse#110344)
overloads already have: the extended precision returns the signed Int64 value (unsaturated
fromDayNum(ExtendedDayNum) for second/subsecond), and the standard minute/hour result is clamped
to [0, UInt32 max]. The standard second result was already monotonic and in range and is kept.
Measured over 10 time zones and 1,523 days including every boundary: values change only for
1970-01-01 east of UTC and for second-based dateDiff/age/timeDiff after 2106-02-07. For every Date
in 9 time zones, toRelativeHourNum, toRelativeMinuteNum and the hour..nanosecond dateDiff/age
results now equal the Date32 results for the same day. A stored key or column computed from the
old wrapped value keeps it until it is rebuilt.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Related: #90461
Related: #108018
Closes #112071
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed wrong
count()results and dropped rows when aDateTime64primary-key column is filtered throughtoStartOfDay,toRelativeSecondNum,toRelativeMinuteNum,toRelativeHourNum,toRelativeDayNum,toRelativeWeekNum,toMonthNumSinceEpochortoYearNumSinceEpochwith values outside theUInt32-seconds range (before 1970 or beyond 2106). These functions claim to be always monotonic to the primary index but their standard-precision results wrapped for out-of-rangeDateTime64, breaking primary-key pruning.Description
The
DateTime64sibling of #108018 (which fixed the same class forDate32).toStartOfDayand the relative-number transforms haveFactorTransform = ZeroTransform, soIFunctionDateOrDateTime::getMonotonicityForRangereports them as always monotonic. Their standard-precisionDateTime64code paths narrowed the result toUInt32/UInt16without saturating, so for arguments outside that range the value wrapped and the function stopped being monotonic. This makes primary-key range analysis produce exact ranges that extend before the selected mark range, which:count();chassert(exact_ranges[i].begin >= range.begin)in the trivial-count projection optimization (optimizeUseAggregateProjection.cpp).Found by the AST fuzzer (amd_msan) on a query that mutated a
Date32key column toDateTime64(5):SELECT count() FROM t WHERE toStartOfDay(d) >= toDateTime('2000-01-01 00:00:00','UTC') SETTINGS force_primary_key = 1.Report: https://s3.amazonaws.com/clickhouse-test-reports/PRs/110310/e242401ecdb1e933c8646546bc2f905d4ed106cd/ast_fuzzer_amd_msan/fatal.log
The fix saturates the
DateTime64executeoverloads to[0, result-type max], matching theDate32fix in #108018, keeping each function monotonic over the wholeDateTime64domain. Adds04538_datetime64_zerotransform_monotonicity_pruning; updates the references of01768_extended_range,04408_datediff_datetime64_overflowand02403_enable_extended_results_for_datetime_functions, which asserted the previous wrapped standard-precision results.Version info
26.8.1.2030