Skip to content

Fix toUnixTimestamp monotonicity for Date and Date32 keys - #117709

Merged
alexey-milovidov merged 3 commits into
masterfrom
fix-to-unix-timestamp-date-monotonicity-117400
Sep 13, 2026
Merged

alexey-milovidov merged 3 commits into
masterfrom
fix-to-unix-timestamp-date-monotonicity-117400

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 2, 2026 •

Copy link
Copy Markdown
Member

toUnixTimestamp used ToNumberMonotonicity, which models every conversion to a number as a plain cast of the argument's internal representation. That is right for the toInt*/toUInt* family, but the Date and Date32 arms of toUnixTimestamp multiply the day number by 86400 and wrap the product around UInt32 (see convertToUnixTimestampFromDate), so the conversion reorders values past 2106-02-07 and for negative day numbers.

KeyCondition transformed primary key range endpoints through the function under the unconditional always-monotonic claim, and the statistics-based part pruning consulted the same claim, so both silently dropped granules and parts holding matching rows:

SELECT count() FROM td WHERE toUnixTimestamp(d) >= 2524608000;  -- 0, wrong
SELECT countIf(toUnixTimestamp(d) >= 2524608000) FROM td;       -- 1, correct

toUnixTimestamp now has its own monotonicity, which claims nothing for a Date/Date32 range that reaches the wrapping days and delegates every other argument type to ToNumberMonotonicity. Ranges that stay inside the representable window keep their pruning, which the test asserts.

Closes: #117400

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 to CHANGELOG.md):

Fixed silently missing rows for predicates on toUnixTimestamp of a Date/Date32 primary key or a column with statistics: the conversion wraps around UInt32 for dates after 2106-02-07, but index analysis assumed it was monotonic everywhere.


Workflow [PR]
Sync PR [sync-upstream/pr/117709]

Version info

  • Merged into: 26.9.1.1341 (included in 26.9 and later)

`toUnixTimestamp` used `ToNumberMonotonicity`, which models every conversion to a
number as a plain cast of the argument's internal representation. That is right for
the `toInt*`/`toUInt*` family, but the `Date` and `Date32` arms of `toUnixTimestamp`
multiply the day number by 86400 and wrap the product around `UInt32`, so the
conversion reorders values past 2106-02-07 and for negative day numbers.

`KeyCondition` transformed primary key range endpoints through the function under the
unconditional always-monotonic claim, and the statistics-based part pruning consulted
the same claim, so both silently dropped granules and parts holding matching rows.

`toUnixTimestamp` now has its own monotonicity, which claims nothing for a `Date` or
`Date32` range that reaches the wrapping days and delegates every other argument type
to `ToNumberMonotonicity`.

Closes: #117400
@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b8525ce]

Summary: ✅


AI Review

Summary

This PR replaces toUnixTimestamp's generic numeric monotonicity with a Date/Date32-aware rule so primary-key and statistics pruning stop dropping matching rows around the UInt32 wrap point. The correctness fix looks sound, but the current evidence still leaves the Date32 optimization claim under-tested.

Tests
  • ⚠️ tests/queries/0_stateless/05060_to_unix_timestamp_date_key_wrap.sql now proves pruning retention for Date, but the Date32 half still only checks count() against countIf(). A regression that degraded the new Date32 branch in ToUnixTimestampMonotonicity to "never monotonic" would still return the same rows after a full scan and keep this test green. Add an EXPLAIN indexes = 1 / Granules: assertion for the in-window Date32 predicate, or a focused unit test that exercises ToUnixTimestampMonotonicity::get(DataTypeDate32(), ...).
Final Verdict

Changes requested: the fix itself looks correct, but the Date32 pruning-retention claim still needs a load-bearing test.

LLVM Coverage Report

Measured on commit b8525ce.

Metric Baseline Current Δ
Lines 88.90% 88.90% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.30% 81.30% +0.00%

