Skip to content

Fix primary key analysis skipping rows for toMonth, toQuarter, toDayOfYear and toDayOfMonth over a DateTime before local 1970-01-01 - #124470

Open
groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:fix-date-part-monotonicity-pre-epoch-datetime
Open

groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:fix-date-part-monotonicity-pre-epoch-datetime

Conversation

@groeneai

@groeneai groeneai commented Oct 7, 2026 •

Copy link
Copy Markdown
Collaborator

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

Fixed primary key, partition key and skip index analysis that could skip matching rows for conditions on toMonth, toQuarter, toDayOfYear and toDayOfMonth over a DateTime column in a time zone west of UTC holding times from local 1969-12-31.

Description

Related: #118721 (comment)
Related: #90461

On 26.3.42.3 and master, with dt DateTime('America/New_York') as the sorting key filled by SELECT toDateTime(number * 3600) FROM numbers(2000), SELECT count() FROM t WHERE toMonth(dt) = 1 returns 0 instead of 744.

A date part is treated as monotonic on a key range when a factor is equal at both ends: the start of the year for toMonth, toQuarter and toDayOfYear, of the month for toDayOfMonth. These factors were toStartOfYear and toStartOfMonth, which saturate a DateTime into Date, so a DateTime on local 1969-12-31 got 1970-01-01, the start of the next month and year. A range crossing local 1970-01-01 was reported monotonic, the key condition got a reversed range and excluded matching granules. In debug builds the same range makes IN throw Invalid binary search result in MergeTreeSetIndex (for example with merge_tree_coarse_index_granularity = 20).

The four functions now use an unclamped start of month or year as the factor. Pruning for Date, Date32, DateTime64 and a DateTime in UTC is unchanged (granule counts compared with master); only DateTime ranges crossing a local period start lose the monotonicity claim. toHour and toTimeWithFixedDate, which this PR also covered at first, are fixed on master by #124530 and #124474.

Found while looking at the AST fuzzer failure on #121116; with #125327 on master, this PR also fixes its Nullable(DateTime('America/New_York')) shape (master returns 96 of 144 rows).


Workflow [PR]
Sync PR [sync-upstream/pr/124470]

groeneai and others added 2 commits October 7, 2026 17:18
`toQuarter`, `toMonth`, `toDayOfYear`, `toDayOfMonth`, `toHour` and
`toTimeWithFixedDate` decided monotonicity on a key range with
`toStartOfYear`, `toStartOfMonth` and `toDate` as factors. Their `DateTime`
overloads saturate into `Date`, so a local 1969-12-31 (a `DateTime` in a zone
west of UTC right after the epoch) got 1970-01-01, the start of the next day,
month and year. A range crossing it was claimed monotonic and the key
condition built a reversed range: `toMonth(dt) = 1` returned 0 instead of 744,
and in debug builds `IN` threw `Invalid binary search result in
MergeTreeSetIndex`. For `DateTime64` the `toDate` factor of `toHour` also
narrowed the day number to `UInt16` and truncated pre-epoch fractions that
`toHour` floors.

Use the unclamped day number of the start of the day, month or year instead,
as `ToDayOfWeekFactorImpl` already does. `toTimeWithFixedDate` truncates
`DateTime64`, so its factor keeps a truncating `DecimalComponents` overload.
Factor values are unchanged for `Date`, `Date32` and the `DateTime64`
year/month cases.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Merge the two-line ToStartOfPeriodFactorImpl comment into one invariant line.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Oct 7, 2026
@groeneai

