Skip to content

Add JSON(DEFAULT PATH TYPE T) type modifier - #119389

Open
amosbird wants to merge 1 commit into
ClickHouse:masterfrom
amosbird:json-default-path-type
Open

amosbird wants to merge 1 commit into
ClickHouse:masterfrom
amosbird:json-default-path-type

Conversation

@amosbird

@amosbird amosbird commented Sep 11, 2026 •

Copy link
Copy Markdown
Collaborator

Add a DEFAULT PATH TYPE T argument to the JSON data type that declares the type of values of all non-typed paths.

Values of non-typed paths are coerced/validated against T at insert (a non-conforming value fails the insert unless type_json_skip_invalid_typed_paths is enabled; JSON null is treated as a missing path). Runtime-discovered dynamic paths are stored as sparse Variant(T) columns instead of Dynamic, and shared data stores bare T values (Array(Tuple(String, T))) instead of self-describing Dynamic blobs. Nullable, Dynamic, Variant and Object are rejected as DEFAULT PATH TYPE.

Missing paths read as default(T) and never appear in output, path enumeration or hashes, even after merges move paths between subcolumn and shared storage. An explicit default(T) value is a real value, distinguishable from a missing path in MAP shared-data serialization; with the ADVANCED shared-data serialization the dense bare-T path columns cannot distinguish an explicit default(T) from a missing path, matching the typed-path read which returns default(T) for a missing path.

Binary encoding version 1 adds the DEFAULT PATH TYPE argument to the JSON type encoding.

Tests: 03553_json_default_path_type (coercion, runtime paths, merges, sub-object and combined subcolumns, nested paths, GROUP BY weak hashes, changing DEFAULT PATH TYPE) and 03553_json_default_path_type_storage (map/map_with_buckets/advanced × compact/wide).

Changelog category (leave one):

  • New Feature

Changelog entry:

Add a DEFAULT PATH TYPE T argument to the JSON data type that declares the type of values of all non-typed paths.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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

@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c5aacf0]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) FAIL
05210_lightweight_update_materialized_cte_in_ignore FAIL cidb
01283_max_threads_simple_query_optimization NOT_FAILED cidb
03273_group_by_in_order_still_used_when_group_by_key_doesnt_match_order_by_key NOT_FAILED cidb
02151_hash_table_sizes_stats_joins_reordered NOT_FAILED cidb

AI Review

Summary

This PR adds JSON(DEFAULT PATH TYPE T) so non-typed JSON paths are coerced to a declared type T, stored as sparse Variant(T) runtime paths plus T-typed shared data, and carried through binary encoding, subcolumn reads, functions, and format integrations. I reviewed the current diff together with all prior discussion and re-checked the late fixes around binary deserialization, invalid-path skipping, and shared-data behavior; I do not see a still-valid correctness, compatibility, or safety issue in the current head.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-feature Pull request with new product feature comp-json-datatype JSON/Dynamic/Object datatype: semi-structured column storage, typed and dynamic paths, sub-object... external Author is not a member of the ClickHouse organization labels Sep 11, 2026
@maxknv maxknv removed the external Author is not a member of the ClickHouse organization label Sep 11, 2026
@clickhouse-gh clickhouse-gh Bot added the external Author is not a member of the ClickHouse organization label Sep 11, 2026
@amosbird
amosbird force-pushed the json-default-path-type branch 2 times, most recently from 945f359 to 9dc9643 Compare September 11, 2026 14:30
Comment thread src/DataTypes/DataTypeObject.h Resolved
Comment thread docs/reference/data-types/newjson.mdx Resolved
@amosbird
amosbird force-pushed the json-default-path-type branch from 9dc9643 to 860e0f1 Compare September 11, 2026 15:30
@amosbird
amosbird force-pushed the json-default-path-type branch 2 times, most recently from bf82fc9 to 961906e Compare September 11, 2026 17:00
Comment thread src/DataTypes/DataTypeObject.cpp Resolved
Comment thread src/Columns/ColumnObject.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing c5aacf08b with master ac85267b8 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 1b9d29136; 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.

Object file sizes

50 object files changed (+246.32 KiB total), 0 added.

Object file Master PR Δ
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionMergedJSONPat… 2.18 MiB 2.29 MiB +112.66 KiB (+5.04%)
src/CMakeFiles/dbms.dir/DataTypes/Serializations/SerializationObjectSharedData.cpp.o 590.88 KiB 619.48 KiB +28.60 KiB (+4.84%)
src/CMakeFiles/dbms.dir/DataTypes/DataTypeObject.cpp.o 651.22 KiB 676.22 KiB +25.00 KiB (+3.84%)
src/CMakeFiles/dbms.dir/Columns/ColumnObject.cpp.o 958.08 KiB 982.40 KiB +24.32 KiB (+2.54%)
src/CMakeFiles/dbms.dir/DataTypes/Serializations/SerializationObject.cpp.o 557.36 KiB 576.79 KiB +19.43 KiB (+3.49%)

719 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

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

Job report