Changed lines: Changed C/C++ lines covered: 21/24 (87.50%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 2, 2026
@yariks5s yariks5s self-assigned this Sep 2, 2026
@zlareb1

zlareb1 commented Sep 2, 2026

Copy link
Copy Markdown
Member

Verified the boundary arithmetic against the execution path (convertToUnixTimestampFromDate computes static_cast<UInt32>(day * 86400), i.e. the product mod 2^32): day 49710 → 4294944000 fits, day 49711 → wraps to 63104, so the > UInt32::max() / 86400 cutoff is exact, and rejecting left < 0 plus null endpoints covers the Date32 pre-1970 and unbounded-range cases. One point worth stating for the record: the conservative "no claim outside [0, 49710]" shape is not merely cautious, it is necessary for Date32 — the product wraps a second time at day 99421 (99421 * 86400 > 2 * 2^32, and Date32 extends to day 120529), so a segment-wise monotonicity claim for the beyond-boundary region would itself be wrong for ranges crossing that day.

One test nit: the description says ranges inside the representable window keep their pruning, but the test asserts only result equality (count() vs the full-scan truth), which cannot distinguish "pruned" from "read and filtered". A future regression that degrades the struct to never claiming monotonicity would pass silently. An EXPLAIN indexes = 1 assertion (or a read_rows check via system.query_log) on the in-window query would pin the pruning-retention claim down.

The remaining silent-wrong siblings in this family are tracked separately (#116946, #117682, #117697, #117696, #111759) and are orthogonal to this diff.

@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing b8525cec7 with master cf7992904 (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

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×1.11 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +29.3 s (+11%) in total before that adjustment.

Job report

@clickhouse-gh clickhouse-gh Bot added the comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... label Sep 4, 2026
alexey-milovidov and others added 2 commits September 10, 2026 11:10
The "safe window" query only compared `count()` against a full scan, which cannot
distinguish "correct with pruning" from "correct after reading every granule". Add a
`Granules:` assertion for an in-window range, plus the contrasting range that reaches
the wrapping days and therefore keeps every granule.

Verified with a control binary in which `ToUnixTimestampMonotonicity` returns no claim
for `Date`/`Date32`: the in-window query then reads `5/5` granules instead of `4/5` and
the test fails, so the new assertion is load-bearing.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Updated:

  • Merged master (the branch was 5235 commits behind) and addressed the test nit that both @zlareb1 and the AI review raised. The test now asserts the pruning directly with EXPLAIN indexes = 1: an in-window range toUnixTimestamp(d) >= 1000000000 reads Granules: 4/5, while toUnixTimestamp(d) < 1000000000 — whose range reaches the wrapping days — reads Granules: 5/5 even though only two rows match. Verified the new line is load-bearing with a control binary in which ToUnixTimestampMonotonicity makes no claim for Date/Date32: the in-window query then reads 5/5 and the test fails.
  • Thank you for the second-wrap note, @zlareb1 — agreed, and that is exactly why the shape is "no claim at all outside [0, 49710]" rather than a segment-wise claim: for Date32 the product wraps again at day 99421, well inside the Date32 range, so any per-segment claim would be wrong for a range crossing it.
  • On the old reds: the Not-ready Set is passed as the second argument stress failure is Logical error: Not-ready Set is passed as the second argument for function 'A (STID: 0250-41a5) #107619, closed on 2026-09-04 — after that CI run — so the fix is on master and comes in with this merge. Parser memory check failed at Resolve master binary and LLVM Coverage at generate_diff_coverage_report.sh; both are infrastructure failures against the stale base and should also clear on the fresh run.

SETTINGS index_granularity = 1, index_granularity_bytes = 0, min_bytes_for_wide_part = 0;
INSERT INTO t_unix_ts_date32 VALUES ('1900-01-01'), ('2000-01-01'), ('2100-01-01'), ('2200-01-01'), ('2299-12-31');

SELECT count(), (SELECT countIf(toUnixTimestamp(d) >= 4000000000) FROM t_unix_ts_date32) FROM t_unix_ts_date32 WHERE toUnixTimestamp(d) >= 4000000000;

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.

The Date half now proves that an in-window range still prunes, but the Date32 half still only checks result equality after filtering.

That leaves the new Date32-specific branch in ToUnixTimestampMonotonicity effectively unpinned: if src/Functions/FunctionsConversion.h stopped recognizing the Int64 key-range endpoints used for Date32, toUnixTimestamp(d) >= 4000000000 would full-scan every granule and this assertion would still stay green.

Please add a focused pruning assertion for the in-window Date32 case as well, for example an EXPLAIN indexes = 1 / Granules: check on this predicate or a small unit test that exercises ToUnixTimestampMonotonicity::get(DataTypeDate32(), ...).

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Sep 12, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 12, 2026
Merged via the queue into master with commit 46715b2 Sep 13, 2026
175 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-to-unix-timestamp-date-monotonicity-117400 branch September 13, 2026 03:45
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 13, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 14, 2026
The `toUnixTimestamp` half of this branch landed on master independently as ClickHouse#117709,
as a `ToUnixTimestampMonotonicity<T>` template with its own test. Both conflicting
hunks are that half, so master's version is kept here and this branch's non-template
`ToUnixTimestampMonotonicity` and its two instantiations are dropped.

What survives is the range-aware `ToDateTimeMonotonicity<DataTypeDateTime>` block:
the `Date`/`Date32` to `DateTime` conversions are still unfixed on master.
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 14, 2026
Master's ClickHouse#117709 now owns `toUnixTimestamp` monotonicity, including its own regression
test 05060_to_unix_timestamp_date_key_wrap, so the assertions here that name
`toUnixTimestamp` no longer cover code this branch changes. They are removed, along with
the two blocks that existed only for them: the `Nullable(Date)` block, whose `DateTime`
spelling is already correct on master and would therefore assert nothing, and the
`toUnixTimestamp`-only window edges, which 05060 and ClickHouse#117709 own.

The wrapped-sorting-key block keeps its scenario and moves to `toDateTime32`, where it
still reddens: on master `ORDER BY toDateTime32(d)` with a predicate on the raw column
returns 0 of the 20 matching rows, and `force_primary_key = 1` succeeds instead of
raising `INDEX_NOT_USED`.

The day-number window check moves from a free helper into the trait as a local lambda.
The helper's shape existed to be shared with the dropped `toUnixTimestamp` trait; with
one caller left its `max_day_num` parameter is always `MAX_DATETIME_DAY_NUM`, and master's
sibling trait already keeps the equivalent check local to itself.
alexey-milovidov added a commit that referenced this pull request Sep 16, 2026
…ion-monotonicity-wrap-116946

Conflict in `src/Functions/FunctionsConversion.h`: both sides added a block after
`ToNumberMonotonicity`. Kept both: this branch's `dateTimeConversionRangeCannotWrap`
and master's `ToUnixTimestampMonotonicity` from #117709.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

4 participants