Skip to content

Do not claim toDate and toDateTime are monotonic over a range they wrap - #117394

Merged
alexey-milovidov merged 8 commits into
masterfrom
fix-to-date-conversion-monotonicity-wrap-116946
Oct 11, 2026
Merged

alexey-milovidov merged 8 commits into
masterfrom
fix-to-date-conversion-monotonicity-wrap-116946

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 31, 2026 •

Copy link
Copy Markdown
Member

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 wrong results from primary-key analysis for predicates such as toDate(dt64_key) >= ... and toDateTime(date32_key) >= ...: at the default date_time_overflow_behavior = 'ignore' the conversion wraps for values the result type cannot hold, so matching rows silently disappeared and count() could overcount.

Documentation entry for user-facing changes

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.

The 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 the instant that wraps differs between time zones (2106-02-07 still fits DateTime in UTC but not in America/Hermosillo; a late 2149-06-06 instant is already 2149-06-07 in Pacific/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. The Date argument of toDateTime wraps as well (Date reaches 2149-06-06, DateTime ends in 2106-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_defined still lets a comparison constant be pushed through a wrapping key expression such as PARTITION BY toDate(ts). That is sound when the expression throws outside its window, but a stored DateTime64 value beyond 2149-06-06 wraps silently at insert time, so WHERE 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_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]
Sync PR [sync-upstream/pr/117394]

Version info

  • Merged into: 26.10.1.2102-master (included in 26.10 and later)

…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
@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7422cfd]

Summary: ✅


AI Review

Summary

This PR correctly hardens the range-mapping side of toDate / toDateTime monotonicity and adds solid stateless coverage for the wrapping and time-zone edge cases. I am still blocking it because the previously reported constant-pushdown path through wrapped stored key expressions is unchanged, so PARTITION BY toDate(ts)-style keys can still mis-prune and return wrong results under the default date_time_overflow_behavior = 'ignore'.

Findings

