Repository navigation
Do not claim toDate and toDateTime are monotonic over a range they wrap - #117394
Conversation
…y wrap
At the default `date_time_overflow_behavior = 'ignore'` the conversion of a
`DateTime64` or `Date32` argument to `Date` or `DateTime` is a plain
narrowing cast, so a value the result type cannot hold wraps around. Both
functions reported themselves as always monotonic anyway, and primary-key
analysis mis-pruned in both directions - matching rows silently disappeared,
and `count()` overcounted through the exact-ranges path:
SET session_timezone = 'UTC';
CREATE TABLE t64 (d DateTime64(3)) ENGINE = MergeTree ORDER BY d
SETTINGS index_granularity = 1, index_granularity_bytes = 0, min_bytes_for_wide_part = 0;
INSERT INTO t64 VALUES ('1900-01-01 00:00:00'),('1969-12-31 23:59:59'),
('2000-01-01 00:00:00'),('2200-01-01 00:00:00'),('2262-04-11 00:00:00');
SELECT count() FROM t64 WHERE toDate(d) >= toDate('2100-01-01'); -- 0, the truth is 1
SELECT countIf(toDate(d) >= toDate('2100-01-01')) FROM t64; -- 1
CREATE TABLE t32 (d Date32) ENGINE = MergeTree ORDER BY d
SETTINGS index_granularity = 1, index_granularity_bytes = 0, min_bytes_for_wide_part = 0;
INSERT INTO t32 VALUES ('1900-01-01'),('1969-12-31'),('2000-01-01'),
('2149-06-06'),('2200-01-01'),('2299-12-31');
SELECT count() FROM t32 WHERE toDate(d) >= toDate('2100-01-01'); -- 5, the truth is 3
SELECT countIf(toDate(d) >= toDate('2100-01-01')) FROM t32; -- 3
The seam was already acknowledged one member up in the same struct:
`ToDateMonotonicity::getPreimage` refuses a non-`DateTime` argument because
"with `date_time_overflow_behavior=ignore` a `DateTime64` or `Date32` source
can wrap and have several disjoint preimages". The guard existed on the
preimage side but was never applied to the monotonicity side.
A range that can wrap is now reported as monotonic only where the conversion
is defined. That still lets `KeyCondition` push a comparison constant through
a key expression such as `PARTITION BY toDate(ts)`, where an unrepresentable
constant is rejected by the dedicated guards in `applyFunctionChainToColumn`,
while it stops `applyMonotonicFunctionsChainToRange` from mapping a key range
through a wrapping conversion. A range that provably converts without
wrapping keeps the full claim, so the index is still used for the ordinary
case - only a range that reaches outside the result type loses pruning.
`03532_key_condition_continuous_range` records one consequence: a chain that
can wrap does not describe an exactly continuous key range, so those queries
now use the generic exclusion search instead of the binary search. That is
the same property whose absence produced the phantom `count()` above.
Closes: #116946
|
Workflow [PR], commit [7422cfd] Summary: ✅
AI ReviewSummaryThis PR correctly hardens the range-mapping side of Findings❌ Blockers
Final Verdict
LLVM Coverage ReportMeasured on commit 7422cfd.
Changed lines: Changed C/C++ lines covered: 38/39 (97.44%) · Uncovered code |
|
Verified the fix shape against master. Two observations from probing the neighboring arms of the same structs:
|
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes8 object files changed (+83.45 KiB total), 0 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units40 translation units recompiled, 263 s compile time in total, 40 of them have a recent master baseline. Median compile-time ratio to the baselines is ×0.93 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio. |
…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.
…he `Date` arm of `toDateTime`
`dateTimeConversionRangeCannotWrap` proved that a range converts without wrapping
against plain UTC limits, but both conversions go through the time zone: `toDate`
takes the local calendar day of a `DateTime64` instant, and `toDateTime` takes the
instant of local midnight of a `Date32` day. So `toDateTime(Date32)` of `2106-02-07`
still fits `DateTime` in `UTC` but wraps in `America/Hermosillo`, and `toDate` of a
late `2149-06-06` UTC instant is already `2149-06-07` in `Pacific/Kiritimati` and
wraps, while the helper still claimed full monotonicity for these ranges.
The time zone is not known to the monotonicity check, but every offset is smaller
than a day in magnitude, so the window is now shrunk by a whole day on each side.
That covers every time zone and only costs pruning for a range that touches the
very edges of the result type.
The `Date` argument of `toDateTime` wraps as well (`Date` reaches `2149-06-06`,
`DateTime` ends in `2106-02-07`: `toDateTime(toDate('2149-06-06'))` is
`2013-04-29 17:31:44`), yet that arm kept an unconditional strict claim. It goes
through the same check now. Primary-key analysis does not push this shape today, so
this only makes the claim truthful, as suggested in the review.
The test gains the two non-UTC boundary cases and the `Date` argument case.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
🕵 @zlareb1 thank you. Point 1 is adopted in c050d53: the One gap remains that I want to leave for a human decision, since it is a trade-off rather than a bug in this PR (master behaves the same). CREATE TABLE probe (ts DateTime64(3)) ENGINE = MergeTree PARTITION BY toDate(ts) ORDER BY ts;
INSERT INTO probe VALUES ('2000-01-01 00:00:00'), ('2120-01-01 00:00:00'), ('2200-01-01 00:00:00');
SELECT count() FROM probe WHERE ts >= toDateTime64('2100-01-01 00:00:00', 3); -- 1, the truth is 2The row from year 2200 lives in a partition whose |
ConvertImpl's if-constexpr chain reaches Enum8/Enum16 as genuine FromDataTypes
(callOnTypeIndex.h maps TypeIndex::Enum8 to DataTypeEnum<Int8>), but the two
special-case branch lists for a date/time target enumerate the concrete integer
and float types and never name the Enums, and IsDataTypeNumber<DataTypeEnum<T>>
is unspecialised, so the IsDataTypeNumber-gated branches miss them too. An enum
source therefore fell through to the generic numeric path and was converted by
a plain static_cast, which is modular rather than saturating:
static_cast<UInt32>(Int8(-1)) is 4294967295.
ToDateTimeMonotonicity meanwhile accepts any source for which
isValueRepresentedByNumber() holds, true for Enum, and returns always-monotonic,
so KeyCondition::applyMonotonicFunctionsChainToRange mapped the key range
through the wrapping conversion with no guard against left > right. A range
spanning zero came out inverted: granules holding matching rows were discarded,
and MergeTreeSetIndex::checkInRange tripped its own begin > end consistency
check, which throws LOGICAL_ERROR under ifndef NDEBUG and returns {true, true}
in release. So the debug abort is the CI signature and the wrong query results
are the release-visible face of one defect.
Adding the two types to the two branch lists makes an enum equivalent to the
integer it is stored as at this seam: same FieldType, same ColumnVector, same
transform instantiation, and the same non-strict Monotonicity the struct already
returns for Int8/Int16, which is right for a saturating many-to-one map. No
monotonicity struct is touched and no new monotonicity semantics are introduced.
This is the design ClickHouse#118717 used for (U)Int128/(U)Int256 against the same defect,
and it restores the invariant ClickHouse#117394 states for numeric arguments.
Measured on 26.8.11.7 (LTS), each enum beside the integer it is stored as:
toDateTime(Enum8('neg' = -1)) 2106-02-07 06:28:15 vs 1970-01-01 00:00:00
toDate(Enum8('neg' = -1)) 2149-06-06 vs 1970-01-01
toDateTime(Enum16('lo' = -32768)) 2106-02-06 21:22:08 vs 1970-01-01 00:00:00
toDate(Enum16('lo' = -32768)) 2059-09-19 vs 1970-01-01
Over a MergeTree table keyed by Enum16('neg' = -1, 'zero' = 0) holding both
members, SELECT count() FROM t WHERE toDateTime(x) = toDateTime(0) returned 0
where the same predicate counted without the index returned 1, and the IN form
aborted a debug build in checkInRange. In-range enum values are unaffected: every
positive member is inside both result ranges.
Four other branch lists name Int8/Int16 and still omit the Enums, and are
deliberately not mirrored here because no carrier was measured behind them:
to Date32 (static_cast<Int32> of Int8/Int16 is exact over the whole enum range),
to Time (Time caps at plus or minus 3599999 seconds, so the whole enum range is
inside it), and to DateTime64 and Time64 (an enum source is rejected with
Code: 70, so the conversion is unreachable).
date_time_overflow_behavior has no effect for an enum source before or after
this change: the GENERATE_OVERFLOW_MODE_CASE switch sits inside a predicate that
is false for Enum, so ConvertImpl is always instantiated with the default Ignore.
Measured under ignore, saturate and throw, an enum agrees with Int8 in all three.
That is the pre-existing family-wide gap ClickHouse#118717's own merged test records, and
it is out of scope here.
05076_datetime_conversion_monotonicity_static_cast is deleted rather than
rebaselined: its wide-integer arms encode the pre-ClickHouse#118717 wrapping semantics, so
four of its reference values now pin behaviour master deliberately changed. The
new 05238_enum_to_datetime_overflow covers the conversion image beside the
integer, in-range controls, the CAST and wrapper forms, the overflow modes, and
the primary-key arms including the one that reproduces the assertion.
Related: ClickHouse#113515
Related: ClickHouse#116946
Related: ClickHouse#118717
Co-Authored-By: Claude Opus 5 <[email protected]>
…ion-monotonicity-wrap-116946
…te`/`toDateTime` `05054_nullable_key_todate_monotonicity` (added on master by the revert of the revert of "Proper partition pruning with dates") failed in Fast test: a `Nullable(DateTime64)` key stores `NULL`s last and index analysis stands them in with `+inf`, so the wrap check rejected every granule touching a `NULL` as unbounded. A range that starts at `+inf` (or ends at `-inf`) holds no finite value, so nothing can wrap: accept it. The granule that mixes real values with a trailing `NULL` still has an unbounded upper side and is still kept, since its real values are not known to fit the result type; the reference of `05054` is updated from 2/10 to 3/10 granules for `toDate` and `toDateTime` (`toDate32` cannot wrap and stays at 2/10). https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117394&sha=21aa02f44ffd0a141e293b51d3640a3ac723807d&name_0=PR&name_1=Fast%20test Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
| * | ||
| * A range that may wrap is reported as monotonic only where the conversion is defined, which is | ||
| * weaker than `is_monotonic`: it still lets `KeyCondition` push a comparison constant through a | ||
| * sorting or partition key expression such as `PARTITION BY toDate(ts)`, where an unrepresentable |
There was a problem hiding this comment.
is_always_monotonic_where_defined is still too strong for key expressions that store the wrapped result themselves. KeyCondition uses this bit to push constants through ORDER BY / PARTITION BY toDate(ts) and toDateTime(d), but with date_time_overflow_behavior = 'ignore' those expressions do not throw outside the safe window at insert time: they wrap and persist the wrapped Date / DateTime key instead. So a query like WHERE ts >= toDateTime64('2100-01-01 00:00:00', 3) can still prune the granule or partition that actually contains 2200-01-01, exactly because the stored key value no longer lies in the “defined subset” this contract assumes. This patch fixes the range-mapping carrier, but it still leaves wrong-result constant pushdown for wrapping key expressions.
To make the contract true, either stop returning is_always_monotonic_where_defined for these conversions on unbounded key-expression ranges, or teach the constant-pushdown path to reject key expressions whose stored values may already be wrapped.
There was a problem hiding this comment.
🕵 Acknowledged; this is the known limitation listed in the PR description and in the earlier PR comment, and it is left for a human decision on purpose. It is not a regression from this PR: master behaves the same way. A stored DateTime64 key value beyond 2149-06-06 wraps silently at insert time under PARTITION BY toDate(ts), so pushing a constant through the expression can still prune that partition. There are two ways to close the gap. One is to drop is_always_monotonic_where_defined for unbounded ranges, which removes partition pruning for PARTITION BY toDate(ts) entirely. The other is to teach KeyCondition constant pushdown to reject key expressions whose stored values may already have wrapped. Either one changes behaviour well beyond this fix, so this PR only fixes the range-mapping path (applyMonotonicFunctionsChainToRange). The thread stays open for the maintainer.
|
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. |
…ion-monotonicity-wrap-116946 Resolve the conflict in `ToDateTimeMonotonicity::get`: master now handles the `Date` and `Date32` arguments of `toDateTime` with its own bounded window, so keep that block and apply this PR's wrap check only to the remaining `DateTime64` argument. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/PRs/117394/2a8b2ab382726dd335c094b86a36ae5ad138c8e3/pr/ast_fuzzer_amd_release_oracle/job.log (NoREC oracle mismatch for |
|
Acknowledged.
I found no existing fix for the NoREC mismatch on |
|
The NoREC mismatch is fixed in #124022. It is not specific to virtual columns: the fuzzer session had |
|
🕵 @groeneai thank you. The current head 7422cfd includes #123738 and its CI is green, so nothing more is needed here for |
…cted optimizeUseNormalProjections narrowed the parent ReadFromMergeTree to the parts the chosen projection does not cover (filterPartsByProjection) and recorded the projection in the query access info before the last point where it can still give up: when the projection stream and the table stream have different headers, the Union path rejects the projection and returns. The projection read was discarded, but the parent read kept the reduced part set, so the parts covered by the projection were read by nobody, and system.query_log.projections named an unused projection. The headers differ with query_plan_remove_unused_columns = 0, which compatibility <= 25.11 sets: on 26.8.10.6, SELECT count() FROM (SELECT a FROM t WHERE b = 5) returned 10 instead of 20 when PROJECTION p (SELECT * ORDER BY b) was added after the first insert. The AST fuzzer found it as a NoREC mismatch on a commit_order projection on PR ClickHouse#117394. Compute has_parent_parts without mutating the parent analysis (filterPartsByProjection keeps exactly the parts in parent_parts), and narrow the parent read and record the projection only after the projection read is wired into the plan, so a rejection has no side effects. Which projection is chosen does not change. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Could this PR get The test's table plus that fuzzed INSERT INTO t_nullable_key SELECT if((number % 3) = 257, NULL, toDateTime64('2026-03-01 00:00:00', 6) + toIntervalHour(number * 65536)), number FROM numbers(40);
SELECT count(), sum(y) FROM t_nullable_key WHERE toDate(x) IN (toDate('2026-03-02'), toDate('2026-03-08'));It aborts on 26.3.54.5, 26.7.33.3, 26.8.30.7, 26.9.21.7 and on master The cherry-picks will conflict: the |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):
Fixed wrong results from primary-key analysis for predicates such as
toDate(dt64_key) >= ...andtoDateTime(date32_key) >= ...: at the defaultdate_time_overflow_behavior = 'ignore'the conversion wraps for values the result type cannot hold, so matching rows silently disappeared andcount()could overcount.Documentation entry for user-facing changes
At the default
date_time_overflow_behavior = 'ignore'the conversion of aDateTime64orDate32argument toDateorDateTimeis a plain narrowing cast, so a value the result type cannot hold wraps around. Both functions reported themselves as always monotonic anyway, and primary-key analysis mis-pruned in both directions — matching rows silently disappeared, andcount()overcounted through the exact-ranges path:The seam was already acknowledged one member up in the same struct:
ToDateMonotonicity::getPreimagerefuses a non-DateTimeargument because "withdate_time_overflow_behavior=ignoreaDateTime64orDate32source can wrap and have several disjoint preimages". The guard existed on the preimage side but was never applied to the monotonicity side.A range that can wrap is now reported as monotonic only where the conversion is defined. That still lets
KeyConditionpush a comparison constant through a key expression such asPARTITION BY toDate(ts), where an unrepresentable constant is rejected by the dedicated guards inapplyFunctionChainToColumn, while it stopsapplyMonotonicFunctionsChainToRangefrom mapping a key range through a wrapping conversion. A range that provably converts without wrapping keeps the full claim, so the index is still used for the ordinary case — only a range that reaches outside the result type loses pruning.The conversions go through the time zone:
toDatetakes the local calendar day of aDateTime64instant, andtoDateTimetakes the instant of local midnight of aDate32day, so the instant that wraps differs between time zones (2106-02-07still fitsDateTimeinUTCbut not inAmerica/Hermosillo; a late2149-06-06instant is already2149-06-07inPacific/Kiritimati). The time zone is not known to the monotonicity check, but every offset is smaller than a day in magnitude, so the proof shrinks the window by a whole day on each side. TheDateargument oftoDateTimewraps as well (Datereaches2149-06-06,DateTimeends in2106-02-07) and goes through the same check, although primary-key analysis does not push that shape today.Known limitation, kept on purpose:
is_always_monotonic_where_definedstill lets a comparison constant be pushed through a wrapping key expression such asPARTITION BY toDate(ts). That is sound when the expression throws outside its window, but a storedDateTime64value beyond2149-06-06wraps silently at insert time, soWHERE ts >= '2100-01-01'can still prune the partition that holds it (see the comment in the PR). The alternative is to report the conversion as not monotonic for an unbounded range, which would drop partition pruning for that shape entirely.03532_key_condition_continuous_rangerecords one consequence: a chain that can wrap does not describe an exactly continuous key range, so those queries now use the generic exclusion search instead of the binary search. That is the same property whose absence produced the phantomcount()above.Closes: #116946
Workflow [PR]
Sync PR [sync-upstream/pr/117394]
Version info
26.10.1.2102-master(included in26.10and later)