Skip to content

Serialize decimal-backed constants exactly in distributed queries - #95055

Merged
alexey-milovidov merged 25 commits into
masterfrom
fix-ast-literal-decimal
Aug 26, 2026
Merged

alexey-milovidov merged 25 commits into
masterfrom
fix-ast-literal-decimal

Conversation

@yakov-olkhovskiy

@yakov-olkhovskiy yakov-olkhovskiy commented Jan 24, 2026 •

Copy link
Copy Markdown
Member

Fix serialization of decimal-backed constants (Decimal, DateTime64, Time64) when a query tree is rebuilt into SQL for distributed / serialized-plan execution.
A DateTime64 constant's underlying value is a scaled decimal. Its raw decimal text used to be serialized as a quoted string and cast to DateTime64 on the shard, where the string is parsed by the date-time text heuristics: fromUnixTimestamp64Milli(0, 'UTC') became _CAST('0', 'DateTime64(3, \'UTC\')) and failed with CANNOT_PARSE_DATETIME (the reported issue), while other values (e.g. 0.5) were silently parsed into the wrong date. Serializing such constants as bare numeric literals instead rounds them through Float64, and is still wrong for high-scale Decimal / DateTime64 / Time64.
Instead of changing the generic Field rendering, the two sites that turn a constant into SQL for a shard now serialize every decimal-backed leaf as an exact String -> Decimal cast with a precision-safe carrier type, reconstructed with the leaf's own type so it round-trips losslessly: ConstantNode::toASTImpl (including the IN / notIn right-hand side) and tryBuildAdditionalFilterAST (the distributed predicate-AST pushdown in ReadFromRemote). The shared helper columnConstantToExactLiteralAST also handles values nested in Array / Tuple / Map / Variant / Dynamic, and names a Variant's active member type explicitly, because conversion to Variant is allowed only from a type equal by name to one of its members.
Closes: #94612
Related: #108425

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 distributed queries that filter or compute on Decimal, DateTime64, or Time64 constants: pushed-down constants could fail with CANNOT_PARSE_DATETIME, lose precision, or change their Dynamic subtype when sent to remote shards.

Documentation entry for user-facing changes

  • Documentation is not required.

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

@clickhouse-gh

clickhouse-gh Bot commented Jan 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7911466]

Summary: ✅


AI Review

Summary

This PR moves decimal-backed constant serialization out of generic Field formatting and into dedicated exact-AST builders for ConstantNode and distributed filter pushdown, which is the right direction. The remaining problem is that two supported surfaces still violate the promised exact round-trip: LowCardinality(DateTime64/Time64) still falls through to the default literal path, and typed JSON(... DateTime64 ...) constants still change meaning under the legacy datetime-number compatibility setting.

Findings

❌ Blockers

  • [src/Analyzer/Utils.cpp:1655-1780] columnConstantToExactLiteralASTImpl still has no TypeIndex::LowCardinality branch. Because typeMayContainDecimal routes LowCardinality(DateTime64/Time64) here, the default path builds _CAST('<raw decimal field>', 'LowCardinality(...)'); convertFieldToType unwraps that to the dictionary type, and the nested DateTime64 / Time64 deserializers treat the quoted value as date-time text instead of the exact decimal carrier. That still reproduces the original CANNOT_PARSE_DATETIME shape for LowCardinality(DateTime64(3, 'UTC')) and leaves LowCardinality(Time64) non-exact as well. Suggested fix: add a TypeIndex::LowCardinality case that serializes the selected dictionary value with the dictionary type via columnConstantToExactLiteralASTImpl, then casts back to the full LowCardinality(...) type.
  • [src/Analyzer/Utils.cpp:1771-1777] The typed-JSON DateTime64 path is still setting-dependent. This branch emits a bare JSON number for typed DateTime64 leaves, but SerializationDateTime64::deserializeTextJSON switches that number back to raw ticks when input_format_read_datetime_number_as_raw_value = 1 (or compatibility = '26.7'). A distributed constant such as {"a":1698543000} in JSON(a DateTime64(9, 'Europe/Berlin')) is then re-read as 1970-01-01 00:00:01.698543000, not the original 2023 instant. Internal remote-constant serialization should not depend on an input-compatibility knob.
