Skip to content

Range-check a UInt64 constant converted to DateTime - #118367

Merged
alexey-milovidov merged 1 commit into
masterfrom
datetime-set-constant-range-117244
Sep 6, 2026
Merged

alexey-milovidov merged 1 commit into
masterfrom
datetime-set-constant-range-117244

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

A DateTime stores a UInt32, so a UInt64 constant that does not fit it cannot equal any value of the column. The conversion took such a constant unchanged - UInt64 is the canonical Field type of DateTime, so it looked like nothing had to be done - and the column insertion downstream truncated it modulo 2^32:

CREATE TABLE t (dt DateTime('UTC')) ENGINE = MergeTree ORDER BY dt;
INSERT INTO t VALUES (0), (1), (2);

SELECT count() FROM t WHERE dt = toUInt64(4294967296);         -- 0
SELECT count() FROM t WHERE dt IN (toUInt64(4294967296));      -- 1, was wrong: matched the epoch row
SELECT count() FROM t WHERE dt NOT IN (toUInt64(4294967296));  -- 2, was wrong: a row lost

-- every equality is individually false, and the OR -> IN rewrite returned all rows:
SELECT count() FROM t
WHERE dt = toUInt64(4294967296) OR dt = toUInt64(4294967297) OR dt = toUInt64(4294967298);  -- 3, was wrong

The Date, Date32 and Time branches next to it already range-check for the same reason; DateTime now does too. A constant outside the range is excluded from a set, as an out-of-range integer for a numeric column already was.

One note on the values path: the issue asks for values('x DateTime', toUInt64(4294967296)) to produce what CAST produces (a wrapped 2106-02-07 06:28:15). It now raises ARGUMENT_OUT_OF_BOUND instead, which is what that path already does for Date, Date32 and even UInt8 - values('x UInt8', toUInt64(256)) has always been an error while CAST wraps. Rejecting it keeps DateTime consistent with every other type there.

Closes: #117244

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 a UInt64 constant that does not fit UInt32 matching an unrelated row of a DateTime column in IN (and in an OR chain of equalities, which is rewritten into IN): the constant was truncated modulo 2^32 instead of being excluded from the set.


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

A `DateTime` stores a `UInt32`, so a `UInt64` constant that does not fit it
cannot equal any value of the column. The conversion took such a constant
unchanged - `UInt64` is the canonical `Field` type of `DateTime`, so it looked
like nothing had to be done - and the column insertion downstream truncated it
modulo 2^32:

    SELECT count() FROM t WHERE dt = toUInt64(4294967296);        -- 0
    SELECT count() FROM t WHERE dt IN (toUInt64(4294967296));     -- 1: matched the epoch row
    SELECT count() FROM t WHERE dt NOT IN (toUInt64(4294967296)); -- 2: a row lost

At default settings the disjunction rewrite turns an `OR` chain of equalities
into `IN`, so a `WHERE` in which every comparison is individually false returned
every row the constants wrapped onto.

The `Date`, `Date32` and `Time` branches next to it already range-check for the
same reason; `DateTime` now does too. A constant outside the range is excluded
from a set, as an out-of-range integer for a numeric column already was, and the
`values` table function rejects it the way it rejects one for `Date` or `UInt8`.

Closes: #117244

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

clickhouse-gh Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b50a2a4]

Summary: ✅


AI Review

Summary

This PR fixes the DateTime constant-coercion bug from issue #117244 by routing UInt64 values through an exact UInt32 range check before they reach the set/value materialization paths, so out-of-range constants are excluded instead of wrapping modulo 2^32. The implementation matches that contract, the new stateless test covers the wrong-result IN / NOT IN / OR cases plus the values table function behavior, and I did not find a remaining correctness issue in the current diff.

Missing context / blind spots
  • ⚠️ I could not run the new query locally because this checkout has no build directory or test binary available; Style check and Fast test were green, while the rest of the CI build/test matrix was still in progress on 2026-09-06.
Final Verdict

✅ No findings in the current diff.

LLVM Coverage Report

Measured on commit b50a2a4.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.20% 81.10% -0.10%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Sep 6, 2026
@zlareb1

zlareb1 commented Sep 6, 2026

Copy link
Copy Markdown
Member

TL;DR: the fix itself looks right and fail-safe on every consumer I traced (set members get excluded exactly, values/INSERT throws loudly, and a null Field in KeyCondition degrades to a full read), but the identical truncation survives a few lines below for DateTime64, and the IPv4 branch mishandles the null Field the fix introduces on other paths.

  1. UInt64 → DateTime64/Time64 (same file, the isDateTime64/isTime64 branches): the conversion funnels through FieldVisitorConvertToNumber<Int64>, whose UInt64 arm is a plain wrap, so a value ≥ 2^63 goes negative instead of being rejected — the same class this PR fixes for DateTime. Verified on a recent build: SELECT toDateTime64(-1, 0, 'UTC') IN (toUInt64(18446744073709551615)) returns 1; on a MergeTree table with DateTime64(0) values (-1, 0, 1), WHERE dt NOT IN (toUInt64(18446744073709551615)) returns 2 of 3 rows; and SELECT x FROM values('x DateTime64(0, ''UTC'')', toUInt64(18446744073709551615)) silently inserts 1969-12-31 23:59:59, while after this PR the identical DateTime shape throws ARGUMENT_OUT_OF_BOUND.

  2. UInt64 → IPv4: the branch calls safeGet<UInt32> on the result of the range-checked conversion, so an out-of-range constant that now yields a null Field throws Bad get: has Null, requested UInt64 (code 170) instead of excluding the member: SELECT toIPv4('0.0.0.4') IN (toUInt64(4294967300)) → BAD_GET. Pre-existing, but the same one-line convertNumericType treatment would cover it.

Happy to file the DateTime64 one separately if it's out of scope here.

@clickhouse-gh

clickhouse-gh Bot commented Sep 6, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing b50a2a408 with master 319bfd73f (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

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

Job report

@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 6, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 6, 2026
Merged via the queue into master with commit f2fe533 Sep 6, 2026
174 checks passed
@alexey-milovidov
alexey-milovidov deleted the datetime-set-constant-range-117244 branch September 6, 2026 15:26
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 6, 2026
pull Bot pushed a commit to AnotherGenZ/ClickHouse that referenced this pull request Sep 20, 2026
```sql
SELECT count() FROM t64 WHERE dt = toUInt64(18446744073709551615);        -- 0
SELECT count() FROM t64 WHERE dt IN (toUInt64(18446744073709551615));     -- 1, a row at 1969-12-31 23:59:59
SELECT count() FROM t64 WHERE dt NOT IN (toUInt64(18446744073709551615)); -- 2 of 3 rows, one is lost
```

The `DateTime64` and `Time64` branches of `convertFieldToTypeImpl` funnelled the
constant through `FieldVisitorConvertToNumber<Int64>`, whose `UInt64` arm is a
plain `T(x)`, so a value that does not fit `Int64` wrapped to a negative tick
count and built a set that matches an unrelated pre-epoch row. PR ClickHouse#118367 fixed
this class for `DateTime`; these two branches were left over, as its review
noted.

The number of whole seconds is now range-checked, and its multiplication by the
scale is checked for overflow, so a constant that no `DateTime64` or `Time64`
value can equal yields Null and stays out of the set and out of a key range -
which is what `=` computes on the same data.

Closes: ClickHouse#118437

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. 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

3 participants