groeneai commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 1 finding) plus my own cold review (2 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ The test checks row counts only, so a factor that never claims monotonicity would pass it DISAGREE Every count line but the mutation-proven toTimeWithFixedDate guard fails on the base build. Outside ranges crossing local 1970-01-01 the factor values are the same as before, so a granule-count line there would pass on master too; granule counts were compared base vs fix on Date, Date32, DateTime('UTC'), DateTime64(3, 'UTC') and match. 01440_to_date_monotonicity already fails if the toHour day factor stops pruning.
2 💡 ToStartOfPeriodFactorImpl repeats the overload skeleton of ToDayOfWeekFactorImpl noted Folding them would change code this PR does not need to touch.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-9:20261007-172200

@groeneai

groeneai commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. DateTime('America/New_York') key with toDateTime(number * 3600) FROM numbers(2000): toMonth(dt) = 1 returns 0 instead of 744 on every run (master debug and official 26.3.33.24); with index_granularity = 8, toDayOfMonth(dt) IN (1, 3) SETTINGS merge_tree_coarse_index_granularity = 20 throws Invalid binary search result in MergeTreeSetIndex on a debug build.
b Root cause explained? The monotonicity factors (toStartOfYear, toStartOfMonth, toDate) saturate a local 1969-12-31 to 1970-01-01, the start of the next day/month/year, so a range crossing it is claimed monotonic and the key condition gets a reversed range. For DateTime64 the toHour factor also wrapped modulo 65536 days and truncated where toHour floors.
c Fix matches root cause? Yes. The factor itself is replaced by an unclamped start of day/month/year (the pattern of the existing toDayOfWeek factor); no guard in the shared monotonicity code.
d Test intent preserved / new tests added? New 05338_date_part_monotonicity_pre_epoch_datetime: the six functions on DateTime, Nullable, the coarse-granularity IN case, DateTime64 wrap and fraction cases, and a toTimeWithFixedDate truncation guard.
e Both directions demonstrated? Yes. Base: 11 wrong lines, then the logical error; 20 randomized runner runs: 15 FAIL, then the server aborted. Fix: reference matches, 50/50 randomized runs and a --no-random-settings run pass. The truncation guard returns 0 with a flooring factor (mutation), 1 with the fix.
f Fix is general across code paths? Every transform with a non-trivial factor checked: six fixed; toDaysInMonth, toMinute, toSecond, sub-second, toISOWeek measured correct; toDayOfWeek already unclamped. timezoneOffset has a different factor problem, not changed here.
g Fix generalizes across inputs (params/datatypes/wrappers)? Date, Date32, DateTime, DateTime64, Nullable, LowCardinality measured. Granule counts are identical to master for Date, Date32, UTC DateTime and DateTime64 keys, so pruning is kept; on a New York key at most the granule crossing local 1970-01-01 is no longer skipped.
h Backward compatible? (maintainer-approved exception only) Yes. Index analysis only: no setting, no format, nothing persisted, function results unchanged.
i Invariants and contracts preserved? "Equal factors means monotonic on the range" now holds on every argument type; each factor reads DateTime64 exactly as its function does (floor, or truncation for toTimeWithFixedDate).

Session id: cron:clickhouse-impl-slot-40:20261007-162800

@clickhouse-gh

clickhouse-gh Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [251ce5a]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug, targeted, old_compatibility) FAIL
Logical error: Invalid binary search result in MergeTreeSetIndex (STID: 3252-3e1a) FAIL cidb
Stateless tests (amd_debug, parallel) FAIL
05632_kafka_insert_undelivered_messages FAIL cidb
Stateless tests (amd_debug, distributed plan, s3 storage, parallel) FAIL
05632_kafka_insert_undelivered_messages FAIL cidb
Stateless tests (arm_binary, parallel) FAIL
05632_kafka_insert_undelivered_messages FAIL cidb
Stateless tests (amd_debug, ParallelReplicas, s3 storage, parallel) FAIL
05632_kafka_insert_undelivered_messages FAIL cidb
00542_access_to_temporary_table_in_readonly_mode NOT_FAILED cidb
01414_push_predicate_when_contains_with_clause NOT_FAILED cidb
01513_optimize_aggregation_in_order_memory_long NOT_FAILED cidb
Stateless tests (arm_binary, ParallelReplicas, plan-based, s3 storage, parallel) FAIL
05632_kafka_insert_undelivered_messages FAIL cidb
04910_promql_dialect_regex_matcher NOT_FAILED cidb
05332_promql_set_operator_empty_on NOT_FAILED cidb
05211_promql_present_over_time_absent_over_time NOT_FAILED cidb
05234_promql_streaming_aggregation_memory NOT_FAILED cidb
04353_text_index_explicit_tokenizer_argument NOT_FAILED cidb
05293_promql_constant_scalar_arithmetic NOT_FAILED cidb
04836_time_series_v10_selector_whole_metric_pk_range NOT_FAILED cidb
05059_promql_empty_by_group NOT_FAILED cidb
05137_join_fixed_string_zero_bytes_runtime_filter NOT_FAILED cidb
20 more test cases not shown

