Skip to content

Fix DateTime64, Date32, Time and Time64 constants past the range of their type in queries sent to remote shards and parallel replicas - #126262

Open
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:fix-datetime64-constant-past-range-remote
Open

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:fix-datetime64-constant-past-range-remote

Conversation

@groeneai

@groeneai groeneai commented Oct 16, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #124831
Related: #95055

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 wrong results of remote, Distributed and parallel-replicas queries with a DateTime64, Date32, Time or Time64 constant past the range of its type, such as WHERE d < toDate32('9999-12-31') + 1 or WHERE valid_to < toDateTime64('9999-12-31 23:59:59', 0, 'UTC') + INTERVAL 1 SECOND: the other server compared against a different value, usually the boundary of the range, or threw VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE with date_time_overflow_behavior = 'throw'.

Description

On 26.8.21.12, with a Date32 table holding 0000-01-01, 9999-12-31 and the day beyond each, SELECT count() FROM remote('127.0.0.1', db.t) WHERE d < toDate32('9999-12-31') + 1 returns 2, while the same filter on the local table returns 3. Time (toTime('999:59:59') + 1), DateTime64 and, on master, Time64 behave the same through remote(), Distributed, parallel replicas and the filter pushdown.

Arithmetic produces such values without a range check. Both places that print a constant into the query for another server (ConstantNode::toASTImpl and the filter pushdown in ReadFromRemote, via columnConstantToExactLiteralAST) sent forms the receiver converts with a range-checked cast: Date32 text (already saturated by the sender), a Time second count, the Decimal carrier for DateTime64/Time64. The cast saturates, or throws under throw.

A DateTime64 leaf is now sent as its raw ticks, _CAST(reinterpret(_CAST('253402300800', 'Int64'), T), T). reinterpret does not accept the other three types on any release, so a Date32/Time/Time64 value past its range is sent as an in-range value plus an offset, which is not range-checked: _CAST(plus(_CAST(0, 'Date32'), 2932897), 'Date32'); for Time64 the sub-second part keeps the carrier. Other constants keep their text, except that Date32/Time values nested in a constant already sent exactly (e.g. one holding a Decimal) are now cast to their type, so an array mixing in-range and out-of-range values has one element type. 26.3, 26.8 and 26.9 receivers evaluate the new forms exactly.

Validation: the test fails on master and passes with the fix, including 50 randomized runs and the parallel-replicas and replicated-database configurations.


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

groeneai and others added 2 commits October 16, 2026 09:22
A DateTime64 constant printed into the query for a shard or replica (by
ConstantNode::toASTImpl and by the ReadFromRemote filter pushdown, both via
columnConstantToExactLiteralAST) was sent as a decimal carrier cast back to
DateTime64. That conversion is range-checked: past 9999-12-31 23:59:59 it
saturates (or throws with date_time_overflow_behavior = 'throw'), while
DateTime64 arithmetic produces such values with no check. So
`valid_to < toDateTime64('9999-12-31 23:59:59', 0, 'UTC') + INTERVAL 1 SECOND`
over remote(), a Distributed table or parallel replicas compared against
9999-12-31 23:59:59 and returned fewer rows than the same query locally.

Send the raw Int64 ticks reinterpreted into the type instead, under an
identity _CAST so that the receiver keeps naming the constant like the
initiator (ConstantNode::receivedFromInitiatorServer). The String -> Int64
hop keeps the source 8 bytes wide: a bare integer literal is typed as the
smallest integer type, which reinterpret would zero-fill. reinterpret to
DateTime64 exists on every supported version (26.3 and 26.8 measured).

Time64 keeps the decimal carrier: reinterpret does not support it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten the DateTime64 and Time64 case comments in columnConstantToExactLiteralASTImpl to the invariants they state.

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

groeneai commented Oct 16, 2026 •

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

Date32 / Time / Time64 commit: review by an independent model (engine: codex; 4 findings) plus my own review (4 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ Pushdown arm stays green if the pushdown declines DISAGREE Unfixed binaries return the wrong rows on this arm ([] for Date32, 1 instead of 2 for DateTime64), which only a shard applying the pushed constant can produce
2 ⚠️ Parallel-replicas arms stay green if replicas are not used DISAGREE Unfixed binaries give count 1 instead of 2 and NOT_FOUND_COLUMN_IN_BLOCK ... While executing Remote
3 💡 OR chain line has in-range constants DISAGREE It guards the new in-range DateTime64 spelling inside an IN set
4 ⚠️ Mixed-version proof DISAGREE Measured: a fixed initiator against 26.3, 26.8 and 26.9 receivers returns the local answer for every type and form, under ignore, throw and saturate
5 💡 Description overstated that only past-range values change text AGREE, fixed Description now says nested Date32/Time values in an exactly-sent constant are cast to their type
6 💡 Changelog said "the last value of the range" AGREE, fixed Now "a different value, usually the boundary of the range"
7 💡 A comment in hasDateOrTimeOutOfRange does not hold for a LowCardinality dictionary AGREE, comment removed A false positive only sends the constant in the exact form, which is still exact
8 💡 Time/Time64 have no pushdown or parallel-replicas arm AGREE, not blocking Same code path as the Date32 arms

DateTime64 commit: review by an independent model (engine: codex; 1 finding) plus my own review (2 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ The pushdown, parallel-replicas and serialize_query_plan arms of 05404 may pass without the path running; index use is not asserted DISAGREE On master these arms give 1, 1, 1 and NOT_FOUND_COLUMN_IN_BLOCK vs local 2, so the other server evaluated the constant; the secondary query reads the same rows on master and with the fix.
2 💡 The in-range OR chain and the GROUP BY constant arm also pass on master AGREE, not blocking They check the new form still works; the IN list is covered by the IN (...) arm, which fails on master.
3 💡 Title and changelog entry named only the upper end of the range AGREE, fixed in the description They now also say "before 0000-01-01".

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

Session id: cron:clickhouse-review-self-slot-58:20261016-215400

@groeneai

groeneai commented Oct 16, 2026 •

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. One server, remote('127.0.0.2') looping back: t < toTime64('999:59:59', 0) + 1, t < toTime('999:59:59') + 1 and d < toDate32('9999-12-31') + 1 give 1 row locally and 0 remotely on every run; LowCardinality(Date32) arrives as day 33.
b Root cause explained? Arithmetic produces a Date32/Time/Time64 value past the range of its type; the constant printer sent it as date text (already saturated by the sender), a second count, or a Decimal carrier, and the receiver's cast back saturates (or throws under date_time_overflow_behavior = 'throw').
c Fix matches root cause? Yes. Such a value is sent as an in-range value of the type plus an offset, which involves no range-checked conversion; the change is in columnConstantToExactLiteralAST, used by both printers.
d Test intent preserved / new tests added? The PR's test is renamed to 05404_date_time_constant_out_of_range_remote and extended with remote() </IN, the pushdown, parallel replicas, Time/Time64 incl. throw, and nested / LowCardinality / mixed-array rows. All DateTime64 lines kept.
e Both directions demonstrated? Yes. The test fails on the previous PR head and on master (return code: 65, every new line differs) and passes with the fix; 50/50 randomized runs, parallel-replicas lane at parallel_replicas_local_plan 0 and 1, and the replicated-database lane pass.
f Fix is general across code paths? Both callers (ConstantNode::toASTImpl, tryBuildAdditionalFilterAST) go through constantNeedsExactLiteralSerialization. serialize_query_plan = 1 ships binary columns (exact). JSON typed paths saturate when the JSON value is built, locally too. Date/DateTime cannot hold a value past their range.
g Fix generalizes across inputs (params/datatypes/wrappers)? Nullable, LowCardinality, LowCardinality(Nullable), Array (also mixing in-range and out-of-range values, with use_variant_as_common_type 0 and 1), Map key and value, Tuple, Variant, Dynamic, Dynamic(max_types = 0), empty containers, NULL; Time64 scales 0/1/3/6/9; both range ends; Int32 and Int64 extremes.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change. In-range constants keep their text byte for byte at the top level; 26.3.33.24, 26.8.21.12 and 26.9 receivers evaluate the new forms exactly under ignore, throw and saturate.
i Invariants and contracts preserved? The sent expression has exactly the declared type (outer _CAST), so both callers still skip the identity cast and the receiver names the constant like the initiator (checked over parallel replicas). Array and Map elements keep one element type.

Session id: cron:clickhouse-impl-self-slot-57:20261016-210400

@clickhouse-gh

clickhouse-gh Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1ce97f7]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_debug, parallel) FAIL
05339_string_filters_during_scan_parquet_short_dictionary_values FAIL cidb
Stateless tests (amd_debug, distributed plan, s3 storage, parallel) FAIL
05339_string_filters_during_scan_parquet_short_dictionary_values FAIL cidb
Stateless tests (arm_binary, parallel) FAIL
05339_string_filters_during_scan_parquet_short_dictionary_values FAIL cidb
Stateless tests (arm_asan_ubsan, azure, parallel) FAIL
05339_string_filters_during_scan_parquet_short_dictionary_values FAIL cidb
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 2/2) FAIL
05339_string_filters_during_scan_parquet_short_dictionary_values FAIL cidb
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) FAIL
05339_string_filters_during_scan_parquet_short_dictionary_values FAIL cidb
01513_optimize_aggregation_in_order_memory_long NOT_FAILED cidb
01414_push_predicate_when_contains_with_clause NOT_FAILED cidb
Stateless tests (arm_binary, AsyncInsert, s3 storage, parallel) FAIL
05339_string_filters_during_scan_parquet_short_dictionary_values FAIL cidb
02912_ingestion_mv_deduplication NOT_FAILED cidb
03008_deduplication_cases_from_docs NOT_FAILED cidb
03008_deduplication_insert_into_partitioned_table NOT_FAILED cidb
00952_insert_into_distributed_with_materialized_column NOT_FAILED cidb

