Repository navigation
Significantly optimize JSON-to-JSON type conversion to avoid full serialize+parse - #107866
Conversation
When converting between JSON types with different parameters (typed paths, skip rules), avoid the expensive full serialize-to-string + parse-from-string pipeline. Instead, reuse unchanged sub-columns by pointer (COW), CAST only changed typed paths, and rebuild only the affected portions. The optimization handles: - Unchanged typed paths: shared by pointer - Changed typed paths: direct CAST between types - New typed paths: from dynamic paths (via CAST or JSON parser), from shared data (via JSON parser + typed node), or filled with defaults - Removed typed paths: converted to Dynamic via promotable type CAST or JSON parser + `DynamicNode`, placed in dynamic paths or shared data - Skip rules: applied to dynamic paths, shared data entries, and removed typed paths - Shared data: reused by pointer when unaffected, rebuilt with sorted merge when entries need extraction or removal Falls back to the format+parse pipeline for structural types (Tuple, Map, Nested, sub-object JSON) and when `max_dynamic_paths`/`max_dynamic_types` change. Uses the JSON parser + `buildJSONExtractTree` node path (same as Object deserialization) for typed-to-Dynamic and Dynamic-to-typed conversions to ensure type inference matches the standard pipeline. Key changes: - `FunctionsConversion.cpp`: `buildObjectConversionPlan`, `convertObjectColumns`, and supporting functions in anonymous namespace - `FunctionsConversion.h`: `json_use_optimized_type_conversion` in `FunctionConvertSettings` - `Settings.cpp`: new `json_use_optimized_type_conversion` Bool setting (default true) - `DataTypeObject.h`: fix `haveSubtypes` to return true - `JSONExtractTree.cpp`: minor style cleanup (clang-tidy) - `03272_json_to_json_cast_4.reference`: updated for optimized path behavior (different dynamic vs shared data allocation, same data values) - New test `04328_json_optimized_type_conversion` covering all branches Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
Workflow [PR], commit [76224a7] Summary: ✅
AI Review
|
…essages Use `castColumnAccurate` instead of `castColumn` in the optimized JSON-to-JSON conversion path (Phase 3: Dynamic → typed) so that numeric overflow is caught instead of silently wrapping. Rewrite `isDynamicElementToTypedCastSafe` with stricter type-group rules to ensure the optimized path only handles conversions where `castColumnAccurate` produces the same result as format+parse: - Int*/UInt*/Float*/Bool → Int*/UInt*/Float*/Bool/String (excluding Float64 → Float32 narrowing, which `accurateCast` rejects). - Date/DateTime/DateTime64 → String only. - String → any simple non-nested type. - Array recurses into element types. Everything else falls back to format+parse. Replace std containers with WithMemoryTracking alternatives (`VectorWithMemoryTracking`, `UnorderedMapWithMemoryTracking`, `UnorderedSetWithMemoryTracking`). Include the offending value in `accurateCast` error messages: - String → numeric: "Cannot parse string '300' as type UInt8" - Numeric → numeric: "Value '300' in column Int64 cannot be safely converted into type UInt8" Add comprehensive test 04329_json_cast_type_safety covering all allowed/disallowed type combinations and overflow behavior. Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=6 K_base=30 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
…ateTime promotion - Fix flaky ordering in 04328 test (Nullable with NULLs section) by using `ORDER BY toString(data::JSON)` to break ties on null `data.a`. - Remove `no-fasttest` tags and `allow_experimental_json_type` setting from both test files. - Add `SET session_timezone = 'UTC'` to 04329 test for determinism. - Skip the optimized JSON conversion path for `accurateCastOrNull` — fall back to format+parse which correctly returns NULL on failure. - Respect `type_json_use_partial_match_to_skip_paths_by_regexp` setting in the skip predicate: use `RE2::FullMatch` when disabled, matching the behavior in `JSONExtractTree.cpp`. - Fix `getPromotedTypeForDynamic` to promote `DateTime` to `DateTime64(9)` when `try_infer_datetimes_only_datetime64` is enabled, matching what the JSON parser would infer in the format+parse path. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…ze-json-type-conversion
…onversion The optimized typed-path conversion (castColumn / castColumnAccurate) bypassed the `type_json_skip_invalid_typed_paths` setting: when enabled, the legacy format+parse path catches per-row coercion failures and inserts defaults, but the direct cast path threw instead. Fix: when the setting is enabled, fall back to format+parse for the three affected code paths and insert defaults on per-row failure: 1. Changed typed paths — use new `convertTypedColumnToTypedSafe` helper instead of `castColumn`. 2. New typed paths from dynamic — use `convertDynamicColumnToTyped` with `skip_on_failure=true` instead of `castColumnAccurate`. 3. Shared-data promotion — catch `insertResultToColumn` / parse failures and leave the row unpopulated (default is inserted at end of row loop). Co-Authored-By: Claude Opus 4.6 <[email protected]>
…:ClickHouse/ClickHouse into optimize-json-type-conversion
…conversion When converting between JSON types with the optimized path, CAST and format+parse can produce different results in two cases: 1. DateTime/DateTime64 with explicit timezone or non-default `date_time_output_format` — the serialized text representation differs from what a plain CAST would produce. 2. String with `try_infer_numbers_from_strings` enabled — CAST keeps the value as String, but format+parse infers "123" as Int64. Add `needsFormatParseFallback` to detect these cases and route them through `convertTypedColumnToDynamic` (format+parse) instead of the fast CAST path. In `JSONExtractTree`, skip the STRING fast path when `try_infer_numbers_from_strings` is enabled so DynamicNode handles the inference. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…zed JSON type conversion Two correctness fixes for the optimized JSON-to-JSON type conversion path: 1. When `date_time_input_format` differs from `cast_string_to_date_time_mode`, the CAST path (using `cast_string_to_date_time_mode`) and the format+parse path (using `date_time_input_format`) produce different DateTime parsing results. Added detection of this divergence in `needsFormatParseFallback` to fall back to format+parse when the settings disagree. 2. When a typed path changes from `Nullable(T)` to non-nullable `T`, the CAST path throws `CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN` on NULL values. Added `removeNullableForCast` helper that strips Nullable before CAST, replacing NULLs with type defaults. Handles `Nullable(T)`, `LowCardinality(Nullable(T))`, and both patterns nested inside `Array(...)`. Co-Authored-By: Claude Opus 4.6 <[email protected]>
master advanced to 26.12, so the settings-history record for the new setting json_use_optimized_type_conversion must be under the current version 26.12, not 26.11. Fixes the Style check settings_changes_history failure. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=107866&sha=17e6c44ea805e7eb7a56803438e30928d660d479&name_0=PR&name_1=Style%20check Co-Authored-By: Claude Opus 4.8 <[email protected]>
… for nested JSON normalization Two more divergences from format+parse: - castMatchesParse accepted conversions whose CAST result differs from the parser: a Decimal paired with a float or another Decimal (CAST does decimal arithmetic, e.g. Float64 0.58 to Decimal64(2) truncates to 0.57, while the parser reads the text 0.58), and a date/time destination fed from a non-identical type (a CAST reads a Time as 1970-01-01 plus the time, the parser reads the text with the current date). Both now require an identical type and otherwise go through the parser. This also removes the strict-vs-skip value difference for these conversions. - convertTypedColumnToTyped and the dynamic<->typed helpers default-constructed JSONExtractInsertSettings, losing the object-parser flags, so normalizing an unchanged nested JSON path (now reached whenever it holds shared data) changed stored keys: json_type_escape_dots_in_keys split a dotted key into nested paths, and the regexp-skip match mode defaulted to partial. The three helpers now initialize escape_dots_in_json_keys, skip_invalid_typed_paths and use_partial_match_to_skip_paths_by_regexp from the format settings, as SerializationJSON::deserializeObject does. Tests: 05820 gains the Decimal and time/date destination conversions (checked identical under optimized strict, optimized skip and format+parse); 05818 gains unchanged nested JSON paths with escaped dotted keys on both shared carriers. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ough the parser The Decimal/date-time fix (7994614) routes a String to DateTime conversion through the parser, so date_time_overflow_behavior = 'throw' now rejects an out-of-range value with INCORRECT_DATA on the optimized path too (previously the direct CAST raised VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE). The optimized and legacy routes now match. Fixes the Fast test failure on 05632. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=107866&sha=7994614dec87b37ab65a41f563325b9badc4e02d&name_0=PR&name_1=Fast%20test Co-Authored-By: Claude Opus 4.8 <[email protected]>
…t parse failures Two more divergences from format+parse: - castMatchesParse accepted FixedString to String, but a CAST strips trailing zero bytes while the parser keeps them, so a FixedString source to String now goes through the parser. - A CAST to a Nullable destination turns a text-parse failure into NULL, while the parser rejects malformed input, so a String source to a Nullable destination now goes through the parser. The parser's extract-tree FixedString node still inserts a null into a Nullable where the format+parse path rejects, so a changed path with a FixedString destination takes the whole-block fallback to match it exactly. Now String to Nullable(UUID)/Nullable(IPv4)/Nullable(IPv6)/Nullable(FixedString) rejects malformed input with INCORRECT_DATA under strict handling (and skips to NULL under type_json_skip_invalid_typed_paths = 1) on both routes, including array elements; FixedString to String keeps its bytes. Tests: 05632 gains the malformed nullable-target rejections (including an array); 05820 gains FixedString to String checked identical under optimized strict, optimized skip and format+parse. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
I merged Since 2026-11-19, stateless tests randomize the MergeTree setting 🤖 Generated with Claude Code |
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=4 K_base=19 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
…uirk Several earlier review fixes sent ordinary conversions through format+parse to reproduce artifacts of the text round trip, which slowed common casts. Keep the CAST result there and record the difference: - A number to Bool uses the CAST (any nonzero is true); the parser truncates through UInt8. - A string to Date uses the CAST, which takes the date part of a date and time string; the parser rejects it. - A negative zero keeps its sign; the round trip writes it as "-0" and reads it back as +0.0. The per-column negative-zero scan, which also ran on unchanged paths, is removed. - FixedString to String uses the CAST, which strips the trailing zero bytes. - Only Time/Time64 conversions go through the parser among date and time types (a CAST reads a number as seconds and a Time as 1970-01-01 plus the time); Date to DateTime and the like use the CAST again. - The whole-block fallback for every FixedString destination is removed. The NULL it was meant to avoid came from the CAST to Nullable, which returns NULL for a string it cannot parse. For that last case, a non-Nullable source to Nullable(T) is now cast to T and wrapped in Nullable, so malformed input is rejected as the parser rejects it, without format+parse. A Nullable string source still goes through the parser, since the rows under its NULLs hold an empty string. removeNullableForCast no longer calls assumeMutable on the nested result: when the array elements hold no NULL, it is the source's own column and stays shared. The array is built from the immutable columns. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… into optimize-json-type-conversion
|
Dear @Fgrtue, 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. |
|
I traced the UBSan abort ( |
`FunctionsConversion.cpp` read `offsets[row - 1]` with `row == 0` in six places added in ClickHouse#107866. `row` is a `size_t`, so the index wraps around before it reaches the `ssize_t` parameter of `PODArray::operator[]`, and the `unsigned-integer-overflow` check of UBSan, enabled in ClickHouse#120906, reports it and stops the server: src/Functions/FunctionsConversion.cpp:2929:73: runtime error: unsigned integer overflow: 0 - 1 cannot be represented in type 'size_t' (aka 'unsigned long') #0 newLeafTypedPathsNeedFormatParse src/Functions/FunctionsConversion.cpp:2929:73 ClickHouse#1 DB::detail::(anonymous namespace)::convertObjectColumns src/Functions/FunctionsConversion.cpp:3343:9 Since the merge of that pull request, the `asan_ubsan` stateless tests on master fail with `UndefinedBehaviorSanitizer: undefined behavior (STID: 0993-9a84)` and `Server died`: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=e903e8848f033e59d209c21e5258e617157ba884&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20distributed%20plan%2C%20parallel%29 Use the signed form `offsets[static_cast<ssize_t>(row) - 1]`, as the rest of the code does. Co-Authored-By: Claude Fable 5.2 <[email protected]>
- `03272_json_to_json_cast_4`: with `json_use_optimized_type_conversion = 0` the legacy format+parse conversion splits the paths between dynamic paths and shared data as the reference did before #107866 updated it; the values are the same. - `05832_join_runtime_filter_bool_cast_key`: the `datetime_time_zone` query prunes only through a `bloom_filter` skip index, which is probed with the exact values of the runtime filter. With `join_runtime_filter_exact_values_limit = 1` its 3 build values become a bloom runtime filter and no granule is dropped (470 with the default limit). https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=106734&sha=456c6c22fb08ccb2359b1a5d2172289fbf6e0ad2&name_0=PR #106734 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…use#107866 Since ClickHouse#107866 a plain CAST of a scalar typed path takes the optimized conversion, so the text round trip is reached through accurateCastOrNull and json_use_optimized_type_conversion = 0. Add both cases, and run the DST fall-back case without the optimized conversion so it still checks the UTC rewrite. 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):
Significantly optimize JSON-to-JSON type conversion to avoid full serialize+parse. Old behaviour can be used by disabling
json_use_optimized_type_conversion.Workflow [PR]
Sync PR [sync-upstream/pr/107866]
Version info
26.12.1.319-master(included in26.12and later)