❌ Blockers

  • [src/Functions/FunctionsConversion.h:4702] is_always_monotonic_where_defined is still advertised for unbounded wrapping key expressions, so KeyCondition continues to push constants through stored keys whose values may already have wrapped at insert time. The current check in src/Storages/MergeTree/KeyCondition.cpp:2234 treats that bit as sufficient for constant pushdown, but once the stored toDate(ts) / toDateTime(d) value has already wrapped, it no longer belongs to the “defined subset” this contract assumes. That still leaves a wrong-result path for shapes like PARTITION BY toDate(ts) with out-of-range DateTime64 rows. [dismissed by author -- https://github.com/Do not claim toDate and toDateTime are monotonic over a range they wrap #117394#discussion_r4092600165]
    Suggested fix: 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 have wrapped.
Final Verdict
  • Status: ❌ Block
  • Minimum required actions: close the remaining constant-pushdown wrong-result path above, or narrow the scope so this PR no longer claims a safe fix for wrapping key-expression analysis.

LLVM Coverage Report

Measured on commit 7422cfd.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 92.20% 92.10% -0.10%
Branches 79.60% 79.60% +0.00%

Changed lines: Changed C/C++ lines covered: 38/39 (97.44%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 31, 2026
Comment thread src/Functions/FunctionsConversion.h Resolved
@zlareb1

zlareb1 commented Aug 31, 2026

Copy link
Copy Markdown
Member

Verified the fix shape against master. Two observations from probing the neighboring arms of the same structs:

  1. The premise that only Date32 and DateTime64 arguments can wrap does not hold for the Date arm of ToDateTimeMonotonicity: SELECT toDateTime(toDate('2149-06-06')) silently wraps to 2013-04-29 17:31:44, yet the which.isDate() arm keeps an unconditional strict always-monotonic claim. Today this is inert — I could not construct a mis-pruning through it because KeyCondition declines the atom upstream (EXPLAIN indexes = 1 shows Condition: true for WHERE toDateTime(date_key) ... shapes), i.e. the claim is defended by a different layer rather than by being true. If the upstream gate is ever relaxed, the Date arm becomes the next carrier, so it may be worth demoting it in the same way while this surface is open.

  2. The same lens applied to ToNumberMonotonicity finds a live sibling that this PR and Do not claim toStartOfInterval is monotonic over a Date32 range it wraps #117396 do not cover: toUnixTimestamp over a Date/Date32 key wraps (day×86400 into UInt32) while the struct models it as a plain cast, and there the mis-pruning does reproduce at pure defaults — filed separately as toUnixTimestamp over a Date/Date32 primary key silently prunes matching rows: the monotonicity model assumes a plain cast but the implementation wraps day*86400 into UInt32 #117400 with a minimal repro.

@yariks5s yariks5s self-assigned this Aug 31, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 7422cfd4a with master 468fbe0bb (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of f2d452133; 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.

Object file sizes

8 object files changed (+83.45 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Functions/FunctionsConversion.cpp.o 21.53 MiB 21.55 MiB +22.67 KiB (+0.10%)
src/CMakeFiles/dbms.dir/Functions/FunctionsConversion_impl17.cpp.o 850.81 KiB 872.58 KiB +21.77 KiB (+2.56%)
src/CMakeFiles/dbms.dir/Functions/FunctionsConversion_impl18.cpp.o 497.77 KiB 518.99 KiB +21.22 KiB (+4.26%)
src/CMakeFiles/dbms.dir/Functions/FunctionsConversion_impl15.cpp.o 519.84 KiB 537.61 KiB +17.76 KiB (+3.42%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

40 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.
The matched translation units cost -23.8 s (-8%) in total before that adjustment.

Job report

alexey-milovidov and others added 2 commits September 16, 2026 09:02
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @zlareb1 thank you. Point 1 is adopted in c050d53: the Date arm of ToDateTimeMonotonicity now goes through the same wrap check as Date32 and DateTime64, so the claim is truthful even though nothing reaches it today. I confirmed the upstream gate on the merged branch: EXPLAIN indexes = 1 shows Condition: true for WHERE toDateTime(date_key) >= ..., and with PARTITION BY toDateTime(d) the pruning of WHERE d >= ... comes from the Min-Max index on d itself (the partition condition is true), so no constant is pushed through toDateTime(Date) anywhere. For that reason I did not add a constant-side guard for the Date argument in applyFunctionChainToColumn; it would be dead code. Point 2 is #117400, fixed by #117709, which this branch now includes through the merge of master.

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). is_always_monotonic_where_defined still lets KeyCondition push a comparison constant through a wrapping key expression, and its soundness argument, that stored key values belong to the subset on which the expression is defined, holds when the expression throws for the rest of the range, but not when it wraps. Verified on the merged branch:

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 2

The row from year 2200 lives in a partition whose toDate(ts) wrapped to 2020-07-27, and the pushed condition toDate(ts) >= '2100-01-01' prunes it. The constant itself is representable, so the guards in applyFunctionChainToColumn do not fire. The only sound alternative I see is to report a wrapping conversion as not monotonic at all for an unbounded range, which would drop partition pruning for the common PARTITION BY toDate(ts64) with WHERE ts64 >= ... shape for every table, to protect rows beyond 2149-06-06. I kept the constant push and recorded the limitation in the description.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 22, 2026
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]>
alexey-milovidov and others added 2 commits September 24, 2026 09:05
…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

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.

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.

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.

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

@clickhouse-gh

clickhouse-gh Bot commented Oct 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.

alexey-milovidov and others added 2 commits October 3, 2026 17:50
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @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 WHERE (_partition_id = 'all') OR (_block_number <= 255) - virtual-column pruning, unrelated to the toDate/toDateTime monotonicity change here) and the Build (amd_fuzzers) failure on the same commit, and provide a fix in a separate PR. If the fix is already in progress, link it here. The other stateless/stress failures were widespread flakes across many PRs on 2026-10-03; master is now merged into this branch.

@groeneai

groeneai commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator

Acknowledged.

Build (amd_fuzzers) on 2a8b2ab is the R_X86_64_PC32 out of range link overflow fixed by #123738. 2a8b2ab does not contain its merge commit 80f00c8 (it is 349 commits behind it); the new head 7422cfd does.

I found no existing fix for the NoREC mismatch on (_partition_id = 'all') OR (_block_number <= 255). I'm investigating it and will follow up here with a separate PR (or my findings).

@groeneai

groeneai commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator

The NoREC mismatch is fixed in #124022. It is not specific to virtual columns: the fuzzer session had query_plan_remove_unused_columns = 0, which makes optimizeUseNormalProjections reject the commit_order projection on a header mismatch, but only after it had already removed the parts covered by that projection from the table read. Those parts were then read by nobody (276 rows vs 308). The same happens on released versions with a regular projection present in only some parts and compatibility <= '25.11'.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai thank you. The current head 7422cfd includes #123738 and its CI is green, so nothing more is needed here for Build (amd_fuzzers). The NoREC mismatch is handled separately in #124022, which does not touch this PR. The one unresolved review thread (constant pushdown through wrapping key expressions such as PARTITION BY toDate(ts)) is a known limitation that master shares, and it is left for a maintainer to decide, as explained in the thread.

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

All good.

@alexey-milovidov alexey-milovidov self-assigned this Oct 11, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 11, 2026
Merged via the queue into master with commit 73c4837 Oct 11, 2026
149 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-to-date-conversion-monotonicity-wrap-116946 branch October 11, 2026 02:01
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 11, 2026
valerypetrov pushed a commit to valerypetrov/ClickHouse that referenced this pull request Oct 11, 2026
…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]>
@groeneai

Copy link
Copy Markdown
Collaborator

Could this PR get pr-must-backport, like #119302? The backports of #119302 brought 05054_nullable_key_todate_monotonicity to 26.3, 26.7, 26.8 and 26.9, where toDate of a DateTime64 is still reported as always monotonic. On 26.9 a debug Stress run already aborted on it: Stress test (amd_debug), Logical error: 'Invalid binary search result in MergeTreeSetIndex' in the test's toDate(x) IN (toDate('2026-03-02'), toDate('2026-03-08')). The server-side AST fuzzer had rewritten the test's INSERT, so the table also held DateTime64 values past 2149-06-06, where toDate wraps.

The test's table plus that fuzzed INSERT reproduces it in clickhouse local with the CI debug binaries:

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 4ee93aea (the last debug build before this PR; the two merges in between do not touch this code). On 73c48370, the merge of this PR, it returns 6 105, the same as with use_primary_key = 0. Without the fuzzed INSERT every binary passes.

The cherry-picks will conflict: the ToDateTimeMonotonicity hunk sits on the range-aware code from #117031, which no release branch has, and 26.7 and 26.3 also lack Monotonicity::is_always_monotonic_where_defined.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... 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

5 participants