Skip to content

Fix Date32 overflow on toStartOfWeek - #105244

Merged
fm4v merged 8 commits into
masterfrom
yarik/fix-toStartOfWeek-with-Date32-overflow
Jun 10, 2026
Merged

fm4v merged 8 commits into
masterfrom
yarik/fix-toStartOfWeek-with-Date32-overflow

Conversation

@yariks5s

@yariks5s yariks5s commented May 18, 2026 •

Copy link
Copy Markdown
Member

Closes: #104970
Closes: #106419

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 incorrect results of toStartOfWeek, toLastDayOfWeek, toMonday, toStartOfMonth, toLastDayOfMonth, toStartOfQuarter and toStartOfYear for Date32 and DateTime64 arguments whose result falls outside the Date range: instead of overflowing into arbitrary dates, results before 1970-01-01 are now clamped to 1970-01-01 and results after 2149-06-06 are clamped to 2149-06-06. This also fixes wrong query results (incorrectly pruned parts and granules) when such functions were used in WHERE over a Date32 or DateTime64 key containing out-of-range values.

Version info

  • Merged into: 26.6.1.590
  • Backported to: 26.5.3.18, 26.4.5.25

@clickhouse-gh

clickhouse-gh Bot commented May 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1a1bd7a]

Summary: ✅


AI Review

Summary

This PR clamps default Date results for several date-rounding functions on out-of-range Date32/DateTime64 values and adjusts monotonicity analysis/tests around the pruning bug. The main implementation direction looks right, but one shared DateTime64 rounding fix is incomplete, and two pruning regressions currently do not exercise the pruning path they are meant to protect.

Missing context / blind spots
  • ⚠️ The latest Praktika report for commit 1a1bd7a57703ca1d23abf32cf94898e58fa2375f was still running/pending in the local ci/tmp/result_pr.json, and this checkout has no local ClickHouse binary, so I could not run the new stateless tests locally. Completed targeted stateless/Fast test results would close this gap.
Findings

⚠️ Majors

  • [src/Functions/TransformDateTime64.h:127] The new negative-fractional DateTime64 floor is applied only in the whole-second fallback branch. Transforms with a DecimalComponents<DateTime64> overload still receive truncated components from splitWithScaleMultiplier, so values like toDateTime64('1969-12-31 23:59:59.5', 1) enter component transforms with whole = 0. That leaves functions such as toStartOfDay, toStartOfMinute, and toStartOfHour rounding from 1970-01-01 under enable_extended_results_for_datetime_functions = 1, violating the same floor-towards-negative-infinity invariant this PR adds for toStartOfMonth.
    Suggested fix: normalize negative fractional DateTime64 values before both component and whole-second dispatch, or introduce a helper that returns floored components and use it from both execute and executeExtendedResult.
Tests
  • ⚠️ [tests/queries/0_stateless/04306_date32_upper_overflow.sql:26] The upper-overflow pruning regression uses ORDER BY tuple(), so c1 is not part of the primary key and the WHERE checks can pass by scanning all rows. Use ORDER BY c1 plus a small index_granularity so the old wrapped toStartOfYear behavior would actually prune a granule/part incorrectly.
  • ⚠️ [tests/queries/0_stateless/04308_date32_pre_epoch_part_pruning.sql:10] The original issue regression has the same gap: ORDER BY tuple() does not exercise KeyCondition/monotonic-function pruning over c1. Make c1 the sorting key and choose granularity/data layout that would fail if pre-epoch rounding poisoned the pruning range again.
  • ⚠️ Add a focused regression for a component-based DateTime64 transform, for example toStartOfDay(toDateTime64('1969-12-31 23:59:59.5', 1)) SETTINGS enable_extended_results_for_datetime_functions = 1, to prove the shared floor fix covers both dispatch paths.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions: fix negative fractional DateTime64 normalization for component-based transforms, add the focused regression, and update 04306/04308 so their WHERE checks exercise primary-key pruning.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 18, 2026
@antonio2368 antonio2368 self-assigned this May 19, 2026

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

