Repository navigation
Serialize decimal-backed constants exactly in distributed queries - #95055
Conversation
|
Workflow [PR], commit [7911466] Summary: ✅
AI ReviewSummaryThis PR moves decimal-backed constant serialization out of generic Findings❌ Blockers
Tests
Final VerdictChanges requested. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 226/233 (97.00%) · Uncovered code |
|
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. |
837c366 to
e9d51a5
Compare
|
Hi, I've merged master and fixed the test. It serializes |
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]>
|
|
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]>
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]>
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]>
|
📊 Cloud Performance Report ✅ AI verdict: 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. clickbenchFlagged queries (1 of 43)
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
|
…imal # Conflicts: # src/Analyzer/Utils.h
`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.
| /// 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)); |
There was a problem hiding this comment.
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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 sizes4 object files changed (+64.84 KiB total), 0 added.
737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units78 translation units recompiled, 477 s compile time in total, 78 of them have a recent master baseline. |
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:
Backport the fix to CC component owner: @KochetovNicolai @novikd Analysis metadata
Introducing change: not identified
|
… 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]>
…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]>
`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]>
Fix serialization of decimal-backed constants (
Decimal,DateTime64,Time64) when a query tree is rebuilt into SQL for distributed / serialized-plan execution.A
DateTime64constant's underlying value is a scaled decimal. Its raw decimal text used to be serialized as a quoted string and cast toDateTime64on the shard, where the string is parsed by the date-time text heuristics:fromUnixTimestamp64Milli(0, 'UTC')became_CAST('0', 'DateTime64(3, \'UTC\'))and failed withCANNOT_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 throughFloat64, and is still wrong for high-scaleDecimal/DateTime64/Time64.Instead of changing the generic
Fieldrendering, the two sites that turn a constant into SQL for a shard now serialize every decimal-backed leaf as an exactString -> Decimalcast with a precision-safe carrier type, reconstructed with the leaf's own type so it round-trips losslessly:ConstantNode::toASTImpl(including theIN/notInright-hand side) andtryBuildAdditionalFilterAST(the distributed predicate-AST pushdown inReadFromRemote). The shared helpercolumnConstantToExactLiteralASTalso handles values nested inArray/Tuple/Map/Variant/Dynamic, and names aVariant's active member type explicitly, because conversion toVariantis allowed only from a type equal by name to one of its members.Closes: #94612
Related: #108425
Changelog category (leave one):
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, orTime64constants: pushed-down constants could fail withCANNOT_PARSE_DATETIME, lose precision, or change theirDynamicsubtype when sent to remote shards.Documentation entry for user-facing changes
Workflow [PR]
Sync PR [sync-upstream/pr/95055]