@amosbird
amosbird force-pushed the json-default-path-type branch from 961906e to f344597 Compare September 12, 2026 06:50
@amosbird
amosbird marked this pull request as draft September 13, 2026 07:40
@amosbird
amosbird force-pushed the json-default-path-type branch 2 times, most recently from a2bd058 to 32d8b50 Compare September 19, 2026 21:44
@clickhouse-gh clickhouse-gh Bot added the submodule changed At least one submodule changed in this PR. label Sep 19, 2026
@amosbird
amosbird force-pushed the json-default-path-type branch from 32d8b50 to 7c7c7fe Compare September 19, 2026 22:02
Comment thread src/Columns/ColumnObject.cpp Resolved
amosbird added a commit to amosbird/ClickHouse that referenced this pull request Sep 20, 2026
- Regenerate docs/reference/data-types/newjson.mdx from the JSON
  Documentation{} source data instead of hand-editing the
  AUTOGENERATED region.
- Initialize weak1/weak2 in gtest_column_object.cpp
  (cppcoreguidelines-init-variables with -Werror).

ClickHouse#119389
Comment thread src/DataTypes/DataTypeObject.cpp Resolved
amosbird added a commit to amosbird/ClickHouse that referenced this pull request Sep 20, 2026
…efault_path_type test

The query ordered by json.a, json.b, but with DEFAULT PATH TYPE Int64 a
missing path reads as 0, so '{"a":0}' and '{}' compare equal under
random settings that change the sort order. Order by sipHash64(json)
instead.

ClickHouse#119389
amosbird added a commit to amosbird/ClickHouse that referenced this pull request Sep 21, 2026
…docs

- Drop config_file_for_test.xml and test_truncated_object* leftovers.
- Revert docs/reference/data-types/newjson.mdx: the DEFAULT PATH TYPE
  documentation lives in the Documentation{} attached at registerDataType
  time; the generated .mdx is refreshed by the docs pipeline and must not
  be hand-edited.

ClickHouse#119389
@amosbird
amosbird force-pushed the json-default-path-type branch from 3549ad8 to b3fba90 Compare September 21, 2026 11:31
amosbird added a commit to amosbird/ClickHouse that referenced this pull request Sep 21, 2026
Declare a default type for every non-typed JSON path. Values of non-typed
paths are coerced/validated against T during insert (a non-conforming value
fails the insert unless type_json_skip_invalid_typed_paths is enabled) and
stored as T instead of its natural JSON type:

- runtime-discovered dynamic paths are stored as sparse Variant(T) columns
  instead of Dynamic;
- shared data stores values as bare T (Array(Tuple(String, T))) instead of
  self-describing Dynamic blobs.

Nullable, Dynamic, Variant and Object are rejected as DEFAULT PATH TYPE.
Missing paths read as default(T) and never appear in output, path
enumeration or hashes, even after merges move paths between subcolumn and
shared storage; an explicit default(T) value is a real value and is
distinguishable from a missing path.

Binary encoding version 1 adds the DEFAULT PATH TYPE argument to the JSON
type encoding (see data-types-binary-encoding.mdx).

ClickHouse#119389
@amosbird
amosbird force-pushed the json-default-path-type branch from 68ed74c to 3b6e26d Compare September 30, 2026 00:21
@amosbird

Copy link
Copy Markdown
Collaborator Author

Status: 3b6e26d is the final tree (rebased on master 5ac4352, single commit). Fixes this round: (1) conflict with the Native-format OOB fix in SerializationObjectSharedData resolved; (2) regression in extractCombinedSubcolumn — skip rules must not be propagated into the synthetic sub-object type (05237_json_combined_subcolumn_skip_rules now passes, verified locally); (3) DPT tests tagged no-fasttest. Remaining failure is Fast test 'Server liveness check failed' — a widespread flake this week (6 distinct PRs in the last 3h: 113399, 120466, 122973, 122982, 114812, 119389), 0 test failures in the run. Needs a maintainer re-run of the Fast test job.

@amosbird
amosbird force-pushed the json-default-path-type branch from 3b6e26d to 80040fd Compare October 5, 2026 06:59
amosbird added a commit to amosbird/ClickHouse that referenced this pull request Oct 5, 2026
Declare a default type for every non-typed JSON path. Values of non-typed
paths are coerced/validated against T during insert (a non-conforming value
fails the insert unless type_json_skip_invalid_typed_paths is enabled) and
stored as T instead of its natural JSON type:

- runtime-discovered dynamic paths are stored as sparse Variant(T) columns
  instead of Dynamic;
- shared data stores values as bare T (Array(Tuple(String, T))) instead of
  self-describing Dynamic blobs.

Nullable, Dynamic, Variant and Object are rejected as DEFAULT PATH TYPE.
Missing paths read as default(T) and never appear in output, path
enumeration or hashes, even after merges move paths between subcolumn and
shared storage; an explicit default(T) value is a real value and is
distinguishable from a missing path in MAP shared-data serialization. With
the ADVANCED shared-data serialization the dense bare-T path columns cannot
distinguish an explicit default(T) value from a missing path, matching the
typed-path read which returns default(T) for a missing path.

