Skip to content

Fix incorrect index pruning for toDateTime(Date) key with large Date values - #101814

Merged
nihalzp merged 14 commits into
ClickHouse:masterfrom
nihalzp:fix-monotonicity-chain-inference
Jun 26, 2026
Merged

nihalzp merged 14 commits into
ClickHouse:masterfrom
nihalzp:fix-monotonicity-chain-inference

Conversation

@nihalzp

@nihalzp nihalzp commented Apr 5, 2026 •

Copy link
Copy Markdown
Member

Given,

CREATE TABLE test (stamp Date)
ENGINE = MergeTree ORDER BY toDateTime(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-06' FROM numbers(3);

OPTIMIZE TABLE test FINAL;
SELECT count() FROM test WHERE stamp >= '2024-11-01' SETTINGS use_primary_key = 0; -- 6 (correct)

SELECT count() FROM test WHERE stamp >= '2024-11-01' SETTINGS use_primary_key = 1; -- 3 (incorrect)

The same class of bug applies to ORDER BY toDate(Date32): Date ends at 2149-06-06 while Date32 reaches 2299-12-31, so large Date32 values wrap in the stored key under the default ignore overflow behavior, while the monotonicity metadata still reports the conversion as always monotonic.

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

Fix incorrect index pruning when a table's sorting key wraps a Date column in toDateTime (for example ORDER BY toDateTime(date_column)) and a query filters on the original column with a comparison like WHERE date_column >= '...'. toDateTime(Date) overflows for Date values beyond the DateTime range (after 2106-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

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.7.1.114

@clickhouse-gh

clickhouse-gh Bot commented Apr 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7b09dc1]

Summary: ✅


AI Review

Summary

This PR changes key-condition inference so monotonic function chains are validated against the non-constant child type, and it allows relaxed constant rewrites through assumeNotNull. The assumeNotNull relaxation itself looks conservative, but the temporal-conversion guard that protects this path is still too narrow, so current head can still use primary-key or partition pruning for stored keys that are non-monotonic under insert-time overflow behavior. That is still a wrong-result risk.

Missing context / blind spots
  • ⚠️ I did not run the stateless tests locally because this checkout has no usable build artifact; a focused CI/local run of the added regressions would close runtime validation, but the blockers below are visible from current source.
Findings