Tests
  • ⚠️ Add a focused distributed regression for LowCardinality(DateTime64(3, 'UTC')) and LowCardinality(Time64(9)) (with allow_suspicious_low_cardinality_types = 1 if needed); the current new tests cover naked, nested, Variant, Dynamic, and typed-JSON cases, but not the wrapper that still falls through.
  • ⚠️ Add the typed JSON(a DateTime64(...)) regression under SET compatibility = '26.7' or SET input_format_read_datetime_number_as_raw_value = 1; the current test only proves the default-setting path.
Final Verdict

Changes requested.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.00% 87.00% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.20% -0.10%

Changed lines: Changed C/C++ lines covered: 226/233 (97.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jan 24, 2026
@evillique evillique self-assigned this Jan 26, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 1, 2026

Copy link
Copy Markdown
Contributor

Dear @evillique, 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.

@clickhouse-gh clickhouse-gh Bot assigned evillique and unassigned evillique Jun 1, 2026
@cv4g cv4g self-assigned this Jun 23, 2026
@cv4g
cv4g force-pushed the fix-ast-literal-decimal branch from 837c366 to e9d51a5 Compare June 23, 2026 11:53
@cv4g

cv4g commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

Hi, I've merged master and fixed the test. It serializes '1734004810.123'::Decimal64(4) now as 1734004810.123::Decimal64(4). In your original change your reference expected 1734004810.123 which however parses as Float64 and may create type mismatches.

Comment thread src/Common/FieldVisitorToString.cpp Resolved
Comment thread src/Common/FieldVisitorToString.cpp Resolved
Comment thread src/Common/FieldVisitorToString.cpp Resolved
A folded Decimal/DateTime64 constant was serialized for remote shards as a
bare numeric literal, which the receiving parser reads as Float64 and rounds,
losing precision for high-scale values (and a quoted string cast straight to
DateTime64 fails to parse for values such as "0").

ConstantNode::toASTImpl now serializes decimal-backed constants as an exact
String -> Decimal cast with a precision-safe carrier type, then casts that to
the final type, so the value round-trips losslessly across the wire.

Related: #94612

Co-authored-by: Yakov Olkhovskiy <[email protected]>
@CLAassistant

CLAassistant commented Jun 24, 2026 •

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
2 out of 3 committers have signed the CLA.

✅ yakov-olkhovskiy
✅ cv4g
❌ cursoragent
You have signed the CLA already but the status is still pending? Let us recheck it.

Comment thread src/Analyzer/ConstantNode.cpp Resolved
cursoragent and others added 2 commits June 24, 2026 18:34
The previous commit applied the exact String -> Decimal carrier to any constant
whose value is a decimal Field, including DateTime64/Time64 and decimal values
wrapped in Variant. That broke casts like Variant(DateTime64) (Decimal cannot be
cast to a Variant that does not contain it) and altered DateTime64 constants that
were already serialized exactly as date-time text by getFieldFromColumnForASTLiteral.

Restrict the carrier to results that are themselves Decimal, which is the only
case that actually loses precision via the bare-literal/Float64 round trip. Fixes
03381_remote_constants, 04229_distributed_cte_timestamp_rename_103508 and
04323_virtual_row_two_shards_pk_alias.

Co-authored-by: Yakov Olkhovskiy <[email protected]>
…/Map

The scalar-only fix left decimals inside Array/Tuple/Map constants serialized as
bare numeric literals, which the remote shard re-parses as Float64 and rounds; the
differing column name then makes the query fail with NOT_FOUND_COLUMN_IN_BLOCK.

Build the literal from getFieldFromColumnForASTLiteral (which already renders
DateTime64 and Variant values in their own exact representation) and recursively
upgrade every decimal leaf to an exact String -> Decimal cast, preserving the
Array/Tuple structure, then cast the whole value to the final type. This also lets
us drop the previous Decimal-only result-type restriction: Variant(DateTime64) no
longer yields a decimal leaf, so it keeps its working date-time-text serialization.

Extends 04408_decimal_constant_exact_serialization_dist with Array/Tuple/Map cases.

Co-authored-by: Yakov Olkhovskiy <[email protected]>
Comment thread src/Analyzer/ConstantNode.cpp Resolved
cursoragent and others added 2 commits June 24, 2026 20:55
FunctionNode::toASTImpl sets add_cast_for_constants=false for the second argument
of in/notIn, so the RHS set constant returned before the exact-decimal branch and
was serialized with bare decimal values. An OR-to-IN rewrite over high-scale
Decimal values then built the set from rounded Float64 constants on the shard and
dropped matching rows.

Run the exact-decimal serialization before the add_cast_for_constants short-circuit:
when casts are suppressed, emit the bare structure with exact String -> Decimal leaf
casts (no outer cast); otherwise wrap in the cast to the constant's type as before.
A cheap type-name check avoids materializing the field for decimal-free constants.

Extends 04408 with a distributed OR-to-IN regression over a high-scale Decimal64
value that cannot round-trip through Float64.

Co-authored-by: Yakov Olkhovskiy <[email protected]>
Replace the fragile constant_value_type->getName().find("Decimal") guard with a
proper recursive type check using IDataType::forEachChild and WhichDataType::isDecimal,
matching the idiom used elsewhere (e.g. DataTypeDynamic, SummingSortedAlgorithm).

Co-authored-by: Yakov Olkhovskiy <[email protected]>
Comment thread src/Analyzer/ConstantNode.cpp Resolved
A Dynamic column's declared type is just Dynamic, so the decimal-containment scan
missed a decimal held in Dynamic: the constant fell through to the bare cast path,
the shard parsed it as Float64 and stored it in Dynamic with a Float64 active subtype
instead of Decimal, changing both the value and the dynamic type across shards.

Engage the exact-decimal serialization for Dynamic types too (their runtime value can
be a decimal not visible in the static type); getFieldFromColumnForASTLiteral unwraps
Dynamic to the active value, and fieldContainsDecimal then decides authoritatively.

Extends 04408 with a distributed Dynamic case asserting value and dynamicType.

Co-authored-by: Yakov Olkhovskiy <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 38 queries analysed

This PR only changes how decimal-backed constants (Decimal/Time64/DateTime64/Dynamic) are serialized into literals sent to remote shards for distributed queries; the new path is gated behind a decimal-type check and leaves all other constants on the existing code path. ClickBench Q4 is a simple single-node aggregation with no decimal or remote-shard constants, so it does not exercise anything this PR changes. The flagged 12.6% improvement (from 6 source runs vs 30 base) is off-path and reads as run-to-run variance rather than a real PR effect, so it has been downgraded to not-sure.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 4 not_sure 262 229 -12.6% <0.0001 Q4 (simple AVG agg, no decimal/remote constants) can't be touched by this decimal-serialization change; off-path delta.

q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 13fc31a3-6bc9-454c-8624-16410a8b22c1
  • MIRAI run: 085a44b9-3df1-4c33-89ca-9022cbea2692
  • PR check IDs:
    • clickbench_114129_1782445877
    • clickbench_114136_1782445877
    • clickbench_114146_1782445877
    • tpch_adapted_1_official_114153_1782445877
    • tpch_adapted_1_official_114167_1782445877
    • tpch_adapted_1_official_114175_1782445877

robot-clickhouse added 3 commits August 24, 2026 00:41
`master` now casts a `Variant` constant's literal to its active member type
before casting it to the `Variant` type, because conversion to `Variant` is
allowed only from a type equal by name to one of its members and a bare
literal does not keep that type (an `Array(UInt64)` is inferred back as
`Array(UInt8)`, a `Point` as `Tuple(Float64, Float64)`).

The exact decimal-backed serialization added here returns before that code
whenever the type may contain a decimal, so a `Variant` that has a `Decimal`
member but currently holds a value of another member reached the shard as
`_CAST(<bare literal>, 'Variant(...)')` and failed with `CANNOT_CONVERT_TYPE`.
Name the member type in `columnConstantToExactLiteralAST` as well; the
wrapping is skipped for a scalar decimal member, which already casts itself
to its own type.

`Dynamic` now recurses into its active member directly instead of going
through the `Variant` branch: `Dynamic` accepts a value of any type, so its
member type must not be named, and naming it would change the stored subtype.
Since 26.8 an unquoted number for a `DateTime64` in the typed-JSON path is
a Unix timestamp in seconds parsed exactly (`readDateTime64AsNumber`), not
the raw scaled value; the ticks form is only read back under the legacy
`input_format_read_datetime_number_as_raw_value`. The exact serialization
still wrote ticks, so a `DateTime64` leaf of a `JSON` constant reached the
shard multiplied by its scale - this broke `03381_remote_constants`, where
`1970-01-01 00:00:01.000` came back as `1970-01-01 00:16:40.000`.

Write each leaf in the form its own parser expects: the scaled decimal value
for `DateTime64` (which already spells out seconds and the exact fraction)
and the raw integer ticks for `Time64`, whose typed path still reads an
unquoted integer as ticks. Renamed the flag to `datetime64_as_numbers`.

The regression in `04408` used a raw tick count as the test's own input
literal, which the same change now rejects; it uses the seconds form.

Drop the duplicate `ASTExpressionList.h` include (`arm_tidy`) and the
"new analyzer" wording rejected by the style check.
Comment thread src/Analyzer/Utils.cpp
/// local date-time text used by the default String path. Dynamic/shared-data paths keep the text
/// form because their value type is inferred from the JSON token.
return make_intrusive<ASTLiteral>(
getFieldFromColumnForASTLiteralImpl(column, row, type, /*is_inside_object=*/false, /*datetime64_as_numbers=*/true));

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.

This JSON carrier is still setting-dependent for typed DateTime64 leaves. With input_format_read_datetime_number_as_raw_value = 1 (or compatibility = '26.7'), SerializationDateTime64::deserializeTextJSON will route the bare number emitted here through readDateTime64AsRawValue, so a value like {"a":1698543000} in JSON(a DateTime64(9, 'Europe/Berlin')) is read back as raw ticks instead of seconds. That turns the serialized 2023 instant into 1970-01-01 00:00:01.698543000 on the shard.

Internal remote-constant serialization should stay invariant under input-compatibility settings, the same way the non-JSON DateTime64 path had to avoid cast_string_to_date_time_mode. Please switch this typed-JSON DateTime64 path to a carrier whose meaning does not depend on input_format_read_datetime_number_as_raw_value, and add a focused distributed regression with that setting enabled.

@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 791146662 with master 3c3a54e67 (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
Binary Master PR Δ
programs/clickhouse-stripped 705.71 MiB 702.70 MiB -3.01 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes

4 object files changed (+64.84 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Analyzer/Utils.cpp.o 420.82 KiB 485.87 KiB +65.05 KiB (+15.46%)

737 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

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

Job report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 26, 2026
Merged via the queue into master with commit 0dbe72f Aug 26, 2026
177 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-ast-literal-decimal branch August 26, 2026 02:23
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 26, 2026
@clickgapai

clickgapai commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor
Reproducer
-- Run against a normal single server (remote('127.0.0.{1,2}') hits it twice).
SET enable_analyzer = 1;

CREATE TABLE ts_94612
(
    device_id UInt32,
    data_time DateTime64(3, 'UTC'),
    data_value UInt64
)
ENGINE = MergeTree ORDER BY (device_id, data_time);

INSERT INTO ts_94612 VALUES (100, fromUnixTimestamp64Milli(1697547086760), 3), (100, fromUnixTimestamp64Milli(1697547086761), 4);

SELECT data_time, max(data_value)
FROM
(
    SELECT device_id, data_time, max(data_value) AS data_value
    FROM remote('127.0.0.{1,2}', currentDatabase(), ts_94612)
    GROUP BY device_id, data_time
)
WHERE data_time >= fromUnixTimestamp64Milli(0, 'UTC')
GROUP BY data_time
ORDER BY data_time;

-- 25.8.33.6: Code: 41. DB::Exception: Cannot parse DateTime: In scope
--   SELECT ... HAVING data_time >= _CAST('0', 'DateTime64(3, \'UTC\')'). (CANNOT_PARSE_DATETIME)
-- Expected (and what 25.2 / master return): the two 2023-10-17 12:51:26.760|.761 rows.

Results:

  • Reproduces on: 26.7, 26.6, 26.5, 26.3, 25.8
  • Does not reproduce on: master
  • Tested versions: master, 26.7, 26.6, 26.5, 26.3, 25.8
  • Also tested (unsupported, context only): 26.2 reproduces
  • ✓ Fix is on master — this PR's change fixes the bug on master. The releases listed above still have the bug and need the backport.

Backport the fix to 26.7, 26.6, 26.5, 26.3, 25.8.

CC component owner: @KochetovNicolai @novikd

Analysis metadata

comp-query-analyzer · Severity P2 · Finding phase_d_pr95055

  • Verified against master build 573230bfe668 (aarch64)
Introducing change: not identified
  • Secondary components: comp-testing, comp-query-optimizer

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 30, 2026
… a shard

The exact literal serializer recursed into a `Dynamic` constant's active member
without naming its type, so the secondary server re-inferred it from the literal:
an `Enum8('7' = 3)` member arrived as `_CAST(3, 'Dynamic')` and was rebuilt as
`UInt8`, a `UInt64` as `UInt8`, an `IPv4` as `String`, a `Map` as an `Array` of
tuples. `IN` then compared against the wrong value, and `=` raised
`NO_COMMON_TYPE`.

Serialize the member the way the `Variant` case already does: name the member
type and then the `Dynamic` type, which also gives `array` and `map` siblings a
common type. The member is recursed with `date_time_as_numbers` forwarded, so a
`DateTime` member travels as its exact timestamp. When the flag is cleared (the
external-database pushdown, which parses the literal itself) the bare member
literal is kept, exactly as before.

This replaces the note added in ClickHouse#95055 that declined to name the member type.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 16, 2026
…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]>
nihalzp pushed a commit to nihalzp/ClickHouse that referenced this pull request Nov 18, 2026
`ReplaceQueryParameterVisitor` substitutes `{ts:DateTime64(3, 'UTC')}` as
`_CAST(<DecimalField>, 'DateTime64(3, \'UTC\')')`. `ASTLiteral` prints a
`DecimalField` as a quoted decimal string, so once the substituted query is
formatted and parsed again (a row policy filter, a column DEFAULT, a
Replicated mutation, ON CLUSTER DDL) the value becomes
`_CAST('20240101', 'DateTime64(3, \'UTC\')')`: a cast from String, which parses
date-time text. With `cast_string_to_date_time_mode = 'best_effort'` an
8-digit number is read as YYYYMMDD, so a row policy `ts <= {ts:DateTime64(...)}`
with a value before 1973-03-03 lets through rows it must hide, a negative value
fails CANNOT_PARSE_DATETIME, and a `Time64` value (decimal seconds are not
`Time64` text) fails CANNOT_PARSE_TEXT on every read. Since ClickHouse#122688 row policy
filters are stored with the parameters substituted, so this is reachable on
26.8+.

Build the substituted AST for any type containing DateTime64 / Time64 with
`columnConstantToExactLiteralAST`, the helper added by ClickHouse#95055 for exactly this
serialization problem in `ConstantNode::toASTImpl` and `ReadFromRemote`: it
writes `_CAST(_CAST('<ticks>', 'DecimalNN(S)'), '<type>')` for every leaf,
also inside Array / Tuple / Map / Nullable, with a carrier wide enough for
DateTime64(9). The parameter visitor runs on the AST before any query tree
exists, so it was the one serialization site that helper did not cover.

Casting from date-time text instead (adding the types to `needCastFromString`)
was rejected: local date-time text is ambiguous across DST overlaps, measured
one hour off for '1730615400.5' as DateTime64(1, 'America/New_York') even in
the query itself. Plain Decimal parameters already round-trip and are left
unchanged, as are Variant / Dynamic / Object and custom-serialization types,
which keep the cast-from-String path.

Already stored broken policies and defaults are not repaired; re-run the
ALTER with the parameter.

Closes ClickHouse#127330

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Development

Successfully merging this pull request may close these issues.

Filter pushdown for distributed table with datetime

9 participants