The individual-value binary serde (RowBinary, Native) uses one on-wire
encoding for every non-typed DPT path — the value coerced to T, serialized
as bare T, wrapped in a length-prefixed blob — independent of whether the
sender kept the path in a runtime path or in shared data; the Field
overloads and the skip path follow the same contract.

Binary encoding version 1 adds the DEFAULT PATH TYPE argument to the JSON
type encoding (see data-types-binary-encoding.mdx).

ClickHouse#119389
@amosbird

amosbird commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator Author

Fast test failed with Server liveness check failed again on 80040fd08a3c93003b8c4953c9aaadeb53cf3e7d (0 test failures — the server process disappeared mid-run at test ~5198 02480_interval_casting_and_subquery, which is unrelated to this PR; system.stack_trace collection returned nothing, exit 210).

This is a repo-wide flake, not caused by this change:

  • cidb: 25+ distinct PRs / 20+ distinct commits hit Server liveness check failed in the last 48h, each 1–3 times, and master itself (pr=0) hit it on 2026-10-01.
  • On this PR, many commits have liveness_fails=0 with 14k+ passing Fast tests; only a few commits each failed once, across different master bases — random, not reproducible.

@groeneai, investigate the failure: Fast test on 80040fd0 and provide a fix in a separate PR (this looks related to the clickhouse-test liveness/hang-check harness, cf. #116243). A maintainer rerun of the flaky Fast test job would also unblock this PR in the meantime.

@groeneai

groeneai commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator

Acknowledged. I'm investigating the Fast test Server liveness check failed failures (server process disappearing mid-run); I'll follow up here with a PR (or my findings) shortly.

@groeneai

groeneai commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator

I looked into it: on this PR it is not a flake, the server crashes.

On 80040fd0 the server got SIGSEGV (NULL pointer read) on SELECT JSONExtractRaw(json, 'a'), JSONExtractRaw(json, 'b') FROM test_json_skip_null ORDER BY rowNumberInAllBlocks() SETTINGS type_json_skip_null_typed_paths = 1 from 04326_json_skip_null_typed_paths; core.QueryPullPipeEx is that crash (server log, search for <Fatal>):

3.0. src/Columns/ColumnVariant.h:158: ColumnVariant::globalDiscriminatorAt (inlined)
3.   src/DataTypes/Serializations/SerializationDynamic.cpp:1172: SerializationDynamic::serializeTextJSON
4.   src/Functions/FunctionsJSON.cpp:319: Executor<NameJSONExtractRaw, ...>::runForObjectColumn<...>
  • All 7 Server liveness check failed runs of this PR's Fast test in the last 7 days are server crashes in JSON queries, 6 of them on this same query (d74629f6, efe95ede, af8ff951, 68ed74cc, 3b6e26da, 80040fd0).
  • On master, 04326_json_skip_null_typed_paths passed all 9078 runs in the last 14 days, and this PR modifies SerializationDynamic, ColumnDynamic, ColumnVariant and ColumnObject. A rerun can pass, but it would only hide the crash.
  • Side note: the diff also reverts part of Use cached serializations for Dynamic fields #113344 in SerializationDynamic.cpp (getSerialization(name, type) back to getSerialization(name) / getDefaultSerialization()). If that is not intended, it looks like a rebase leftover.
  • It is not repo-wide either: master Fast test has no such failure in the last 7 days, and the other PRs hitting it crash in queries that exercise their own changes (e.g. SIGSEGV in exponentialTimeDecaying on the PR that adds it as an aggregate, SIGFPE under enable_adaptive_aggregator on the adaptive aggregator PR).

The harness part is real, and it is mine: when the server process is gone, the hung check still reports Server liveness check failed (the job log even prints "Unable to locate any ClickHouse server process. It must have crashed"), and the test that crashed the server gets no result, so a crash reads as a flake. That label comes from my #115080. I'll send a separate PR so a dead server is reported as Server died with a pointer to the crash, and link it here.

@Ergus Ergus added the can be tested Allows running workflows for external contributors label Oct 5, 2026
@groeneai

groeneai commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator

Here is the separate PR: #124032

With it, a server that dies mid-run is reported as Server died instead of Server liveness check failed, and Fast test adds the fatal error from the server log as a report row with its stack trace (on the 80040fd0 logs that is one Segmentation fault row). A server that is alive but not answering is still reported as Server liveness check failed.

@amosbird
amosbird force-pushed the json-default-path-type branch from 80040fd to 09a5b08 Compare October 7, 2026 23:10
amosbird added a commit to amosbird/ClickHouse that referenced this pull request Oct 7, 2026
`DEFAULT PATH TYPE T` declares the type of every path of a `JSON` column
that has no explicit type hint. On insert, values of such paths are
converted to `T`; a value that cannot be converted fails the insert unless
`type_json_skip_invalid_typed_paths` is enabled, and JSON `null` means the
path is missing. `T` cannot be `Nullable`, `LowCardinality(Nullable)`,
`Dynamic`, `Variant`, `JSON` or `Nothing`.

Storage:
- dynamic paths are sparse `Variant(T)` columns instead of `Dynamic`,
  where NULL means the path is missing in the row;
- shared data stores values as `T` (`Array(Tuple(String, T))`);
- the individual-value binary serialization (used by the `RowBinary`
  formats) writes each non-typed value as a length-prefixed `T` blob.

With the `advanced` shared data serialization a stored `default(T)` is not
distinguishable from a missing path when reading a single path.

The JSON type binary encoding uses version 1 with an appended encoded `T`
only when the modifier is present, so the encoding of other `JSON` types
is unchanged. Without the modifier nothing changes.

Tests: `05338_json_default_path_type`, `05339_json_default_path_type_storage`,
and gtests in `gtest_column_object.cpp` and
`gtest_data_types_binary_encoding.cpp`.

ClickHouse#119389
amosbird added a commit to amosbird/ClickHouse that referenced this pull request Oct 8, 2026
`DEFAULT PATH TYPE T` declares the type of every path of a `JSON` column
that has no explicit type hint. On insert, values of such paths are
converted to `T`; a value that cannot be converted fails the insert unless
`type_json_skip_invalid_typed_paths` is enabled, and JSON `null` means the
path is missing. `T` cannot be `Nullable`, `LowCardinality(Nullable)`,
`Dynamic`, `Variant`, `JSON` or `Nothing`.

Storage:
- dynamic paths are sparse `Variant(T)` columns instead of `Dynamic`,
  where NULL means the path is missing in the row;
- shared data stores values as `T` (`Array(Tuple(String, T))`);
- the individual-value binary serialization (used by the `RowBinary`
  formats) writes each non-typed value as a length-prefixed `T` blob.

With the `advanced` shared data serialization a stored `default(T)` is not
distinguishable from a missing path when reading a single path.

The JSON type binary encoding uses version 1 with an appended encoded `T`
only when the modifier is present, so the encoding of other `JSON` types
is unchanged. Without the modifier nothing changes.

Tests: `05338_json_default_path_type`, `05339_json_default_path_type_storage`,
and gtests in `gtest_column_object.cpp` and
`gtest_data_types_binary_encoding.cpp`.

ClickHouse#119389
@amosbird
amosbird force-pushed the json-default-path-type branch from 09a5b08 to 9dffed7 Compare October 8, 2026 08:29
Comment thread src/Dictionaries/DictionaryHelpers.h Resolved
amosbird added a commit to amosbird/ClickHouse that referenced this pull request Oct 8, 2026
`DEFAULT PATH TYPE T` declares the type of every path of a `JSON` column
that has no explicit type hint. On insert, values of such paths are
converted to `T`; a value that cannot be converted fails the insert unless
`type_json_skip_invalid_typed_paths` is enabled, and JSON `null` means the
path is missing. `T` cannot be `Nullable`, `LowCardinality(Nullable)`,
`Dynamic`, `Variant`, `JSON` or `Nothing`.

Storage:
- dynamic paths are sparse `Variant(T)` columns instead of `Dynamic`,
  where NULL means the path is missing in the row;
- shared data stores values as `T` (`Array(Tuple(String, T))`);
- the individual-value binary serialization (used by the `RowBinary`
  formats) writes each non-typed value as a length-prefixed `T` blob.

With the `advanced` shared data serialization a stored `default(T)` is not
distinguishable from a missing path when reading a single path.

The JSON type binary encoding uses version 1 with an appended encoded `T`
only when the modifier is present, so the encoding of other `JSON` types
is unchanged. Without the modifier nothing changes.

`generateRandom` produces `T` values for non-typed paths of such columns,
and `ColumnObject` rejects dynamic path and shared data columns whose
layout disagrees with its default path type.

Tests: `05338_json_default_path_type`, `05339_json_default_path_type_storage`,
and gtests in `gtest_column_object.cpp` and
`gtest_data_types_binary_encoding.cpp`.

ClickHouse#119389
@amosbird
amosbird force-pushed the json-default-path-type branch from 9dffed7 to 16cde35 Compare October 8, 2026 13:30
amosbird added a commit to amosbird/ClickHouse that referenced this pull request Oct 9, 2026
`DEFAULT PATH TYPE T` declares the type of every path of a `JSON` column
that has no explicit type hint. On insert, values of such paths are
converted to `T`; a value that cannot be converted fails the insert unless
`type_json_skip_invalid_typed_paths` is enabled, and JSON `null` means the
path is missing. `T` cannot be `Nullable`, `LowCardinality(Nullable)`,
`Dynamic`, `Variant`, `JSON` or `Nothing`.

Storage:
- dynamic paths are sparse `Variant(T)` columns instead of `Dynamic`,
  where NULL means the path is missing in the row;
- shared data stores values as `T` (`Array(Tuple(String, T))`);
- the individual-value binary serialization (used by the `RowBinary`
  formats) writes each non-typed value as a length-prefixed `T` blob.

With the `advanced` shared data serialization a stored `default(T)` is not
distinguishable from a missing path when reading a single path.

The JSON type binary encoding uses version 1 with an appended encoded `T`
only when the modifier is present, so the encoding of other `JSON` types
is unchanged. Without the modifier nothing changes.

`generateRandom` produces `T` values for non-typed paths of such columns,
and `ColumnObject` rejects dynamic path and shared data columns whose
layout disagrees with its default path type.

Tests: `05338_json_default_path_type`, `05339_json_default_path_type_storage`,
and gtests in `gtest_column_object.cpp` and
`gtest_data_types_binary_encoding.cpp`.

ClickHouse#119389
@amosbird
amosbird force-pushed the json-default-path-type branch from 16cde35 to 6c6d50b Compare October 9, 2026 03:16
Comment thread src/Columns/ColumnObject.cpp Resolved
amosbird added a commit to amosbird/ClickHouse that referenced this pull request Oct 10, 2026
`DEFAULT PATH TYPE T` declares the type of every path of a `JSON` column
that has no explicit type hint. On insert, values of such paths are
converted to `T`; a value that cannot be converted fails the insert unless
`type_json_skip_invalid_typed_paths` is enabled, and JSON `null` means the
path is missing. `T` cannot be `Nullable`, `LowCardinality(Nullable)`,
`Dynamic`, `Variant`, `JSON` or `Nothing`.

Storage:
- dynamic paths are sparse `Variant(T)` columns instead of `Dynamic`,
  where NULL means the path is missing in the row;
- shared data stores values as `T` (`Array(Tuple(String, T))`);
- the individual-value binary serialization (used by the `RowBinary`
  formats) writes each non-typed value as a length-prefixed `T` blob.

With the `advanced` shared data serialization a stored `default(T)` is not
distinguishable from a missing path when reading a single path.

The JSON type binary encoding uses version 1 with an appended encoded `T`
only when the modifier is present, so the encoding of other `JSON` types
is unchanged. Without the modifier nothing changes.

`generateRandom` and the Parquet variant reader produce `T` values for
non-typed paths of such columns, and `ColumnObject` rejects dynamic path and shared data columns whose
layout disagrees with its default path type.

Tests: `05338_json_default_path_type`, `05339_json_default_path_type_storage`,
`05355_json_default_path_type_parquet_variant`, and gtests in `gtest_column_object.cpp` and
`gtest_data_types_binary_encoding.cpp`.

ClickHouse#119389
@amosbird
amosbird force-pushed the json-default-path-type branch from 6c6d50b to c51df89 Compare October 10, 2026 07:29
amosbird added a commit to amosbird/ClickHouse that referenced this pull request Oct 10, 2026
`DEFAULT PATH TYPE T` declares the type of every path of a `JSON` column
that has no explicit type hint. On insert, values of such paths are
converted to `T`; a value that cannot be converted fails the insert unless
`type_json_skip_invalid_typed_paths` is enabled, and JSON `null` means the
path is missing. `T` cannot be `Nullable`, `LowCardinality(Nullable)`,
`Dynamic`, `Variant`, `JSON` or `Nothing`.

Storage:
- dynamic paths are sparse `Variant(T)` columns instead of `Dynamic`,
  where NULL means the path is missing in the row;
- shared data stores values as `T` (`Array(Tuple(String, T))`);
- the individual-value binary serialization (used by the `RowBinary`
  formats) writes each non-typed value as a length-prefixed `T` blob.

With the `advanced` shared data serialization a stored `default(T)` is not
distinguishable from a missing path when reading a single path.

The JSON type binary encoding uses version 1 with an appended encoded `T`
only when the modifier is present, so the encoding of other `JSON` types
is unchanged. Without the modifier nothing changes.

Values of non-typed paths inserted as a `Field` are converted to `T` like
`CAST`. `generateRandom` and the Parquet variant reader produce `T` values
for non-typed paths, and `ColumnObject` rejects dynamic path and shared
data columns whose layout disagrees with its default path type. The
`Native` format documentation describes the layout of such columns.

Also fix the binary deserialization of `JSON` with a duplicated typed path
and `type_json_skip_duplicated_paths=1`: the skipped value was not consumed,
so the rest of the row was read from the middle of it.

Tests: `05338_json_default_path_type`, `05339_json_default_path_type_storage`,
`05355_json_default_path_type_parquet_variant`, and gtests in `gtest_column_object.cpp` and
`gtest_data_types_binary_encoding.cpp`.

ClickHouse#119389
@amosbird
amosbird force-pushed the json-default-path-type branch from c51df89 to 10b60f0 Compare October 10, 2026 08:55
amosbird added a commit to amosbird/ClickHouse that referenced this pull request Oct 10, 2026
`DEFAULT PATH TYPE T` declares the type of every path of a `JSON` column
that has no explicit type hint. On insert, values of such paths are
converted to `T`; a value that cannot be converted fails the insert unless
`type_json_skip_invalid_typed_paths` is enabled, and JSON `null` means the
path is missing. `T` cannot be `Nullable`, `LowCardinality(Nullable)`,
`Dynamic`, `Variant`, `JSON` or `Nothing`.

Storage:
- dynamic paths are sparse `Variant(T)` columns instead of `Dynamic`,
  where NULL means the path is missing in the row;
- shared data stores values as `T` (`Array(Tuple(String, T))`);
- the individual-value binary serialization (used by the `RowBinary`
  formats) writes each non-typed value as a length-prefixed `T` blob.

With the `advanced` shared data serialization a stored `default(T)` is not
distinguishable from a missing path when reading a single path.

The JSON type binary encoding uses version 1 with an appended encoded `T`
only when the modifier is present, so the encoding of other `JSON` types
is unchanged. Without the modifier nothing changes.

Values of non-typed paths inserted as a `Field` are converted to `T` like
`CAST`. `generateRandom` and the Parquet variant reader produce `T` values
for non-typed paths (the Parquet reader honors
`type_json_skip_invalid_typed_paths` for them), and `ColumnObject` rejects dynamic path and shared
data columns whose layout disagrees with its default path type. The
`Native` format documentation describes the layout of such columns.

Also fix the binary deserialization of `JSON` with a duplicated typed path
and `type_json_skip_duplicated_paths=1`: the skipped value was not consumed,
so the rest of the row was read from the middle of it.

Tests: `05338_json_default_path_type`, `05339_json_default_path_type_storage`,
`05355_json_default_path_type_parquet_variant`, and gtests in `gtest_column_object.cpp` and
`gtest_data_types_binary_encoding.cpp`.

ClickHouse#119389
@amosbird
amosbird force-pushed the json-default-path-type branch from 10b60f0 to f5bca90 Compare October 10, 2026 12:10
Comment thread src/Formats/JSONExtractTree.cpp Resolved
`DEFAULT PATH TYPE T` declares the type of every path of a `JSON` column
that has no explicit type hint. On insert, values of such paths are
converted to `T`; a value that cannot be converted fails the insert unless
`type_json_skip_invalid_typed_paths` is enabled, and JSON `null` means the
path is missing. `T` cannot be `Nullable`, `LowCardinality(Nullable)`,
`Dynamic`, `Variant`, `JSON` or `Nothing`.

Storage:
- dynamic paths are sparse `Variant(T)` columns instead of `Dynamic`,
  where NULL means the path is missing in the row;
- shared data stores values as `T` (`Array(Tuple(String, T))`);
- the individual-value binary serialization (used by the `RowBinary`
  formats) writes each non-typed value as a length-prefixed `T` blob.

With the `advanced` shared data serialization a stored `default(T)` is not
distinguishable from a missing path when reading a single path.

The JSON type binary encoding uses version 1 with an appended encoded `T`
only when the modifier is present, so the encoding of other `JSON` types
is unchanged. Without the modifier nothing changes.

Values of non-typed paths inserted as a `Field` are converted to `T` like
`CAST`. `generateRandom` and the Parquet variant reader produce `T` values
for non-typed paths (the Parquet reader honors
`type_json_skip_invalid_typed_paths` for them; like the `JSON` text
input, a skipped value does not take a slot of `max_dynamic_paths`), and `ColumnObject` rejects dynamic path and shared
data columns whose layout disagrees with its default path type. The
`Native` format documentation describes the layout of such columns.

Also fix the binary deserialization of `JSON` with a duplicated typed path
and `type_json_skip_duplicated_paths=1`: the skipped value was not consumed,
so the rest of the row was read from the middle of it.

Tests: `05338_json_default_path_type`, `05339_json_default_path_type_storage`,
`05355_json_default_path_type_parquet_variant`, and gtests in `gtest_column_object.cpp` and
`gtest_data_types_binary_encoding.cpp`.

ClickHouse#119389

@Avogar Avogar left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, the overall looks good. I left some comments as a first review round, mostly about the serialization part and keeping plain JSON hot paths unaffected. I'll do a more detailed pass after these are addressed.

Comment on lines +77 to +81
if (isNullableOrLowCardinalityNullable(default_path_type) || type_id == TypeIndex::Nothing || type_id == TypeIndex::Variant
|| type_id == TypeIndex::Dynamic || type_id == TypeIndex::Object)
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"DEFAULT PATH TYPE {} is not allowed in {} type: Nullable, Nothing, Dynamic, Variant and Object types are not supported",
default_path_type->getName(), magic_enum::enum_name(schema_format));

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't like that we don't support Nullable(T) as default type. And I don't see any problems with adding support for that. We have all information about nulls already:

  • In dynamic paths we use Variant(T) and its subcolumn Variant(T).T is naturally Nullable(T), so we don't need to do anything, for T we just need to remove Nullable from this subcolumn during read/extraction.
  • In shared data we store rows without null, so if row doesn't contain the value we just insert default in the destination subcolumn, which is null for Nullable(T).