❌ Blockers

  • [src/Storages/MergeTree/KeyCondition.cpp:1689] The rejection still depends on the query-time date_time_overflow_behavior. Stored sorting-key values may already have been materialized under the default ignore behavior, but a query with date_time_overflow_behavior = 'saturate' or 'throw' makes this helper return true for toDateTime(Date)/toDateTime(Date32). Then a predicate on the source column can be rewritten into key space and prune wrapped rows that still satisfy the original predicate. Suggested fix: reject these source/result pairs independently of the current query setting, or otherwise prove the stored key behavior for every part before using the chain. Existing thread: Fix incorrect index pruning for toDateTime(Date) key with large Date values #101814 (comment)
  • [src/Storages/MergeTree/KeyCondition.cpp:1689] The guard is keyed to func.getName() == "toDateTime", so equivalent key expressions such as CAST(stamp, 'DateTime'), analyzer _CAST, and other wrappers that produce DateTime from Date/Date32 still bypass the rejection while using the same non-monotonic stored values. Suggested fix: base the rejection on the argument and result types of the key function, not the SQL spelling. Existing thread: Fix incorrect index pruning for toDateTime(Date) key with large Date values #101814 (comment)
  • [src/Storages/MergeTree/KeyCondition.cpp:1689] The same invariant is still missing for other narrowing temporal transforms. Current source only special-cases toDateTime, while ToDateImpl::execute wraps Date32 values above Date max under ignore, ToDateTimeImpl::execute wraps DateTime64 values outside DateTime, and standard relative transforms store into UInt16/UInt32 result columns. These chains can still map a matching source row below the transformed query bound and prune it. Suggested fix: reject wrap-prone source/result pairs such as Date32 -> Date, DateTime64 -> Date/DateTime, and DateTime64 -> toRelativeDayNum/toRelativeSecondNum, while keeping safe transforms function/range-aware. Existing threads: Fix incorrect index pruning for toDateTime(Date) key with large Date values #101814 (comment) and Fix incorrect index pruning for toDateTime(Date) key with large Date values #101814 (comment)
  • [src/Storages/MergeTree/KeyCondition.cpp:1689] [dismissed by author -- https://github.com/Fix incorrect index pruning for toDateTime(Date) key with large Date values #101814#discussion_r3425591330] Date -> UInt32 second counters remain a real instance of the same wrong-result class: Date reaches 2149-06-06, but toRelativeSecondNum(Date)/toUnixTimestamp(Date) store seconds in UInt32, so large Date values wrap below a 2024 lower bound while the current helper still accepts the chain. The author marked this out of scope, but the PR’s contract is to stop unsafe monotonic-chain pruning for wrapped temporal keys.
Tests
  • ⚠️ The added tests only cover the original ORDER BY toDateTime(Date) spelling under the default query setting plus the assumeNotNull cases. Please add focused regressions for the remaining unsafe variants: non-ignore query settings over parts built with ignore, CAST(stamp, 'DateTime'), toDate(Date32), toDateTime(DateTime64), toDate(DateTime64), toRelativeSecondNum(DateTime64), and the dismissed toRelativeSecondNum(Date)/toUnixTimestamp(Date) case.
Final Verdict

Status: ❌ 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.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Apr 5, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

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.

@nihalzp
nihalzp force-pushed the fix-monotonicity-chain-inference branch from 0b12c2d to 832aaf3 Compare April 7, 2026 14:48
@yariks5s yariks5s self-assigned this Apr 7, 2026
@nihalzp

nihalzp commented Apr 16, 2026 •

Copy link
Copy Markdown
Member Author

Integration test (test_storage_iceberg_with_spark/test_partition_pruning.py::test_partition_pruning) is failing because we used to incorrectly determine that the chain toRelativeDayNum(assumeNotNull(Nullable(Date32))) is always monotonic. However, that is not right and can lead to wrong result:

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';

@clickhouse-gh

clickhouse-gh Bot commented Jun 1, 2026

Copy link
Copy Markdown
Contributor

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.

@clickhouse-gh clickhouse-gh Bot assigned yariks5s and unassigned yariks5s Jun 1, 2026
/// 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);

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.

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

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.

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.

@alexey-milovidov

Copy link
Copy Markdown
Member

Picked this up: merged the latest master (the branch was ~760 commits behind) and addressed the remaining review feedback.

Addressed the unsafe-rewrite concern (ee8fde291e9): isFunctionReallyMonotonic now rejects toDateTime(Date)/toDateTime(Date32) as non-monotonic regardless of the query-time date_time_overflow_behavior. Gating on the query-time setting was unsafe — part keys are materialized at insert time (default ignore), so a query overriding the setting to saturate/throw could re-enable unsafe pruning of granules with wrapped key values. The now-unused date_time_overflow_behavior_ignore member was removed.

Tests:

  • 04078_key_condition_todatetime_date_monotonicity extended with saturate and throw regressions (built under default ignore, queried with the override) — both correctly skip the index and return the right count. Verified locally.
  • 04099_assume_not_null_key_condition reference updated for master's Partition Min-Max → Min-Max index-label rename (part-level min-max index feature; pruning behavior unchanged).

Ran a regression batch of monotonicity / key-condition / date-overflow tests locally — all pass.

Comment thread src/Storages/MergeTree/KeyCondition.cpp Outdated
bool KeyCondition::isFunctionReallyMonotonic(const IFunctionBase & func, const IDataType & arg_type) const
{
if (date_time_overflow_behavior_ignore && func.getName() == "toDateTime")
if (func.getName() == "toDateTime")

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.

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').

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

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.

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.

@alexey-milovidov

Copy link
Copy Markdown
Member

Merged the latest master (~412 commits behind) and addressed the remaining review feedback and CI failures.

Broadened the overflow guard (5329f8f93ac): isFunctionReallyMonotonic no longer keys off the toDateTime function name. It now rejects Date/Date32 -> DateTime conversions by the (argument type -> result type) pair, so CAST(x, 'DateTime'), the analyzer/internal _CAST, accurateCast, etc. are all covered (they all reuse ToDateTimeMonotonicity<DataTypeDateTime>). Added an ORDER BY CAST(stamp, 'DateTime') regression to 04078.

Fixed an Iceberg partition-pruning regression (same commit): the previous revision passed the function argument type to the always_monotonic callback, which forwarded it to getMonotonicityForRange. For range-sensitive monotonicities such as toRelativeDayNum(Date32) (Iceberg DATE maps to Date32), calling getMonotonicityForRange with empty bounds returns non-monotonic, silently disabling valid pruning — this is what broke test_storage_iceberg_with_spark/test_partition_pruning across all integration configs (assert 0 == 3). The callback now receives both the argument type (for isFunctionReallyMonotonic) and the result type (for getMonotonicityForRange, preserving the prior behavior). Verified locally that days(date) pruning is restored (3/4 parts pruned) and that all 04078/04099 cases still behave correctly.

Stabilized 04099 (8991957a20c): its EXPLAIN indexes = 1 output differs under parallel replicas, the old analyzer, and a replicated database; added no-parallel-replicas, no-old-analyzer, and no-replicated-database tags (same pattern as 00944_minmax_nan).

CI report: #101814

Comment thread src/Storages/MergeTree/KeyCondition.cpp Outdated
/// 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())))

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.

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).

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

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 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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

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.

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.

@alexey-milovidov

Copy link
Copy Markdown
Member

Merged the latest master (the branch was ~485 commits behind) to refresh the base and pick up the read-in-order virtual-row boundary flake fix (#106664) — both CI reds on the previous revision (Server died and the Virtual row boundary violated in MergingSortedAlgorithm logical error, STID 2651-3359) are that known flake, unrelated to this PR.

Broadened the overflow guard (6c7f00c896f): addressed the remaining review thread by also rejecting toDate(Date32). Date ends at 2149-06-06 while Date32 reaches 2299-12-31, so under the default ignore behavior ToDateImpl::execute(Int32) wraps the day number via static_cast<UInt16> and the stored key is non-monotonic for large dates, while ToDateMonotonicity still reports Date32 input as always monotonic — the exact analog of the Date/Date32 -> DateTime case. isFunctionReallyMonotonic now detects it by the same (argument type -> result type) pair, so all spellings (toDate, CAST, _CAST, accurateCast) are covered. Extended 04078_key_condition_todatetime_date_monotonicity with a toDate(Date32) regression.

Built and verified locally: both 04078 and 04099 pass; the new case returns the correct count (6) and force_primary_key = 1 throws INDEX_NOT_USED.

alexey-milovidov added a commit to nihalzp/ClickHouse that referenced this pull request Jun 11, 2026
…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]>
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
Comment thread src/Storages/MergeTree/KeyCondition.cpp Outdated
return false;
if (isDate32(arg) && isDate(result))
return false;
if (isDateTime64(arg) && (isDateTime(result) || isDate(result)))

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.

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).

Comment thread src/Storages/MergeTree/KeyCondition.cpp Outdated
/// `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))

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.

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.

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.

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.

@clickhouse-gh

clickhouse-gh Bot commented Jun 26, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.30% 85.30% +0.00%
Functions 92.60% 92.60% +0.00%
Branches 77.50% 77.60% +0.10%

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

Full report · Diff report

@nihalzp
nihalzp added this pull request to the merge queue Jun 26, 2026
Merged via the queue into ClickHouse:master with commit 1b21a3b Jun 26, 2026
167 checks passed
@nihalzp
nihalzp deleted the fix-monotonicity-chain-inference branch June 26, 2026 16:24
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 26, 2026
alexey-milovidov added a commit to fhw12345/ClickHouse that referenced this pull request Aug 15, 2026
`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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…ain-inference

Fix incorrect index pruning for `toDateTime(Date)` key with large `Date` values
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Development

Successfully merging this pull request may close these issues.

extractMonotonicFunctionsChainFromKey passes result_type instead of arg_type to isFunctionReallyMonotonic, bypassing Date→DateTime overflow check

4 participants