AI Review

Summary

Preserves out-of-range DateTime64, Date32, Time, and Time64 constants in queries sent to remote shards and parallel replicas. No actionable findings. The new regression test, two existing serialization and filter-pushdown tests, and 24 integer-boundary cases under all three overflow modes passed against the PR's CI binary.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 16, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @yakov-olkhovskiy @KochetovNicolai, could you review this? A DateTime64 constant past 9999-12-31 23:59:59 was sent to remote shards and parallel replicas through the exact decimal carrier from #95055, and its cast back to DateTime64 saturates on the receiver; the leaf is now sent as its raw Int64 ticks reinterpreted into the type.

@clickhouse-gh clickhouse-gh Bot added the comp-distributed Distributed table engine & query routing across shards (sharding/load balancing). label Oct 16, 2026
groeneai and others added 2 commits October 16, 2026 21:48
…er exactly

A constant printed into the query for another server (`ConstantNode::toASTImpl`, and the filter
pushdown in `ReadFromRemote`) is converted back there by a cast. For these three types every such
form is range-checked, so a value past the range, which arithmetic produces freely
(`toDate32('9999-12-31') + 1`, `toTime('999:59:59') + 1`), reaches the receiver as the boundary:
- `Date32` was sent as date text, which saturates at `0000-01-01` / `9999-12-31` already on the
  sender, or in the pushdown as the raw day number, which a cast reads as a Unix timestamp past
  `DATE_LUT_MAX_EXTEND_DAY_NUM` (2932897 -> day 33);
- `Time` as its second count, and `Int -> Time` saturates at 999:59:59 on 26.8+;
- `Time64` through the exact decimal carrier of ClickHouse#95055, and `Decimal -> Time64` saturates since ClickHouse#117667.
So `remote()`, `Distributed`, parallel replicas and the pushdown filtered on another value than the
initiator (local 1 row, remote 0), and `date_time_overflow_behavior = 'throw'` made the receiver throw.

Such a value is now sent as an in-range value of the same type plus an offset, because arithmetic is
the one operation that is not range-checked:
`_CAST(plus(_CAST(0, 'Date32'), 2932897), 'Date32')`, `_CAST(plus(_CAST(0, 'Time'), 3600000), 'Time')`,
and for `Time64` the sub-second part through the existing carrier plus the whole seconds:
`_CAST(plus(_CAST(_CAST('0.999', 'Decimal32(3)'), 'Time64(3)'), 3600000), 'Time64(3)')`.
`reinterpret`, used for `DateTime64` in the previous commit, does not accept these types on any
released version (`Code: 43`), so it would turn a wrong answer into an error on every older receiver.
The forms above were measured exact on 26.3.33.24, 26.8.21.12 and 26.9 receivers under `ignore`,
`throw` and `saturate`, including the Int32 extremes for Date32/Time, the Int64 extremes for Time64(0),
and Time64(9) near the Int64 tick limit.