Probably need to regenerate some references from old tests.

fm4v added 2 commits June 6, 2026 23:48
`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
Comment thread src/Functions/DateTimeTransforms.h Resolved
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.
Comment thread src/Functions/IFunctionDateOrDateTime.h Resolved
fm4v added 2 commits June 10, 2026 00:13
…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.
@fm4v

fm4v commented Jun 9, 2026 •

Copy link
Copy Markdown
Member

fable 5 reviewed the PR and pushed two follow-up commits addressing the remaining gaps:

1. Round negative DateTime64 towards negative infinity in executeExtendedResult

TransformDateTime64::executeExtendedResult truncated negative fractional DateTime64 values towards zero, while execute rounds towards negative infinity. Since this PR routes the monotonicity factor comparison through executeExtendedResult, a key in the last fractional second before a pre-epoch period boundary was attributed to the next period by the factor while actual execution attributes it to the previous one — a granule like [1964-12-31 23:59:59.9, 1965-08-15] would be wrongly declared monotonic for toMonth and could be pruned for WHERE toMonth(d) = 12. The same rounding bug was already user-visible in the extended-results path on master:

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 12

2. Clamp the upper Date overflow of date rounding functions as well

std::max(res, 0) only fixes the pre-epoch wrap. A Date32 above 2149-06-06 still wrapped through UInt16 (toStartOfYear(toDate32('2200-01-01')) → 2020-07-27), and the wrong-result mechanism of #106419 reproduces identically in the upper range:

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 std::clamp(res, 0, DATE_LUT_MAX_DAY_NUM), saturating to 2149-06-06 (consistent with ToDateImpl saturation), which keeps the functions genuinely monotonic over the whole Date32 domain. The remaining wrapped values in 01921_datatype_date32.reference (2120-… for the 2299-… inputs) are updated accordingly, and both fixes come with regression tests (04306_date32_upper_overflow, 04307_datetime64_pre_epoch_subsecond_monotonicity).

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();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@clickhouse-gh

clickhouse-gh Bot commented Jun 10, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.60% 84.70% +0.10%
Functions 92.30% 92.30% +0.00%
Branches 77.20% 77.30% +0.10%

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

Full report · Diff report

@fm4v

fm4v commented Jun 10, 2026

Copy link
Copy Markdown
Member

Status: everything is green except CH Inc sync, which is red for an external reason: the private unit test MetadataInKeeperTest.TestConcurrentUpdatesFromHints is failing near-deterministically on private master since 2026-06-09 ~19:00 UTC (66 failures across 32 unrelated PRs on the first day, including master runs). Three attempts on the sync PR all failed on this single test; nothing else fails. Tracked in ClickHouse/clickhouse-private#60290 — once that test is fixed on private master, a rerun of the sync job will re-merge master and the check will go green.

@fm4v
fm4v enabled auto-merge June 10, 2026 08:12
@fm4v
fm4v added this pull request to the merge queue Jun 10, 2026
Merged via the queue into master with commit 4e8816f Jun 10, 2026
166 checks passed
@fm4v
fm4v deleted the yarik/fix-toStartOfWeek-with-Date32-overflow branch June 10, 2026 08:31
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 10, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Jun 10, 2026
robot-ch-test-poll added a commit that referenced this pull request Jun 10, 2026
Cherry pick #105244 to 26.4: Fix Date32 overflow on toStartOfWeek
robot-ch-test-poll added a commit that referenced this pull request Jun 10, 2026
Cherry pick #105244 to 26.5: Fix Date32 overflow on toStartOfWeek
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jun 10, 2026
alexey-milovidov added a commit that referenced this pull request Jun 11, 2026
Backport #105244 to 26.4: Fix Date32 overflow on toStartOfWeek
alexey-milovidov added a commit that referenced this pull request Jun 11, 2026
Backport #105244 to 26.5: Fix Date32 overflow on toStartOfWeek
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…5244

Backport ClickHouse#105244 to 26.4: Fix Date32 overflow on toStartOfWeek
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.4-must-backport v26.5-must-backport

Projects

None yet

7 participants