Skip to content

Region layout (v2) of the SHARED typed paths of JSON - #132369

Open
Avogar wants to merge 11 commits into
masterfrom
shared-type-hints-regions
Open

Avogar wants to merge 11 commits into
masterfrom
shared-type-hints-regions

Conversation

@Avogar

@Avogar Avogar commented Nov 17, 2026 •

Copy link
Copy Markdown
Member

Related: #127000
Related: #128157

Adds version v2 of the storage of the SHARED typed paths of JSON, selected by the MergeTree setting object_typed_shared_data_serialization_version = 'v2' (the default stays v1). In Wide parts, the data of every SHARED path is also stored apart for the whole part, so a query that reads a few SHARED paths reads only their bytes instead of the shared data of all paths.

v1: all SHARED paths in one stream

1-v1-layout

In v1 (#127000) the SHARED paths of a part live in a constant number of files: granule by granule, the data of every path one after another, with a marks entry per granule pointing at the start of each path's piece. The piece of a path holds all its substreams.

2-v1-read

A read of one path takes its piece from every granule and appends each substream to its part of the column. The pieces are scattered over the whole file, between the data of the other paths. What such a read pays:

  • One small piece per granule: a few KiB of compressed data, thousands of pieces per part.
  • Between two pieces, either a read through the gap (on object storage a narrow read costs as much as the whole column) or a new request per piece (thousands of requests per query).
  • Over-read per piece: the read buffer fetches at least its own size, and its only bound is the end of the read task.
  • Filesystem cache pollution: the cache works in segments of 4 MiB, so a cold read of one path caches the data of all paths.
  • Marks: the reader needs the marks of every granule, and the volume of marks grows as paths times granules.
  • Shared compressed blocks: depending on the sizes of the paths and of the granules, a block holds the data of several paths, which the read decompresses too.
  • Prefetch does not help: the pieces are too many and too small, and prefetching the stream means prefetching the whole file.
  • CPU: a seek and a block decompression per path per granule.
  • It gets worse as the JSON grows: adaptive granularity gives bigger rows more granules, and so smaller pieces.

v2: a region per substream of every path

3-v2-layout

A Wide part in v2 keeps the plain layout and also stores every substream of every SHARED path as a region: the substream's bytes for the whole part, cut into compressed blocks at granules, with a mark per granule. A region has the same layout as a column file of a Wide part. All regions are in one .paths_region_data file, and the marks of each region are a slice of one .paths_region_marks file, so the number of files stays constant. The .header records, per path and substream, the sizes of its region and of its marks slice.

The plain layout stays for reads of the whole column, merges and mutations. The cost is that the SHARED data of a Wide part is stored twice. Compact parts, and typed shared data nested inside a path, keep v1.

Reading a path through views of its regions

4-v2-read

The prefix read (the .header) tells the reader where the regions of the requested paths are. MergeTreeReaderWide opens each region as a view: a byte range of .paths_region_data with its slice of .paths_region_marks, opened as an ordinary MergeTreeReaderStream over ReadBufferFromFileView, with the slice loaded through the mark cache. From then on a region is read like a separate column file: seeks to marks, skipped granules, prefetch and the mark cache work unchanged.

The view also passes its byte range down as read bounds (ReadBuffer::setReadBounds). FileCache::getOrSet uses them to keep the alignment of its segments within the region, so the cache does not download the neighbouring regions.

Regions are used by reads of a SHARED path, of a subcolumn of one, and of a sub-object with at most object_shared_data_max_sub_object_paths_to_read_separately (32) paths. A read of the whole column, or of a wider sub-object, uses the plain layout.

A read through regions has none of the problems of the plain layout listed above, while the number of files stays constant: its data is contiguous, bounded, cached and prefetched as a separate column file, with its own marks and compressed blocks. Reads of the whole column, merges and mutations read every path anyway and use the plain layout; a sub-object with more paths than the limit uses it too and pays its costs.

Writing the regions, and temporary data

5-v2-spill

The regions are written at the end of the part, after all granules. A part written from one block, which is every insert, serializes them straight from the block. Merges and mutations see the data granule by granule, so they buffer each substream of each path in memory until the end of the part.

When the buffers of a part write exceed serialization_spill_max_bytes_to_buffer, the largest buffer is spilled as one segment: the data plus the granule offsets that cut it into blocks and marks at the end. The budget is shared by all JSON columns of the part write.

Spills go first to the server's temporary storage (tmp_path, tmp_policy, or the filesystem cache of temporary_data_in_cache). Space is reserved ahead in steps of 64 MiB, so a lack of space is a refusal before writing, not a failed write. When the storage refuses, or a limit is reached, the part write moves its spills to the part's disk: a tmp_data_<uuid> directory of the table. The directory is removed when the part write ends, and by the cleanup of tmp_ directories at the table's startup after a crash. At the end of the part, the segments of every substream are read back in order and written into its region with the part's codec.

Setting Level Default Meaning
serialization_spill_max_bytes_to_buffer MergeTree 128 MiB The memory budget of a part write, for all its columns together. 0 buffers everything in memory.
serialization_spill_max_temporary_data_size MergeTree 0 The limit of one part write in the temporary storage. 0 means no limit of its own.
max_temporary_data_on_disk_size_for_serialization_spills server 0 The limit of all part writes together in the temporary storage. 0 means the ratio below.
max_temporary_data_on_disk_ratio_for_serialization_spills server 0.3 That limit as a ratio of the size of the temporary storage.
serialization_spill_to_part_disk_only MergeTree false Spill to the part's disk from the start. Also the behaviour when the temporary storage is the distributed cache.
serialization_spill_error_mode MergeTree throw When an error loses data already spilled to the temporary storage: throw fails the part write, skip writes the part without the regions, which is then read from the plain layout.

The limits are within max_temporary_data_on_disk_size. An error on the part's disk always fails the part write.

Benchmark

Reads of SHARED typed paths in v1 and v2, on one ClickHouse Cloud service (a replica of 32 GiB, max_threads 8), each table merged to one part. S1: 50 M rows, 100 paths in 10 prefixes (UInt64, String, Float64, Array). S2: 5 M rows, 1000 paths in 100 prefixes (UInt64, String). Cold: the filesystem, mark and uncompressed caches dropped before each run; warm: after a warm-up run. Medians of 3 cold and 5 warm runs. The sub-object is json.^g3 (S1) and json.^g42 (S2), 10 paths each.

Cold:

dataset query layout time read from S3 S3 GETs memory
S1 one path v1 8105 ms 5.38 GiB 185 44.82 MiB
v2 214 ms 55.75 MiB 13 37.00 MiB
three paths v1 6605 ms 5.35 GiB 196 126.13 MiB
v2 522 ms 172.65 MiB 53 218.76 MiB
ten paths v1 7609 ms 5.01 GiB 292 65.60 MiB
v2 1347 ms 294.39 MiB 159 346.23 MiB
sub-object v1 4696 ms 5.38 GiB 210 296.27 MiB
v2 1195 ms 480.46 MiB 162 2.02 GiB
S2 one path v1 12601 ms 8.58 GiB 290 50.43 MiB
v2 107 ms 5.33 MiB 4 27.39 MiB
three paths v1 12374 ms 8.59 GiB 291 71.39 MiB
v2 158 ms 20.43 MiB 11 81.35 MiB
ten paths v1 12262 ms 8.54 GiB 307 68.83 MiB
v2 364 ms 70.71 MiB 36 281.86 MiB
sub-object v1 11284 ms 8.59 GiB 297 119.27 MiB
v2 240 ms 75.59 MiB 42 454.73 MiB

Warm:

dataset query layout time read from the filesystem cache memory
S1 one path v1 184 ms 889.44 MiB 42.93 MiB
v2 66 ms 56.02 MiB 36.75 MiB
three paths v1 563 ms 2.32 GiB 130.96 MiB
v2 286 ms 202.40 MiB 236.83 MiB
ten paths v1 1507 ms 3.87 GiB 68.72 MiB
v2 915 ms 564.03 MiB 354.39 MiB
sub-object v1 850 ms 1.55 GiB 302.50 MiB
v2 871 ms 585.39 MiB 2.09 GiB
S2 one path v1 97 ms 572.88 MiB 50.10 MiB
v2 11 ms 5.51 MiB 27.28 MiB
three paths v1 248 ms 1.13 GiB 75.69 MiB
v2 33 ms 21.02 MiB 103.92 MiB
ten paths v1 847 ms 4.48 GiB 73.50 MiB
v2 110 ms 73.17 MiB 336.54 MiB
sub-object v1 276 ms 657.50 MiB 115.50 MiB
v2 134 ms 79.73 MiB 487.67 MiB

Other changes

  • MergeTreeReaderWide opens the streams listed by the deserialized prefixes before the read, so that their marks load in parallel. Metadata streams load no marks, and cached subcolumn streams are prefetched.
  • TemporaryDataOnDisk can reserve space ahead (tryReserveMore) and has a scope for serialization spills with its own limit.
  • New profile events: ObjectTypedSharedDataRegionReads, ObjectTypedSharedDataPlainLayoutReads, SerializationSpilledSegments, SerializationSpilledBytes, SerializationSpilledUncompressedBytes, SerializationSpillFiles, SerializationSpilledToPartDisk, SerializationSpillErrors. New metric: TemporaryFilesForSerializationSpills.

Changelog category (leave one):

  • Performance Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Add version v2 of the storage of the SHARED typed paths of JSON (MergeTree setting object_typed_shared_data_serialization_version = 'v2'). In Wide parts, the data of each SHARED path is also stored separately for the whole part, so a query that reads a few SHARED paths reads only their data instead of the shared data of all paths. Merges and mutations buffer this data in memory and spill it to the temporary storage or to the part's disk beyond serialization_spill_max_bytes_to_buffer.


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

Avogar and others added 3 commits November 16, 2026 15:21
…-regions

# Conflicts:
#	src/DataTypes/Serializations/ISerialization.h
#	src/DataTypes/Serializations/SerializationObjectTypedSharedData.h
#	src/Interpreters/FileCache/FileCache.cpp
#	src/Interpreters/TemporaryDataOnDisk.cpp
#	src/Interpreters/TemporaryDataOnDisk.h
#	src/Storages/MergeTree/IMergeTreeDataPart.h
#	src/Storages/MergeTree/IMergeTreeDataPartInfoForReader.h
#	src/Storages/MergeTree/LoadedMergeTreeDataPartInfoForReader.h
#	src/Storages/MergeTree/MergeTreeDataPartWriterWide.h
#	src/Storages/MergeTree/tests/gtest_merge_tree_marks_loader.cpp
…-regions

Resolve the conflict with PR 131011 in MergeTreeReaderWide: take the resolved
substreams, keep the stream keys of views for the stream map, the prefetched
set and the average value size hints.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f33e3fd]

Summary: ❌

job_name test_name status info comment
Stress test (amd_msan) FAIL
Cannot start clickhouse-server FAIL cidb
Check failed FAIL cidb

AI Review

Summary

Adds the v2 region layout for JSON paths declared SHARED, together with buffered serialization, spilling, stream views, and cache bounds. Earlier spill-count bounds and test-setting fixes are present. No additional inline finding was identified, but the following previously dismissed concerns remain applicable to the current code.

Consumer scope for the new representation: whole-column reads, merges, mutations, and wide sub-objects retain the plain layout; path/subcolumn and narrow sub-object readers translate their streams to region views. MergeTreeReaderWide opens those views and validates mark counts; MergeTreeReaderStream bounds data reads; MergeTreeMarksLoader reads marks slices; packed-file views, asynchronous/gather readers, and filesystem caches translate or propagate the byte bounds.

Findings

❌ Blockers

  • src/Core/SettingsEnums.cpp:553: The new persistent layout has no experimental gate. object_typed_shared_data_serialization_version = 'v2' enables the new format and spill/write machinery without an experimental opt-in; its setting declaration still has flags 0. Add an experimental gate for new writes while preserving reads of existing parts. [dismissed by author -- https://github.com/Region layout (v2) of the SHARED typed paths of JSON #132369#discussion_r4605184513] The author considers the feature non-experimental; the review requirement for a new on-disk format still applies, and retaining v1 as the default does not supply that gate.

  • src/DataTypes/Serializations/SerializationObjectTypedSharedData.cpp:1799: A stored row count can drive disproportionate allocation before input validation. A .paths_marks entry declaring 1000000000 rows for JSON(SHARED a UInt64) reaches SerializationNumber<UInt64>::deserializeBinaryBulk, which resizes for at least 8 GB before reading data. Requesting one row still decodes the entire declared granule. Bound the decoded count against appropriate column/granule metadata, decode in bounded chunks, or link a tracking issue for the pre-existing decoder defect. [dismissed by author -- https://github.com/Region layout (v2) of the SHARED typed paths of JSON #132369#discussion_r4633385780] Its origin in v1 and the same risk in other marks readers do not validate malformed bytes reaching this decoder through v2 whole-column reads and merges.

  • src/Storages/MergeTree/MergeTreeData.cpp:5181: Recovery can orphan private spill objects on zero-copy disks. After process termination during spilling, tmp_data_ directories reach removeSharedTemporaryDirectory. For replicated object-storage tables with allow_remote_fs_zero_copy_replication = 1, this removes metadata with keep_shared = true, permanently retaining blobs that have no committed part or owner. Give positively identified private spill directories a recovery path that removes their objects. [dismissed by author -- https://github.com/Region layout (v2) of the SHARED typed paths of JSON #132369#discussion_r4633385796] Normal destructor cleanup does not cover process termination, and the supported setting remains able to select this recovery path even if the author does not use it.

⚠️ Majors

  • src/Storages/MergeTree/MergeTreeSettings.cpp:439: The claimed performance benefit has no measurements exercising v2. The description contains no timings or resource measurements, and tests/performance/json_shared_typed_paths.xml still selects default v1. Functional coverage cannot establish the benefit or the write/merge cost of storing shared data twice. [dismissed by author -- https://github.com/Region layout (v2) of the SHARED typed paths of JSON #132369#discussion_r4605184530] The limitation cited for configuring old/new CI servers does not prevent a reproducible v1 versus v2 benchmark on the patched server.
Tests
  • ⚠️ Supply a focused v1 versus v2 narrow-read comparison, preferably with cold object-storage/cache reads, plus insert/merge time and peak memory while spilling.
  • ⚠️ Add a malformed plain-layout marks case proving an oversized row count fails without a large allocation, and a recovery case checking remote spill objects after process termination with zero-copy replication enabled.
Final Verdict

Status: ❌ Block

Gate new-format writes, bound or explicitly track the malformed-marks allocation, correct private-spill recovery on zero-copy disks, and provide performance evidence. The dismissed threads were left unchanged; no duplicate inline comments were posted.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-json-datatype JSON/Dynamic/Object datatype: semi-structured column storage, typed and dynamic paths, sub-object... labels Nov 17, 2026
Avogar and others added 2 commits November 17, 2026 18:15
- `no-fasttest` for the tests 05457 and 05479 that enable fail points, as the
  style check `failpoint_tests_are_isolated` requires.
- `TemporaryDataReadBuffer` takes its seekable reader from the holder after the
  move, for clang 23 `-Wlifetime-safety-dangling-field-moved`.
- `[[nodiscard]]` and initialized variables for clang-tidy.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=132369&sha=43fc440b32d8c7989f17246009cdf1de04b495ba&name_0=PR
PR: #132369

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Metadata streams load no marks now, so a read of a `JSON` or `Dynamic` column
loads and opens fewer marks files: 05109 loads 16 marks files instead of 22
(the object structure and the dynamic structures of its 5 paths), and 03198
opens 7 files instead of 8 (the marks of `d.dynamic_structure`).

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=132369&sha=e20e2f51e6cf7b403047f02a133c29463feb09ba&name_0=PR&name_1=Fast%20test
PR: #132369

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Core/SettingsEnums.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f33e3fd85 with master 6f06fe03d (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

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 ⚠️

780 object files changed (+1.43 MiB total), 2 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/DataTypes/Serializations/SerializationObjectTypedSharedData.cpp.o 283.11 KiB 547.45 KiB +264.34 KiB (+93.37%)
src/CMakeFiles/dbms.dir/DataTypes/Serializations/SerializationSpiller.cpp.o new 101.89 KiB +101.89 KiB
src/CMakeFiles/clickhouse_common_io.dir/IO/PiecewiseWriteBuffer.cpp.o new 60.17 KiB +60.17 KiB
src/CMakeFiles/dbms.dir/DataTypes/Serializations/SerializationObject.cpp.o 637.39 KiB 692.61 KiB +55.21 KiB (+8.66%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeReaderWide.cpp.o 463.65 KiB 515.61 KiB +51.96 KiB (+11.21%)
src/CMakeFiles/dbms.dir/DataTypes/Serializations/SerializationObjectSharedData.cpp.o 658.27 KiB 698.30 KiB +40.04 KiB (+6.08%)
src/CMakeFiles/dbms.dir/DataTypes/Serializations/SerializationObjectTypedSharedDataPath.cpp.o 135.70 KiB 174.50 KiB +38.80 KiB (+28.59%)
src/CMakeFiles/dbms.dir/DataTypes/Serializations/SerializationSubObjectTypedSharedData.cpp.o 130.73 KiB 168.03 KiB +37.30 KiB (+28.54%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/IMergeTreeDataPart.cpp.o 1.62 MiB 1.65 MiB +33.67 KiB (+2.03%)
src/CMakeFiles/dbms.dir/Interpreters/TemporaryDataOnDisk.cpp.o 275.38 KiB 306.55 KiB +31.16 KiB (+11.32%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeDataPartWriterWide.cpp.o 404.39 KiB 434.75 KiB +30.36 KiB (+7.51%)
src/CMakeFiles/dbms.dir/Core/SettingsEnums.cpp.o 2.50 MiB 2.52 MiB +24.78 KiB (+0.97%)
src/CMakeFiles/dbms.dir/Interpreters/Context.cpp.o 3.67 MiB 3.69 MiB +24.15 KiB (+0.64%)
src/CMakeFiles/dbms.dir/DataTypes/Serializations/SerializationVariant.cpp.o 423.36 KiB 446.06 KiB +22.70 KiB (+5.36%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeData.cpp.o 4.73 MiB 4.75 MiB +20.50 KiB (+0.42%)
src/CMakeFiles/dbms.dir/DataTypes/Serializations/SerializationMap.cpp.o 1.81 MiB 1.83 MiB +19.25 KiB (+1.04%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergedBlockOutputStream.cpp.o 316.61 KiB 333.31 KiB +16.71 KiB (+5.28%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeSettings.cpp.o 1.21 MiB 1.22 MiB +16.47 KiB (+1.33%)

716 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

3955 translation units recompiled, 15496 s compile time in total, 3953 of them have a recent master baseline.

Symbol sizes
Binary Symbol Master PR Δ
programs/clickhouse ProfileEvents::global_counters_storage 14.69 MiB 14.75 MiB +64.00 KiB (+0.43%)

Job report

CI fixes:
- `05182` reference: metadata streams no longer load marks, so a read loads 15
  marks files, not 21.
- `FileSegment::reserve` grew an unbound segment's range by the written data plus
  the request, but a reserve-ahead leaves reserved space unwritten and
  `size_to_reserve` was already reduced by it, so the range could end below
  `reserved_size` and the next reserve aborted. Grow it to cover the reservation.
- `05475` inserts 100000 rows instead of 400000: the same layout is exercised and
  the test no longer times out under a sanitizer.

Hardening of the v2 header and spilled-segment decode:
- Bound the per-path substream count read from the header before allocating.
- Reject a decoded granule run that would exceed the part's granules, and check a
  spilled segment was consumed exactly, instead of looping or reading past it.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=132369&sha=887cbf35cdfe6090ba2e7c03815cce3f8266915c&name_0=PR
PR: #132369

Co-Authored-By: Claude Opus 4.8 <[email protected]>
- `GranuleOffsets::read` takes the size of the encoded data and rejects an
  entry count above it before allocating: each entry takes at least one byte.
- 05458, 05488 and 05489 reset `max_block_size` before scanning
  `system.query_log`, which the tiny blocks of their reads would slow down.

PR: #132369

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- The caches a region read needs are lazily allocated: `columns_read_sizes` and
  `registered_mark_cache_keys` are unique_ptrs, null on parts that never read a
  region, so a part without a JSON column does not grow by them.
- `getColumnReadSize` returns the column size directly for a column without
  dynamic subcolumns, instead of caching a value equal to it, so the cache is
  populated only on parts that have such a column.
- 05474 checks only that the region's cached start is not aligned to the cache
  boundary. The end is dropped: its edge segment can be absent after prefetch or
  eviction, which made the check flaky, while the start is a stable witness that
  the bounds clamp the read on both of the stacked caches.

PR: #132369

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Avogar and others added 3 commits November 23, 2026 13:45
…-regions

Conflicts with PR 128157 (now in master), PR 133356 (PREWHERE subcolumn sizing
through the query's caches) and PR 121829 (mark cache key by part name):
- subcolumn sizing keeps the streams cache of the regions and takes master's
  getColumnAndSubcolumnSizes, canCalculateSubcolumnSizeFromMemory and the read
  settings of getListOfStreamsForColumns;
- the read sizes keep their lazily allocated cache;
- the mark cache key of a slice extends master's key by part name;
- 05457 takes master's faster version.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…-regions

Conflicts in TemporaryDataOnDisk with PR 120906 (UBSan check of unsigned
overflows): the scopes keep the reservation accounting of this branch, whose
compare-and-add already leaves every scope unchanged when a limit refuses;
master's getTemporaryFileReserveSize is kept.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

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

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant