Repository navigation
Fix incorrect index pruning for toDateTime(Date) key with large Date values - #101814
Conversation
|
Workflow [PR], commit [7b09dc1] Summary: ✅
AI ReviewSummaryThis PR changes key-condition inference so monotonic function chains are validated against the non-constant child type, and it allows relaxed constant rewrites through Missing context / blind spots
Findings❌ Blockers
Tests
Final VerdictStatus: ❌ Block Minimum required action: make the monotonic-chain rejection cover insert-time stored-key overflow semantics by source/result behavior rather than query setting or function name, and add the focused wrong-result regressions above. |
|
The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix. |
0b12c2d to
832aaf3
Compare
|
Integration test ( DROP TABLE IF EXISTS test;
CREATE TABLE test (d Nullable(Date32))
ENGINE = MergeTree PARTITION BY toRelativeDayNum(assumeNotNull(d)) ORDER BY tuple() SETTINGS allow_nullable_key = 1;
INSERT INTO test VALUES ('1969-12-31');
INSERT INTO test VALUES ('2024-01-20');
INSERT INTO test VALUES ('2024-01-30');
INSERT INTO test VALUES ('2024-02-20');
SELECT count() FROM test WHERE d <= '2024-01-25'; -- returns 1 (incorrect)
SELECT count() FROM test WHERE d <= '2024-01-25' SETTINGS use_partition_pruning = 0; -- returns 2 (correct)
EXPLAIN indexes = 1 SELECT count() FROM test WHERE d <= '2024-01-25'; |
|
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. |
| /// next_node is the non-constant child of cur_node, so next_node->result_type | ||
| /// is the child's output type, which is the input type to cur_node's function. | ||
| if (is_valid_chain) | ||
| is_valid_chain = always_monotonic(*cur_node->function_base, *next_node->result_type); |
There was a problem hiding this comment.
This still lets the unsafe chain through when the SELECT overrides date_time_overflow_behavior away from ignore. The function in cur_node->function_base is the stored sorting-key action, and existing part key values may have been produced with the default ignore behavior, but isFunctionReallyMonotonic consults the query-time KeyCondition setting. With a table using ORDER BY toDateTime(stamp), a query like SELECT count() ... WHERE stamp >= '2024-11-01' SETTINGS date_time_overflow_behavior = 'saturate' makes this always_monotonic check pass for toDateTime(Date), so the wrapped large-Date granule can be pruned again even though the predicate is on stamp. Please reject toDateTime(Date)/toDateTime(Date32) based on the key function behavior, or conservatively reject this reverse rewrite regardless of the current query setting, and add the same regression with a non-ignore query setting.
There was a problem hiding this comment.
Good catch — fixed in ee8fde2.
You're right that gating on the query-time date_time_overflow_behavior is unsafe: the sorting key is materialized at insert time, so a part may hold wrapped (non-monotonic) key values produced under the default ignore behavior while the query runs with saturate or throw. There is no per-part record of the behavior used to build the key.
isFunctionReallyMonotonic now rejects toDateTime(Date)/toDateTime(Date32) regardless of the query-time setting (the date_time_overflow_behavior_ignore flag is removed, as it is no longer consulted anywhere). I verified the exact scenario you described — a table built under the default ignore then queried with SETTINGS date_time_overflow_behavior = 'saturate' — now correctly skips the index (force_primary_key throws INDEX_NOT_USED) and returns the right count. 04078_key_condition_todatetime_date_monotonicity was extended with both saturate and throw regressions.
There was a problem hiding this comment.
Current head still has the query-setting gate here: src/Storages/MergeTree/KeyCondition.cpp:1689 only rejects the chain when date_time_overflow_behavior_ignore is true, and that member is initialized from the query context at src/Storages/MergeTree/KeyCondition.cpp:1354. So SETTINGS date_time_overflow_behavior = 'saturate'/'throw' still skips the rejection for toDateTime(Date) even though stored key values may have been materialized under ignore.
|
Picked this up: merged the latest Addressed the unsafe-rewrite concern ( Tests:
Ran a regression batch of monotonicity / key-condition / date-overflow tests locally — all pass. |
| bool KeyCondition::isFunctionReallyMonotonic(const IFunctionBase & func, const IDataType & arg_type) const | ||
| { | ||
| if (date_time_overflow_behavior_ignore && func.getName() == "toDateTime") | ||
| if (func.getName() == "toDateTime") |
There was a problem hiding this comment.
This guard is too narrow for the invariant being enforced. A key can spell the same conversion as ORDER BY CAST(stamp, 'DateTime') (or the analyzer/internal _CAST form), and FunctionCast exposes the function name as CAST/_CAST while reusing ToDateTimeMonotonicity<DataTypeDateTime>, which still reports Date/Date32 input as always monotonic. That leaves the same insert-time wrapped key values eligible for the reverse rewrite and primary-key pruning, just under a different SQL spelling.
Please reject Date/Date32 -> DateTime conversions based on the conversion result type as well as the function name, or explicitly cover CAST/_CAST to DateTime, and add the same regression with ORDER BY CAST(stamp, 'DateTime').
There was a problem hiding this comment.
Fixed in 5329f8f.
isFunctionReallyMonotonic no longer keys off the function name. It now rejects the conversion by the (argument type -> result type) pair: if the argument is Date/Date32 and the function result is DateTime, it is treated as non-monotonic. This covers toDateTime, CAST(x, 'DateTime'), the analyzer/internal _CAST, accurateCast, and any other spelling that reuses ToDateTimeMonotonicity<DataTypeDateTime>, since they all produce a DateTime result from a Date/Date32 argument.
Verified that ORDER BY CAST(stamp, 'DateTime') now also throws INDEX_NOT_USED under force_primary_key and returns the correct count; added the ORDER BY CAST(stamp, 'DateTime') regression to 04078_key_condition_todatetime_date_monotonicity.
There was a problem hiding this comment.
Current head still keys the rejection on func.getName() == "toDateTime" at src/Storages/MergeTree/KeyCondition.cpp:1689. The type-pair based check described in the reply is not present, so CAST(stamp, 'DateTime'), _CAST, and other spellings that produce DateTime from Date/Date32 are still accepted by this guard.
|
Merged the latest Broadened the overflow guard ( Fixed an Iceberg partition-pruning regression (same commit): the previous revision passed the function Stabilized CI report: #101814 |
| /// under the default `ignore` behavior, while the query runs with `saturate` or `throw`. There is no | ||
| /// per-part record of the behavior used to build the key, so we conservatively never treat | ||
| /// `Date`/`Date32` -> `DateTime` as monotonic for index analysis. | ||
| if (isDateOrDate32(unwrap(&arg_type)) && isDateTime(unwrap(func.getResultType().get()))) |
There was a problem hiding this comment.
This guard still leaves the same unsafe reverse rewrite enabled for toDate(Date32). ToDateMonotonicity<DataTypeDate> reports Date32 input as always monotonic, but ToDateImpl::execute(Int32) under the default ignore behavior narrows with static_cast<UInt16>, so dates after 2149-06-06 wrap in the stored key. For example:
CREATE TABLE test (stamp Date32)
ENGINE = MergeTree ORDER BY toDate(stamp) SETTINGS index_granularity = 1;
INSERT INTO test SELECT '2024-10-30' FROM numbers(3);
INSERT INTO test SELECT '2024-11-19' FROM numbers(3);
INSERT INTO test SELECT '2149-06-07' FROM numbers(3);
OPTIMIZE TABLE test FINAL;
SELECT count() FROM test WHERE stamp >= '2024-11-01';The large Date32 values satisfy the predicate, but their stored toDate key wraps below the lower bound, so the same primary-key pruning path can drop them. Please reject narrowing temporal conversions whose result range is smaller than the source domain (at least Date32/DateTime64 -> Date, and DateTime64/wide numeric -> DateTime) in this source/result-type check, and add a regression for ORDER BY toDate(Date32).
There was a problem hiding this comment.
Good catch — confirmed and fixed in 6c7f00c.
toDate(Date32) narrows to Date (ends 2149-06-06) while Date32 reaches 2299-12-31, so under the default ignore behavior ToDateImpl::execute(Int32) wraps via static_cast<UInt16> and the stored key becomes non-monotonic for large dates, while ToDateMonotonicity still reports Date32 input as always monotonic. isFunctionReallyMonotonic now also rejects the Date32 -> Date pair (same type-pair detection as Date/Date32 -> DateTime, so all spellings are covered), and 04078_key_condition_todatetime_date_monotonicity gains a toDate(Date32) regression. Verified locally: the query returns the correct count and force_primary_key throws INDEX_NOT_USED.
There was a problem hiding this comment.
The Date32 -> Date case is fixed, but the broader narrowing-conversion issue from the original comment is still present for DateTime64. Current code at src/Storages/MergeTree/KeyCondition.cpp:1633-1635 only rejects Date/Date32 -> DateTime and Date32 -> Date; it still accepts DateTime64 -> DateTime and DateTime64 -> Date, while FunctionsConversion.h:2075-2086 converts those through TransformDateTime64<ToDateTimeImpl> / TransformDateTime64<ToDateImpl> and the monotonicity metadata at FunctionsConversion.h:4037-4091 reports them as always monotonic.
That can still prune matching rows, e.g. ORDER BY toDateTime(ts64) with a DateTime64 row in 2140 and WHERE ts64 >= '2100-01-01': the predicate row satisfies the original condition, but the stored DateTime key wraps below the transformed lower bound under the default ignore behavior. Please include at least DateTime64 -> DateTime and DateTime64 -> Date in this type-pair rejection and add regressions for those keys.
There was a problem hiding this comment.
Fixed in 0f2a426.
isFunctionReallyMonotonic now also rejects the DateTime64 -> DateTime and DateTime64 -> Date pairs: DateTime64 spans 1900-01-01..2299-12-31, exceeding both targets, and TransformDateTime64 over ToDateTimeImpl/ToDateImpl wraps pre-epoch (negative) and beyond-maximum values alike under the default ignore behavior, while the monotonicity metadata at FunctionsConversion.h still reports these conversions as always monotonic. The type-pair detection covers all spellings (toDateTime/toDate/CAST/_CAST/accurateCast).
04078_key_condition_todatetime_date_monotonicity gains regressions for both pairs (ORDER BY toDateTime(stamp) with a 2140 row and ORDER BY toDate(stamp) with a 2200 row, both returning the correct count and throwing INDEX_NOT_USED under force_primary_key). 03980_datetime64_preepoch_partition_pruning_explain is updated accordingly: the Partition condition mapped through the narrowing key is no longer built at all — the stored partition values may have wrapped at insert time regardless of the query constant, so the previous constant-value check was insufficient — while the Min-Max index over the raw source column still prunes, leaving the part-level pruning outcomes unchanged. The first query of 02373_datetime64_monotonicity drops its force_* settings since toDateTime over DateTime64 no longer uses the index by design.
There was a problem hiding this comment.
Current head still only rejects func.getName() == "toDateTime" at src/Storages/MergeTree/KeyCondition.cpp:1689. There is no Date32 -> Date or DateTime64 -> Date/DateTime rejection in isFunctionReallyMonotonic; the checks at src/Storages/MergeTree/KeyCondition.cpp:1588-1624 only guard transforming the query constant, so they do not make the stored key function non-monotonic for out-of-range row values.
|
Merged the latest Broadened the overflow guard ( Built and verified locally: both |
…or index analysis `DateTime64` spans 1900-01-01..2299-12-31, exceeding both `DateTime` (~2106-02-07) and `Date` (2149-06-06) on at least one side, so `toDateTime`/`toDate` (and any `CAST` spelling) over a `DateTime64` argument wraps under the default `ignore` overflow behavior while the monotonicity metadata still reports the conversion as always monotonic. `isFunctionReallyMonotonic` now rejects this type pair as well. `04078_key_condition_todatetime_date_monotonicity` gains regressions for both pairs. `03980_datetime64_preepoch_partition_pruning_explain` is updated: the `Partition` condition mapped through the narrowing key is no longer built at all (the stored partition values may have wrapped at insert time regardless of the query constant), while the `Min-Max` index over the raw source column still prunes, so the part-level pruning outcomes are unchanged. The first query of `02373_datetime64_monotonicity` drops its `force_primary_key`/`force_index_by_date` settings, since `toDateTime` over `DateTime64` no longer uses the index by design. Reported in ClickHouse#101814 (comment) Co-Authored-By: Claude Fable 5 <[email protected]>
| return false; | ||
| if (isDate32(arg) && isDate(result)) | ||
| return false; | ||
| if (isDateTime64(arg) && (isDateTime(result) || isDate(result))) |
There was a problem hiding this comment.
This still leaves unsafe DateTime64 -> narrowed numeric date/time transforms accepted as monotonic. IFunctionDateOrDateTime reports ZeroTransform functions as always monotonic for unbounded DateTime64 input, but the standard relative functions store smaller integer keys. For example, toRelativeSecondNum(DateTime64) produces seconds that are stored in the UInt32 result column; a 2140-01-01 value is 5364662400 seconds and wraps to 1069695104, while WHERE ts >= '2024-11-01' transforms the constant to 1730419200, so a granule containing that matching row can be pruned. toRelativeDayNum(DateTime64) has the same problem after the Date day range: 2200-01-01 day 84006 is stored as 18470, below the transformed 2024-11-01 lower bound.
Please also reject DateTime64 chains such as toRelativeDayNum/toRelativeSecondNum whose standard result type is narrower than the source domain, or make their monotonicity return non-monotonic for unbounded DateTime64, and add a regression with ORDER BY toRelativeSecondNum(ts) or ORDER BY toRelativeDayNum(ts).
| /// `toStartOfSecond`, do not wrap and stay monotonic, and `DateTime64` -> `DateTime`/`Date` is already | ||
| /// rejected above. | ||
| const WhichDataType which_result(*result); | ||
| if ((isDateTime64(arg) || isTime64(arg)) |
There was a problem hiding this comment.
This type-pair guard is not precise enough for the invariant. It still misses Date -> UInt32 second counters: Date reaches 2149-06-06, but toRelativeSecondNum(Date) and toUnixTimestamp(Date) store seconds in UInt32, so a large value like 2149-06-06 wraps below a 2024-11-01 lower bound while getMonotonicityForRange still reports the Date input as always monotonic. A key such as ORDER BY toRelativeSecondNum(stamp) can therefore still prune a granule that satisfies WHERE stamp >= '2024-11-01'. At the same time, rejecting every DateTime64/Time64 -> UInt8/UInt16/UInt32 result also disables safe encodings like toYYYYMM(DateTime64) or toYear(DateTime64), whose values fit the supported DateTime64 range and are monotonic. Please make this check function/range-aware, reject the actual wrap-prone transforms, and add a regression for the Date -> seconds case.
There was a problem hiding this comment.
Out of scope for this PR. The PR fixes the wrong monotonic chain validation. toDateTime(Date) was just one of the cases where it gave wrong result because of the incorrect validation.
b1914ee to
b2ee302
Compare
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 14/15 (93.33%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 11 line(s) · Uncovered code |
`ORDER BY toUnixTimestamp(ts)` with `ts DateTime64` lost primary-key pruning for plain filters on `ts` in 26.7: PR ClickHouse#101814 correctly started asking `getMonotonicityForRange` over the function's argument type, but `ToNumberMonotonicity` had no support for `DateTime64` arguments and answered "unknown", so `KeyCondition::extractMonotonicFunctionsChainFromKey` rejected the monotonic chain. Teach `ToNumberMonotonicity` to answer for `DateTime64` arguments: the conversion truncates the fractional part toward zero and throws a `DECIMAL_OVERFLOW` exception instead of wrapping around, so it preserves order everywhere it is defined. Only the unbounded question is answered positively: index analysis applies chain functions to whole columns of index values, which may contain values outside the target type's range, so claiming monotonicity over concrete ranges would make the analysis throw an exception on parts with such values. Issue: ClickHouse#114407 Co-Authored-By: Claude Fable 5 <[email protected]>
…ain-inference Fix incorrect index pruning for `toDateTime(Date)` key with large `Date` values
Given,
The same class of bug applies to
ORDER BY toDate(Date32):Dateends at2149-06-06whileDate32reaches2299-12-31, so largeDate32values wrap in the stored key under the defaultignoreoverflow behavior, while the monotonicity metadata still reports the conversion as always monotonic.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix incorrect index pruning when a table's sorting key wraps a
Datecolumn intoDateTime(for exampleORDER BY toDateTime(date_column)) and a query filters on the original column with a comparison likeWHERE date_column >= '...'.toDateTime(Date)overflows forDatevalues beyond theDateTimerange (after2106-02-07), so the stored key is non-monotonic; ClickHouse will no longer use primary key pruning for this key/predicate combination because doing so could drop granules that contain matching rows. Closes #101744.Documentation entry for user-facing changes
Version info
26.7.1.114