Repository navigation
Saturate an Enum8 or Enum16 converted to DateTime or Date - #118039
alexey-milovidov merged 8 commits into
Conversation
… plain cast
ConvertImpl pairs a DateTime target with an order-preserving transform for
Date, Date32, Int8, Int16, Int32, Int64, UInt64, Float32, Float64, BFloat16,
DateTime and DateTime64 only. Every other source type falls through to the
generic `vec_to[i] = static_cast<ToFieldType>(vec_from[i])`, which does not
preserve order: an Enum16 member of -1 becomes 4294967295 while 0 stays 0,
and a wide integer above the 32-bit range wraps to a smaller value.
ToDateTimeMonotonicity claimed monotonicity for all of them anyway, because
its DateTime arm falls back to an unconditional claim for every source whose
isValueRepresentedByNumber is true. applyMonotonicFunctionsChainToRange then
converts both ends of a granule's key range and never re-checks the ordering,
so it returns an inverted range. MergeTreeSetIndex::checkInRange computes
begin > end on it and throws "Invalid binary search result in
MergeTreeSetIndex"; the AST fuzzer hit exactly this on an Enum16 sorting key.
Release builds return {true, true} from that branch instead of throwing, but
the same inverted range reaches comparison atoms, where it silently drops
granules that do contain matching rows. The wrong results therefore occur in
every build, which is why this is a bug fix rather than a CI fix.
Replace the unconditional claim with the allow-list of source types that
actually convert in order, and strip LowCardinality first because several
getMonotonicityForRange callers pass the key column's raw type rather than a
stripped one. Index analysis can only become more conservative as a result.
This mirrors the Time/Time64 target guard in the same struct, which fixed the
same class of defect for a different carrier.
Sources whose monotonicity claim was inert because the conversion itself
throws (Decimal, IPv4, IPv6, Time64) now return no claim as well, which is
strictly safer and changes no observable behaviour.
…order
The previous commit's message said `ConvertImpl` pairs a `DateTime` target with
an order-preserving transform for `Date`, `Date32`, the native integers and
floats, `BFloat16`, `DateTime` and `DateTime64`, and the in-diff comment said
the allow-listed types saturate or fit `UInt32` exactly. That is wrong for
`Date`, `Date32` and `DateTime64`. At the default
`date_time_overflow_behavior = 'ignore'` `ToDateTimeImpl` takes neither its
`Throw` nor its `Saturate` branch and casts a `time_t` above the `UInt32` range
straight through, so `toDateTime(toDate('2149-06-06'))` is
`2013-04-29 17:31:44`, as `02900_date_time_check_overflow.reference` already
records. Those three sources are non-monotonic as well; that is a separate
defect, addressed by ClickHouse#117394 and ClickHouse#117031, and this change leaves them alone.
The allow-list itself is unchanged and remains correct. It declines the source
types that have no dedicated `DateTime` branch at all and are narrowed by a
plain `static_cast`, which is the defect the fuzzer hit. Only the justification
was overstated, and the comment now states what the allow-list is instead.
`index_granularity = 1` with `index_granularity_bytes = 0` is what makes the granule count equal the row count whatever the runner randomizes, so the assertions read the monotonicity decision rather than a granule layout. `min_bytes_for_wide_part = 0` is load-bearing for a less obvious reason, so it now says so. `index_granularity_bytes = 0` turns off adaptive granularity, and `MergeTreeData::canUsePolymorphicParts` then reports a reason whenever `min_rows_for_wide_part` or `min_bytes_for_wide_part` is not zero, because parts with non-adaptive granularity can be stored only in Wide format. The test runner randomizes `min_bytes_for_wide_part` over `[0, 1 GiB]`, and it fails a run on any server warning, so without the pin 37 of 50 runs failed on that warning with correct query results; with it, 50 of 50 pass.
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex), two rounds.
Round 2 re-review of the resulting tree: no findings. Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-9:20260904-093500 |
|
Workflow [PR], commit [1dc0b83] Summary: ✅
AI ReviewSummaryThis PR correctly reroutes ordinary Findings
Tests
Final Verdict
LLVM Coverage ReportMeasured on commit 1dc0b83.
Changed lines: Changed C/C++ lines covered: 2/2 (100.00%) · Uncovered code |
|
cc @nihalzp @hanfei1991, could you review this? |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units61 translation units recompiled, 464 s compile time in total, 61 of them have a recent master baseline. |
|
@groeneai please update your branch with master |
…time-static-cast-monotonicity
|
Updated: merged |
CI finish ledger - 3976352Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260908-013052 |
|
Master has fixed most of what this PR guards, so I am reducing the diff rather than just resolving the conflict. #118717 (merged 2026-09-13) makes
Of the 7 source types this PR rejects, 4 (the wide integers) are now order-preserving, so the guard would remove their primary-key pruning:
The PR's own test agrees: run against plain master, both I will reduce this to the |
…time-static-cast-monotonicity # Conflicts: # src/Functions/FunctionsConversion.h
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]>
toDateTime is monotonic for source types it narrows by a plain castEnum8 or Enum16 converted to DateTime or Date
Internal second-model review: adjudication log (click to expand)Pre-publication review of the reduced diff (3 files,
Two checks produced no finding, recorded so they are not re-derived. Merged #118717 also edited Severity: ❌ blocker / |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-7:20260922-130700 |
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118039&sha=377c4dfccf135d9c5f489fbe61f38725b1847d55&name_0=PR&name_1=Storage%20memory%20check and provide a fix in a separate PR. If the fix is already in progress, link it here. The only red is |
|
Investigated. No new PR from me: #121364 is exactly this failure, already open and approved. Per-stack, on the failing head Not attributable to any diff, at byte level: the pair Fix presence:
|
CI finish ledger - 377c4dfEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
176 checks, all completed: 134 success, 39 skipped, 1 failing job (the two remaining reds are the Session id: cron:our-pr-ci-monitor:20260922-230208 |
CI finish ledger - a61d971Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
One honest qualification on that owner, because it changes what to expect, and it is measured Session id: cron:our-pr-ci-monitor:20260923-163416 |
Related: #113515
Related: #116946
Related: #117394
Related: #118717
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed wrong results when an
Enum8orEnum16value is converted toDateTimeorDate. A negative member wrapped instead of saturating like theInt8/Int16it is stored as, sotoDateTimeof an enum returned a far-future timestamp and primary-key analysis discarded granules that did contain matching rows.Description
On 26.8.11.7 (LTS), over a
MergeTreetable keyed byEnum16('neg' = -1, 'zero' = 0)holding bothmembers,
SELECT count() FROM t WHERE toDateTime(x) = toDateTime(0)returns 0, while the same predicatecounted without the index returns 1. Measured there, each enum member beside the integer it is stored as:
toDateTime(-1)2106-02-07 06:28:151970-01-01 00:00:00toDate(-1)2149-06-061970-01-01ConvertImpl's branch lists for those two targets name the concrete integer and float types but not theEnums, so an enum fell through to the generic numeric path, where a negative value wraps rather than
saturates, while index analysis was still told it is monotonic. This adds
Enum8/Enum16to both lists,so an enum takes the same saturating transform its
Int8/Int16already uses. No monotonicity struct istouched: once the conversion saturates, the non-strict monotonicity it claims holds again. That is the
design merged #118717 used for
(U)Int128/(U)Int256against the same defect. The wrong value aboveneeds no index at all, so it is a defect separate from the monotonicity declaration itself (#117394).
The inverted range also aborts a debug build in
MergeTreeSetIndex::checkInRange, which is how CI foundit: this
AST fuzzer (amd_debug)job,over a fuzzer-mutated
Enum16key. The new test reproduces it withWHERE toDateTime(x) IN (toDateTime(0), toDateTime(1)).Date32,Time,toUnixTimestampand in-rangeenum values are unaffected.
One thing I left out, yours to call:
accurateCast(Enum8('neg' = -1), 'DateTime')returns a value insteadof throwing
Code: 70as it does fortoInt8(-1), becausecan_apply_accurate_castexcludes Enum. Thatpredicate is target-agnostic, so changing it alters
accurateCastof an enum to every numeric target.Happy to do it here or separately.
Workflow [PR]
Sync PR [sync-upstream/pr/118039]
Version info
26.10.1.1127-master(included in26.10and later)