The only problem is that you use T in advanced shared datain per-granule columns of dynamic paths. But we just need to use Variant(T) there instead of T. Also because sub-object/combined subcolumn uses these columns and should keep the information about rows with nulls (which we loose when we use just T here).

So let's support Nullable(T) as default type and switch to Variant(T) in advanced shared data serialization.

/// Use StringHashForHeterogeneousLookup hash for hash maps to be able to use std::string_view in find() method.
using PathToColumnMap = UnorderedMapWithMemoryTracking<String, WrappedPtr, StringHashForHeterogeneousLookup, StringHashForHeterogeneousLookup::transparent_key_equal>;
using PathToDynamicColumnPtrMap = UnorderedMapWithMemoryTracking<String, ColumnDynamic *, StringHashForHeterogeneousLookup, StringHashForHeterogeneousLookup::transparent_key_equal>;
using PathToDynamicColumnPtrMap = UnorderedMapWithMemoryTracking<String, IColumn *, StringHashForHeterogeneousLookup, StringHashForHeterogeneousLookup::transparent_key_equal>;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changing ColumnDynamic * to IColumn * here removes all benefits from using PathToDynamicColumnPtrMap. Originally it was added to avoid virtual calls on IColumn on hot loops over dynamic paths. With default type we can switch to ColumnVariant *. Not sure how to implement it in a good way, maybe we just need 2 maps and decide what to use based on presense of the default path type. Smth like this:

