Skip to content

Fix wrong primary-key pruning for toStartOfDay and relative-number functions on out-of-range DateTime64 - #110344

Merged
fm4v merged 10 commits into
ClickHouse:masterfrom
groeneai:fix-tostartofday-datetime64-monotonicity-saturation
Aug 28, 2026
Merged

fm4v merged 10 commits into
ClickHouse:masterfrom
groeneai:fix-tostartofday-datetime64-monotonicity-saturation

Conversation

@groeneai

@groeneai groeneai commented Jul 14, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #90461
Related: #108018

Closes #112071

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

Fixed wrong count() results and dropped rows when a DateTime64 primary-key column is filtered through toStartOfDay, toRelativeSecondNum, toRelativeMinuteNum, toRelativeHourNum, toRelativeDayNum, toRelativeWeekNum, toMonthNumSinceEpoch or toYearNumSinceEpoch with values outside the UInt32-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-range DateTime64, breaking primary-key pruning.

Description

The DateTime64 sibling of #108018 (which fixed the same class for Date32).

toStartOfDay and the relative-number transforms have FactorTransform = ZeroTransform, so IFunctionDateOrDateTime::getMonotonicityForRange reports them as always monotonic. Their standard-precision DateTime64 code paths narrowed the result to UInt32/UInt16 without 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:

  • in release builds: silently drops granules holding matching rows, returning a wrong count();
  • in debug/sanitizer builds: trips 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 Date32 key column to DateTime64(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 DateTime64 execute overloads to [0, result-type max], matching the Date32 fix in #108018, keeping each function monotonic over the whole DateTime64 domain. Adds 04538_datetime64_zerotransform_monotonicity_pruning; updates the references of 01768_extended_range, 04408_datediff_datetime64_overflow and 02403_enable_extended_results_for_datetime_functions, which asserted the previous wrapped standard-precision results.

Version info

  • Backported to: 26.8.1.2030

…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT count() FROM t WHERE toStartOfDay(d) >= toDateTime('2000-01-01','UTC') SETTINGS force_primary_key=1 on a DateTime64(5) MergeTree key returns 0 (correct 4); reproduces on demand across all 8 functions.
b Root cause explained? toStartOfDay/relative-num transforms have FactorTransform=ZeroTransform -> getMonotonicityForRange claims is_always_monotonic=true. Their standard-precision DateTime64 execute overloads narrowed to UInt32/UInt16 without saturating, so out-of-range inputs wrapped -> non-monotonic -> PK exact-range analysis produces exact_ranges extending before the mark range -> wrong pruning (release) / chassert(exact_ranges[i].begin >= range.begin) abort (debug/msan).
c Fix matches root cause? Yes. Saturates the DateTime64 overloads to [0, result-type max] so the always-monotonic claim holds; identical mechanism to the merged Date32 fix #108018.
d Test intent preserved / new tests added? New 04538_datetime64_zerotransform_monotonicity_pruning (pk count == countIf for all 8 funcs + trivial-count-projection path). 01768/04408 reference updates reflect the corrected monotonic (saturated) standard-precision results; those tests still exercise their original code paths.
e Demonstrated in both directions? Yes. Pristine binary (build id 5b42d855...): wrong (0 vs 4; 28 vs 22). Fixed binary (7b682248...): correct (4==4, 28==28) for all 8 functions; 04401 Date32 and DateTime in-range unchanged.
f Fix is general, not a narrow patch? Yes. Fixed the whole ZeroTransform-factor family, not just the one fuzzed function: toStartOfDay, toRelativeSecondNum/Minute/Hour/Day/WeekNum, toMonthNumSinceEpoch, toYearNumSinceEpoch (empirically enumerated as the mis-pruning siblings).
g Generalizes across inputs/types? Verified monotonic (non-decreasing) across the full DateTime64 domain incl. pre-1970 and extreme reinterpret values for every one of the 8 functions. DateTime (UInt32), Date, Date32 paths untouched; extended-results (dateDiff/age) paths untouched.
h Backward compatible? Behavior change is limited to out-of-range standard-precision DateTime64 results (previously wrapped, now saturated) — a bug fix identical in kind to #108018, which changed the analogous Date32 outputs without a setting gate or SettingsChangesHistory entry.
i Invariants and contracts preserved? Upholds the getMonotonicityForRange always-monotonic contract for these functions (the invariant that was being violated). No format/lock/ownership changes.

Session id: cron:clickhouse-worker-slot-0:20260714-064400

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @nihalzp @al13n321 — could you review? This is the DateTime64 sibling of #108018: same ZeroTransform-factor functions, same saturation fix, for the out-of-range DateTime64 monotonicity class from #90461. Found by the AST fuzzer.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [23c636c]

Summary: ✅


AI Review

Summary

This PR fixes most of the out-of-range monotonicity breaks around DateTime64/Date round-down and relative-number transforms, and the added regression coverage closes the previously raised DateTime64 and Date gaps. I do not think it is ready to merge yet because the default toStartOfInterval(..., INTERVAL DAY) path still advertises is_always_monotonic = true while preserving wrapped pre-epoch Date32 buckets, so a Date32 primary key can still mis-prune.

Findings
❌ Blockers
  • [src/Functions/toStartOfInterval.cpp:400] [dismissed by author -- https://github.com/Fix wrong primary-key pruning for toStartOfDay and relative-number functions on out-of-range DateTime64 #110344#discussion_r3614593508] The default Date32 INTERVAL DAY path still violates the monotonicity contract that this PR is trying to restore. ToStartOfInterval<IntervalKind::Kind::Day>::execute(Int32, ...) returns a negative second count for pre-1970 buckets, and the default loop here still stores it through saturatingResultCast<false, UInt32>, i.e. a plain narrowing cast. That keeps 04545's distinct wrapped surface values (1969-12-31 and 1970-01-01 stay different), but it also means the function decreases across the epoch boundary while getMonotonicityForRange still returns is_always_monotonic = true. A MergeTree key on Date32 can therefore still mis-prune for predicates such as toStartOfInterval(d, INTERVAL 10 DAY) >= .... The same root cause also affects dateTrunc('day', d) when function_date_trunc_return_type_behavior = 1, because it delegates to this overload. I still consider this real because preserving the old wrapped buckets does not make the function monotonic; it only hides the bug from the non-pruning value test.
    Suggested fix: either saturate the narrowing Date32 -> DateTime result for this carrier too (and update the value tests accordingly), or stop advertising global monotonicity for the unsupported Date32 standard-precision DAY path. If the compatibility surface must stay unchanged, add a focused pruning regression and gate monotonicity on a representable carrier/range instead of the current unconditional true.
Final Verdict

Changes requested: the Date32 default toStartOfInterval(..., INTERVAL DAY) monotonicity hole is still open.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.10% 79.10% +0.00%

Changed lines: Changed C/C++ lines covered: 46/47 (97.87%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 14, 2026
@yariks5s yariks5s self-assigned this Jul 14, 2026
…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks, both paths verified locally against a debug build.

Finding 1 (round-down transforms + toStartOfInterval): confirmed and fixed. With a DateTime64 primary key and enable_extended_results_for_datetime_functions = 0, the pruned count() dropped to 0 (vs 4 true rows) for toStartOfMinute/FiveMinutes/TenMinutes/FifteenMinutes/Hour, timeSlot, and default toStartOfInterval(..., INTERVAL 1 {MINUTE,HOUR,DAY}); INTERVAL 1 WEEK/YEAR (Date result) mis-pruned too (7 vs 6, and 4 vs 6). Fixed in eb6e1bb:

  • ToStartOf{Minute,FiveMinutes,TenMinutes,FifteenMinutes,Hour}Impl and TimeSlotImpl DateTime64 overloads now clamp<Int64>(..., 0, UInt32 max), mirroring toStartOfDay.
  • toStartOfInterval saturates its result store, but only for the narrowing Date (UInt16) and DateTime (UInt32) result types; the wider Date32 (Int32) and DateTime64 (Int64) extended-results paths hold the full range and are left unchanged (verified: ext HOUR 2299-12-31 05:30 -> 2299-12-31 05:00:00, correct).
  • Extended 04538 with above/below-wrap rows for every newly covered function; it fails on the pre-fix binary and passes after.

Finding 2 (toRelativeMonthNum): not affected, no change needed. DateLUTImpl::toRelativeMonthNum is year * 12 + month, but year comes from the LUT, which clamps to [DATE_LUT_MIN_YEAR, DATE_LUT_MAX_YEAR] = [1900, 2299] (findIndex bounds the index). So across the entire representable DateTime64 range the result stays in [22801, 27600], well inside UInt16, and the static_cast<UInt16> never wraps. The 5461-04-01 / 65536-month boundary is unreachable: a DateTime64 argument cannot represent a year beyond 2299. Confirmed empirically (pruned count() == unpruned countIf() == 4 across 1900..2262). The same holds for toRelativeQuarterNum ([7600, 9199]) and toRelativeYearNum ([1900, 2299]).

groeneai added 2 commits July 20, 2026 12:45
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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Follow-up on the widened saturation (pushed e128607): the previous commit's toStartOfInterval cast saturated the narrowing Date/DateTime result for every argument type, which over-reached onto Date/Date32 arguments whose out-of-range interval rounding is already defined in DateLUTImpl. That broke two pre-existing master tests on the merged tree:

  • 04545_tostartof_month_week_day_interval_extreme_overflow (WEEK/DAY on Date32): the clamp collapsed pre-epoch buckets that master expects to floor/round distinctly.
  • 02403_enable_extended_results_for_datetime_functions: separately, the round-down transforms' reference still had the old wrapped 2056-03-09 values for pre-1970 DateTime64.

Fix:

  1. saturatingResultCast is now gated on a DateTime64 argument (std::is_same_v<TimeDataType, DataTypeDateTime64>). Date/Date32/DateTime keep the plain cast, byte-identical to master.
  2. Regenerated the six stale 02403 round-down lines to the correct saturated 1970-01-01 00:00:00, matching the already-correct toStartOfDay row on the same input.

Verified on a local merged-with-master build: 04545 and 04538 pass, 02403 reference is byte-identical to the built binary's output.

Comment thread src/Functions/DateTimeTransforms.h Resolved
/// 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>;

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 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).
@groeneai

Copy link
Copy Markdown
Collaborator Author

Both Date-carrier paths verified against a debug build and fixed in 65c2640.

Finding 1 (ToStartOfDayImpl / ToRelativeSecondNumImpl on the Date carrier): confirmed, fixed. A Date beyond 2106-02-07 (Date max is 2149-06-06) floors to a start-of-day / seconds-since-epoch value that exceeds the UInt32 result, so the execute(UInt16 d, ...) overloads wrapped while getMonotonicityForRange kept reporting always-monotonic. With a Date primary key and enable_extended_results_for_datetime_functions = 0, pruned count() was 1 vs 3 true rows for both. Fixed: both UInt16 overloads now clamp<Int64>(..., 0, UInt32 max), matching the DateTime64 overloads. The other relative-number Date overloads do not wrap (toRelativeMinuteNum maxes at ~94M, toRelativeHourNum at ~1.57M, both well inside UInt32), so only these two needed it.

Finding 2 (toStartOfInterval on the Date / Date32 carriers): split.

  • Date carrier, high side: confirmed and fixed. toStartOfInterval(toDate('2106-02-08'), INTERVAL 1 DAY) wrapped to 1970-01-01 17:31:44 (pruned 1 vs 3 true). The wrap is inside ToStartOfInterval<Day>::execute(UInt16 d, ...) (its own static_cast<UInt32>), not at the result cast, so it is saturated there; the surface value now matches toStartOfDay exactly (2106-02-07 06:28:15). INTERVAL WEEK/MONTH/QUARTER/YEAR on a Date return Date and round down within range, so they do not wrap.
  • Date32 carrier, pre-epoch: not changed, and this is deliberate. A pre-epoch Date32 floors to a negative second value; the standard-precision result type is DateTime (UInt32), which cannot represent negative seconds. Clamping to [0, UInt32 max] would collapse distinct pre-epoch buckets into 1970-01-01, which regresses 04545 (toStartOfInterval(toDate32('1970-01-01'), INTERVAL 10 DAY) != toStartOfInterval(toDate32('1969-12-31'), INTERVAL 10 DAY)). The pre-epoch Date32 value simply is not representable monotonically in the UInt32 codomain, so a correct fix there needs the extended-result path (Date32/DateTime64) or per-range monotonicity, which is a larger change outside this PR's out-of-range-DateTime64 scope. Flagging for @yariks5s: worth a separate issue if the Date32 pre-epoch toStartOfInterval pruning matters.

04538 extended with Date-carrier rows (fails on the pre-fix binary, passes after). 04545, 02403, 04401, 01768, 04408 all pass on a merged-with-master build.

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 006dde1

Every 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 CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Integration tests (amd_asan_ubsan, db disk, old analyzer, 4/6) / test_storage_kafka/test_batch_fast.py::test_kafka_flush_by_time flaky (chronic Kafka batch-flush timing; 6 master/rel + 3 PR hits in 30d, unrelated to this DateTime64 pruning diff) a fix task is created (investigating at full effort; fixing-PR link to follow here)

Session id: cron:our-pr-ci-monitor:20260720-213000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the test_kafka_flush_by_time failure on this PR's CI finish ledger: #112004.

The failure is not caused by this PR and is not a StorageKafka flush race. The assertion that failed is the row-count column, not the flush count: the produce loop built a new KafkaProducer for every message, and one slow broker-version probe cost enough messages to fall short of count() >= 15 while uniqExact(ts) was still correct at 2.

@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 78.20% 78.20% +0.00%

Changed lines: Changed C/C++ lines covered: 31/31 (100.00%) · Uncovered code

Full report · Diff report

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

Copy link
Copy Markdown
Collaborator Author

Merged master. The conflict was in src/Functions/toStartOfInterval.cpp and it was semantic, not textual.

Master gained an arithmetic fast path for SECOND/MINUTE/HOUR intervals (tryExecuteArithmeticRounding). It stores its result with a plain static_cast, which reintroduced exactly the wrap this PR removes: for a DateTime64 past 2106,

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:15

Since the function still reports itself as always monotonic, a DateTime64 primary key could mis-prune again for those three interval kinds. The fast path now takes the same compile-time saturate flag as the generic loop, so both paths agree for every argument type.

One thing worth flagging in master's own 04509_to_start_of_interval_fast_path. Its out of LUT range checks compare toStartOfInterval against the dedicated toStartOf* functions using the standard-precision DateTime result. Every value in those ranges saturates to a bound of that type, so both sides became constant and the check could no longer fail: 80000 of 80000 rows clamped, 2 distinct results. It now runs with enable_extended_results_for_datetime_functions = 1, where the result is a DateTime64 and nothing clamps (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 beforehand.

Also fixed a vacuous check of my own: the trivial-count projection arm of 04538 did not pin optimize_use_projections, which gates the implicit projections and is randomized, and an ordinary read returns the same count. force_optimize_projection cannot cover this because it only throws while a MergeTree read remains in the plan (optimizeTree.cpp:703) and the projection replaces that read, so there is an EXPLAIN assertion on _exact_count_projection instead.

Verified on a merged-with-master debug build (Build ID f3e9108a34ddfbcc7966c1defd06e7f78efdc1d6): 04509, 04538, 04545, 02403, 01768, 04408 and 04356 all pass, and 04538 is green over 15 randomized runs. No submodule pin drift. @ Nikita Fomichev's 02403 reference commit is preserved as an ancestor.

One residual for @yariks5s, unchanged by this merge and not something I want to alter unilaterally: saturating toRelativeSecondNum makes differences collapse where the previous wrap preserved them (toRelativeSecondNum of two values one minute apart in 2200 now differ by 0 instead of 60), because both land on the UInt32 maximum. That follows from the saturation approach chosen in the first commit of this PR rather than from anything here. If you would rather withdraw the monotonicity claim per range than saturate, that is a bigger change than this branch carries.

@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 23c636c4c with master 3662ba8a9 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 691.73 MiB 688.72 MiB -3.01 MiB (-0.44%)

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 units

131 translation units recompiled, 1332 s compile time in total, 131 of them have a recent master baseline.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 23c636c

CI 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 OK with 0 dropped jobs, and every skip carries a real reason (not affected by the changed files, no build-affecting changes, not labeled pr-performance, reused from cache), so the run has genuine coverage rather than a dropped matrix.

Check / test Reason Owner / fixing PR
(none) no check failed on this head -
Sync - CH Inc sync (private, not actionable)

Two notes:

  • The previous ledger covered 006dde1d and owned one failure, test_kafka_flush_by_time. Its fixing PR Fix flaky test_kafka_flush_by_time by reusing one Kafka producer #112004 is merged (2026-07-27) and is an ancestor of this head, and the test does not fail here. That line is discharged.
  • The Stateless tests (amd_llvm_coverage, ...) jobs report internal failures in their summaries while concluding green, because that job class force-sets its own status. Naming them so the green is not taken on trust - 04661_refreshable_mv_cancel_during_planning, 04001_attach_clone_part_level_reset, 03971_rename_tables_race_read_consistency, 04418_create_table_as_select_subquery_access, 04501_distributed_query_client_version_internal_contexts, 04320_url_engine_dispatch_partition_and_format, 04327_s3queue_server_credentials, 04626_create_or_replace_drop_privilege_preflight, 04511_remote_named_collection_complex_overrides, 04541_create_as_select_table_scoped_insert_grant, 04726_kill_undrop_table_busy_wait, 04626_s3_base_setting. Each one passed 3 of 3 reruns under the same randomized settings, none is in this PR's diff, and none touches the datetime saturation path this PR changes, so none is attributable here.

Bugfix validation (functional tests, amd64/aarch64) both pass. Their summaries read Failed: 5, Passed: 0 because the five regression tests here are expected to fail against master HEAD, which is what the job asserts.

Session id: cron:our-pr-ci-monitor:20260813-220000

@clickhouse-gh

clickhouse-gh Bot commented Aug 14, 2026

Copy link
Copy Markdown
Contributor

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.

@nihalzp nihalzp self-assigned this Aug 17, 2026
@groeneai groeneai added the groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding label Aug 19, 2026
@fm4v
fm4v added this pull request to the merge queue Aug 28, 2026
Merged via the queue into ClickHouse:master with commit 3cf20c6 Aug 28, 2026
362 of 363 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 28, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Aug 28, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Aug 29, 2026
…Day and relative-number functions on out-of-range DateTime64
clickhouse-gh Bot added a commit that referenced this pull request Aug 29, 2026
Backport #110344 to 26.8: Fix wrong primary-key pruning for toStartOfDay and relative-number functions on out-of-range DateTime64
@robot-ch-test-poll robot-ch-test-poll added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 7, 2026
@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

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 src/Functions/toStartOfInterval.cpp, because tryExecuteArithmeticRounding does not exist on 26.6 or 26.7. That same hunk holds the constexpr bool saturate declaration while the generic rounding loop that reads saturate merges cleanly, so taking the release side wholesale does not compile, and deleting the use compiles but makes the backport an inert no-op. If either PR is reopened I can supply the resolution as a merge into its backport/26.x/110344 base.

pull Bot pushed a commit to Mu-L/ClickHouse that referenced this pull request Sep 19, 2026
…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]>
opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Nov 6, 2026
…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]>
shankar-iyer pushed a commit to shankar-iyer/ClickHouse that referenced this pull request Nov 9, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding 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.6-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

toStartOfDay(Date) index pruning wrong for large Date values past the DateTime 2106 overflow — the #101814 fix covers only toDateTime

7 participants