Skip to content

Significantly optimize JSON-to-JSON type conversion to avoid full serialize+parse - #107866

Merged
Avogar merged 61 commits into
masterfrom
optimize-json-type-conversion
Nov 23, 2026
Merged

Avogar merged 61 commits into
masterfrom
optimize-json-type-conversion

Conversation

@Avogar

@Avogar Avogar commented Jun 18, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Performance Improvement

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

  • Merged into: 26.12.1.319-master (included in 26.12 and later)

Avogar and others added 2 commits June 18, 2026 14:19
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]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [76224a7]

Summary: ✅


AI Review

⚠️ Review sessions stopped as a cybersecurity risk

The model provider stopped these review sessions as a possible cybersecurity risk:

  • attempt 1: gpt-6.1-sol

This summary comes from a session with gpt-5.4. A session is typically stopped when it reaches a memory-safety finding, and the finding is lost with it, so this review can miss a real defect. Please review the change in detail, and run the review internally with a model that has cyber access.

Summary

This PR replaces most JSON→JSON format+parse conversions with an optimized sub-column reuse path and adds json_use_optimized_type_conversion, but it still leaves one important compatibility hole: metadata-only type changes (for example removing a SKIP rule) bypass both the setting and compatibility mode, so there is no complete way back to the pre-26.12 behavior. Because the PR ships a default-on behavior change without a full rollback path, I would block it until either the legacy escape hatch is honored for those casts or the feature is scoped/documented more narrowly.

PR Metadata
  • Changelog category: Performance Improvement is fine.
  • Changelog entry: the sentence Old behaviour can be used by disabling json_use_optimized_type_conversion. is not accurate today, because metadata-only JSON type changes still bypass the setting. Exact replacement if the code is left as-is: Significantly optimize many JSON-to-JSON type conversions to avoid full serialize+parse. Adds setting \json_use_optimized_type_conversion` to control the optimized path for non-identity conversions.`
Findings

❌ Blockers

  • [src/Functions/FunctionsConversion.cpp:2687] [dismissed by author -- https://github.com/Significantly optimize JSON-to-JSON type conversion to avoid full serialize+parse #107866#discussion_r4638560563] buildObjectConversionPlan/plan.isIdentity() still treat removed SKIP rules as an identity conversion, and the wrapper at [src/Functions/FunctionsConversion.cpp:3851] returns the source column before it ever checks json_use_optimized_type_conversion. That means CAST(j AS JSON) with json_use_optimized_type_conversion = 0 still keeps the new semantics for metadata-only JSON type changes instead of forcing legacy format+parse, which is exactly the rollback path the setting description and changelog promise. The setting history at [src/Core/Settings.cpp:10861] [dismissed by author -- https://github.com/Significantly optimize JSON-to-JSON type conversion to avoid full serialize+parse #107866#discussion_r3452985861] also records true -> true, so SET compatibility = '26.11' cannot restore the pre-26.12 behavior either. This is still a compatibility break without a complete migration path.
    Suggested fix: either route metadata-only JSON type changes through convertObjectViaFormatParse when the setting or compatibility profile requests legacy behavior, or stop advertising json_use_optimized_type_conversion and compatibility as a full way back to the old conversion semantics.
Tests
  • ⚠️ Add a focused stateless regression for removing a SKIP rule under json_use_optimized_type_conversion = 0 and, if compatibility is meant to restore the old behavior, under SET compatibility = '26.11', so the rollback path is proven end-to-end.
Final Verdict

Status: ❌ Block

The optimization work itself is substantial and the CI is green, but the remaining compatibility gap is large enough that I would not merge it as a default-on behavior change yet.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jun 18, 2026
Comment thread src/Functions/FunctionsConversion.cpp Resolved
Comment thread src/Functions/FunctionsConversion.cpp Resolved
…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]>
Comment thread src/Functions/FunctionsConversion.cpp Resolved
Comment thread src/Functions/FunctionsConversion.cpp Resolved
Comment thread src/Functions/FunctionsConversion.cpp Resolved
Comment thread src/Functions/FunctionsConversion.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

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
  • StressHouse run: b01d435d-22f1-46e4-8c39-9d54778c0636
  • MIRAI run: f82e9eb7-468d-49c0-a56f-1a6181648a7a
  • PR check IDs:
    • clickbench_2029501_1790477910
    • clickbench_2029521_1790477910
    • clickbench_2029793_1790477938
    • tpch_adapted_1_official_2029807_1790477939
    • tpch_adapted_1_official_2029844_1790477940
    • tpch_adapted_1_official_2030110_1790477970

