Repository navigation
Do not claim toStartOfInterval is monotonic over a Date32 range it wraps - #117396
alexey-milovidov wants to merge 11 commits into
Conversation
…t wraps
The saturation that keeps `toStartOfInterval` monotonic covers `DateTime64`
arguments only, so a `Date32` argument outside the standard-precision result
range is still narrowed by a plain cast: the day-and-below units store a
negative second count through an unsaturated `UInt32`, and the week-and-above
units wrap `Int32` day numbers in the `UInt16` `Date` result. The function
reported itself as always monotonic anyway, and primary-key analysis
mis-pruned in both directions - matching rows silently disappeared, and
`count()` overcounted through the exact-ranges path:
SET session_timezone = 'UTC';
CREATE TABLE t32 (d Date32) ENGINE = MergeTree ORDER BY d
SETTINGS index_granularity = 1, index_granularity_bytes = 0, min_bytes_for_wide_part = 0;
INSERT INTO t32 VALUES ('1900-01-01'),('1969-12-31'),('2000-01-01'),
('2149-06-06'),('2200-01-01'),('2299-12-31');
SELECT count() FROM t32
WHERE toStartOfInterval(d, INTERVAL 1 DAY) >= toDateTime('2050-01-01', 'UTC');
-- 0, the truth is 2
SELECT count() FROM t32
WHERE toStartOfInterval(d, INTERVAL 1 YEAR) >= toDate('2100-01-01');
-- 5, the truth is 3
`dateTrunc` delegates to the same rounding and carried the same unconditional
claim, so it is fixed alongside. It only needs the check when its result
narrows: at `function_date_trunc_return_type_behavior = 0` a `Date32`
argument widens the result to `Date32`/`DateTime64` instead, and nothing
wraps.
A range that can wrap is now reported as monotonic only where the rounding is
defined. That still lets `KeyCondition` push a comparison constant through a
key expression such as `PARTITION BY toStartOfInterval(d, INTERVAL 1 MONTH)`,
where an unrepresentable constant is rejected by the dedicated guards in
`applyFunctionChainToColumn`, while it stops
`applyMonotonicFunctionsChainToRange` from mapping a key range through a
wrapping rounding. A range that fits the result type keeps the full claim, so
the index is still used for the ordinary case.
Closes: #116945
|
Workflow [PR], commit [f09ad9f] Summary: ✅
AI ReviewSummaryThis PR narrows the monotonicity claims of Findings❌ Blockers
Tests
Final VerdictStatus: ❌ Block
LLVM Coverage ReportMeasured on commit f09ad9f.
Changed lines: Changed C/C++ lines covered: 81/85 (95.29%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes6 object files changed (+76.65 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units8 translation units recompiled, 16 s compile time in total, 8 of them have a recent master baseline. |
…erval-date32-monotonicity-116945
Master gained `05091_rewrite_in_to_join_repeated_alias`, so the test moves to `05176`. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Two things were too coarse.
The shared bound used the `DateTime` cutoff for every narrowing result, but a
`Date` result - what the week-and-above units return - holds day numbers up to
`2149-06-06`, well past the 2106 where the `UInt32` seconds of a `DateTime`
result run out. A `Date32` key range such as `[2107-01-01, 2140-01-01]` does not
wrap through a `Date` result, so it kept no primary-key pruning for no reason.
The bound now follows the result family.
`toStartOfInterval` keyed the check off the argument type alone, but the result
is only narrower for some overloads: with
`enable_extended_results_for_datetime_functions = 1`, and for the `origin`
overload, it is `Date32`/`DateTime64`, which holds the whole `Date32` domain.
It now carries the same result-type context that `dateTrunc` already had, so the
global monotonicity claim survives wherever nothing narrows.
While checking the window, the lower end turned out to be wrong as well: the
week alignment of the rounding starts on `1970-01-05`, so
`toStartOfInterval(toDate32('1970-01-01'), INTERVAL 1 WEEK)` rounds down to
`1969-12-29` and the `UInt16` `Date` result wraps it to `2149-06-04`. A granule
spanning that wrap was mapped as if the rounding were increasing, which pruned it
away entirely - `count()` returned 0 where 4 and 6 rows matched. The window now
starts at the first Monday at or after the epoch.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…erval-date32-monotonicity-116945
…he rounding to the range bounds Address the review threads: the guard was a fixed day-number window per result family, which was both too coarse and too loose. - Too coarse: a year rounding of 2149-12-31 or a month rounding of 2149-06-30 still fits `Date`, and a year or month rounding of 1970-01-01 does not reach back before the epoch, but the shared `[1970-01-05, 2149-06-06]` window rejected those ranges and lost primary-key pruning on them. - Too loose: the `DateTime` bound was only right in UTC. In `America/Hermosillo` the local midnight of 2106-02-07 is already past `UInt32`, so the guard claimed monotonicity over a wrapping range. - `Nullable(Date32)` slipped past both the return-type classification and the argument-type check on tables with `allow_nullable_key`. The check now applies the very rounding the function executes (`toStartOfDayInterval`, `toStartOfWeekInterval`, ...) to both bounds of the range, in the time zone of the result type, and requires both rounded values to fit the result type: the rounding is non-decreasing in the wide type, so this is exact. The `Nullable` and `LowCardinality` wrappers are stripped from both the return type and the key column type. `buildImpl` is reached with unvalidated arguments for a `NULL` argument, so the interval argument is read defensively there.
… and cover the reviewed cases Master took `05176`. The new cases check that a year, quarter or month rounding of a late-2149 or early-1970 `Date32` range is still pruned, that the month rounding of July 2149 wraps and is not mapped through, that a `Nullable(Date32)` key is guarded, and that a day rounding in `America/Hermosillo` is not claimed monotonic over 2106-02-07 while the same range in UTC still is.
…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]>
…erval-date32-monotonicity-116945
…column statistics The `EXPLAIN` checks passed only because the default `minmax` statistic pruned whole parts: with `index_granularity_bytes = 0` there is no final mark, so the primary key alone can never prune the last granule. When `auto_statistics_types` is randomized to a set without `minmax` (e.g. `countmin,tdigest,uniq_v2`), the checks failed in every flaky-check job. Pin `auto_statistics_types = ''` and use an adaptive granularity so the primary key is what is tested. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117396&sha=a95d02696b589251117be5d4d33540752bad6635&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20distributed%20plan%2C%20s3%20storage%2C%20parallel%29 #117396 Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
| /// `enable_extended_results_for_datetime_functions` or with the `origin` overload the result | ||
| /// is `Date32`/`DateTime64` instead, which holds the whole `Date32` domain, so nothing wraps. | ||
| if (date32_narrowing && isDate32IgnoringWrappers(type) && !date32RangeFitsRoundingResult(*date32_narrowing, left, right)) | ||
| return {.is_always_monotonic_where_defined = true}; |
There was a problem hiding this comment.
Using is_always_monotonic_where_defined here is still unsafe for the Date32-narrowing case. KeyCondition::canConstantBeWrappedByMonotonicFunctions accepts that flag under the assumption that rows outside the "defined" subset could never be stored in the key at all (see src/Storages/MergeTree/KeyCondition.cpp:2218-2223), but that assumption does not hold here: toStartOfInterval(toDate32('2149-07-01'), INTERVAL 1 MONTH) still materializes the wrapped Date 1970-01-25 instead of throwing.
That means a table keyed or partitioned by toStartOfInterval(d, INTERVAL 1 MONTH) can contain matching rows whose stored key compares below a perfectly representable comparison constant such as toDate('2100-01-01'). A predicate like d >= toDate32('2100-01-01') can therefore be relaxed to key >= toDate('2100-01-01') and prune the 2149-07-* rows incorrectly. The mirrored dateTrunc branch has the same problem. I think this needs to return plain non-monotonicity for the unbounded case, or the constant-push path needs a separate way to reject wrapped-but-storable outputs.
|
This is wrong, and we should change It should return the same data type as its argument: Date for Date, Date32 for Date32, DateTime64 for DateTime64. |
`toStartOfInterval` chose its result type by the interval unit: `Date` for `WEEK` and longer, `DateTime`
for `DAY` down to `SECOND`. A `Date32` or `DateTime64` argument outside the range of the narrower type was
wrapped, e.g. `toStartOfInterval(toDate32('1900-01-01'), INTERVAL 1 DAY)` returned `2036-02-07 06:28:16`,
and the rounding of a `Date` to days produced a `DateTime`.
Now the result has the type of the argument: `Date` for `Date`, `Date32` for `Date32`, `DateTime` for
`DateTime`, and `DateTime64` of the same scale for `DateTime64`. The value computed by `ToStartOfInterval`
(a day number, seconds, or ticks of a subsecond unit) is converted to the representation of the result type.
For the origin overload with an argument finer than a subsecond unit, the grid anchored at the origin is
computed in the scale of the argument, so the part of the origin finer than the unit is kept.
The old behavior is available with `to_start_of_interval_preserves_argument_type = 0`.
ClickHouse#117396 (comment)
Co-Authored-By: Claude Opus 5.5 (1M context) <[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]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):
Fixed wrong results from primary-key analysis for predicates over
toStartOfIntervalanddateTruncon aDate32key: the rounding wraps for values the narrower result type cannot hold, so matching rows silently disappeared andcount()could overcount.Documentation entry for user-facing changes
The saturation that keeps
toStartOfIntervalmonotonic coversDateTime64arguments only, so aDate32argument outside the range of a narrower result type is still narrowed by a plain cast: the day-and-below units store a negative second count through an unsaturatedUInt32, and the week-and-above units wrapInt32day numbers in theUInt16Dateresult. The function reported itself as always monotonic anyway, and primary-key analysis mis-pruned in both directions — matching rows silently disappeared, andcount()overcounted through the exact-ranges path:The same seam sits just after the epoch, because the week alignment of the rounding starts on
1970-01-05:toStartOfInterval(toDate32('1970-01-01'), INTERVAL 1 WEEK)rounds down to1969-12-29, which theUInt16Dateresult wraps to2149-06-04. A granule spanning that wrap was mapped as if the rounding were increasing and pruned away entirely, socount()returned 0 where 4 and 6 rows matched.dateTruncdelegates to the same rounding and carried the same unconditional claim, so it is fixed alongside.A range that can wrap is now reported as monotonic only where the rounding is defined. That still lets
KeyConditionpush a comparison constant through a key expression such asPARTITION BY toStartOfInterval(d, INTERVAL 1 MONTH), where an unrepresentable constant is rejected by the dedicated guards inapplyFunctionChainToColumn, while it stopsapplyMonotonicFunctionsChainToRangefrom mapping a key range through a wrapping rounding.Everything that does not wrap keeps the full claim, so the index is still used for the ordinary case:
toStartOfYearInterval,toStartOfMonthInterval, ..., in the time zone of the result type) to both bounds of the key range and requires both rounded values to fit the result type; the rounding is non-decreasing in the wide type, so this is exact. A year rounding of[2149-06-07, 2149-12-31]still fitsDateand stays prunable, a week rounding of[1970-01-01, 1970-01-03]reaches back before the epoch and does not, and a day rounding inAmerica/Hermosilloruns out ofUInt32seconds a day earlier than in UTC.NullableandLowCardinalitywrappers on the key type are stripped before the check.enable_extended_results_for_datetime_functions = 1, for theoriginoverload, and fordateTruncatfunction_date_trunc_return_type_behavior = 0, the result isDate32/DateTime64, which holds the wholeDate32domain, and the function stays globally monotonic.Closes: #116945
🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/117396]