Only values past the range change their wire text. `constantNeedsExactLiteralSerialization` sends a
constant through the exact walk when its type needs it or when it holds an out-of-range `Date32`/`Time`
value, so every in-range top-level constant keeps its text byte for byte (measured). Inside the walk an
in-range `Date32`/`Time` leaf is cast to its type, so an array mixing in-range and out-of-range values
has one element type; without the cast the receiver throws `NO_COMMON_TYPE` under
`use_variant_as_common_type = 0`. The walk also learns `LowCardinality`, which `allow_suspicious_low_cardinality_types`
allows around `Date32`/`Time` and which used to send `_CAST(2932897, 'LowCardinality(Date32)')` (day 33).

JSON typed paths are not affected: the value is already saturated when the JSON constant is built,
locally too. The test of the previous commit is renamed to a type-neutral name and extended.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop two comments (one restating a function name, one that does not hold for a LowCardinality dictionary), shorten the makeOffsetCastAST and constantNeedsExactLiteralSerialization comments to one line, and keep the columnConstantToExactLiteralAST doc closer to master's wording.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai changed the title Fix DateTime64 constants outside 0000-01-01..9999-12-31 in queries sent to remote shards and parallel replicas Fix DateTime64, Date32, Time and Time64 constants past the range of their type in queries sent to remote shards and parallel replicas Oct 16, 2026
@clickhouse-gh clickhouse-gh Bot added comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). and removed comp-distributed Distributed table engine & query routing across shards (sharding/load balancing). labels Oct 16, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 17, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 1ce97f702 with master d1959d808 (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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1ce97f7

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 (amd_debug, parallel) / 05339_string_filters_during_scan_parquet_short_dictionary_values master regression from my merged #124131 (semantic conflict with the test added by #124507), not from this PR (it changes only how out-of-range DateTime64, Date32, Time and Time64 constants are sent to remote shards): line 4 prints 0 instead of 1; the tested merge tree 5a37964cfafe does not contain the revert (merged 03:14Z) #126396 (external, merged)
Stateless tests (amd_debug, distributed plan, s3 storage, parallel), (arm_asan_ubsan, azure, parallel), (arm_binary, parallel), (arm_binary, AsyncInsert, s3 storage, parallel), (arm_binary, ParallelReplicas, s3 storage, parallel), (arm_binary, s3 storage, DBReplicated, parallel, 2/2) / 05339_string_filters_during_scan_parquet_short_dictionary_values same master failure, the only failed test in each of these jobs #126396 (the owner of the first row)
Mergeable Check, PR praktika rollups of the rows above #126396 (the owner of the rows above)

#126396 reverts #124131 on master, and #126397 re-lands it with the test adjusted. The only other FAIL rows on this head are the Config Workflow / Pre Hooks and Finish Workflow / Post Hooks rows of the two earlier attempts, which stopped on the missing can be tested label; the final attempt passed both.

Session id: cron:our-pr-ci-monitor:20261017-100010

middas-0706 pushed a commit to middas-0706/ClickHouse that referenced this pull request Oct 28, 2026
…o other servers

A `Decimal(P, S)` value is bounded only by its native integer, not by `P`:
`toDecimal64(1, 18)` is a `Decimal(18, 18)` holding 1, and
`toDecimal32(0.6, 9) + toDecimal32(0.6, 9)` is a `Decimal(9, 9)` equal to 1.2.
The analyzer printed every `Decimal` constant for another server as
`_CAST('<text>', '<type>')`, and the receiver's `String -> Decimal` conversion
(`readDecimalText`) rejects more integer digits than `P - S`, so `remote()`,
`Distributed`, parallel replicas, `IN` sets, the filter pushdown and
`serialize_query_plan = 1` failed with `ARGUMENT_OUT_OF_BOUND` where the local
query succeeded. Released 26.3 and 26.8 behave the same.

Under the ParallelReplicas CI configuration (`parallel_replicas_local_plan = 1`)
the other replicas hit this error in every run of
`05339_decimal_wide_comparison_scale_overflow`, but the coordinator usually
cancels them first, which is why the test failed only once (PR ClickHouse#126018).

A value with `|raw| >= 10^P` (exactly the condition `readDecimalText` rejects) is
now sent as its native integer reinterpreted into the type,
`_CAST(reinterpret(_CAST('<raw>', 'IntN'), T), T)`: a same-width `reinterpret`
copies the bytes, and the outer `_CAST` over constants keeps
`receivedFromInitiatorServer()` true, so the receiver names the column like the
initiator. Values within the precision keep their text form byte-for-byte.
26.3, 26.8 and 26.9 receivers evaluate the new form exactly. Same form as
ClickHouse#126262 uses for `DateTime64` ticks.

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

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-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). 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