Skip to content

Fix key analysis skipping rows for wrapping toDate keys and date-time text in tuple constants - #125960

Open
groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:fix-key-condition-wrapping-todate-tuple-text-timezone
Open

groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:fix-key-condition-wrapping-todate-tuple-text-timezone

Conversation

@groeneai

@groeneai groeneai commented Oct 15, 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 and partition pruning skipping matching rows in two cases: a range condition on a DateTime64 or Date32 column whose key is toDate, toDateTime or CAST(... AS Date) of that column while some stored values lie outside the Date or DateTime range, and a Tuple column with a DateTime element compared with a tuple constant holding date-time text when session_timezone differs 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:

  1. ORDER BY toDate(ts) over ts DateTime64(3, 'UTC') holding 1969-12-31 12:00:00 and 1970-01-01 12:00:00: WHERE ts <= '1970-01-02' returns 1 row instead of 2. Same for PARTITION BY toDate(ts), toDateTime(ts), CAST(ts AS Date) and Date32 sources. Under the default date_time_overflow_behavior = 'ignore' these conversions wrap (toDate('1969-12-31 12:00:00') is 2149-06-06) and the key stores the wrapped value, yet their monotonicity claim let KeyCondition push the constant through the key. A range that may wrap is now not monotonic.
  2. t Tuple(DateTime, UInt8) with a key over the tuple (cityHash64(t), t.1, a skip index), queried under another session_timezone than 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/Date32 column no longer prunes through a toDate/toDateTime key of it. That includes ClickStack's default otel_traces key (ServiceName, SpanName, toDateTime(Timestamp)): a Timestamp window there then prunes only through the daily partition and any ServiceName/SpanName condition. On ORDER BY toDate(ts), 1M rows over 1000 days, last 10 days: 2/123 granules before, 123/123 after. Equality still prunes, DateTime sources keep the pushdown, and PARTITION BY toDate(ts) still prunes parts through the Min-Max index on ts (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 the Date/DateTime range (possible when that column is in the partition key, as in otel_traces).

05401 and 05402 fail on master; 03980 changes only in its partition-key conditions (now true).

🤖 Generated with Claude Code


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

…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]>
@groeneai

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 review (1 major, 2 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ The price of fix 1 was shown on a synthetic table only; the same lost range pushdown hits toDateTime(Timestamp) keys such as ClickStack's otel_traces AGREE, fixed in the description The description names it and the one alternative
2 ⚠️ 05402 asserts that pruning stays active only for the cityHash64(t) table DISAGREE The t.1 and skip-index tables reach the helper with the same input type; dropping the nested recursion or the DateTime64 leaf turns their count lines red (0 instead of 8 on master)
3 💡 Keys computed under date_time_overflow_behavior = 'saturate' or 'throw' also lose the pushdown DISAGREE The behaviour a part was written under is not recorded, so no table can be proven free of wrapped keys

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

Session id: cron:clickhouse-review-slot-8:20261015-062000

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes: 05401 / 05402 fail on master on every run (1 vs 2 rows, 0 vs 8 rows), also on 26.8.21.12 and 26.3.33.24.
b Root cause explained? (1) toDate/toDateTime wrap under date_time_overflow_behavior = 'ignore' but reported is_always_monotonic_where_defined, so KeyCondition pushed constants through keys stored wrapped. (2) Tuple text elements were CAST in the time zone of the table's types, not the session's.
c Fix matches root cause? Yes: the trait no longer claims monotonicity for a range that may wrap; the existing text normalization now covers tuple elements.
d Test intent preserved / new tests added? Two new SQL tests, each wrong line paired with a full-scan countIf; controls for equality pruning, DateTime pushdown and tuple pruning. 03980 keeps its intent; only its partition-key condition text changes.
e Both directions demonstrated? Yes: runner FAIL on master (inverse diff on every wrong line), OK with the fix; 100/100 randomized runs OK.
f Fix is general across code paths? Both wrapping producers fixed (CAST AS Date/DateTime shares them); the throwing producer is kept. Both KeyCondition call sites of the helper are covered.
g Fix generalizes across inputs (params/datatypes/wrappers)? DateTime64/Date32, Nullable keys, ORDER BY/PARTITION BY, range/BETWEEN/equality/IN; DateTime/DateTime64/Nullable tuple elements, nested and named tuples, skip index, explicit-zone element.
h Backward compatible? (maintainer-approved exception only) Yes: no setting or format change. Range pruning through toDate(dt64)-style keys is lost (measured in the description).
i Invariants and contracts preserved? Yes: the fields the consumers read for these ranges were already false; the helper only mutates a local copy and declines (no atom) on a failed conversion.

Session id: cron:clickhouse-impl-slot-5:20261015-053600

@clickhouse-gh

clickhouse-gh Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0cb2781]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) FAIL
05345_text_index_prewhere_read_step_order FAIL cidb
01513_optimize_aggregation_in_order_memory_long NOT_FAILED cidb
01414_push_predicate_when_contains_with_clause NOT_FAILED cidb
02884_create_view_with_sql_security_option NOT_FAILED cidb

AI Review

Summary

Reviewed #125960 at 0cb2781af37e271be4c89569d6d71f43d47eb130. The change prevents unsafe range pruning through wrapping date conversions and normalizes date-time text in tuple constants using comparison semantics. No outstanding findings remain; the previous Dynamic/Variant sibling-type issue is addressed by preserving child columns and adding regression cases. Its review thread has been resolved.

Missing context / blind spots
  • ⚠️ The latest commit's build and targeted test artifacts were not available during review, and no matching local binary was available. Passing CI results for 05401, 05402, 03980, and 05293 would close this validation gap.
Final Verdict

✅ Approve based on the current code and regression coverage, subject to normal CI completion.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @yariks5s @Algunenano, could you review this and add can be tested? I cannot add labels at the moment, so CI has not started. It stops toDate/toDateTime from claiming monotonicity over a range where they wrap, so key analysis no longer pushes a constant through a key that stores wrapped values, and it reads date-time text inside tuple constants in the session time zone, as top-level text already is.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 15, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Oct 15, 2026
groeneai and others added 3 commits October 15, 2026 08:09
…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]>
@nihalzp nihalzp added the can be tested Allows running workflows for external contributors label Oct 15, 2026
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
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]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 0cb2781af37e271be4c89569d6d71f43d47eb130 was not compared: the CI logs cluster did not answer (exception 241, code 500: { "meta": [ { "name": "file", "type": "String" }, { "name…).

See the job log for details.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 0cb2781

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
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05345_text_index_prewhere_read_step_order flaky, not from this PR (it changes key analysis for toDate keys and tuple constants, not text indexes): the known read_order_index_first 0 -> 1 diff in the ParallelReplicas lane, 107 of 107 reruns passed; it failed on 65 PRs and on master in the last 30 days #125892 (mine, open)
Mergeable Check, PR praktika rollups of the row above #125892 (mine, open)

Both Bugfix validation (functional tests) jobs passed; their FAIL rows are the inverted result for 05293_key_condition_monotonic_transform_strict_bounds, an existing test this PR adjusts, which passes on master. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261015-190014

opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Nov 6, 2026
…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]>
@clickhouse-gh clickhouse-gh Bot added comp-key-condition Analysis of a filter against a key. KeyCondition turns a WHERE condition into ranges over the pri... and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 19, 2026

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-key-condition Analysis of a filter against a key. KeyCondition turns a WHERE condition into ranges over the pri... 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