AI Review

Summary

PR #124470, head 251ce5a00c749475ab8448ca5a2d72e6ab639549, fixes incorrect pruning for toMonth, toQuarter, toDayOfYear and toDayOfMonth over DateTime values on local 1969-12-31. The signed period factors distinguish the boundary without changing SQL results. No actionable findings remain. Factor consumers checked: IFunctionDateOrDateTime compares the factors without narrowing; the optional-time-zone adapter supplies the effective zone; ExpressionJIT, KeyCondition, primary/partition/skip-index analysis and MergeTreeSetIndex consume the resulting monotonicity decision. The new regression test passes in the current-head Fast test report.

Missing context / blind spots
  • ⚠️ The full current-head CI suite is still pending. Its completed Praktika report will close that validation gap. No local tests were run, as required for this CI review job.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 7, 2026
@groeneai
groeneai requested review from nihalzp and yariks5s October 7, 2026 17:55
@clickhouse-gh clickhouse-gh Bot added the comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... label Oct 7, 2026
@yariks5s yariks5s self-assigned this Oct 7, 2026
Comment thread src/Functions/DateTimeTransforms.h Resolved
@groeneai

groeneai commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 0beec9e

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted, old_compatibility) / Logical error: Invalid binary search result in MergeTreeSetIndex (STID: 3252-3a4a) not from this PR: the fuzzer reused this PR's test table with toRelativeDayNum(dt) IN (...), a function this PR does not change. toRelativeDayNum wraps a local 1969-12-31 to 65535 and reproduces the same exception on master with a plain DateTime('America/New_York') key #124511 (mine, open)
PR rollup, red only because of the row above #124511 (mine, open)
Sync - CH Inc sync (private, not actionable by me)

All 149 check runs completed, Finish Workflow is green, and CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261008-020432

groeneai and others added 2 commits October 22, 2026 12:27
…onicity-pre-epoch-datetime

Master now gives toHour and toTimeWithFixedDate their own factors
(ToClockPeriodStartFactorImpl, ToDayAndUTCOffsetFactorImpl), which already keep
the local day 1969-12-31 unclamped, so take master's for both, drop this branch's
ToTimeWithFixedDateFactorImpl and the now unused Day period of
ToStartOfPeriodFactorImpl.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
toHour and toTimeWithFixedDate over a pre-epoch DateTime and DateTime64 are
fixed on master by ClickHouse#124530 and ClickHouse#124474, so their queries pass there and no
longer test this change. toTimeWithFixedDate also rounds a pre-epoch
DateTime64 down to whole seconds on master now, so the expected row of the
removed DateTime64 case no longer exists.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai changed the title Fix primary key analysis skipping rows for toMonth, toDayOfMonth and toHour over a DateTime before local 1970-01-01 Fix primary key analysis skipping rows for toMonth, toQuarter, toDayOfYear and toDayOfMonth over a DateTime before local 1970-01-01 Oct 22, 2026
@clickhouse-gh clickhouse-gh Bot added comp-datetime Date/DateTime/TimeZone datatypes and date-time semantics. and removed comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... labels Oct 22, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 251ce5a00 with master 86d40c731 (stripped binary size, per-symbol sizes and ThinLTO time; 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.

Compile time of recompiled translation units

133 translation units recompiled, 765 s compile time in total, 133 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×0.94 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost -26.1 s (-3%) in total before that adjustment.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7b23e29

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted) / Logical error: Invalid binary search result in MergeTreeSetIndex (STID: 3252-4fe1) not from this PR (it changes the toQuarter, toMonth, toDayOfMonth and toDayOfYear factors only): the query is toRelativeDayNum(dt) NOT IN (7, 1, 257) over a LowCardinality(DateTime('America/New_York')) key holding local 1969-12-31, where toRelativeDayNum wraps from 65535 to 0 but is still claimed monotonic. Same mechanism as the STID 3252-3a4a row on the previous head #124511 (mine, open)
Stateless tests (amd_debug, sequential) / 05339_iceberg_top_k_query_condition_cache master breakage, not from this PR: the test failed on all master commits from the #126987 merge 41d5f3406f9d until its revert, and the tested merge tree ddc3c03cefb0 contains #126987 but not the revert #127378 (external, merged revert)
Stateless tests (amd_debug, distributed plan, s3 storage, sequential) / 05339_iceberg_top_k_query_condition_cache same master breakage #127378 (external, merged revert)
Stateless tests (arm_asan_ubsan, azure, sequential, 2/2) / 05339_iceberg_top_k_query_condition_cache same master breakage #127378 (external, merged revert)
Stateless tests (arm_binary, sequential) / 05339_iceberg_top_k_query_condition_cache same master breakage #127378 (external, merged revert)
Stateless tests (arm_binary, AsyncInsert, s3 storage, sequential) / 05339_iceberg_top_k_query_condition_cache same master breakage #127378 (external, merged revert)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, sequential) / 05339_iceberg_top_k_query_condition_cache same master breakage #127378 (external, merged revert)
Stateless tests (arm_binary, s3 storage, DBReplicated, sequential) / 05339_iceberg_top_k_query_condition_cache same master breakage #127378 (external, merged revert)
Mergeable Check, PR praktika rollups of the rows above #124511 and #127378 (the owners of the rows above)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261022-163012

@clickhouse-gh

clickhouse-gh Bot commented Nov 9, 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.

@yariks5s yariks5s self-assigned this Nov 9, 2026
@yariks5s

Copy link
Copy Markdown
Member

@groeneai please update the branch with master

…onicity-pre-epoch-datetime

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master in 251ce5a (clean merge, the PR's own diff is unchanged). On the merged debug build 05338_date_part_monotonicity_pre_epoch_datetime passes 50/50 randomized runs, and today's master still returns 0 instead of 744 for toMonth(dt) = 1 on the test's table, so the fix is still needed.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 251ce5a

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted, old_compatibility) / Logical error: Invalid binary search result in MergeTreeSetIndex (STID: 3252-3e1a) not from this PR (it changes the toQuarter, toMonth, toDayOfMonth and toDayOfYear factors only): the query is toRelativeDayNum(dt) IN tuple(256) over merge(''), and toRelativeDayNum wraps on the local day 1969-12-31 while it is still claimed monotonic. Same mechanism as the STID 3252-3a4a and 3252-4fe1 rows on earlier heads #124511 (mine, open)
Stateless tests (amd_debug, parallel) / 05632_kafka_insert_undelivered_messages master breakage, not from this PR: on master since 18:00Z, the test's CREATE TABLE ... ENGINE = Kafka(<named collection>) fails with Code: 36 ... Kafka property topic.metadata.propagation.max.ms can only be specified in a named collection defined in the server configuration file; it failed on 9 of the 11 master commits tested since then (master report) #134255 (external, open)
Stateless tests (arm_binary, parallel) / 05632_kafka_insert_undelivered_messages same master breakage #134255 (external, open)
Stateless tests (amd_debug, ParallelReplicas, s3 storage, parallel) / 05632_kafka_insert_undelivered_messages same master breakage #134255 (external, open)
Stateless tests (amd_debug, distributed plan, s3 storage, parallel) / 05632_kafka_insert_undelivered_messages same master breakage #134255 (external, open)
Stateless tests (arm_binary, ParallelReplicas, plan-based, s3 storage, parallel) / 05632_kafka_insert_undelivered_messages same master breakage #134255 (external, open)

Mergeable Check and PR are the praktika rollups of the rows above.

Session id: cron:our-pr-ci-monitor:20261124-220031

This branch has not been deployed

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

Labels

can be tested Allows running workflows for external contributors comp-datetime Date/DateTime/TimeZone datatypes and date-time semantics. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants