Repository navigation
Fix Date32 overflow on toStartOfWeek - #105244
Conversation
|
Workflow [PR], commit [1a1bd7a] Summary: ✅
AI ReviewSummaryThis PR clamps default Missing context / blind spots
Findings
Tests
Final VerdictStatus: Minimum required actions: fix negative fractional |
antonio2368
left a comment
There was a problem hiding this comment.
Probably need to regenerate some references from old tests.
`toStartOfWeek`, `toMonday`, `toLastDayOfWeek`, `toStartOfMonth`, `toLastDayOfMonth`, `toStartOfQuarter` and `toStartOfYear` now clamp pre-epoch rounding results to `1970-01-01` for the `Date` result type instead of overflowing through `UInt16`. Regenerate the reference files of the two pre-existing tests that encoded the old overflowed output. https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=105244&sha=fe0ab6b5fbaf7adc6250f0ee0f9d5306735a9818&name_0=PR&name_1=Fast%20test
The pre-epoch clamp added to `toMonday`, `toStartOfMonth` and `toStartOfYear` is correct for the returned `Date` value, but these impls are also the `FactorTransform` used by `getMonotonicityForRange` for `toDayOfWeek`, `toDayOfMonth`, `toDaysInMonth`, `toMonth`, `toQuarter` and `toDayOfYear`. Clamping the factor collapsed every pre-epoch week/month/year to `0`, so a range spanning several periods was wrongly reported as monotonic, which can make primary-key/partition pruning skip rows that actually match (e.g. `WHERE toDayOfWeek(date32_key) = 5`). Use the unclamped, order-preserving `executeExtendedResult` for the Date32 and DateTime64 factor comparisons (gated by `requires`, falling back to `execute` for factor transforms that do not provide it). The clamp stays on `execute`, so the returned values are unchanged. Adds 04305_date32_pre_epoch_monotonicity covering toDayOfWeek (Date32 and DateTime64), toMonth and toDayOfMonth.
…dResult
`TransformDateTime64::executeExtendedResult` truncated the fractional part of a
negative `DateTime64` towards zero, while `execute` rounds towards negative
infinity. A value in the last fractional second of a day was attributed to the
next day: `toStartOfMonth(toDateTime64('1969-12-31 23:59:59.5', 1))` with
`enable_extended_results_for_datetime_functions = 1` returned `1970-01-01`
while `toMonth` of the same value returns `12`.
This also matters for the monotonicity analysis, which now compares factor
transforms through `executeExtendedResult`: the factor must attribute boundary
values to the same period as the actual execution, otherwise a granule whose
key range crosses a pre-epoch period boundary could be wrongly declared
monotonic and pruned.
`std::max(res, 0)` only fixed the pre-epoch wrap of `toStartOfWeek`,
`toLastDayOfWeek`, `toMonday`, `toStartOfMonth`, `toLastDayOfMonth`,
`toStartOfQuarter` and `toStartOfYear`. A `Date32` value above `2149-06-06`
still wrapped through UInt16: `toStartOfYear(toDate32('2200-01-01'))` returned
`2020-07-27`. This also produced wrong query results through the same
monotonicity mechanism as #106419,
just in the upper range: a `WHERE toStartOfYear(c1) < toDate('1980-01-01')`
filter over a part with post-2149 values pruned rows that match per-row
evaluation.
Use `std::clamp(res, 0, DATE_LUT_MAX_DAY_NUM)` so out-of-range results
saturate to `2149-06-06`, consistent with `ToDateImpl` saturation, keeping the
functions monotonic over the whole `Date32` domain.
|
fable 5 reviewed the PR and pushed two follow-up commits addressing the remaining gaps: 1.
SET enable_extended_results_for_datetime_functions = 1;
SELECT toStartOfMonth(toDateTime64('1969-12-31 23:59:59.5', 1)); -- returned 1970-01-01, while toMonth() of the same value returns 122.
CREATE TABLE repro2 (c1 Date32) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO repro2 SELECT toDate32('2140-01-01') + toIntervalDay(number * 10) FROM numbers(5500);
OPTIMIZE TABLE repro2 FINAL;
SELECT countIf(toStartOfYear(c1) < toDate('1980-01-01')) FROM repro2; -- 365
SELECT count() FROM repro2 WHERE toStartOfYear(c1) < toDate('1980-01-01'); -- 0 (wrong)Now all sites use I also updated the changelog entry in the description to cover the full set of affected functions and the pruning aspect. |
| -- function analysis prunes parts that contain matching rows. `countIf` (per-row evaluation) | ||
| -- is the ground truth and must match. | ||
| DROP TABLE IF EXISTS t_date32_upper; | ||
| CREATE TABLE t_date32_upper (c1 Date32) ENGINE = MergeTree ORDER BY tuple(); |
There was a problem hiding this comment.
This test is meant to prove that the upper overflow no longer breaks pruning, but ORDER BY tuple() leaves the table without a primary key (hasPrimaryKey is false when primary_key.column_names is empty). That means the WHERE queries below do not exercise KeyCondition/monotonicity pruning at all; they can pass by scanning and evaluating every row.
Please make c1 the sorting key, and use a small index_granularity like 04305_date32_pre_epoch_monotonicity, so the WHERE result would fail with the old wrapped toStartOfYear behavior.
The original reproducer: a WHERE filter over `toStartOfYear` of a `Date32` column returned 0 rows when a merge-formed part contained a few pre-1970 values, while `countIf` of the identical expression counted them correctly. #106419
| -- `WHERE expr` must return the same rows that `countIf(expr)` counts. | ||
|
|
||
| DROP TABLE IF EXISTS issue_repro; | ||
| CREATE TABLE issue_repro (c1 Date32) ENGINE = MergeTree ORDER BY tuple(); |
There was a problem hiding this comment.
This reproducer is meant to guard the KeyCondition/monotonic-function pruning bug from #106419, but ORDER BY tuple() leaves c1 out of the primary key (hasPrimaryKey is false for an empty key). The WHERE queries below can pass by scanning the part and evaluating every row, so the test would not fail if the pruning bug came back.
Please sort by c1 and use a small index_granularity (as in 04305_date32_pre_epoch_monotonicity) so the WHERE and countIf checks actually exercise mark pruning over toStartOfYear/toStartOfMonth/toStartOfQuarter.
| else | ||
| { | ||
| const auto components = DecimalUtils::splitWithScaleMultiplier(t, scale_multiplier); | ||
| auto components = DecimalUtils::splitWithScaleMultiplier(t, scale_multiplier); |
There was a problem hiding this comment.
This fixes the Int64-transform branch, but the same DateTime64 floor invariant is still broken for transforms that take DecimalComponents<DateTime64>. For example, toStartOfDay, toStartOfMinute, toStartOfHour, and the five/ten/fifteen-minute variants enter the branch above, where splitWithScaleMultiplier gives whole = 0, fractional = -5 for toDateTime64('1969-12-31 23:59:59.5', 1). Those transforms then round from whole second 0, so toStartOfDay(... ) SETTINGS enable_extended_results_for_datetime_functions = 1 still returns 1970-01-01 00:00:00.0 instead of 1969-12-31 00:00:00.0.
Please normalize negative fractional DateTime64 values before both component and whole-second dispatch, or provide a helper that returns floored components and use it in both execute and executeExtendedResult. Add a regression for at least one component-based transform such as toStartOfDay or toStartOfMinute.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 54/72 (75.00%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 1 line(s) · Uncovered code |
|
Status: everything is green except |
Cherry pick #105244 to 26.4: Fix Date32 overflow on toStartOfWeek
Cherry pick #105244 to 26.5: Fix Date32 overflow on toStartOfWeek
Backport #105244 to 26.4: Fix Date32 overflow on toStartOfWeek
Backport #105244 to 26.5: Fix Date32 overflow on toStartOfWeek
…5244 Backport ClickHouse#105244 to 26.4: Fix Date32 overflow on toStartOfWeek
Closes: #104970
Closes: #106419
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix incorrect results of
toStartOfWeek,toLastDayOfWeek,toMonday,toStartOfMonth,toLastDayOfMonth,toStartOfQuarterandtoStartOfYearforDate32andDateTime64arguments whose result falls outside theDaterange: instead of overflowing into arbitrary dates, results before1970-01-01are now clamped to1970-01-01and results after2149-06-06are clamped to2149-06-06. This also fixes wrong query results (incorrectly pruned parts and granules) when such functions were used inWHEREover aDate32orDateTime64key containing out-of-range values.Version info
26.6.1.59026.5.3.18,26.4.5.25