…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]>
Comment thread src/Functions/FunctionsConversion.cpp Resolved
Comment thread src/Functions/FunctionsConversion.cpp Resolved
Comment thread src/Core/SettingsChangesHistory.cpp Resolved
Comment thread src/Functions/FunctionsConversion.cpp Resolved
Comment thread src/Functions/FunctionsConversion.cpp Resolved
…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]>
Comment thread src/Functions/FunctionsConversion.cpp Resolved
Comment thread src/Formats/JSONExtractTree.cpp Resolved
Avogar and others added 4 commits July 9, 2026 14:51
…: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]>
Comment thread src/Functions/FunctionsConversion.cpp Resolved
Comment thread src/Functions/FunctionsConversion.cpp Resolved
…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]>
Comment thread src/Functions/FunctionsConversion.cpp Resolved
Avogar and others added 2 commits November 20, 2026 01:48
… 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]>
Comment thread src/Functions/FunctionsConversion.cpp Resolved
…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]>
Comment thread src/Functions/FunctionsConversion.cpp Resolved
@nickitat

Copy link
Copy Markdown
Member

I merged master into this branch to pick up #133069.

Since 2026-11-19, stateless tests randomize the MergeTree setting enable_adaptive_codec_selection, and 05293_autopr_statistics_plan_based failed in this PR's CI because of that, not because of the changes here. The fix pins the setting in the test; it is in master now, so the next CI run should not hit it.

🤖 Generated with Claude Code

@stresshouse

stresshouse Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

📊 Cloud Performance Report

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

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
  • StressHouse run: f9925991-84b8-4276-a9ff-945250d42a0f
  • MIRAI run: 012b5f9c-5c15-4b6e-9a90-b5f623d9f4c6
  • PR check IDs:
    • clickbench_529539_1795202716
    • clickbench_529546_1795202716
    • tpch_adapted_1_official_529581_1795202716
    • tpch_adapted_1_official_529602_1795202716

Avogar and others added 2 commits November 20, 2026 13:17
…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]>
@Avogar
Avogar enabled auto-merge November 23, 2026 13:15
@clickhouse-gh

clickhouse-gh Bot commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

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.

@Avogar
Avogar added this pull request to the merge queue Nov 23, 2026
Merged via the queue into master with commit e903e88 Nov 23, 2026
196 checks passed
@Avogar
Avogar deleted the optimize-json-type-conversion branch November 23, 2026 20:19
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 23, 2026
@groeneai

Copy link
Copy Markdown
Collaborator

I traced the UBSan abort (unsigned integer overflow: 0 - 1 in convertObjectColumns, FunctionsConversion.cpp:3649 and :2929) that kills the server in the amd_asan_ubsan and arm_asan_ubsan stateless jobs on master to this PR: the reproducer crashes at its merge commit e903e88 and not at its first parent ace90f6 (amd_asan_ubsan builds). I opened a revert: #133935. A maintainer can choose the revert or the fix in #133910.

zghong pushed a commit to zghong/ClickHouse that referenced this pull request Nov 24, 2026
`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]>
PedroTadim added a commit that referenced this pull request Nov 24, 2026
- `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]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 24, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-json-datatype JSON/Dynamic/Object datatype: semi-structured column storage, typed and dynamic paths, sub-object... pr-performance Pull request with some performance improvements 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.

7 participants