/// ColumnObject.h
template <bool has_default_path_type>
using DynamicPathColumn = std::conditional_t<has_default_path_type, ColumnVariant, ColumnDynamic>;

template <bool has_default_path_type>
using PathToDynamicColumnPtrMap = UnorderedMapWithMemoryTracking<String, DynamicPathColumn<has_default_path_type> *, ...>;

/// One of them is always empty.
PathToDynamicColumnPtrMap<false> dynamic_paths_ptrs;
PathToDynamicColumnPtrMap<true> variant_paths_ptrs;

template <bool has_default_path_type>
auto & getDynamicPathsPtrs()
{
    if constexpr (has_default_path_type)
        return variant_paths_ptrs;
    else
        return dynamic_paths_ptrs;
}

/// ColumnObject.cpp
void ColumnObject::popBack(size_t n)
{
    if (default_path_type)
        popBackImpl<true>(n);
    else
        popBackImpl<false>(n);
}

template <bool has_default_path_type>
void ColumnObject::popBackImpl(size_t n)
{
    for (auto & [_, column] : typed_paths)
        column->popBack(n);
    for (auto & [_, column] : getDynamicPathsPtrs<has_default_path_type>())
        column->popBack(n);
    shared_data->popBack(n);
}

Or maybe you will have better idea.

const ColumnArray::Offsets & getSharedDataOffsets() const { return assert_cast<const ColumnArray &>(*shared_data).getOffsets(); }

std::pair<ColumnString *, ColumnString *> getSharedDataPathsAndValues()
std::pair<ColumnString *, IColumn *> getSharedDataPathsAndValues()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same problem here, we will pay virtual calls on IColumn now on hot paths where we need ColumnString methods in plain JSON with no default type.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And changes below this are related to the problem

Comment on lines +60 to +85
/// With `DEFAULT PATH TYPE T` the value of a non-typed path in row binary formats is a
/// length-prefixed blob with the binary serialization of `T`.
template <typename Serialize>
void writeDefaultPathTypeValue(WriteBuffer & ostr, const Serialize & serialize)
{
WriteBufferFromOwnString value_buf;
serialize(value_buf);
writeStringBinary(value_buf.str(), ostr);
}

/// Reads (or skips) the blob written by `writeDefaultPathTypeValue`.
String readDefaultPathTypeValue(ReadBuffer & istr, const FormatSettings & settings)
{
String value;
readStringBinary(value, istr, settings.binary.max_binary_string_size ? settings.binary.max_binary_string_size : SerializationString::MAX_STRING_SIZE);
return value;
}

template <typename Deserialize>
void deserializeDefaultPathTypeValue(const String & value, const Deserialize & deserialize)
{
ReadBufferFromString buf(value);
deserialize(buf);
if (!buf.eof())
throw Exception(ErrorCodes::INCORRECT_DATA, "Unexpected trailing data in the binary value of a JSON path with default path type");
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't understand why we need this. We know T in advance and we can serialize/deserialize into the T column directly. And when we need to read into the shared data we can use readParsedValueIntoString just like we do it for Dynamic paths right now. This whole logic of size + serialized value as string is not needed here at all in my opinion.

@@ -1169,13 +1212,31 @@ void SerializationObject::deserializeBinaryBulkWithMultipleStreams(
void SerializationObject::serializeBinary(const Field & field, WriteBuffer & ostr, const DB::FormatSettings & settings) const

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This code looks strange. I would expect the coming Field to have already converted types, so for each path:

  • if it's a typed path, it has value of the corresponding type
  • if it's not a typed path and default path type is enabled, it has exactly value of thistype
  • otherwise it has valud of any type and Dynamic handles it

This is not the place we should convert fields to the expected types.

is_missing_path is also not needed here. If default type is non Nullable type, we should not get nulls anyhow, if it's Nullable(T) and somehow we got null here, we can safely write it in binary serialization, because we would use default type serialization which is Nullable serialization.

}

/// Shared data values are `String` (binary `Dynamic` values) for ordinary JSON and `T` with `DEFAULT PATH TYPE T`.
void serializeCopyValues(const IColumn & values_column, const DataTypePtr & default_path_type, WriteBuffer & ostr, size_t offset, size_t limit)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't understand why we use for loop + serializeBinary/deserializeBinary. We just need to save somewhere the values serialization and use regular shared_data_values_serialization-> serializeBinaryBulkWithMultipleStreams()/shared_data_values_serialization-> deserializeBinaryBulkWithMultipleStreams(). It's ok to serialize values into different streams.


/// With `DEFAULT PATH TYPE T` shared data values have type `T`. Fills either a `T` column
/// (a missing path is `default(T)`) or a `Variant(T)` column (a missing path is NULL).
void fillDefaultPathTypeColumnFromSharedData(IColumn & path_column, std::string_view path, const IColumn & shared_data_column, size_t start, size_t end)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's move it to the ColumnObject::fillPathColumnFromSharedData. This method should decide based on the default type presence how to fill the path from shared data.

Comment on lines +745 to +746
/// With `DEFAULT PATH TYPE T` convert values of all non-typed paths to `T` like `CAST` before changing
/// any subcolumn, so a value that cannot be converted to `T` doesn't leave subcolumns misaligned.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would expect fields to be already converted here. As we expect it for any other typed subcolumns. Probably we need to implement the conversion somewhere in convertFieldToType

auto & shared_data_values_chars = shared_data_values->getChars();
if (const auto * variant = typeid_cast<const ColumnVariant *>(&column))
{
shared_data_values->insertFrom(variant->getVariantByLocalDiscriminator(0), variant->offsetAt(n));

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are many places that work with the values of dynamic paths of JSON with default path type by hand: getVariantByLocalDiscriminator(0)/getVariantByGlobalDiscriminator(0) + offsetAt(n) to read a value, insertIntoVariantFrom(0, ...) to insert one, deserializeBinaryIntoVariant(0, default_path_type->getDefaultSerialization(), ...) to deserialize one, and in JSONExtractTree::insertIntoDynamicPath even a manual push of the local discriminator and the offset. Local and global discriminators are mixed (it works only because there is a single variant), and the knowledge of how a dynamic path stores its values is spread over ColumnObject, SerializationObject, JSONExtractTree, Parquet decoding, Analyzer and aggregate functions.

Let's encapsulate it in methods of ColumnObject and use them everywhere instead. For example:

/// For `JSON(DEFAULT PATH TYPE T)`: dynamic paths are `Variant(T)`, where NULL means the path is absent in the row.

/// The column with values of type `T` of the dynamic path and the row in it with the value of row `n`.
/// The path must be present in row `n`.
std::pair<const IColumn &, size_t> getDynamicPathValue(const ColumnVariant & path_column, size_t n) const;
/// Appends value `n` of the column `src` of type `T` to the dynamic path.
void insertDynamicPathValueFrom(ColumnVariant & path_column, const IColumn & src, size_t n) const;
/// Binary serialization of the value of row `n` and deserialization of a value appended to the dynamic path.
void serializeDynamicPathValueBinary(const ColumnVariant & path_column, size_t n, WriteBuffer & ostr, const FormatSettings & settings) const;
void deserializeDynamicPathValueBinary(ColumnVariant & path_column, ReadBuffer & istr, const FormatSettings & settings) const;

This is only an example, feel free to choose the methods and names you like. The point is that the layout of a dynamic path is handled in one place. As methods of ColumnObject they can also check that the object has default path type and use the default_path_serialization stored in the column, so callers don't need to pass default_path_type->getDefaultSerialization() around.

Comment on lines +609 to +614
/// Only streams that contain nothing but a prefix: with `DEFAULT PATH TYPE` the dynamic paths are `Variant(T)`,
/// whose discriminators stream holds the prefix followed by data, and it can be shared with an already
/// positioned subcolumn reader, so seeking it to the start here would break that reader.
auto enumerate_callback = [&](const SubstreamPath & path)
{
if (hasPrefix(path))
if (hasPrefix(path, /*use_specialized_prefixes_and_suffixes_substreams=*/ true))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't seem to be the right place to change anything. SerializationObject should know nothing about reader logic and seeking of the stream outside, it just has one job - call the callback on newly discovered streams. It it should workf for any prefixes out of the box, not only for specific prefixes stored in separate files.

Probably we need a fix in the reader in the prefixes_prefetch_callback callback. Or even propagate some dynamic_streams_enumerate_callback instead and on reader side decide what to do with new dynamic streams, either prefetch something like prefixes of not

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-json-datatype JSON/Dynamic/Object datatype: semi-structured column storage, typed and dynamic paths, sub-object... external Author is not a member of the ClickHouse organization pr-feature Pull request with new product feature submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants