Repository navigation
Fix key analysis skipping rows for wrapping toDate keys and date-time text in tuple constants - #125960
Fix key analysis skipping rows for wrapping toDate keys and date-time text in tuple constants#125960groeneai wants to merge 5 commits into
toDate keys and date-time text in tuple constants#125960Conversation
…e-time text `toDate` and `toDateTime` over `DateTime64`/`Date32` wrap outside the result type's range under the default `date_time_overflow_behavior = 'ignore'`, and the wrapped value is what a sorting or partition key stores. `ToDateMonotonicity` and `ToDateTimeMonotonicity` still answered `is_always_monotonic_where_defined` for a range that may wrap, so `KeyCondition::canConstantBeWrappedByMonotonicFunctions` pushed a range constant through such a key (`ts <= c` -> `toDate(ts) <= toDate(c)`) and pruned the granule or partition holding a wrapped key. That flag is only sound for a conversion that throws outside its range (stored keys cannot hold such values); a range that may wrap now reports no monotonicity. Equality and `IN` keep pruning through the deterministic path, which wraps the constant the same way, and `PARTITION BY toDate(ts)` keeps part pruning through the Min-Max index on `ts`. Range pushdown through `ORDER BY toDate(dt64)` is lost (measured 2/123 -> 123/123 granules for the last 10 days of 1M rows); no query-time check can prove a table holds no wrapped keys, since the insert-time behaviour is not recorded. This is the residual left open in ClickHouse#117394. `tryNormalizeTextConstantForZonelessDateTimeInput` (ClickHouse#120114) converted text read against a zone-less `DateTime`/`DateTime64` key input in the session time zone, as the comparison does, but only for a top-level constant. A tuple constant with a text element was CAST in the time zone the table's types were built with, naming another instant than the comparison, and the matching granules were skipped. The helper now walks tuples by position, the way the comparison pairs elements, converting only text leaves that meet a zone-less date-time element. Both reproduce on 26.8.21.12 and 26.3.33.24 and were found in the review of ClickHouse#96225. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 1 finding) plus my own review (1 major, 2 nits).
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-8:20261015-062000 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-5:20261015-053600 |
|
Workflow [PR], commit [0cb2781] Summary: ❌
AI ReviewSummaryReviewed #125960 at Missing context / blind spots
Final Verdict✅ Approve based on the current code and regression coverage, subject to normal CI completion. |
|
cc @yariks5s @Algunenano, could you review this and add |
…rapping-todate-tuple-text-timezone Resolve the conflict with ClickHouse#96225 in `KeyCondition.cpp`: the zone-less date-time text normalization now takes the constant as a `ColumnWithTypeAndName`. The tuple recursion moves into a `Field`-level helper, and the column is rebuilt only when a text element was converted, so other constants keep their original columns as on master. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e condition `ORDER BY toDate(ts)` over a `DateTime64` no longer carries a range condition, because `toDate` may wrap such a value and the key stores the wrapped result. The case checks that a `DateTime64` input keeps the strict bound unmoved, which needs a key that still pushes the comparison down, so it uses `toStartOfDay(ts)`. The marks it selects (49 of 96) and its count are the same as before. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ments
The comparison pairs tuple elements by position, while the cast of a constant
to the key's tuple type pairs two named tuples by name. Converting the text
elements of such a constant by position made that cast succeed on swapped
values: with `t Tuple(d DateTime, n UInt8)` and
`t = CAST(('2026-01-01 12:00:00', 1), 'Tuple(n String, d UInt8)')` the index
skipped all 8 matching rows, and a nested `Nullable(Tuple)` element made the
cast throw `TYPE_MISMATCH`, where master declines the transform because the
text does not parse as `UInt8`. A tuple level whose text was converted and whose
names differ from the key's is now declined, so the constant pairs with the key
as on master; named constants with the key's own names are still normalized.
05402 covers a same-order, a reordered and a nested reordered named constant.
A named constant without text whose names reorder the key's elements is left
as it is: its name-mapped cast is the separate finding of ClickHouse#96225 that ClickHouse#123868
addresses.
Found by the second-model review of the merge with master.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Rebuilding a normalized tuple constant from its `Field` dropped the active
type of every `Dynamic` and `Variant` element next to the text element: a
`Dynamic` holding a `Date` came back holding its day number, which the cast
to the transform's `DateTime` input then read as seconds. Key analysis
pushed that wrong constant through `cityHash64(t)` and pruned matching rows:
t = ('2026-01-01 12:00:00', CAST(toDate('2026-01-02'), 'Dynamic'))
returned 0 instead of 8 on the previous head (8 on master dd14a5a). The
same happens with a `Variant(Date, DateTime('UTC'))` holding a `DateTime`.
Convert the text elements on the constant's column instead: only converted
elements get a new column, the others keep theirs, as the master-side
caller already does when it hands the data column to the transforms.
Reported by the AI review on ClickHouse#125960.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Build profile diff (arm_release)Commit See the job log for details. |
CI finish ledger - 0cb2781Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Both Session id: cron:our-pr-ci-monitor:20261015-190014 |
…e32 range they wrap With the legacy result types (to_start_of_interval_preserves_argument_type = 0, which any compatibility below 26.11 restores, and the only behaviour of every release up to 26.10; for dateTrunc, function_date_trunc_return_type_behavior = 1) a Date32 argument is rounded into Date (WEEK..YEAR) or DateTime (DAY) and stored with a plain cast, so dates before 1970 and after 2149 (2106 for DateTime) wrap. getMonotonicityForRange nevertheless returned is_monotonic and is_always_monotonic unconditionally, so: - KeyCondition mapped mark ranges through a decreasing function and pruned granules wrongly in both directions (ORDER BY d: rows dropped, DESC: kept); - matchesExactContinuousRange derived exact ranges through it, so the exact count path counted rows without the filter, and when a skip index had trimmed the selected ranges at analysis time the exact range ended past the selected one: chassert(exact_ranges[i].end <= range.end) (AST fuzzer, STID 2508-5221); - sort-order propagation treated the rounding as order preserving, so ORDER BY toStartOfInterval(d, ...) returned rows out of order; - KeyCondition pushed a condition on d through a sorting or partition key toStartOfInterval(d, ...), whose stored values wrap, and skipped matching granules and partitions. When the argument, with LowCardinality and Nullable removed, is Date32 and the result type is Date or DateTime, getMonotonicityForRange now rounds both bounds of the range with the same ToStartOfInterval<unit>::execute overload the function executes. The rounding is non-decreasing in that wide type, so the range maps without wrapping iff both rounded bounds fit the result type ([0, 65535] days for Date, [0, UInt32 max] seconds for DateTime in the result's time zone). Then only is_monotonic is claimed for the range; otherwise, and for an unbounded or non-integer bound or a non-constant interval, nothing is claimed. is_always_monotonic is never claimed for these results: the function is not monotonic on its whole domain, and the functions stress test treats is_always_monotonic on some ranges with is_monotonic false on others as broken monotonicity. is_always_monotonic_where_defined is not claimed either: a sorting or partition key toStartOfInterval(d32, ...) stores the wrapped values, so a condition on d pushed through it pruned matching rows (the reasoning of ClickHouse#125960 for toDate). Values, result types and settings do not change: saturating the Date32 values was rejected during the review of ClickHouse#110344 (see ClickHouse#116945), because the legacy setting exists to restore the old results exactly. This re-applies the monotonicity guard of the closed ClickHouse#117396 to the legacy result types that ClickHouse#122129 kept. Cost, legacy mode with a Date32 key only: a range whose rounding wraps is not pruned through the function, and the exact count and ordering optimizations are not used for these narrowing roundings, and a condition on the column is not pushed through such a key expression. Closes ClickHouse#116945 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed primary key and partition pruning skipping matching rows in two cases: a range condition on a
DateTime64orDate32column whose key istoDate,toDateTimeorCAST(... AS Date)of that column while some stored values lie outside theDateorDateTimerange, and aTuplecolumn with aDateTimeelement compared with a tuple constant holding date-time text whensession_timezonediffers from the time zone the table was created with. A range condition on such a column no longer uses such a key for pruning.Description
Related: #96225 (two of its review findings). On 26.8.21.12 and 26.3.33.24 both drop matching rows:
ORDER BY toDate(ts)overts DateTime64(3, 'UTC')holding1969-12-31 12:00:00and1970-01-01 12:00:00:WHERE ts <= '1970-01-02'returns 1 row instead of 2. Same forPARTITION BY toDate(ts),toDateTime(ts),CAST(ts AS Date)andDate32sources. Under the defaultdate_time_overflow_behavior = 'ignore'these conversions wrap (toDate('1969-12-31 12:00:00')is2149-06-06) and the key stores the wrapped value, yet their monotonicity claim letKeyConditionpush the constant through the key. A range that may wrap is now not monotonic.t Tuple(DateTime, UInt8)with a key over the tuple (cityHash64(t),t.1, a skip index), queried under anothersession_timezonethan at creation:t = ('2026-01-01 12:00:00', 1)returns 0 rows instead of 8. Fix rows silently dropped by pruning when a string constant is compared with a zone-less DateTime key #120114 read such text in the session zone only for a top-level constant; tuple elements are now read the same way, by position.Price of 1, the trade-off #117394 (comment) left to a maintainer: a range on a
DateTime64/Date32column no longer prunes through atoDate/toDateTimekey of it. That includes ClickStack's defaultotel_traceskey(ServiceName, SpanName, toDateTime(Timestamp)): aTimestampwindow there then prunes only through the daily partition and anyServiceName/SpanNamecondition. OnORDER BY toDate(ts), 1M rows over 1000 days, last 10 days: 2/123 granules before, 123/123 after. Equality still prunes,DateTimesources keep the pushdown, andPARTITION BY toDate(ts)still prunes parts through the Min-Max index onts(6/996 either way). The alternative that keeps it: allow the pushdown only for parts whose Min-Max index on the source column lies inside theDate/DateTimerange (possible when that column is in the partition key, as inotel_traces).05401and05402fail on master;03980changes only in its partition-key conditions (nowtrue).🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/125960]